It’s time to ask “what’s the point?” and “what’s the point is three-fold. We are going to discuss three important aspects in having a deep understanding of flatMap
:
We are going to show that
map
,zip
andflatMap
form a kind of functional, domain-specific language for modeling pipelines of data. And seeing a usage of one of these operators we will already have a strong intuition for what that line of code could possibly be doing, without even knowing too much about the types involved.Once we see that we will have convinced ourselves that these operations have a very well-defined signature, and we shouldn’t be smudging it in order to suite our needs. Sometimes we’ll have a function signature that looks kinda like
flatMap
but it isn’t quite and we’ll want to call itflatMap
for ease. We want to make the case that everything we have learned shows us that is the wrong decision, and our APIs will be better off if we do not do that.And then finally, we begin to ask ourselves very complex questions about how all of these operators interact with each other. These are problems that we feel would have been intractable if we didn’t already have a solid foundation of understand the purpose of
map
,zip
andflatMap
, and we would have had a very difficult time coming up with any concise, clear answers.
The meanings behind the signatures of map
, zip
and flatMap
are very concise, and describe very well what their purpose is. This intuition is so strong that we can be presented with a whole new type that we are not familiar with and be told it has a map
operation and instantly know that means we can unwrap the type, apply a transformation and wrap it back up. Or be told that it has a zip
operation and so that we can take a bunch of values, independently run their computations, and obtain a new, single value from the type. Or be told that it has a flatMap
operation, and now you know you can can sequence these values together so that one follows another.
So, let’s look at what power this gives us by looking at some interesting uses of these operators on some concrete types: