Haskell Language Monads Monad as a Subclass of Applicative


As of GHC 7.10, Applicative is a superclass of Monad (i.e., every type which is a Monad must also be an Applicative). All the methods of Applicative (pure, <*>) can be implemented in terms of methods of Monad (return, >>=).

It is obvious that pure and return serve equivalent purposes, so pure = return. The definition for <*> is too relatively clear:

mf <*> mx = do { f <- mf; x <- mx; return (f x) }                 
       -- = mf >>= (\f -> mx >>= (\x -> return (f x)))
       -- = [r   | f <- mf, x <- mx, r <- return (f x)]   -- with MonadComprehensions
       -- = [f x | f <- mf, x <- mx]                   

This function is defined as ap in the standard libraries.

Thus if you have already defined an instance of Monad for a type, you effectively can get an instance of Applicative for it "for free" by defining

instance Applicative < type > where
    pure  = return
    (<*>) = ap

As with the monad laws, these equivalencies are not enforced, but developers should ensure that they are always upheld.