Skip to content

Commit

Permalink
support closures
Browse files Browse the repository at this point in the history
  • Loading branch information
CarloLucibello committed Dec 7, 2022
1 parent 30cee5f commit 9986158
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 1 deletion.
2 changes: 2 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ authors = ["Mike J Innes <[email protected]>"]
version = "0.4.1"

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

[compat]
ConstructionBase = "1.4"
Documenter = "0.27"
julia = "1.6"

Expand Down
1 change: 1 addition & 0 deletions src/Functors.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module Functors

using ConstructionBase: constructorof
export @functor, @flexiblefunctor, fmap, fmapstructure, fcollect

include("functor.jl")
Expand Down
2 changes: 1 addition & 1 deletion src/functor.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function functor(T, x)
if isempty(names)
return (), _ -> x
end
S = T.name.wrapper # remove parameters from parametric types
S = constructorof(T) # remove parameters from parametric types and support anonymous functions
vals = ntuple(i -> getfield(x, names[i]), length(names))
return NamedTuple{names}(vals), y -> S(y...)
end
Expand Down
11 changes: 11 additions & 0 deletions test/basics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,17 @@ end
@test_throws Exception functor(NamedTuple{(:x, :y)}, (z=33, x=1))
end

@testset "anonymous functions" begin
model = let W = rand(2,2), b = ones(2)
x -> tanh.(W*x .+ b)
end
newmodel = fmap(zero, model)
@test newmodel isa Function
@test newmodel([1,2]) == [0,0]
@test newmodel.W == [0 0; 0 0]
@test newmodel.b == [0, 0]
end

###
### Extras
###
Expand Down

0 comments on commit 9986158

Please sign in to comment.