We’re back for our first episode of 2019. Hope everyone had a nice break, and we’re ready to start some new material.
The title of this episode is “the many faces of flatMap
”, and if you’ve been a following Point-Free for awhile you may know that we’ve done this style of episode twice before. First we did “The Many Faces of Map”, where we showed that map
is a very universal operation that goes far beyond the map
that Swift defines on sequences and optionals. It’s in fact the unique function with its signature that satisfies a simple property, and that tells us that map
isn’t something we invent but rather something we discover. It was there all along whether or not we knew it. This empowered us to define map
on many new types, which unlocks a lot of nice compositions.
A few months after that we did a 3-part series of episodes called “The Many Faces of Zip” (part 1, part 2, part 3), where we similarly showed that zip
can also be generalized far beyond the zip
that is defined on sequences in the Swift standard library. We could define zip
on optionals, result types, function types, and even asynchronous values. We also saw that zip
allows you to do map
-like operations, but just with functions that take more than one argument, which is simply not possible with map
alone. So zip
unlocked something new for us.
Today’s episode completes a trilogy of operations, and honestly it’s kind of shocking that Point-Free launched nearly a year ago and this is our first time talking about it. I think a lot of people would assume this topic is the bread and butter of functional programming, and although quite important, in our 41 previous episodes so far we have shown that you can still do a lot without it.
We are of course talking about flatMap
!
Swift ships with two flatMap
methods, one on sequences and one on optionals, but the idea of flatMap
is so much bigger than just that. It is a further generalization of the ideas of map
and zip
in that it can express things that are just not possible with map
and zip
alone. So today we begin to get comfortable with flatMap
and expand our understanding of what its true purpose is.
We try to make episodes stand on their own as much as possible, but flatMap
is so intimately related to map
and zip
that this just isn’t possible to do. We think you’ll get the most from this episode if you’ve seen our previous episodes on map
and zip
(part 1, part 2, part 3) because we are building off of those ideas quite a bit.