Skip to content

Instantly share code, notes, and snippets.

@nem035
Created October 4, 2016 18:15
Show Gist options
  • Save nem035/3904c3e03988794dd2f2338056cd31ae to your computer and use it in GitHub Desktop.
Save nem035/3904c3e03988794dd2f2338056cd31ae to your computer and use it in GitHub Desktop.
function MONAD(modifier) {
const prototype = Object.create(null);
function unit(value) {
const monad = Object.create(prototype);
monad.bind = function(f, ...args) {
return f(value, ...args);
};
if (typeof modifier === 'function') {
modifier(monad, value);
}
return monad;
};
unit.lift = function (name, func) {
prototype[name] = function (...args) {
return unit(this.bind(func, args));
};
return unit;
}
return unit;
}
var ajax = MONAD().lift('alert', alert);
var monad = ajax('Hello world.');
monad.alert();
const maybe = MONAD(function (monad, value) {
if (value === null || value === undefined) {
monad.is_null = true;
monad.bind = function() {
return monad;
}
}
});
var monad = maybe(null);
monad.bind(alert);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment