Created
November 12, 2017 23:16
-
-
Save mvaldesdeleon/7c7853f489726758779414a9c21e7145 to your computer and use it in GitHub Desktop.
Reader monad
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
function Reader(x) { | |
this.x = x; | |
} | |
Reader.prototype.run = function(env) { | |
return this.x(env); | |
} | |
Reader.of = function(x) { | |
return new Reader(() => x); | |
} | |
Reader.prototype.map = function(fn) { | |
return new Reader(env => fn(this.run(env))); | |
} | |
Reader.prototype.join = function() { | |
return new Reader(env => this.run(env).run(env)); | |
} | |
Reader.prototype.chain = function(fn) { | |
return this.map(fn).join(); | |
} | |
Reader.ask = new Reader(env => env); | |
Reader.of(2) | |
.map(x => x * 2) | |
.chain(x => Reader.ask.map(env => env + x)) | |
.map(x => x * 3) | |
.chain(x => Reader.ask.map(env => x - env)) | |
.run(3); // 18 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment