Elixir:从for循环返回值

iph*_*aaw 1 for-loop elixir

我要求Elixir中的for循环返回一个计算值.

这是我的简单示例:

a = 0
for i <- 1..10
do
    a = a + 1
    IO.inspect a
end

IO.inspect a
Run Code Online (Sandbox Code Playgroud)

这是输出:

warning: variable i is unused
  Untitled 15:2

2
2
2 
2
2
2
2 
2
2
2
1
Run Code Online (Sandbox Code Playgroud)

我知道我没有使用过,可以用来代替本例中的a,但这不是问题.问题是如何让for循环返回变量a = 10?

Dog*_*ert 8

你不能这样做,因为Elixir中的变量是不可变的.你的代码真正做的是在每次迭代中创建一个新的a内部for,并且根本不修改外部a,所以外部a保持为1,而内部保持为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
Run Code Online (Sandbox Code Playgroud)

输出:

1
2
3
4
5
6
7
8
9
10
10
Run Code Online (Sandbox Code Playgroud)