Una monade è un oggetto che ha :
- 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
T
and produces a value of typeM<T>
.- A generic function bind which accepts a value of type
M<T>
and a function fromT
toM<U>
, and produces anM<U>
.
Ma come apparirebbe in un linguaggio tipicamente debolmente digitato come JavaScript?
Primo tentativo:
// 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;
}