Skip to content

Instantly share code, notes, and snippets.

@masaeedu
Last active March 22, 2018 18:50
Show Gist options
  • Save masaeedu/4ac20c39233f264c3e3bff4ed437b103 to your computer and use it in GitHub Desktop.
Save masaeedu/4ac20c39233f264c3e3bff4ed437b103 to your computer and use it in GitHub Desktop.
The Reader monad
const { match } = require("natch");
const compose = f => g => x => f(g(x));
const kleisli = bind => fk => gk => compose(bind(fk))(gk);
// The reader module
const Reader = (() => {
// Constructors
const Pure = v => ({ t: "pure", v });
const Get = v => ({ t: "get", v });
// Misc
const ask = Get(Pure);
const addGet = a => bind(b => pure(a + b))(ask);
const runConst = x =>
match(
m => m.t,
["pure", ({ v }) => v],
["get", ({ v }) => runConst(x)(v(x))]
);
// Monad
const pure = Pure;
const bind = f =>
match(
m => m.t,
["pure", ({ v }) => f(v)],
["get", ({ v }) => Get(kleisli_(f)(v))]
);
const kleisli_ = kleisli(bind);
return { Pure, Get, ask, addGet, runConst, pure, bind };
})();
const { pure, bind, runConst, addGet } = Reader;
const question = addGet(5);
console.log(runConst(15)(question));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment