Created
February 27, 2019 14:32
-
-
Save devonestes/5d2611740b684232c2456cb18e0ce612 to your computer and use it in GitHub Desktop.
Filter map varieties in Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for num <- [1, 2, 3], num < 3, do: num * 2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[1, 2, 3] | |
|> Enum.filter(fn num -> num < 3 end) | |
|> Enum.map(fn num -> num * 2 end) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Enum.flat_map([1, 2, 3], fn num -> | |
if num < 3 do | |
[num * 2] | |
else | |
[] | |
end | |
end) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[1, 2, 3] | |
|> Enum.reduce([], fn num, acc -> | |
if num < 3 do | |
[num * 2 | acc] | |
else | |
acc | |
end | |
end) | |
|> Enum.reverse() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. I usually write
reduce
with simple condition like this