用for循环填充列表 [英] Fill a List with a for-loop

查看:139
本文介绍了用for循环填充列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能用这个简单的for循环填充列表?

  new_data = [] 
for data< - old_data do
new_data = List.insert_at(new_data,-1,data)
end

在这个操作之后,即使循环执行了N次,我的 new_data 列表仍然是空的。

Elixir变量真的是不可变的吗?因为在这个例子中不是一个循环,它是一个列表理解。 / p>

您可以将理解结果分配给:

  new_data = for data<  -  old_data do 
data
end



  new_data = List.insert_at(new_data,-1,data)



new_data 变量对理解的范围是本地的。您可以使用以前的 new_data 值,但是您将无法重新绑定外部范围。这就是为什么 new_data 在理解之后仍然是 [] 。范围规则在 http://elixir-lang.readthedocs.org /en/latest/technical/scoping.html


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.

解决方案

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

这篇关于用for循环填充列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆