Wednesday, August 16, 2017

An Aside About flatMap and Monads

Matt Gallagher:

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. A map 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 any Sequence, produces a second Sequence kind that isn’t necessarily the same as the first and returns the concatenation as an Array. This function is only a monad if both the Sequence arguments are Array. All other usage of this function results in not-a-monad.

[…]

For the purpose of flatMap, it appears that Optional 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 that flatMap(x) needs to be read backwards. The function is really flatten(map(x)) – a map and then a flatten – which would be more correctly transcribed as mapFlatten.

Comments RSS · Twitter

Leave a Comment