I am trying to understand elixir stream.
First I have a list that iterate through a range and multiple with 2.
iex(5)> stream = 1..3 |>
...(5)> Enum.map(&IO.inspect(&1)) |>
...(5)> Enum.map(&(&1 * 2)) |>
...(5)> Enum.map(&IO.inspect(&1)) |>
...(5)> Enum.reduce(4, &+/2)
1
2
3
2
4
6
16
Here everything is clear, every enum return a list for further processing the list. It iterates four times for each element in the list.
Lets build it with stream:
iex(4)> stream = 1..3 |>
...(4)> Stream.map(&IO.inspect(&1)) |>
...(4)> Stream.map(&(&1 * 2)) |>
...(4)> Stream.map(&IO.inspect(&1)) |>
...(4)> Enum.reduce(4, &+/2)
1
2
2
4
3
6
16
Here it iterates only at once for each number in the range not like the example above with enum. What I do not understand is, how the accumulator of Enum.reduce keep the value and make a recursive call by them self, when it iterates only once?
When I iterate an enum as follow:
iex(25)> f = fn(x, y) ->
...(25)> IO.puts(y)
...(25)> x + y
...(25)> end
#Function<12.54118792/2 in :erl_eval.expr/5>
iex(26)> iter = 1..5 |> Enum.reduce(4, f)
4
5
7
10
14
19
then I can imaging, how enum.reduce pass the accumulator to the next recursive call.
But how the stream pass the accumulator for the next recursion call, if the iteration by stream execute only once?