I have been looking into FP languages (off and on) for some time and have played with Scala, Haskell, F#, and some others. I like what I see and understand some of the fundamental concepts of FP (with absolutely no background in Category Theory - so don't talk Math, please).
So, given a type M[A]
we have map
which takes a function A=>B
and returns a M[B]
. But we also have flatMap
which takes a function A=>M[B]
and returns a M[B]
. We also have flatten
which takes a M[M[A]]
and returns a M[A]
.
In addition, many of the sources I have read describe flatMap
as map
followed by flatten
.
So, given that flatMap
seems to be equivalent to flatten compose map
, what is its purpose? Please don't say it is to support 'for comprehensions' as this question really isn't Scala-specific. And I am less concerned with the syntactic sugar than I am in the concept behind it. The same question arises with Haskell's bind operator (>>=
). I believe they both are related to some Category Theory concept but I don't speak that language.
I have watched Brian Beckman's great video Don't Fear the Monad more than once and I think I see that flatMap
is the monadic composition operator but I have never really seen it used the way he describes this operator. Does it perform this function? If so, how do I map that concept to flatMap
?
BTW, I had a long writeup on this question with lots of listings showing experiments I ran trying to get to the bottom of the meaning of flatMap
and then ran into this question which answered some of my questions. Sometimes I hate Scala implicits. They can really muddy the waters. :)