Fill a List with a for-loop

前端 未结 1 1263
不知归路
不知归路 2020-12-19 03:05

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
相关标签:
1条回答
  • 2020-12-19 04:03

    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

    0 讨论(0)
提交回复
热议问题