A monad is an object that has:
- A transformation that takes a type and produces a new type. In C# we call such a transformation a "generic type". We have a generic type
M<T>, we have a typeint, and we produce a new typeM<int>.- A generic function unit which accepts a value of type
Tand produces a value of typeM<T>.- A generic function bind which accepts a value of type
M<T>and a function fromTtoM<U>, and produces anM<U>.
But what would this look like in a weakly, dynamically typed language like JavaScript?
First attempt:
// 1 is not possible because of the typing system?
function monadify(m) { // `m` is a function
if(typeof m !== 'function') {
throw new TypeError('m must be a function');
}
// Returns a function that will apply m to t.
// "Wraps the value t".
m.unit = function(t) { // 2
return function() {
return m(t);
};
};
// Returns a function that will apply `m` to `t` and then apply `fn` to the result.
// Binds `fn` to `m`.
m.bind = function(m, fn) {
return function(t) { // 3
return fn(m(t));
};
};
return m;
}