TExcelTAD
Home › Haskell › Haskell State Monad

Haskell State Monad

Without mutable variables, a computation that needs to "update" something (a counter, a random seed, a stack) has to take the current state as an argument and return the new state along with its result. That works, but threading the state by hand is tedious and easy to get wrong. The State monad from the mtl package (bundled with GHC) does the threading for you.

The problem: threading state by hand

Here is a tiny stack machine written with explicit state passing:

haskell · try it yourself
type Stack = [Int]

push :: Int -> Stack -> ((), Stack)
push x s = ((), x : s)

pop :: Stack -> (Int, Stack)
pop (x : rest) = (x, rest)
pop [] = (0, [])

program :: Stack -> (Int, Stack)
program s0 =
  let ((), s1) = push 3 s0
      ((), s2) = push 4 s1
      (a, s3) = pop s2
      (b, s4) = pop s3
      ((), s5) = push (a * b) s4
   in pop s5

main :: IO ()
main = print (program [])
(12,[])

Every step takes the previous state (s0, s1, …) and returns the next. Use s2 where s3 was meant and you have a silent bug.

The same program with State

A value of type State s a is a computation that, given a state of type s, produces a result of type a and a new state. Inside do, the state is passed along invisibly:

haskell · try it yourself
import Control.Monad.State

type Stack = [Int]

push :: Int -> State Stack ()
push x = modify (x :)

pop :: State Stack Int
pop = do
  s <- get
  case s of
    (x : rest) -> do
      put rest
      return x
    [] -> return 0

program :: State Stack Int
program = do
  push 3
  push 4
  a <- pop
  b <- pop
  push (a * b)
  pop

main :: IO ()
main = do
  print (runState program [])
  print (evalState program [])          -- only the result
  print (execState (push 1 >> push 2) [9])   -- only the final state
(12,[])
12
[2,1,9]
Function Meaning
get read the current state
put s replace the state
modify f apply f to the state
gets f read a part of the state: f <
gt; get
state f build a step from a function s -> (a, s)
runState m s0 run, returning (result, finalState)
evalState m s0 run, returning only the result
execState m s0 run, returning only the final state

Nothing is actually mutated: State is just a wrapper around a function s -> (a, s), and >>= connects those functions so each step receives the state the previous one returned.

Example: numbering items

A classic use is labelling things with fresh numbers, for instance assigning IDs while walking a tree:

haskell · try it yourself
import Control.Monad.State

data Tree a = Leaf a | Node (Tree a) (Tree a)
  deriving Show

fresh :: State Int Int
fresh = do
  n <- get
  put (n + 1)
  return n

label :: Tree a -> State Int (Tree (Int, a))
label (Leaf x) = do
  n <- fresh
  return (Leaf (n, x))
label (Node l r) = Node <
gt; label l <*> label r main :: IO () main = do let tree = Node (Node (Leaf 'a') (Leaf 'b')) (Leaf 'c') print (evalState (label tree) 1) print (evalState (mapM (\x -> (\n -> (n, x)) <
gt; fresh) "xyz") 100)
Node (Node (Leaf (1,'a')) (Leaf (2,'b'))) (Leaf (3,'c'))
[(100,'x'),(101,'y'),(102,'z')]

mapM, forM, replicateM and when all work in State, because they work in any monad.

Example: a deterministic random number generator

Pseudo-random generators are a natural fit: each draw uses the current seed and produces the next one. This linear congruential generator is completely deterministic, so the output is the same on every run:

haskell · try it yourself
import Control.Monad.State
import Control.Monad (replicateM)

-- One step of a linear congruential generator (constants from Numerical Recipes)
nextRand :: State Int Int
nextRand = do
  seed <- get
  let seed' = (1664525 * seed + 1013904223) `mod` 4294967296
  put seed'
  return seed'

rollDie :: State Int Int
rollDie = (\r -> r `mod` 6 + 1) <
gt; nextRand main :: IO () main = do print (evalState (replicateM 10 rollDie) 2026) print (evalState (replicateM 10 rollDie) 2026) -- same seed, same rolls let (rolls, seedAfter) = runState (replicateM 3 rollDie) 7 print (rolls, seedAfter)
[6,3,2,5,6,3,4,5,6,3]
[6,3,2,5,6,3,4,5,6,3]
([1,4,5],2630631676)

The real random package exposes the same idea: a generator value that you pass along, often inside State.

Example: a word-frequency counter

The state can be any type, for example a Map. Using modify with a strict map update keeps the counter tidy:

haskell · try it yourself
import Control.Monad.State
import qualified Data.Map.Strict as Map

countWord :: String -> State (Map.Map String Int) ()
countWord w = modify (Map.insertWith (+) w 1)

countAll :: [String] -> State (Map.Map String Int) Int
countAll ws = do
  mapM_ countWord ws
  gets Map.size                      -- number of distinct words

main :: IO ()
main = do
  let text = words "to be or not to be that is the question"
      (distinct, freq) = runState (countAll text) Map.empty
  print distinct
  print (Map.toList (Map.filter (> 1) freq))
8
[("be",2),("to",2)]

Note: Since mtl 2.3, Control.Monad.State no longer re-exports Control.Monad, so import replicateM, forM_ and friends from Control.Monad yourself (mapM and mapM_ are in the Prelude). The module comes from mtl; the underlying type is StateT s Identity from transformers, which the next lesson explains.

Test yourself

What does execState (modify (* 2) >> modify (+ 1)) 5 return?

  1. 10
  2. 11
  3. 12
  4. ((), 11)

What is a State s a value, conceptually?

  1. A mutable variable
  2. A function from a state s to a result a and a new state
  3. A global variable of type s
  4. A list of states

Which function runs a State computation and returns only its result?

  1. runState
  2. execState
  3. evalState
  4. get