Haskell MonadReader Class
MonadReader is a typeclass for computations that can read a shared environment. Any stack with an environment can provide its operations.
Ask returns the environment
Ask returns the value given to runReader. The value is 9.
import Control.Monad.Reader
main :: IO ()
main = print (runReader ask 9)Asks transforms the environment
Asks length counts the letters in hello. The count is 5.
import Control.Monad.Reader
main :: IO ()
main = print (runReader (asks length) "hello")Local changes the environment inside
Local adds 10 to the environment for one computation. The inner result is 15.
import Control.Monad.Reader
main :: IO ()
main = print (runReader (local (+ 10) ask) 5)Example
import Control.Monad.Reader
computation :: Reader Int (Int, Int, Int)
computation = do
a <- ask
b <- asks (* 3)
c <- local (+ 10) ask
return (a, b, c)
main :: IO ()
main = print (runReader computation 4)Key points
- Ask: ask returns the whole environment.
- Asks: asks applies a function to the environment and returns the result.
- Local: local runs a computation with a changed environment.
- Scope: a local change affects only the computation inside local.
- Reuse: the same reader code works in Reader and in a larger stack.
In this example, ask gives 4, asks triples it to 12, and local adds 10 for the inner ask to give 14.
Note
the environment is read only, local never changes the outer environment.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does local (+ 10) ask return when the outer environment is 5?