我正在尝试实现本文第一章中的示例,如下所示:
data Tree a = Fork (Tree a) (Tree a) | Leaf a | Nil deriving (Show) instance Monad Tree where return a = Leaf a Nil >>= f = Nil Leaf a >>= f = f a Fork u v >>= f = Fork (u >>= f) (v >>= f) tree1 = Fork (Fork (Leaf 2) Nil) (Fork (Leaf 2) (Leaf 3)) tree2 = Fork (Leaf 2) (Leaf 3) f 2 = Fork Nil (Leaf "Two") f 3 = Fork (Leaf "Three") (Leaf "String") tree3 = tree2 >>= f
当我在GHC中运行它时,我收到此错误:
monads.hs:3:10: No instance for (Applicative Tree) arising from the superclasses of an instance declaration In the instance declaration for ‘Monad Tree’ Failed, modules loaded: none.
我试过把它添加到开头
class Monad m where return :: a -> m a (>>=) :: m a -> (a -> m b) -> m b
但我得到这个错误:
monads.hs:7:10: Ambiguous occurrence ‘Monad’ It could refer to either ‘Main.Monad’, defined at monads.hs:1:1 or ‘Prelude.Monad’, imported from ‘Prelude’ at monads.hs:1:1 (and originally defined in ‘GHC.Base’)
什么是最正确的修复?
要扩展Louis Wasserman的注释,您需要在声明实例时添加Applicative
(因此Functor
)Monad
实例.编写Monad
实例后,其他实例始终相同:
import Control.Monad (liftM, ap) instance Functor Tree where fmap = liftM instance Applicative Tree where pure = return (<*>) = ap
这改变是因为每个Monad
都是Applicative
(使用这个实例),但不是相反,所以它在道德上是一个超类.然而,之后Applicative
被添加到标准库中,Monad
因为它不会成为真正的超类很长一段时间,因为这会破坏人们的代码.最近,由于Applicative
已经非常普遍使用,社区决定建立Applicative
一个真正的超类Monad
,一次打破每个人的代码,但为未来改进它.这就是你所看到的.
问题是,就像文档指定的那样.该Monad
班的签名是:
class Applicative m => Monad m where --...
这意味着,为了定义类型的实例Monad
,首先需要定义该类型Applicative
.自签署Applicative
国家以来,问题更严重:
class Functor f => Applicative f where --...
所以你首先需要制作Tree
一个实例Functor
.在论文中,这不是必要的,因为 - 据我所知,在Prelude
这些约束的早期版本中没有必要.
现在为了让它工作,我们首先制作Tree
一个实例Functor
.因此,我们需要定义一个函数fmap
,对于给定的函数f :: a -> b
,它将a映射Tree a
到Tree b
:
instance Functor Tree where fmap f (Leaf a) = Leaf $ f a fmap f (Fork u v) = Fork (fmap f u) (fmap f v) fmap _ Nil = Nil
现在我们已经定义了这个,我们可以定义Applicative
:
instance Applicative Tree where pure = Leaf (<*>) (Leaf f) = fmap f (<*>) Nil = const $ Nil
最后我们可以定义Monad
实例:
instance Monad Tree where return a = Leaf a Nil >>= f = Nil Leaf a >>= f = f a Fork u v >>= f = Fork (u >>= f) (v >>= f)