I am trying to get a grasp on Haskell using the online book Learn you a Haskell for great Good.
I have, to my knowledge, been able to understand Monads so far until I hi
The State
monad is essentially
type State s a = s -> (a,s)
a function from one state (s
) to a pair of the desired result (a
) and a new state. The implementation makes the threading of the state implicit and handles the state-passing and updating for you, so there's no risk of accidentally passing the wrong state to the next function.
Thus a function that takes k > 0
arguments, one of which is a state and returns a pair of something and a new state, in the State s
monad becomes a function taking k-1
arguments and returning a monadic action (which basically is a function taking one argument, the state, here).
In the non-State setting, pop
takes one argument, the stack, which is the state. So in the monadic setting, pop
becomes a State Stack Int
action taking no explicit argument.
Using the State
monad instead of explicit state-passing makes for cleaner code with fewer opportunities for error, that's what the State
monad accomplishes. Everything could be done without it, it would just be more cumbersome and error-prone.