home icon indicating copy to clipboard operation
home copied to clipboard

Thinking loops in Elixir

Open utterances-bot opened this issue 1 year ago • 6 comments

Thinking loops in Elixir

Approaches for converting imperative loops into functional Elixir.

https://alexpearce.me/2023/06/elixir-loops/

utterances-bot avatar Jun 15 '23 09:06 utterances-bot

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)

bossek avatar Jun 15 '23 09:06 bossek

Heh, quite right @bossek! for is pretty flexible and I struggled to come up with a short example that for couldn't manage.

alexpearce avatar Jun 15 '23 09:06 alexpearce

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

RuthraiahThulasi avatar Jun 17 '23 08:06 RuthraiahThulasi

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

RuthraiahThulasi avatar Jun 21 '23 10:06 RuthraiahThulasi

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.

mxgrn avatar Jun 22 '23 07:06 mxgrn

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.

alimnastaev avatar Sep 19 '23 12:09 alimnastaev