Elixir: Return value from for loop

前端 未结 1 1651
别跟我提以往
别跟我提以往 2020-12-22 00:51

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
           


        
1条回答
  •  礼貌的吻别
    2020-12-22 01:07

    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
    

    0 讨论(0)
提交回复
热议问题