我必须实现Applicative和Functor来实现Monad

tre*_*ore 7 monads haskell functor applicative fam-proposal

我正在尝试实现Monad实例.作为一个更简单的示例,假设以下内容:

data Maybee a = Notheeng | Juust a 

instance Monad Maybee where
   return x = Juust x
   Notheeng >>= f = Notheeng
   Juust x >>= f = f x
   fail _ = Notheeng 
Run Code Online (Sandbox Code Playgroud)

据我所知,这应该是Maybe的标准实现.但是,这不会编译,因为编译器抱怨:

没有实例(Applicative Maybee)

同样,一旦给出Applicative,他就想要一个Functor实例.

所以:简单的问题:在我实现Monad之前,我是否必须始终实现Functor和Applicative?

Nic*_*las 11

是的,事实并非如此,这是ghc7.10中以Functor-Applicative-Monad Proposal名义引入的变化.


Jer*_*ist 8

必须为Functor和定义实例Applicative(第二个是新版本的Haskell中的新要求),但它实际上没什么大不了的,因为如果你不想手工编写自己的实例,你可以使用这些实例:

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

-- Monad m

instance Functor m where
    fmap = liftM

instance Applicative m where
    pure  = return
    (<*>) = ap
Run Code Online (Sandbox Code Playgroud)


And*_*ács 6

使用GHC 7.10及更高版本,您必须实现FunctorApplicative.Monad强制超类实例的类定义:

class Functor f => Applicative f where ...
class Applicative m => Monad m where ...
Run Code Online (Sandbox Code Playgroud)

请注意,一旦有了Monad实例,就可以一般性地定义FunctorApplicative实例,而无需额外的工作:

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
Run Code Online (Sandbox Code Playgroud)

  • 实际上并非如此:在7.8及更早版本中,"Monad"没有任何超类限制. (2认同)