Why can\'t I fill a list with this simple for-loop?
new_data = []
for data <- old_data do
new_data = List.insert_at(new_data, -1, data)
end
In Elixir, you can't mutate the value your variable is referencing as explained in Are Elixir variables really immutable?. For in this instance is not a "loop" it is a list comprehension.
You can assign to the result of a comprehension with:
new_data = for data <- old_data do
data
end
In your line:
new_data = List.insert_at(new_data, -1, data)
The new_data
variable is local to the scope of the comprehension. You can use your previous new_data
value, but you won't be able to rebind for the outside scope. Which is why new_data
is still []
after your comprehension. The scoping rules are explained in http://elixir-lang.readthedocs.org/en/latest/technical/scoping.html