gpt4 book ai didi

haskell - 声明 Monad 时出现 "No instance of Applicative"错误

转载 作者:行者123 更新时间:2023-12-02 18:42:05 25 4
gpt4 key购买 nike

我正在尝试实现 this paper 第一章中的示例,如下所示:

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 的评论,您现在需要在声明 Monad 时添加一个 Applicative(因此也是 Functor)实例实例。一旦您编写了 Monad 实例,其他实例始终是相同的:

import Control.Monad (liftM, ap)

instance Functor Tree where
fmap = liftM
instance Applicative Tree where
pure = return
(<*>) = ap

这发生了变化,因为每个 Monad 都是一个 Applicative (使用这个实例),但反之则不然,所以它在道德上是一个父类(super class)。然而,Applicative 是在 Monad 之后添加到标准库中的,因此很长一段时间以来它都没有成为真正的父类(super class),因为这会破坏人们的代码。最近,由于 Applicative 的使用非常普遍,社区决定使 Applicative 成为 Monad 的真正父类(super class),一次破坏了每个人的代码,但改进了为了 future 。这就是您所看到的。

关于haskell - 声明 Monad 时出现 "No instance of Applicative"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34641279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com