Last active
August 29, 2015 14:07
-
-
Save pselle/fd156a219c56aab529f3 to your computer and use it in GitHub Desktop.
Functors and monads
This file contains hidden or 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
var _Container = function(val) { this.val = val } | |
var Container = function(val) { return new _Container(val); } | |
Container.prototype.map = function(f) { | |
return new Container(f(this.val)); | |
} | |
Container.prototype.flatMap = function(f) { | |
return f(this.val); | |
} | |
var c = Container(2); | |
// functor | |
c.map(function(x) { return x+2}); | |
// monad | |
c.flatMap(function(x){ return Container(x+2)}).flatMap(function(x) {return Container(x*-1)}); |
Updated! I evidently didn't have alerts for comments set up. Thanks, Brian!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looking great! Just two things:
new
keyword in front of Container (that's what the extra Container method is for)c.flatMap(function(x){ return Container(x+2) }).flatMap(function(x) {return Container(x* -1) });
Try it out with some https://github.com/folktale or https://github.com/fantasyland monads to see different behaviors via different "Containers", but remember they call
flatMap
chain
. Good stuff!