2008/09/20

Definition of bind operator for State monad?

instance Monad (State s) where 
return a = State $ \s -> (a,s)
(State x) >>= f = State $ \s -> let (v,s') = x s in runState (f v) s'


instance
Monad (State s) where
return a = State $ \s -> (a, s)
m >>= k = State $ \s -> let
(a, s') = runState m s
in runState (k a) s

Hmm, how and why are they different? The latter one makes sense to me, but I cannot get the part to apply x to s in the former one.

Update:

I got it. I just did not notice that the former used pattern matching against to deconstruct the first argument (State x), where as the latter used field selector (runState). Note that the State monad is declared as follows:
newtype State s a = State { runState :: s -> (a, s) }

Labels: