Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix fcollect to respect object identity instead of ==; document order #25

Merged
merged 5 commits into from
Oct 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "Functors"
uuid = "d9f16b24-f501-4c13-a1f2-28368ffc5196"
authors = ["Mike J Innes <[email protected]>"]
version = "0.2.5"
version = "0.2.6"

[compat]
julia = "1"
Expand Down
21 changes: 13 additions & 8 deletions src/functor.jl
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ fmapstructure(f, x; kwargs...) = fmap(f, x; walk = (f, x) -> map(f, children(x))
fcollect(x; exclude = v -> false)

Traverse `x` by recursing each child of `x` as defined by [`functor`](@ref)
and collecting the results into a flat array.
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`.
Expand Down Expand Up @@ -192,11 +193,15 @@ julia> fcollect(m, exclude = v -> Functors.isleaf(v))
Bar([1, 2, 3])
```
"""
function fcollect(x; cache = [], exclude = v -> false)
x in cache && return cache
if !exclude(x)
push!(cache, x)
foreach(y -> fcollect(y; cache = cache, exclude = exclude), children(x))
end
return cache
function fcollect(x; output = [], cache = Base.IdSet(), exclude = v -> false)
# note: we don't have an `OrderedIdSet`, so we use an `IdSet` for the cache
# (to ensure we get exactly 1 copy of each distinct array), and a usual `Vector`
# for the results, to preserve traversal order (important downstream!).
x in cache && return output
ericphanson marked this conversation as resolved.
Show resolved Hide resolved
if !exclude(x)
push!(cache, x)
push!(output, x)
foreach(y -> fcollect(y; cache=cache, output=output, exclude=exclude), children(x))
end
return output
end
5 changes: 5 additions & 0 deletions test/basics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ end
m3 = Foo(m2, m0)
m4 = Bar(m3)
@test all(fcollect(m4) .=== [m4, m3, m2, m1, m0])

m1 = [1, 2, 3]
m2 = [1, 2, 3]
m3 = Foo(m1, m2)
@test all(fcollect(m3) .=== [m3, m1, m2])
end

struct FFoo
Expand Down