Skip to content

Commit

Permalink
Implements flatmap and iteration methods for Some and Nothing
Browse files Browse the repository at this point in the history
flatmap is the composition of map and flatten. It is important for functional programming patterns.

Some tasks that can be easily attained with list-comprehensions, including the composition of filter and mapping, or flattening a list of computed lists, can only be attained with do-syntax style if a flatmap functor is available. (Or appending a `|> flatten`, etc.)

Filtering can be implemented by outputing empty lists or singleton lists for the values to be removed or kept. A more proper approach would be the optional monad, though, usually implemented in Julia as a union of Some and Nothing.

This patch therefore also implements iteration methods for Some and Nothing, to enable the filtermap pattern with flatmap.
  • Loading branch information
nlw0 committed Apr 2, 2022
1 parent 0c57e66 commit 75c7bc9
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
7 changes: 2 additions & 5 deletions base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1206,14 +1206,11 @@ julia> flatmap(1:3) do j
(3, 2)
```
"""
# flatmap(f, c...) = flatten(map(f, c...))
flatmap = flatten map
# flatmap = flatten ∘ map
flatmap(f, c...) = flatten(map(f, c...))

# Allows filtering through `flatten` (or `flatmap`) by removing `nothing` values
iterate(_::Nothing) = nothing
iterate(x::Some{T}) where T = (something(x), nothing)
iterate(x::Some{T}, state::Nothing) where T = nothing
length(x::Some{T}) where T = 1

"""
partition(collection, n)
Expand Down
5 changes: 5 additions & 0 deletions base/some.jl
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,8 @@ macro something(args...)
something = GlobalRef(Base, :something)
return :($something($expr))
end

# Allows filtering through `flatten` (or `flatmap`) by retaining `Some` values
iterate(x::Some{T}) where T = (something(x), nothing)
iterate(x::Some{T}, state::Nothing) where T = nothing
length(x::Some{T}) where T = 1

0 comments on commit 75c7bc9

Please sign in to comment.