Functors.jl
Flux makes use of the Functors.jl to represent many of the core functionalities it provides.
Functors.jl is a collection of tools designed to represent a functor. Flux makes use of it to treat certain structs as functors. Notable examples include the layers that Flux defines.
Functors.isleaf
— FunctionFunctors.children
— Functionchildren(x)
Return the children of x
as defined by functor
. Equivalent to functor(x)[1]
.
Functors.fcollect
— Functionfcollect(x; exclude = v -> false)
Traverse x
by recursing each child of x
as defined by functor
and collecting the results into a flat array, ordered by a breadth-first traversal of x
, respecting the iteration order of children
calls.
Doesn't recurse inside branches rooted at nodes v
for which exclude(v) == true
. In such cases, the root v
is also excluded from the result. By default, exclude
always yields false
.
See also children
.
Examples
julia> struct Foo; x; y; end
julia> @functor Foo
julia> struct Bar; x; end
julia> @functor Bar
julia> struct NoChildren; x; y; end
julia> m = Foo(Bar([1,2,3]), NoChildren(:a, :b))
Foo(Bar([1, 2, 3]), NoChildren(:a, :b))
julia> fcollect(m)
4-element Vector{Any}:
Foo(Bar([1, 2, 3]), NoChildren(:a, :b))
Bar([1, 2, 3])
[1, 2, 3]
NoChildren(:a, :b)
julia> fcollect(m, exclude = v -> v isa Bar)
2-element Vector{Any}:
Foo(Bar([1, 2, 3]), NoChildren(:a, :b))
NoChildren(:a, :b)
julia> fcollect(m, exclude = v -> Functors.isleaf(v))
2-element Vector{Any}:
Foo(Bar([1, 2, 3]), NoChildren(:a, :b))
Bar([1, 2, 3])
Missing docstring for Functors.functor
. Check Documenter's build log for details.
Functors.fmap
— Functionfmap(f, x; exclude = isleaf, walk = Functors._default_walk)
A structure and type preserving map
that works for all functor
s.
By default, traverses x
recursively using functor
and transforms every leaf node identified by exclude
with f
.
For advanced customization of the traversal behaviour, pass a custom walk
function of the form (f', xs) -> ...
. This function walks (maps) over xs
calling the continuation f'
to continue traversal.
Examples
julia> struct Foo; x; y; end
julia> @functor Foo
julia> struct Bar; x; end
julia> @functor Bar
julia> m = Foo(Bar([1,2,3]), (4, 5));
julia> fmap(x -> 2x, m)
Foo(Bar([2, 4, 6]), (8, 10))
julia> fmap(string, m)
Foo(Bar("[1, 2, 3]"), ("4", "5"))
julia> fmap(string, m, exclude = v -> v isa Bar)
Foo("Bar([1, 2, 3])", (4, 5))
julia> fmap(x -> 2x, m, walk=(f, x) -> x isa Bar ? x : Functors._default_walk(f, x))
Foo(Bar([1, 2, 3]), (8, 10))