Elixir:从for循环返回值 [英] Elixir: Return value from for loop
问题描述
以下是我的简单示例:
a = 0
for i < - 1..10
do
a = a + 1
IO.inspect a
end
IO.inspect a
这是输出:
警告:变量i未使用
无标题15:2
2 $ b b 2 b b 2 b b 2 b b 2 b b 2 b b 2 b b 2 b b 2 b b 2 b $ b
我知道我没有使用,可以在这个例子中用来代替a,但那不是题。问题是你如何获得for循环返回变量a = 10?解决方案
你不能这样做,因为Elixir中的变量是不可变的。你的代码真正做的是在每一次迭代中在中为
创建一个新的 a
,并且不修改外部的 a
,所以外部的 a
保持为1,而内部的总是 2
。对于这种初始值模式+更新每个可枚举迭代的值,可以使用 Enum.reduce / 3
:
#这段代码正好完成了你的代码在具有可变变量的语言中所做的事情。
#a最初为0
a = Enum.reduce 1..10,0,fn i,a - >
new_a = a + 1
IO.inspect new_a
#我们将a设置为new_a,这是每次迭代时+1加
new_a
end
#a这里是
的最终值IO.inspect a
输出: p>
1
2
3
4
5
6
7
8
9
10
10
I have a requirement for a for loop in Elixir that returns a calculated value.
Here is my simple example:
a = 0
for i <- 1..10
do
a = a + 1
IO.inspect a
end
IO.inspect a
Here is the output:
warning: variable i is unused
Untitled 15:2
2
2
2
2
2
2
2
2
2
2
1
I know that i is unused and can be used in place of a in this example, but that's not the question. The question is how do you get the for loop to return the variable a = 10?
You cannot do it this way as variables in Elixir are immutable. What your code really does is create a new a
inside the for
on every iteration, and does not modify the outer a
at all, so the outer a
remains 1, while the inner one is always 2
. For this pattern of initial value + updating the value for each iteration of an enumerable, you can use 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
Output:
1
2
3
4
5
6
7
8
9
10
10
这篇关于Elixir:从for循环返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!