Must I implement Applicative and Functor to implement a Monad

三世轮回 提交于 2019-12-09 17:21:34

问题


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?


回答1:


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



回答2:


Yes, it wasn't the case before, it's a change that was introduced in ghc7.10 under the name of Functor-Applicative-Monad Proposal.




回答3:


It is compulsory to define instances for Functor and Applicative (the second one is a new requirement in newer versions of Haskell), but it's actually no big deal because if you don't want to hand-write your own instances you can just use these ones:

import Control.Applicative (Applicative(..))
import Control.Monad       (liftM, ap)

-- Monad m

instance Functor m where
    fmap = liftM

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


来源:https://stackoverflow.com/questions/29844824/must-i-implement-applicative-and-functor-to-implement-a-monad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!