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