-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Description
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.