[英]Must I implement Applicative and Functor to implement a Monad
I'm trying to implement a Monad instance. 我正在尝试实现Monad实例。 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. 据我所知,这应该是Maybe的标准实现。 However, this doesn't compile, because the compiler complains:
但是,这不会编译,因为编译器抱怨:
No instance for (Applicative Maybee)
没有实例(Applicative Maybee)
and similarly he wants a Functor instance once the Applicative is given. 同样,一旦给出Applicative,他就想要一个Functor实例。
So: Simple question: Must I always implement Functor and Applicative before I can implement a Monad? 所以:简单的问题:在我实现Monad之前,我是否必须始终实现Functor和Applicative?
是的,事实并非如此,这是ghc7.10中以Functor-Applicative-Monad Proposal名义引入的变化。
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: 为
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
With GHC 7.10 and above, you must implement Functor
and Applicative
. 使用GHC 7.10及更高版本,您必须实现
Functor
和Applicative
。 The class definitions for Monad
mandate the superclass instances: Monad
的类定义Monad
要求超类实例:
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: 请注意,一旦您拥有
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.