iphaaw
iphaaw

Reputation: 7204

Elixir: Return value from for loop

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?

Upvotes: 1

Views: 1627

Answers (1)

Dogbert
Dogbert

Reputation: 222168

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

Upvotes: 8

Related Questions