-
-
Save michaelficarra/cd66c547cbd0d4daa9e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Yep! https://gist.github.com/pselle/fd156a219c56aab529f3#comment-1318385