I am learning about the State monad in the book "Learn You a Haskell for Great Good!" by Miran Lipovaca. For the following monad instance:
instance Monad (State s) where
return x = State $ \s -> (x,s)
(State h) >>= f = State $ \s -> let (a, newState) = h s
(State g) = f a
in g newState
I am having trouble understanding the definition for the >>=
function. I am not sure whether h
is the stateful computation (i.e. the function that takes a state and returns a result with an updated state) or whether it is a state. I am guessing that it must be a stateful computation since it is applied to the state (of type s
) in the lambda function to produce the result (a, newState)
.
But from the type declaration of State s a
:
newtype State s a = State { runState :: s -> (a,s) }
The state is of type s
and the result is of type a
. So for the monad instance, is the s
in instance Monad (State s)
the type of the state or is it actually the stateful computation? Any insights are appreciated.
newtype {- StatePassingComputations -} State s a = MkState { runState :: s -> (a,s) }
would've probably been a lot less confusing, in a newbies--oriented book. – Will Ness