I find quite useful the lists:filtermap
in Erlang I wonder if could be helpful to expose this function also in the Enum module
Enum.filter_map/3
actually exists and has been deprecated.
iex(2)> Enum.filter_map([1,2,3,4], fn x -> rem(x, 2) == 0 end, fn x -> x * x end)
warning: Enum.filter_map/3 is deprecated. Use Enum.filter/2 + Enum.map/2 or for comprehensions instead
iex:2
[4, 16]
As the warning suggests for
does a great job at various ways of filtering – be it using patterns or using binary conditionals – as well as allowing you to map any matched values.
You can use Enum.flat_map
too, but for
is nicer.
1 Like
You can also use Enum.redcue(...) |> Enum.reverse()
.
iex(1)> for i <- 1..10, rem(i, 2) == 0, do: i * 2
[4, 8, 12, 16, 20]
iex(2)> Enum.reduce(1..10, [], fn i, acc ->
...(2)> if rem(i, 2) == 0, do: [i * 2 | acc], else: acc
...(2)> end) |> Enum.reverse()
[4, 8, 12, 16, 20]
iex(3)> Enum.filter_map(1..10, fn i -> rem(i, 2) == 0 end, fn i -> i * 2 end)
warning: Enum.filter_map/3 is deprecated. Use Enum.filter/2 + Enum.map/2 or for comprehensions instead
iex:3
[4, 8, 12, 16, 20]
In this case for
is nicer.