Skip to content

Instantly share code, notes, and snippets.

@jliuhtonen
Created April 13, 2016 17:53
Show Gist options
  • Save jliuhtonen/189facfd3841e0c1888b58caf4bfb9aa to your computer and use it in GitHub Desktop.
Save jliuhtonen/189facfd3841e0c1888b58caf4bfb9aa to your computer and use it in GitHub Desktop.
Reader monad in Elm for fun and profit
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
@ivan-demchenko
Copy link

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment