Member-only story

Stream.unfold/2

Dunya Kirkali
3 min readMay 17, 2022

Photo by Thomas Renaud on Unsplash

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 returns nil.

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…

Dunya Kirkali
Dunya Kirkali

Written by Dunya Kirkali

I'm an engineering manager passionate about empowering engineers to deliver exceptional work through collaboration and innovation.

No responses yet

Write a response