Reader and Writer

Reader: a shared environment

State threads a value that changes. Reader threads a value that does not: a configuration, a connection pool, a clock. It is a function from that environment to the result:

newtype Reader r a = Reader { runReader :: r -> a }

ask returns the environment, asks applies a projection to it, and local runs a sub-computation with a changed copy without touching the caller. A deep call chain can therefore read the configuration without taking it as an argument at every level.

A configuration read by many functions

The program has a record with a name and an hourly rate. Two functions read it, one directly and one through asks, and local runs the same price with a different rate:

module Main (main) where import Control.Monad.Reader (Reader, asks, local, runReader) data Config = Config { configName :: String , configRate :: Int } deriving (Show) greeting :: Reader Config String greeting = do name <- asks configName pure ("hello, " ++ name) price :: Int -> Reader Config Int price hours = do rate <- asks configRate pure (hours * rate) main :: IO () main = do print (runReader greeting (Config "ada" 20)) print (runReader (price 3) (Config "ada" 20)) print (runReader (local (\c -> c {configRate = 10}) (price 3)) (Config "ada" 20)) print (runReader (asks configRate >>= \r -> pure (r * 2)) (Config "ada" 20))

ghc -Wall -O1 -o reader reader.hs
./reader

"hello, ada"
60
30
40

The third line is local: the modified record exists only inside the parentheses, and the fourth line shows that the outer environment still has the rate 20 after it. There is no copy of the configuration in a global variable and nothing to reset, because the environment is an argument to runReader and every call gets the one it was given.

Writer: a value and a log

Writer is the other side: a computation that returns a value and accumulates an output, where the output is any Monoid from the previous lesson, most often a list of strings:

newtype Writer w a = Writer { runWriter :: (a, w) } tell :: Monoid w => w -> Writer w ()

tell appends to the log and returns unit. The interesting part is what happens when two steps are combined: >>= appends the logs with <> in the order the steps ran, so the log is deterministic and a reader can trust it.

A log without a global variable

A function that both computes and explains what it did is the natural use:

module Main (main) where import Control.Monad.Writer (Writer, execWriter, runWriter, tell) type Log = [String] audit :: [Int] -> Writer Log Int audit values = do tell ["count: " ++ show (length values)] tell ["sum: " ++ show (sum values)] pure (sum values) main :: IO () main = do print (runWriter (audit [1, 2, 3])) print (execWriter (audit [4, 5])) print (runWriter (audit []))

ghc -Wall -O1 -o audit audit.hs
./audit

(6,["count: 3","sum: 6"])
["count: 2","sum: 9"]
(0,["count: 0","sum: 0"])

runWriter gives the value and the log, execWriter drops the value. The empty list still produces a log of two lines, because the two tell calls run whether or not there is anything to add up. That is a difference from a print statement inside the function: the logging is part of the return type, so a caller can keep the log, throw it away, or combine it with another one.

module Main (main) where import Control.Monad.Writer (Writer, listen, runWriter, tell) type Log = [String] step :: String -> Int -> Writer Log Int step label value = do tell [label ++ ": " ++ show value] pure (value * 2) main :: IO () main = do print (runWriter (step "a" 1 >>= step "b")) let (result, entries) = runWriter (mapM (step "x") [1, 2]) print result mapM_ putStrLn entries print (runWriter (listen (step "c" 5)))

ghc -Wall -O1 -o steps steps.hs
./steps

(4,["a: 1","b: 2"])
[2,4]
x: 1
x: 2
((10,["c: 5"]),["c: 5"])

The first line shows the chained log: the entry of a comes before the entry of b, and the value of the first step was passed to the second. The last line is listen: it runs a computation and gives the log twice, once as the value and once in the outer log, which is how a caller inspects what a nested action produced.

tell, listen and the order

The three functions worth knowing by name:

Reader and Writer are the two halves of State: one reads, the other appends. None of them can do IO, and that is the point: a function that logs is still a pure function, and the runner decides whether the log is printed, stored or ignored. The next lesson stacks these monads on top of IO with a transformer.

Exercises

  1. Add a configDebug :: Bool field and print the greeting twice, once with local and the flag set.
  2. Write loggedSum :: [Int] -> Writer [String] Int that tells the running total after every element.
  3. Use censor to replace every log line of an action with a fixed one.
  4. Explain why runReader takes the environment as its second argument and what a partially applied runReader greeting is.
  5. Turn the report of the previous lesson into a Writer of lines and run it.
  6. Compare the type of ask with the type of get and say what changes in the state.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does ask return in the reader monad?

    Answer

    The whole environment

    ask is the environment itself; asks takes a function and returns the projection.

  2. What does local f action do?

    Answer

    Runs action with f applied to the environment, leaving the caller untouched

    local changes the environment only inside the sub-computation.

  3. What does tell need from its argument?

    Answer

    A Monoid instance

    The log is accumulated with the monoid operation, so the type of the log must be a Monoid.

  4. What does this program print? module Main (main) where import Control.Monad.Writer (Writer, runWriter, tell) main :: IO () main = print (runWriter (tell ["a"] >> tell ["b"] :: Writer [String] ()))

    Answer

    ((),["a","b"])

    The log is appended in the order the steps run, and the value is unit.

  5. Which runner drops the value and keeps the log?

    Answer

    execWriter

    execWriter returns only the accumulated log.

  6. What does this program print? module Main (main) where import Control.Monad.Reader (asks, runReader) main :: IO () main = print (runReader (asks (* 2)) (21 :: Int))

    Answer

    42

    asks applies the function to the environment, so doubling 21 gives 42.

  7. How is the log of a Writer combined when two actions run in sequence?

    Answer

    With the monoid operation, in the order the actions ran

    The Writer instance appends the two logs with <>, so the order is the order of the steps.

  8. What does listen action add to the result?

    Answer

    The log of the action, as part of the value

    listen returns the value paired with the log the action produced.

  9. Why can a Reader computation not print its configuration?

    Answer

    Its type has no IO, so printing does not type check

    A Reader returns a pure value; an effect needs IO or a transformer over IO.

  10. What does runReader greeting config return?

    Answer

    The string greeting computed with config

    Reader is a function from the environment to the value, so runReader applies it.

The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev