Fill a List with a for-loop

烂漫一生 提交于 2019-12-09 03:05:50

问题


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

After this operation my new_data list is still empty, even though the loop is N times executed.


回答1:


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



来源:https://stackoverflow.com/questions/33830686/fill-a-list-with-a-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!