Joël Quenneville Profile picture
I craft software, mostly on the web. I love best practices, patterns, and functional programming.

Sep 6, 2022, 8 tweets

#Ruby's Enumerator.produce is a really cool method! It can generate an infinite series where each item is used to calculate the next.

✨ For example the series of even numbers:

Interestingly though, Enumerator.produce cannot be used to generate more complex series like squares because the input from each step is the output of the previous step

To generate squares, we need to decouple the input to our block from the return value. *Ideally* we could call our block like:

The functional programming world has a function called "unfold" that looks a lot like Enumerator.produce but with the following additions:

1. it can halt by returning nil
2. it uses a separate "seed" value as the input for each step rather than using the previous output

We can make our own unfold using Enumerator's constructor

With this method in hand, we can finally get our series of squares!

"unfold" is useful because it allows you to generate complex enumerations without needing to go full manual with the constructor.

It is powerful enough that you could even implement Enumerator.produce in terms of it! 😆

There is a lot of theory behind this kind of method. unfold and other related functions can be used to abstract away all the manual parts of looping.

If you want to do a *deep* dive, google "anamorphism" 🤓

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling