State monad in Haskell

State monad is a good way to simulate stateful program in Haskell, for example, we can have the following program to compuate the sum of a list of number

1. First example

sum :: Num a => [a] -> State a ()
sum [] = return ()
sum (x:xs) = do
  cur <- get
  put $ cur + x
  sum xs

to use this program, we write

let finalState = execState (sum [1, 2, 3]) 0

2. Corresponding to folding

You might feel, doesn't that just foldl? Exactly! Consider foldl :: (a -> b -> b) -> b -> m a -> b, the m a usually is [a] (if this can help you consider it concretely), but generally we just have a endofunctor m here. The state monad is just the corresponding of it, we access b by get and put, where we have it as parameter & returns in foldl. We have general pattern matching for the m a, this would be helpful if m a is complex. In this sense State is just a corresponding of foldl, but consider that State has two type parameters, it actually more easier to use.

The idea is State b () is same as M.foldl (consider M.foldl as foldl for M), but State s a can be more general, that means we can do transformation & collection at once! Thus, State s a means we collecting s (state), and transform whatever input to a. Another interesting thing is since State s a has no requires input, a can be quite freely generated (though this will not be usual).

3. Invokes

There have three functions can invoke a State, the first argument is the stateful program, the second is the initial state

  1. runState :: State s a -> s -> (a, s)
  2. evalState :: State s a -> s -> a
  3. execState :: State s a -> s -> s

In fact, we can reduce them to one:

  1. evalState = fst . runState
  2. execState = snd . runState

4. Conclusion

Let's review the ideas: State monad is a corresponding or improved folding, there have three functions to use it. I think these are enough to help you write a proper stateful program in Haskell. If you want to know more about monad transformer, since you have to stack these monads, refer to flexiable context 1. Then that's it, hope this acrticle helps you to fimilar with replacing assignment with stateless concept.


Date: 2023-04-13 Thu 16:10
Author: Lîm Tsú-thuàn