Last year, many people have dipped their toes into functional programming. Unfortunately, one of the side-effects of learning functional programming is a great amount of people trying to explain monads. Many explanations I’ve seen were bad and only add to the existing confusion. This makes me quite upset sometimes.
So here’s my very short (and slightly simplified) explanation:
If you can define
flatMapfor a type, the type is often called a monad.
For example, you can define
Array. Array is a monad. You can define
flatMap for optionals.
Optional is a monad. You can also define
flatMap for other types, such as functions, tuples, reactive cocoa signals, the
Result type, and many more. Defining
flatMap for a type often is really useful, even if it’s not “officially” a monad. That’s really all there’s to it.
If you care for a longer explanation in Swift, then Alexandros’s articles are pretty good. If you prefer video, have a look at John Gallagher’s talk. Finally, if you like reading books, you can read my book Functional Programming in Swift or Learn You a Haskell.