Question 1-2

Complete the following class definition by writing the >>= function for the Maybe type.

data Maybe a = Just a | Nothing
instance Monad (Maybe a) where
    return x        =  Just x
For this type, the expression x >>= f operator should yield Just (f(data)) if x is Just data, and it should yield Nothing if x is Nothing.

Solution

data Maybe a = Just a | Nothing
instance Monad (Maybe a) where
    return x        =  Just x

    Nothing  >>= f  =  Nothing
    (Just x) >>= f  =  Just (f x)

Back to Exam Review 1