abhillman
abhillman

Reputation: 4332

Maybe Monad and >>=

The type signature for >>= is the following:

(>>=) :: Monad m => m a -> (a -> m b) -> m b

And the following makes sense to me (it is also one of the monad laws):

(>>=) (Just 1) (id . return) == Just 1

Yet the Prelude gives the following:

Prelude> :t (>>=) (Just 1) id
(>>=) (Just 1) id :: Num (Maybe b) => Maybe b

I would have expected the Prelude to return some error as the type signature on id is (a -> a) as opposed to Monad m => (a -> m b).

Is there a great way to understand what is going on here? Is there any use for (>>=) (Just 1) id?

Upvotes: 0

Views: 131

Answers (1)

kosmikus
kosmikus

Reputation: 19637

The type of id is c -> c (using a different letter so not to conflict with a and b that occur in the type of >>=). We can unify c -> c with a -> Maybe b if we pick c = a = Maybe b.

So this means that >>= in your example is used at type:

(>>=) :: Maybe (Maybe b) -> (Maybe b -> Maybe b) -> Maybe b

Now you have

(>>=)    (Just 1)           id

For Just 1 to be of type Maybe (Maybe b), Maybe b must be in Num (because then 1 can be interpreted as Maybe b).

Upvotes: 3

Related Questions