我必须实施Applicative和Functor来实施Monad [英] Must I implement Applicative and Functor to implement a Monad
问题描述
我试图实现一个Monad实例。作为一个简单的例子,假设如下:
$ $ $ $ $ $ $ $ $数据Maybee a = Notheeng | Juust a
实例Monad Maybee其中
return x = Juust x
Notheeng>> = f = Notheeng
Juust x>> = f = fx
失败_ = Notheeng
这应该是Maybe的标准实现,据我所知。然而,这不会编译,因为编译器抱怨:
lockquote
没有实例适用于Maybee
类似地,他希望Functor实例一旦给定Applicative。
所以:简单的问题:我必须在我实现Monad之前,总是实现Functor和Applicative?解决方案 使用GHC 7.10或更高版本,必须实现 Functor
和 Applicative
。类的定义为 Monad
命令超类实例:
class Functor f =>应用f其中...
类应用m => Monad m其中...
请注意,一旦您拥有 Monad
实例, Functor
和 Applicative
实例可以一般定义,不需要额外的努力:
import Control.Monad
- 假设我们定义了一个Monad实例:
instance Monad m where ...
实例Functor m其中
fmap = liftM
实例应用程序m其中
pure = return
(< *> ;)= ap
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?
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
这篇关于我必须实施Applicative和Functor来实施Monad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!