Created
April 13, 2016 17:53
-
-
Save jliuhtonen/189facfd3841e0c1888b58caf4bfb9aa to your computer and use it in GitHub Desktop.
Reader monad in Elm for fun and profit
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
module Reader where | |
type Reader ctx a = Reader (ctx -> a) | |
unit: a -> Reader any a | |
unit x = | |
Reader (\_ -> x) | |
runReader: Reader ctx a -> ctx -> a | |
runReader r ctx = case r of | |
(Reader f) -> f ctx | |
withContext: ctx -> Reader ctx a -> a | |
withContext = flip runReader | |
andThen: Reader ctx a -> (a -> Reader ctx b) -> Reader ctx b | |
andThen reader bindFn = | |
Reader (\ctx -> | |
let a = runReader reader ctx | |
newReader = bindFn a | |
in runReader newReader ctx | |
) | |
(>>=): Reader ctx a -> (a -> Reader ctx b) -> Reader ctx b | |
(>>=) = andThen | |
ask: Reader ctx ctx | |
ask = Reader identity |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!