Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accumulate a list in an `Enum.each` loop

Tags:

list

elixir

I have a method that receives a list of strings, and generates a list of list of words.

def some(words) do
  result = []
  Enum.each(words, fn word ->
    result = result ++ [["something", word], ["something else", word]]
  end
  result
end

This method doesn't work as expected, since it always returns an empty list.

This, I think, it's because of variable shadowing.

What should this code be rewritten in order to work?

like image 226
ProGM Avatar asked Sep 12 '25 04:09

ProGM


1 Answers

Variables in elixir are immutable, so you cannot change a list from within a loop. Sometimes it may "look like" variables are mutable because you can re-assign them, but this will only be visible within the same scope.

To get the desired result, you can use Enum.flat_map/2 as follows.

def some(words) do
  Enum.flat_map words, fn word ->
    [["something", word], ["something else", word]]
  end
end
like image 77
Patrick Oscity Avatar answered Sep 13 '25 18:09

Patrick Oscity