Monads explained simply
In short: A monad is a pattern for chaining computations that carry “extra behaviour” (no result, an error, a list, a side effect) cleanly one after another.
In more detail: It wraps a value in a container and offers an operation (bind, flatMap) that applies a function to the contents while handling the extra behaviour itself.
In Depth
- Option/Maybe: A value or “nothing”.
flatMapruns the next function only if a value is there. This removes nested null checks. - Result/Either: Success or error. The first error aborts the chain.
- List:
flatMapapplies a function to every element and flattens the results. - Promise/Future: A value that arrives later.
thencorresponds tobind. - Laws: Left identity, right identity and associativity make sure chains can be rearranged predictably.
- Mnemonic: A monad is an assembly line where each step already receives its input “unpacked”.
See also: Currying