The opposite of `fold`

If you write Elm, you may have worked with fold functions like List.foldl.

Yesterday I chatted with Joël Quenneville and learned about unfold, a kind of inverse process, and how it can be useful.

Here’s my summary:

Where fold takes:

  • A reducing function
  • An initial data type (e.g. Tree, List)
  • A list

And returns:

  • A new data type with all the list values reduced into it.

foldl : (a -> b -> b) -> b -> List a -> b

unfold does the opposite.

It takes:

  • A function for generating new values
  • An initial data type (e.g. Tree, List)

And returns:

  • A list of values

unfold : (a -> Maybe (b, a)) -> a -> List b

This can be used for generating a list of values from a data source.

Here’s an implementation of unfold, and a sample program that generates a range of integers:

For you FP jargon-heads out there, I learned an unfold is called an “anamorphism”.

I won’t be saying that too much, but do what you will with that knowledge:

Thanks to Joël Quenneville for the clear explanations, as ever!

Curious to learn more?

Watch Joël’s talk: “Inverting a Binary Tree with 1 Line of Elm” at the Elm Online Meetup:

This post was originally a Twitter thread as part of Ship 30 for 30.