Elixir:来自for循环的返回值
问题描述:
我要求Elixir中的for循环返回一个计算值。Elixir:来自for循环的返回值
这里是我的简单的例子:
a = 0
for i <- 1..10
do
a = a + 1
IO.inspect a
end
IO.inspect a
这里是输出:
warning: variable i is unused
Untitled 15:2
2
2
2
2
2
2
2
2
2
2
1
我知道,我是不用的,可以代替一个在这个例子中使用,但是这不是这个问题。问题是你如何获得for循环来返回变量a = 10?
答
你不能这样做,因为Elixir中的变量是不可变的。你的代码真的在每个迭代中在for
内部创建一个新的a
,并且根本不修改外部a
,所以外部的a
保持为1,而内部的总是2
。对于初始值+更新可枚举的每次迭代的值的这种模式,则可以使用Enum.reduce/3
:
# This code does exactly what your code would have done in a language with mutable variables.
# a is 0 initially
a = Enum.reduce 1..10, 0, fn i, a ->
new_a = a + 1
IO.inspect new_a
# we set a to new_a, which is a + 1 on every iteration
new_a
end
# a here is the final value of a
IO.inspect a
输出:
1
2
3
4
5
6
7
8
9
10
10