Skip to content

Instantly share code, notes, and snippets.

@michaelficarra
Forked from pselle/monads.js
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelficarra/cd66c547cbd0d4daa9e1 to your computer and use it in GitHub Desktop.
Save michaelficarra/cd66c547cbd0d4daa9e1 to your computer and use it in GitHub Desktop.
function Container(val) {
this.val = val
}
// Functor's `fmap` in Haskell
Container.prototype.map = function(f) {
return new Container(f(this.val));
};
// Monad's `>>=` (pronounced bind) in Haskell
Container.prototype.flatMap = function(f) {
return f(this.val);
};
// Monad's `return` in Haskell
Container.of = function(val) {
return new Container(val);
};
var c = Container.of(2);
c.map(function(x) {
return x+2;
}); // === Container.of(4)
c.flatMap(function(x){
return Container.of(x+2);
}).flatMap(function(x){
return Container.of(x * -1);
}); // === Container.of(-4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment