Skip to content

Commit 40b77a8

Browse files
support closures
1 parent 81c99cc commit 40b77a8

File tree

4 files changed

+16
-2
lines changed

4 files changed

+16
-2
lines changed

Project.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@ authors = ["Mike J Innes <mike.j.innes@gmail.com>"]
44
version = "0.4.0"
55

66
[deps]
7+
ConstructionBase = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
78
Documenter = "e30172f5-a6a5-5a46-863b-614d45cd2de4"
89
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
910

1011
[compat]
12+
ConstructionBase = "1.4"
1113
Documenter = "0.27"
1214
julia = "1.6"
1315

src/Functors.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
module Functors
22

3+
using ConstructionBase: constructorof
34
export @functor, @flexiblefunctor, fmap, fmapstructure, fcollect
45

56
include("functor.jl")

src/functor.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
function functor(T, x)
1+
function functor(T::Type, x)
22
names = fieldnames(T)
33
if isempty(names)
44
return (), _ -> x
55
end
6-
S = T.name.wrapper # remove parameters from parametric types
6+
S = constructorof(T) # remove parameters from parametric types and support anonymous functions
77
vals = ntuple(i -> getfield(x, names[i]), length(names))
88
return NamedTuple{names}(vals), y -> S(y...)
99
end

test/basics.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,17 @@ end
148148
@test_throws Exception functor(NamedTuple{(:x, :y)}, (z=33, x=1))
149149
end
150150

151+
@testset "anonymous functions" begin
152+
model = let W = rand(2,2), b = ones(2)
153+
x -> tanh.(W*x .+ b)
154+
end
155+
newmodel = fmap(zero, model)
156+
@test newmodel isa Function
157+
@test newmodel([1,2]) == [0,0]
158+
@test newmodel.W == [0 0; 0 0]
159+
@test newmodel.b == [0, 0]
160+
end
161+
151162
###
152163
### Extras
153164
###

0 commit comments

Comments
 (0)