kirqe
kirqe

Reputation: 2470

Elixir Stream.unfold setting up new state

Here's an example of displaying a fibonacci sequence with elixir using Stream.unfold.

Stream.unfold({0,1}, fn {f1,f2} -> {f1, {f2, f1+f2}} end) |> Enum.take(15)

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

Why does it require to provide f1 in {f1, {f2, f1+f2}} and not just {f2, f1+f2}?

Because in the explanation of the code above author says:

The new state moves one down the sequence, so an initial state of {f1,f2} becomes a new state of {f2,f1+f2}.

Upvotes: 1

Views: 542

Answers (1)

Dogbert
Dogbert

Reputation: 222090

That's because f1 is the value that should be yielded by the stream to the consumer while {f2, f1 + f2} is the state the unfold operation needs for the next iteration. Generating Fibonacci numbers requires 2 values in the state to work.

If you were generating natural numbers instead, you could do with a tuple of 2 integers:

iex(1)> Stream.unfold(0, fn x -> {x, x + 1} end) |> Enum.take(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 4

Related Questions