Member-only story
Stream.unfold/2
The Stream module in Elixir is full of amazingness! One of those hidden gems is the Stream.unfold/2 function.
Today I would like to take the time and show you a couple of example usages of the unfold function to help make you understand how powerful it can be.
But first, let’s start by reading the documentation for Stream.unfold/2:
Emits a sequence of values for the given accumulator.
Successive values are generated by calling
next_fun
with the previous accumulator and it must return a tuple with the current value and next accumulator. The enumeration finishes if it returnsnil
.
The unfold function is one of the many generators provided to us in the Stream module as we can see that it emits a sequence of values. Very similar to the Stream.iterate/2 function.
A couple of differences however are:
- The fact that Stream.unfold/2 could eventually end a stream by returning nil
- You have more control over the accumulator that you pass over to the next iteration
And these differences make Stream.unfold/2 very powerful.
Iterator
The first example we’ll be looking at is how you can use Stream.unfold/2 as if it were Stream.iterate/2. If we would like to create a stream…