Skip to content

Instantly share code, notes, and snippets.

@devonestes
Created February 27, 2019 14:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devonestes/5d2611740b684232c2456cb18e0ce612 to your computer and use it in GitHub Desktop.
Save devonestes/5d2611740b684232c2456cb18e0ce612 to your computer and use it in GitHub Desktop.
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