|
|
|
|
|
by jodersky
1434 days ago
|
|
I usually tell people that monads are an abstraction which encourage writing code with less branches. Consider the following code where you would like to multiply a number by two, but this number is potentially undefined: var x = ... // a number or null
if (x == null) return null
else return x * 2
Now, imagine if x were a list containing zero or one numbers (if the number is undefined, the list is empty). In this case, you could refactor the code as follows: var xs = ... // a list of zero or one numbers
return xs.map(x => x * 2)
The advantage of the second snippet is that there are no branches, thus making it easier to reason about the code.Thus, in order to understand 80% of their utility in 20% time, I can recommend that you think of a monad as a wrapper around a value which allows you to treat special cases uniformly. In this case, a list of one or zero items. Of course there is more to it, but I this is usually enough to get people to stop worrying and interested in exploring more. |
|