Skip to content

Instantly share code, notes, and snippets.

@pselle
Last active August 29, 2015 14:07
Show Gist options
  • Save pselle/fd156a219c56aab529f3 to your computer and use it in GitHub Desktop.
Save pselle/fd156a219c56aab529f3 to your computer and use it in GitHub Desktop.
Functors and monads
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)});
@DrBoolean
Copy link

Looking great! Just two things:

  1. No need for new keyword in front of Container (that's what the extra Container method is for)
  2. flatMap expects a Container returned. That's the magic behind monads:
    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!

@pselle
Copy link
Author

pselle commented Oct 15, 2014

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