Reputation: 113
In the book "Learn You A Haskell for Great Good", The implementation of >>= operator in (State s) Monad is:
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
As we know, the >>= operator has the type >>=::m a -> (a -> m b) -> m b
. The second parameter of this operator is a function f whose type is (a -> m b)
, so why the type of input of function f in the implementation of (State s) is not s -> (a, s)
but just the result a
?
Thanks for everybody! I think I have figured out how >> = works. We cannot treat the input type of function f as the type contained in Monad, but we should consider it as the input type of monad.
Upvotes: 1
Views: 84
Reputation: 152737
Since f
has type a -> m b
(actually, a -> State s b
), its input has type a
. It is the output whose type has the shape s -> (b, s)
(actually, State s b
) you mention.
Upvotes: 3