State Monad

Do checkout Reader Monad and Writer Monad before reading this for context.

Earlier on we encountered the Reader and Writer Monads both of which offered some part of functionality we wanted.

Combining ideas from these gives us the State Monad

data State s a = State (s -> (a, s))

instance Monad (State s) where
  return a = State $ \s -> (a, s)
  State st >>= f = State $ \s -> let (a, s2) = st s
                                     State st2 = f a
                                 in  st2 s2

This gives us the following operations

-- Leaves state unchanged, result is set to state
get :: State s s
get = State $ \s -> (s, s)

-- Sets result to () and updates state
put :: s -> State s ()
put x = State $ \s -> ((), x)

-- Modifies state
modify :: (s -> s) -> State s ()
modify f = State $ \s -> ((), f s)

Extras

  • You may checkout this repository for basic implementations of State, Reader, Writer Monads.

References

Haskell wiki - state monad