Skip to content

Instantly share code, notes, and snippets.

@andelf
Created November 25, 2013 06:34
Show Gist options
  • Select an option

  • Save andelf/7637199 to your computer and use it in GitHub Desktop.

Select an option

Save andelf/7637199 to your computer and use it in GitHub Desktop.
Monad in javascript.
function MONAD(modifier) {
var prototype = Object.create(null);
function unit(value) {
var monad = Object.create(prototype);
monad.bind = function (func, args) {
return func.apply(undefined,
[value].concat(Array.prototype.slice.apply(args || [])));
};
if (typeof modifier == 'function') {
monad = modifier(monad, value);
}
return monad;
};
unit.method = function (name, func) {
prototype[name] = func;
return unit;
};
unit.lift = function (name, func) {
prototype[name] = function (args) {
return unit(this.bind(func, args));
};
return unit;
};
return unit;
}
var identity = MONAD()
.lift('print', function(n) {console.log("Id", n);})
.lift('asNumber', function(n) { return Number(n); });
var m = identity("Hello World");
m.bind(console.log);
m.print();
var m2 = identity("250.100");
m2.asNumber().print();
console.log(m2)
var maybe = MONAD(funcion(monad, value) {
if (value == null) {
monad.bind = funcion () { return monad; };
}
return monad;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment