Definition of bind operator for State monad?
From All About Monads:
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'
From Control.Monad.State.Lazy:
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:
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: haskell
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home