1

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 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.