Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 57 ยท Functors, applicatives and monads

State, Reader, Writer and Monad Transformers

Learn the State, Reader and Writer monads, then stack effects with StateT and ExceptT and the mtl style. Includes a runnable State stand-in.

Haskell functions are pure, so a function cannot quietly read a configuration, bump a counter or append to a log. When you need those things, you pass them around explicitly. Doing that by hand gets tiresome: every function takes an extra argument and returns an extra result. The State, Reader and Writer monads hide that plumbing behind do-notation, without giving up purity.

Once you want two of these effects at the same time, or one of them together with failure, you stack them with monad transformers. This lesson shows each monad, then how they combine. The real library code (transformers and mtl) is read-only here. The runnable blocks are JavaScript stand-ins that build a State monad from plain functions, so you can see how it works inside.

The idea: hide a parameter

Suppose you want to give each item in a list a fresh number. Without help, you thread the counter through every call:

HASKELL
label :: Int -> String -> (String, Int)
label n name = (show n ++ ":" ++ name, n + 1)

labelAll :: Int -> [String] -> ([String], Int)
labelAll n []       = ([], n)
labelAll n (x : xs) =
  let (y, n1)   = label n x
      (ys, n2)  = labelAll n1 xs
  in  (y : ys, n2)

The shape s -> (a, s) ("take the current state, return a result and a new state") appears everywhere. State is a newtype around exactly that shape, and its monad instance does the threading for you.

State

State s a is a computation that reads and updates a state of type s and produces an a. It lives in Control.Monad.State (from mtl) or Control.Monad.Trans.State (from transformers).

HASKELL
import Control.Monad.State

fresh :: State Int Int
fresh = do
  n <- get          -- read the state
  put (n + 1)       -- replace it
  return n

labelAll :: [String] -> State Int [String]
labelAll = mapM (\name -> do
  i <- fresh
  return (show i ++ ":" ++ name))

-- evalState (labelAll ["a", "b", "c"]) 0  ==> ["0:a","1:b","2:c"]

The core operations are:

Operation Meaning
get Return the current state
put s Replace the state
modify f Apply f to the state (modify' is strict)
gets f Read the state through a function
runState m s Run, return (result, finalState)
evalState m s Run, keep only the result
execState m s Run, keep only the final state

There is no hidden mutation: runState is an ordinary function from an initial state to a result. Running the same computation twice with the same start gives the same answer, which keeps the code easy to test.

Three monads, three jobs

State A value you read and update.
Reader A value you only read.
Writer A log you only append to.

Each hides one extra parameter or result.

1 / 2
JS Build State from plain functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reader and Writer

Reader passes a read-only environment (a config, a database handle, a user) to every step without listing it as a parameter. ask returns the environment, asks f reads part of it, and local f m runs m with a modified environment.

HASKELL
import Control.Monad.Reader

data Config = Config { indent :: Int, bullet :: String }

item :: String -> Reader Config String
item text = do
  n <- asks indent
  b <- asks bullet
  return (replicate n ' ' ++ b ++ " " ++ text)

nested :: Reader Config [String]
nested = do
  a <- item "top"
  b <- local (\c -> c { indent = indent c + 2 }) (item "child")
  return [a, b]

-- runReader nested (Config 0 "-")  ==> ["- top","  - child"]

Writer collects output next to the result. The log type must be a Monoid, so that logs from two steps can be joined with <>.

HASKELL
import Control.Monad.Writer

factorial :: Integer -> Writer [String] Integer
factorial 0 = do
  tell ["factorial 0 = 1"]
  return 1
factorial n = do
  r <- factorial (n - 1)
  let v = n * r
  tell ["factorial " ++ show n ++ " = " ++ show v]
  return v

-- runWriter (factorial 3) gives (6, [... three log lines ...])

A plain list as a log has poor performance when appended on the left in long computations. For heavy logging, use a different monoid such as a difference list, or an IO-based logger.

Why transformers?

Each of these monads is a separate type, and do blocks only work inside one monad. What if you need state and the possibility of failure? Writing State Int (Maybe a) is awkward: you would unwrap the Maybe by hand at every step.

A monad transformer is a type that adds an effect to any base monad. By convention it ends in T:

Transformer Adds Unwraps to
StateT s m a State s -> m (a, s)
ReaderT r m a Read-only environment r -> m a
WriterT w m a Log m (a, w)
ExceptT e m a Failure with an e m (Either e a)
MaybeT m a Failure without reason m (Maybe a)

The plain monads are special cases: State s is StateT s Identity, where Identity is the monad that does nothing. To run an action from the layer below, use lift; in a stack with IO at the bottom, liftIO lifts an IO action from any depth.

HASKELL
import Control.Monad.State
import Control.Monad.Except

type App = ExceptT String (State Int)

step :: Int -> App ()
step n = do
  total <- lift get
  when (total + n > 10) $ throwError ("limit exceeded at " ++ show n)
  lift (put (total + n))

-- runState (runExceptT (mapM_ step [3, 4, 5])) 0
--   ==> (Left "limit exceeded at 5", 7)

The failure stopped the loop, and the state after the two successful steps (7) is still there, because the state sits below the error layer.

Order matters

Swap the layers and the meaning changes. StateT Int (Either String) a unwraps to Int -> Either String (a, Int): when an error occurs, there is no state in the result at all, because it is thrown away with the Left. With ExceptT String (State Int) you always get the final state, even after an error. Pick the order that matches what you want to happen on failure, such as "roll back" versus "keep partial progress".

mtl style: write once, run in any stack

Calling lift everywhere is noisy. The mtl library provides type classes that describe capabilities: MonadState s m, MonadReader r m, MonadWriter w m, MonadError e m and MonadIO m. Functions are written against the classes, and get, put, ask, tell and throwError work without lift:

HASKELL
# LANGUAGE FlexibleContexts #
import Control.Monad.State
import Control.Monad.Except

addChecked :: (MonadState Int m, MonadError String m) => Int -> m ()
addChecked n = do
  total <- get
  when (total + n > 10) $ throwError "too big"
  put (total + n)

addChecked runs in ExceptT String (State Int), in StateT Int (Either String) or in any other stack that provides both capabilities. The cost is some type-class machinery and, in deep stacks, performance overhead; many teams use a single ReaderT Env IO stack instead, which is simple and fast. You will meet effect systems that go further in Effect Systems and Free Monads.

JS Two layers: failure on top of state

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does evalState m 0 return?

    evalState runs the computation and keeps the result. execState keeps the final state and runState returns both.
  2. 2. Which monad is the right choice for a read-only configuration passed to many functions?

    Reader gives every step access to an environment through ask or asks, but steps cannot change it (except locally with local).
  3. 3. What is State s in terms of StateT?

    The plain monads are transformers over Identity, the monad that adds no effect.
  4. 4. Why does ExceptT String (State Int) keep the state after an error, while StateT Int (Either String) does not?

    In the second stack the whole result, including the state, is wrapped inside the Either, so a Left carries no state.

Summary

  • State, Reader and Writer hide a changing value, a read-only value and a log, without any real mutation.
  • runState, evalState and execState run a State computation from an initial state.
  • Transformers such as StateT and ExceptT stack effects; lift and liftIO reach lower layers.
  • The order of layers changes what a failure does to your state or log.
  • mtl classes (MonadState, MonadError, ...) let you write code that works in any suitable stack.

Next, we leave pure code and look at how Haskell talks to the world: IO Basics.