home
home copied to clipboard
Thinking loops in Elixir
Thinking loops in Elixir
Approaches for converting imperative loops into functional Elixir.
Hi, you can still use for
approach:
require Integer
all_numbers = [4, 2, 5, 9, 6, 1, 0]
even_numbers = for num <- all_numbers, Integer.is_even(num), do: num
IO.inspect(even_numbers)
Heh, quite right @bossek! for
is pretty flexible and I struggled to come up with a short example that for
couldn't manage.
there is a reduce option in for loop , which can be treated as 3rd option
acc = [] for x <- 1..40, reduce: acc do acc -> [ x | acc ] end
Updating the above example using 3 approach using loop reduce
all_numbers = [4, 2, 5, 9, 6, 1, 0] even_numbers = []
for num <- all_numbers, reduce: even_numbers do even_numbers -> if Integer.mod(num, 2) == 0 do even_numbers = [num | even_numbers] else even_numbers end end
Enum.flat_map/2: maps a function and flattens the final list. Useful if an invocation of the mapping function returns multiple elements.
I would add: multiple or zero elements.
You also can loop using Enum.filter/2 (or Enum.reject/2
with reversed logic)
Enum.filter(all_numbers, &rem(&1, 2) == 0)
But underneath, it's all reduce
or tail call recursion
.