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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With