Skip to content

Instantly share code, notes, and snippets.

@iahu
Created September 26, 2014 03:00
Show Gist options
  • Save iahu/014ea1c2145bf836cc4c to your computer and use it in GitHub Desktop.
Save iahu/014ea1c2145bf836cc4c to your computer and use it in GitHub Desktop.
a Maybe Monad
function Maybe() {
Object.freeze(this);
}
function Just (x) {
this.toString = function () { return "Just " + x.toString(); };
this.just = x;
Object.freeze(this);
}
Just.prototype = new Maybe();
Just.prototype.constructor = Just;
function Nothing () {
this.toString = function () { return "Nothing"; };
Object.freeze(this);
}
Nothing.prototype = new Maybe();
Nothing.prototype.constructor = Nothing;
Maybe.unit = function (x) {
return new Just(x);
};
Maybe.bind = function (f) {
return function (a) {
if ( a instanceof Just ) {
return f( a.just );
} else if (a instanceof Nothing) {
return new Nothing();
} else {
throw Error("argument is not a Maybe instance.");
}
};
};
Maybe.lift = function (f) {
return function (x) {
try {
return new Just( f(x) );
} catch(e) {
return new Nothing();
}
};
};
Maybe.do = function (m) {
var fns = Array.prototype.slice.call(arguments, 1);
fns.forEach(function(fn) {
m = Maybe.bind( fn )(m);
});
return m;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment