4 ms·
Since everyone is just writing their own explanation of monads, here is mine: Monads are a pattern for function chaining. It can be compared with fluent interf
by goto11 4y ago
Since everyone is just writing their own explanation of monads, here is mine:
Monads are a pattern for function chaining. It can be compared with fluent interfaces in OOP, which is also a pattern for chaining operations. A fluent interface does not imply any particular semantics - the semantics of a fluent chain will depend on the specific object it is used on. Same with monads, where each type which support the monad pattern provide its own unique semantic for how the operations are performed.
The name "monad" is misleading since it is a noun. Perhaps "Chainable" would be a better name?
The pattern can be used in any language which support higher-order functions, but without any syntax sugar support it tend to be rather verbose compared to say fluent interfaces. But with built-in syntax sugar support like in Haskell, monads becomes viable for many purposes.
Since JavaScript is the lingua franca of today, here is an example of a method chain in JavaScript:
[1,2,3].map(a => a + 1).filter(b => b != 3)
The same result using the monad pattern:
[1,2,3].flatMap(a => [a + 1]).flatMap(b => b != 3 ? [b] : [])
The strength of the monad pattern is that it is more composable. For example the same result can be achieved by nesting rather then chaining:
[1,2,3].flatMap(a => [a + 1].flatMap(b => b != 3 ? [b] : []))
Although in both cases it is clearly more verbose than the first non-monad method chain. But with some syntactic sugar with hide the repeated flatMap boilerplate, it can be made pretty concise.
- avgcorrection 4y ago> The name "monad" is misleading since it is a noun. Perhaps "Chainable" would be a better name? Other type classes can be chained. Like Applicative. Applicative is a chain where you cannot inspect the per-step state or whatever. But you can with Monad.