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.
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
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;s
, so action
cannot be influenced by any old value in your program—only an s
or some value reachable from some s
;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.