Haskell LanguageState Monad

Introduction

State monads are a kind of monad that carry a state that might change during each computation run in the monad. Implementations are usually of the form State s a which represents a computation that carries and potentially modifies a state of type s and produces a result of type a, but the term "state monad" may generally refer to any monad which carries a state. The mtl and transformers package provide general implementations of state monads.

Remarks

Newcomers to Haskell often shy away from the State monad and treat it like a taboo—like the claimed benefit of functional programming is the avoidance of state, so don't you lose that when you use State? A more nuanced view is that:

  • State can be useful in small, controlled doses;
  • The State type provides the ability to control the dose very precisely.

The reasons being that if you have action :: State s a, this tells you that:

  • action is special because it depends on a state;
  • The state has type s, so action cannot be influenced by any old value in your program—only an s or some value reachable from some s;
  • The runState :: State s a -> s -> (a, s) puts a "barrier" around the stateful action, so that its effectfulness cannot be observed from outside that barrier.

So this is a good set of criteria for whether to use State in particular scenario. You want to see that your code is minimizing the scope of the state, both by choosing a narrow type for s and by putting runState as close to "the bottom" as possible, (so that your actions can be influenced by as few thing as possible.