What the Heck Is a Monad
This is the first important part of a monad. You have to have a way to create one. In this case, the constructor,
Maybe.Something, fills that role. In other languages, this is known asunitor the inconveniently-named functionreturn. It’s a function that takes one parameter, and returns a monad that wraps that parameter.[…]
It’s important that the block returns an already-wrapped monad, so that we can chain these calls. This is a big part of why monads are useful.
[…]
Functional programmers took a great name like
ifSomethingand made it totally inscrutable by calling itflatMap. (In some of the literature, it’s also known asbind. In Haskell, aka peak inscrutability, it’s invoked with the operator>>=.)[…]
To build
map, we wrap the result of themapblock with the constructor and send that toflatMap:[…]
For something to be monad, in addition to implementing bind and unit, it has to follow some special rules.
Previously: Functor and Monad in Swift, Higher Order Functions in Swift 2.
Update (2015-10-07): Jeremy W. Sherman:
Re: monads, I point people at this article when they want to tackle the hilariously compact yet accurate “monoid in the category of endofunctors” definition. Unpacks the jargon, but does use Haskell syntax.