Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thinking loops in Elixir #75

Open
utterances-bot opened this issue Jun 15, 2023 · 6 comments
Open

Thinking loops in Elixir #75

utterances-bot opened this issue Jun 15, 2023 · 6 comments

Comments

@utterances-bot
Copy link

Thinking loops in Elixir

Approaches for converting imperative loops into functional Elixir.

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

Copy link

bossek commented Jun 15, 2023

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)

Copy link
Owner

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

Copy link

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

Copy link

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

Copy link

mxgrn commented Jun 22, 2023

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.

Copy link

alimnastaev commented Sep 19, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants