State

State is a function

A computation that reads and writes a piece of state can be written as a plain function that takes the old state and returns the value and the new state. The State monad is a newtype around exactly that function:

newtype State s a = State { runState :: s -> (a, s) }

The monad instance threads the state from one step to the next, so >>= is function composition with a pair in the middle. That is all the magic: no mutable cell, no IO, and the whole computation stays a pure function. The Control.Monad.State module of mtl adds the helpers get, put, modify and gets on top.

A counter in the state monad

A counter is the smallest useful state: every step increments the state and reads the new value. The recursive helper carries the results in a plain list, while the counter lives in the monad:

module Main (main) where import Control.Monad.State (State, execState, get, gets, modify', put, runState) tick :: State Int () tick = modify' (+ 1) countTo :: Int -> State Int [Int] countTo n = go n [] where go 0 acc = pure (reverse acc) go k acc = do tick value <- get go (k - 1) (value : acc) main :: IO () main = do print (runState (countTo 3) 0) print (execState (countTo 3) 0) print (runState (put 10 >> tick >> gets (* 2)) 0)

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

([1,2,3],3)
3
(22,11)

runState returns the value and the final state, execState drops the value and keeps the state. The third line is the whole API in one expression: put 10 replaces the state, tick increments it to 11 and gets (* 2) reads it and doubles it, without writing the state back.

A stack with get and put

A stack is a state that several operations have to share. push changes it and returns nothing, pop reads it and returns the top element, and the empty case is a value, not an exception:

module Main (main) where import Control.Monad.State (State, execState, get, modify', put, runState) type Stack = [Int] push :: Int -> State Stack () push x = modify' (x :) pop :: State Stack (Maybe Int) pop = do stack <- get case stack of [] -> pure Nothing top : rest -> do put rest pure (Just top) main :: IO () main = do print (runState (mapM_ push [1, 2, 3] >> pop >> pop) []) print (execState (mapM_ push [4, 5]) []) print (runState (pop :: State Stack (Maybe Int)) [])

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

(Just 2,[1])
[5,4]
(Nothing,[])

get reads the state and returns it as a value; put replaces it and returns (). modify' is the two together, and the prime means the new state is evaluated before it is stored, which matters when the state grows and is explained in the lesson on strictness. The second line shows execState: the pushes ran, the values they returned are unused, and only the final stack is printed.

modify and a running total

The state does not have to be a single number. A pair of a sum and a count gives a mean, and every step updates both fields in one modify':

module Main (main) where import Control.Monad.State (State, execState, get, modify', runState) type Total = (Int, Int) add :: Int -> State Total () add n = modify' $ \(total, count) -> (total + n, count + 1) mean :: State Total Double mean = do (total, count) <- get pure (fromIntegral total / fromIntegral count) main :: IO () main = do print (runState (mapM_ add [4, 8, 6] >> mean) (0, 0)) print (execState (mapM_ add [4, 8, 6]) (0, 0))

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

(6.0,(18,3))
(18,3)

The tuple is the state, and mean only reads it: get does not change the state, so the pair after the run is the one the three add steps left. Writing this without the monad means passing the pair through every function by hand, which is what the monad removes.

runState, execState and the order

A State value is a description, and nothing runs until one of the three runners is applied:

A runner can be applied more than once to the same computation with a different starting state, and each run is independent, because the state is an argument and not a cell. That is the property to remember when the next lessons put State over IO: the transformer keeps the state threaded the same way, and the runner is what decides when the thread starts.

Exercises

  1. Write next :: State Int Int that returns the current value and then increments the state.
  2. Run countTo 5 twice from the same starting state and compare the two results.
  3. Add a peek :: State Stack (Maybe Int) that reads the top of the stack without removing it.
  4. Compute the minimum and the maximum of a list in one pass with a state of two Maybe Int values.
  5. Explain why modify (+ 1) and modify' (+ 1) give the same answer here and differ in memory use on a long run.
  6. Rewrite countTo without the accumulator and explain what the state is doing instead.

Questions

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

  1. What is a State s a value, before it runs?

    Answer

    A function from the old state to a value and a new state

    State is a newtype around s -> (a, s), so it is a pure function until a runner applies it.

  2. What does runState return?

    Answer

    (a, s)

    runState gives the value and the final state; evalState and execState drop one of them.

  3. What does put do?

    Answer

    Replaces the state and returns unit

    put writes a new state; get reads it, and modify is the combination.

  4. What does this program print? module Main (main) where import Control.Monad.State (execState, modify') main :: IO () main = print (execState (modify' (+ 5) >> modify' (* 2)) (10 :: Int))

    Answer

    30

    The first step makes the state 15 and the second doubles it to 30.

  5. What does get return?

    Answer

    The current state as the value, without changing it

    get reads the state into the value position; the state itself is left alone.

  6. Which runner gives only the final state?

    Answer

    execState

    execState runs the computation for its effect on the state and drops the value.

  7. What does this program print? module Main (main) where import Control.Monad.State (runState) main :: IO () main = print (runState (pure (7 :: Int)) "start")

    Answer

    (7,"start")

    pure leaves the state untouched, so the pair is the value and the state that was given.

  8. Why does the prime in modify&#39; matter?

    Answer

    It evaluates the new state instead of storing a thunk

    The strict version avoids a chain of thunks in the state, which is a space leak in a long run.

  9. Can the same State computation be run twice with different starting states?

    Answer

    Yes, it is a pure function and each run is independent

    Since the state is an argument, the value can be applied to as many starting states as you like.

  10. What does gets f do?

    Answer

    Applies f to the state and returns the result

    gets is a read followed by a projection, without changing the state.

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