Skip to content

Instantly share code, notes, and snippets.

@mvaldesdeleon
Created November 12, 2017 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvaldesdeleon/7c7853f489726758779414a9c21e7145 to your computer and use it in GitHub Desktop.
Save mvaldesdeleon/7c7853f489726758779414a9c21e7145 to your computer and use it in GitHub Desktop.
Reader monad
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