Search code examples
haskellmonadsfunctorapplicativefam-proposal

Must I implement Applicative and Functor to implement a Monad


I'm trying to implement a Monad instance. As a simpler example, assume the following:

data Maybee a = Notheeng | Juust a 

instance Monad Maybee where
   return x = Juust x
   Notheeng >>= f = Notheeng
   Juust x >>= f = f x
   fail _ = Notheeng 

This should be the standard implementation of Maybe as far as I know. However, this doesn't compile, because the compiler complains:

No instance for (Applicative Maybee)

and similarly he wants a Functor instance once the Applicative is given.

So: Simple question: Must I always implement Functor and Applicative before I can implement a Monad?


Solution

  • With GHC 7.10 and above, you must implement Functor and Applicative. The class definitions for Monad mandate the superclass instances:

    class Functor f => Applicative f where ...
    class Applicative m => Monad m where ...
    

    Note that once you have a Monad instance, the Functor and Applicative instances can be defined generically with no additional effort:

    import Control.Monad
    
    -- suppose we defined a Monad instance:
    instance Monad m where ...
    
    instance Functor m where
        fmap = liftM
    
    instance Applicative m where
        pure = return
        (<*>) = ap