Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Filter map varieties in Elixir
for num <- [1, 2, 3], num < 3, do: num * 2
[1, 2, 3]
|> Enum.filter(fn num -> num < 3 end)
|> Enum.map(fn num -> num * 2 end)
Enum.flat_map([1, 2, 3], fn num ->
if num < 3 do
[num * 2]
else
[]
end
end)
[1, 2, 3]
|> Enum.reduce([], fn num, acc ->
if num < 3 do
[num * 2 | acc]
else
acc
end
end)
|> Enum.reverse()
@50kudos
Copy link

50kudos commented Feb 28, 2019

Nice. I usually write reduce with simple condition like this

[1, 2, 3]
|> Enum.reduce([], fn 
  num, acc when num < 3 -> [num * 2 | acc]
  _num, acc -> acc
end)
|> Enum.reverse()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment