Skip to content

Implement a filtermap (or flatmap) function to make do-syntax as powerful as list comprehensions #44294

@nlw0

Description

@nlw0

Suggestion: Julia offers map and filter, which is great, and using the list comprehension we can also perform a filtermap, eg

julia> sample = randn(5)
5-element Vector{Float64}:
 -0.06735837502279898
  0.09030518381226459
 -0.26615854113225973
 -1.4282255796719185
  0.5329984098262069

julia> [x^2+10 for x in sample if x < 0]
3-element Vector{Float64}:
 10.004537150685712
 10.070840369017652
 12.039828306429188

A filtermap function would allow us to perform the same operation, using do-syntax for writing the function. The problem is how to define an interface, since you basically would need to define two functions, one for the filter and another for the map. The suggestion is that this could be accomplished by using Some and Nothing, and then we flatten the output to produce the final filtered result.

julia> function filtermap(f, x)
         mm = map(f,x)
         [something(x) for x in mm if !isnothing(x)]
end
filtermap (generic function with 1 method)

julia> filtermap(sample) do x
         if x<0 x^2+10 else nothing end
       end
3-element Vector{Float64}:
 10.004537150685712
 10.070840369017652
 12.039828306429188

I couldn't find the suggestion anywhere, so here it goes. Hopefully it's not too futile. I only think it's a good idea because right now this is a unique feature of list comprehension, and I feel it would be nice if do-syntax was more on par with it straight out of the box.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions