Skip to content

Instantly share code, notes, and snippets.

@michaelficarra
Forked from pselle/monads.js
Last active August 29, 2015 14:07

Revisions

  1. michaelficarra revised this gist Oct 15, 2014. 1 changed file with 26 additions and 9 deletions.
    35 changes: 26 additions & 9 deletions monads.js
    Original file line number Diff line number Diff line change
    @@ -1,13 +1,30 @@
    var _Container = function(val) { this.val = val }
    var Container = function(val) { return new _Container(val); }
    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);
    }
    var c = new Container(2);
    // functor
    c.map(function(x) { return x+2});
    // monad
    c.flatMap(function(x){ return x+2}).flatMap(function(x) {return x* -1 });
    };

    // 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)
  2. @pselle pselle created this gist Oct 15, 2014.
    13 changes: 13 additions & 0 deletions monads.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    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 = new Container(2);
    // functor
    c.map(function(x) { return x+2});
    // monad
    c.flatMap(function(x){ return x+2}).flatMap(function(x) {return x* -1 });