Last active
December 9, 2022 12:16
-
-
Save dankreiger/b43560aa4f92c52c0f1eeb4ea41cdd6e to your computer and use it in GitHub Desktop.
reader monad
This file contains 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
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