![](/img/trans.png)
[英]Why can't I implement these functions with a Functor/Applicative constraint only?
[英]Must I implement Applicative and Functor to implement a Monad
我正在尝试实现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
据我所知,这应该是Maybe的标准实现。 但是,这不会编译,因为编译器抱怨:
没有实例(Applicative Maybee)
同样,一旦给出Applicative,他就想要一个Functor实例。
所以:简单的问题:在我实现Monad之前,我是否必须始终实现Functor和Applicative?
是的,事实并非如此,这是ghc7.10中以Functor-Applicative-Monad Proposal名义引入的变化。
为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
使用GHC 7.10及更高版本,您必须实现Functor
和Applicative
。 Monad
的类定义Monad
要求超类实例:
class Functor f => Applicative f where ...
class Applicative m => Monad m where ...
请注意,一旦您拥有Monad
实例,就可以一般性地定义Functor
和Applicative
实例,而无需额外的工作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.