Open Gozala opened 11 years ago
/Cc @luciferous
The rule is your not allowed to talk about category theory when explaining monads!
Or you have to teach everyone category theory.
Let's look at something simple like function application. Consider the following definition of functions f
and g
:
// f: x -> y
var f = function(x) { return x + 1 }
// g: x -> y
var g = function(x) { return x * 3 }
Remember that every monad has two basic operators: then
(composition/concatenation) and unit
(think of this as instantiation, or creating a new object). There is a monad which captures the pattern of function application called the Identity
monad.
// then: Identity a -> (a -> Identity b) -> Identity b
var then = function(ma) {
return function(q) { // q: a -> Identity b
return q(ma);
}
}
// unit: a -> Identity a
var unit = function(x) { return x }
Then we can compose Identity
s together:
// x: Identity x
var x = unit(1);
then(x, f) // => 2
then(x, g) // => 3
then(then(x, f), g) // => 6
If unit
were to box its value instead of returning it without modification, you could imagine something like the following:
x.then(f).then(g) // => 6
I do believe I have an understanding of state monads & would love a session about other flavors.