Elixir: Return value from for loop

隐身守侯 提交于 2019-12-29 09:21:55

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/39698504/elixir-return-value-from-for-loop

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