Skip to content

Instantly share code, notes, and snippets.

@dankreiger
Last active December 9, 2022 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dankreiger/b43560aa4f92c52c0f1eeb4ea41cdd6e to your computer and use it in GitHub Desktop.
Save dankreiger/b43560aa4f92c52c0f1eeb4ea41cdd6e to your computer and use it in GitHub Desktop.
reader monad
type T_UnaryFunction<I, O> = (x: I) => O;
type T_Fn<I, O> = {
run: T_UnaryFunction<I, O>;
chain: <P>(f: T_UnaryFunction<O, T_Fn<I, P>>) => T_Fn<I, P>;
map: <A>(f: T_UnaryFunction<O, A>) => T_Fn<I, A>;
};
const Fn = <I, O = I>(run: T_UnaryFunction<I, O>): T_Fn<I, O> => ({
run,
chain: <P>(f: T_UnaryFunction<O, T_Fn<I, P>>) => Fn((x) => f(run(x)).run(x)),
map: <P>(f: T_UnaryFunction<O, P>) => Fn((x: I) => f(run(x))),
});
Fn.ask = <T>() => Fn((x:T) => x);
Fn.of = <T>(x: T) => Fn((_) => x);
const res = Fn<string>(x => x.toUpperCase())
.chain((upper) => Fn.ask<string>().map((lower) => [upper, lower]))
.run('hello');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment