You can try this code out in your browser on tonicdev
Have you ever chained a bunch of functions together?
Maybe in jQuery?
$('div').css('color', 'red') .slideUp(2000) .slideDown(2000)
or with promises or node streams?
It’s a powerful, expressive, & concise way to program.
It’s easy to do when you have a set of functions that accept an object and return an object of the same type.
These four functions all work with jQuery DOM elements:
- .css(‘color’, ‘red’)
These four functions all work with Numbers:
Check out this chain:
const isEven = x => x % 2 == false .map(add(1)) .map(multiply(4)) .filter(isEven) .map(power(2)) 
Here’s a few properties that arrays have that make them good for chaining:
- there’s a way to put something into an array ()
- there’s a way to get something out of an array ()
- in fact,
i === [i]
- in fact,
- there are functions that take arrays and return other arrays, like
.map(fn), which does three things:
- unwrap the array
- apply a apply regular (not array-specific) function to the value inside
- wrap the result back up into an array
When a data structure has those properties ^^, it is a monad.
jQuery DOM elements are not a monad because there isn’t really a way to put something in and take it back out.
The Array Monad has some special features that distinguish it from other monads, namely:
- it’s good for holding a bunch of values in a particular order
- it’s good for finding a value if you know its index
Monads (“chainable containers”) are such a generic idea that people have conceived of monads suited to all sorts of particular tasks, such as:
the Maybe Monad and the Either Monad, which make it easy to chain functions together that might fail
the Task/Future monad, which makes it easy to chain functions together that perform long-running or asynchronous tasks
the IO monad, which makes it easy to control exactly when and how a chain of functions interacts with the outside world
Functions within a program might all return different monads. This program has a long-running function that returns a Task monad, a randomly-failing function that returns a Maybe monad, and a logging function that returns an IO monad.
However, functions in a chain must all accept and return the same type of monad. The chain in this program is based around the Task monad. We’ll use functions to convert the Maybe and IO monads into Task monads.
Let’s get started.