An Aside About flatMap and Monads
The way Haskell deals with these problems is that you can interact with these services freely but you never get access to the result. Instead, you get a container (an IO monad) that you can never unwrap. If you never unwrap a container containing side effects, then you remain free from the impact of those side effects – your actions remain the same regardless of whether the container holds a fully parsed data structure or a file-not-found error.
How can you handle a container that you can never unwrap? With transformations like
map
, of course. Amap
transformation in Haskell is effectively your code telling the runtime system: please look inside the container for me and should the container contain a value, then apply this function.[…]
A true monad transformation requires that all the container types involved be the same kind - a restriction which is not enforced, here. This [Swift]
flatMap
function operates on anySequence
, produces a secondSequence
kind that isn’t necessarily the same as the first and returns the concatenation as anArray
. This function is only a monad if both theSequence
arguments areArray
. All other usage of this function results in not-a-monad.[…]
For the purpose of
flatMap
, it appears thatOptional
is treated as a collection and is permitted to be mixed and matched like any other collection. This bothers some people but personally, I think it makes sense. I’ve always been more concerned by the naming problem caused by the fact thatflatMap(x)
needs to be read backwards. The function is reallyflatten(map(x))
– a map and then a flatten – which would be more correctly transcribed asmapFlatten
.