4 ms·
Sure, here's the practical description : A monad is a data structure that holds one value, but that value may be of one of several types. It implements a `map`
by duped 5y ago
Sure, here's the practical description :
A monad is a data structure that holds one value, but that value may be of one of several types. It implements a `map` function which allows conversion to the same monad with different set of types, eg there is some function `map` defined as :
fn map ( f : Tn -> Un, Monad<T1, T2, ..., Tn, ... TN>) -> Monad<T1, T2, ..., Um, ..., TN)
for each type the value may be in the Monad.
Two commonly used examples are the Optional and Result monads. An Optional is either a value of type T, or the empty type None. A Result is a value of type T or some error E.
The utility of monads is their ability to chain operations. With optionals, you can map the results of functions that may or may not return results without handling the None case explicitly. With Result types you may chain operations that return errors, and handle both the successes and cases where you need to convert errors.
Monads can be expressed in many languages, but they make the most sense in languages with algebraic data types (to express a value is one of a set of possible types, aka union/sum types) and first-class functions (where functions can be passed as an argument, or else implementing `map` may be difficult).
The mathematical parlance is really harmful to their adoption because as an abstraction, monads are stupidly easy to use.
- kaba0 5y agoI think you describe only a Functor, not a Monad. A Monad also has to have either a `bind` or a `flatmap` function, besides the `(f)map`. Basically the point of a monad is to depend on the output of another monad data type of its kind — e.g. it can take an IO String and use the encapsulated String value to produce another IO X. This would be IO (IO X) without the flatmap, or the bind function that can remove this double encapsulation.
- duped 5y agoThis is what I was attempting to describe. `bind` is implicit, it's the constructor of a monad. In my definition `map` is serving the purpose of your flatmap, I didn't mean to imply double encapsulation.