State s awhich represents a computation that carries and potentially modifies a state of type
sand produces a result of type
a, but the term "state monad" may generally refer to any monad which carries a state. The
transformerspackage provide general implementations of state monads.
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:
Statetype provides the ability to control the dose very precisely.
The reasons being that if you have
action :: State s a, this tells you that:
actionis special because it depends on a state;
actioncannot be influenced by any old value in your program—only an
sor some value reachable from some
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.