javascript monad structure.
interface.
interface M<T> {
// return
function unit<T>(value: T): M<T> {
}
// >>=
function bind<T, U>(instance: M<T>, transform: (value: T) => M<U>): M<U> {
}
}
- bind(unit(x), f) == f(x)
- bind(m, unit) == m
- bind(bind(m, f), g) == bind(m, x => bind(f(x), g))
new Identity(5).bind(x =>
new Identity(6).bind(x2 =>
new Identity(x + x2)
)
);
// => Identity(11)
new Just(5).bind(x =>
new Just(6).bind(x2 =>
new Just(x + x2)
)
);
// => Just(11)
new Just(5).bind(x =>
Nothing.bind(x2 =>
new Just(x + x2)
)
);
// => Nothing
do syntax
doM(function*() {
let v1 = yield new Just(5);
let v2 = yield new Just(6);
return new Just(v1 + v2);
}());
// => Just(11)
let p1 = doM(function*() {
let v1 = yield Promise.resolve(5);
let v2 = yield Promise.resolve(6);
return v1 + v2;
}());
p1.bind(v => console.log(v * v)); // 121
let p2 = doM(function*() {
let v1 = yield Promise.resolve(5);
let v2 = yield Promise.reject(new Error('Failure'));
return v1 + v2;
}());
p2.bind(v => console.log(v * v)); // empty
p2.catch(e => console.log(e.message)); // 'Failure'
Install
$ npm i -D data.monad
Use
var Monad = require('data.monad');