gpt4 book ai didi

haskell - 运行 Literate Haskell 代码时没有 (GHC.Base.Alternative Parser) 错误实例

转载 作者:行者123 更新时间:2023-12-02 16:46:48 25 4
gpt4 key购买 nike

我正在尝试执行 Graham Hutton 的《Haskell 编程》书中的示例 ( http://www.cs.nott.ac.uk/~gmh/book.html )。尽管这些示例是用 haskell 编写的,但我可以启动 ghci 来加载示例;例如ghci cipher.lhs (http://www.cs.nott.ac.uk/~gmh/cipher.lhs):

GHCi, version 7.10.2: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main ( cipher.lhs, interpreted )
Ok, modules loaded: Main.
*Main> let2int 'a'
0

但是对于一些示例,由于 ghci 的变化,我遇到了一些问题;例如,在第 8 章的 Parsing.ls 中,我有 No instance for (Applicative ...) 错误。

来自https://ghc.haskell.org/trac/ghc/wiki/Migration/7.10我得到了通过添加一些代码来消除一些错误的提示。

> instance Applicative Parser where
> pure = return
> (<*>) = ap -- defined in Control.Monad
>
> instance Functor Parser where
> fmap = liftM
>
> instance Alternative Parser where
> (<|>) = mplus
> empty = mzero

但是,我无法解决此错误消息:

Not in scope: type constructor or class ‘Alternative’

这是怎么回事,如何解决这个问题?导致问题的原始代码来自:http://www.cs.nott.ac.uk/~gmh/Parsing.lhs

解决方案

添加此代码效果很好:

import qualified Control.Applicative as CA
instance CA.Alternative Parser where ...

最佳答案

直接从 Link您发布了:

GHC says No instance for (Alternative ...)

A side-effect of the AMP is that Alternative became a super-class of MonadPlus. The easy remedy:

instance Alternative Foo where (<|>) = mplus empty = mzero

所以这里应该是:

import Control.Applicative

instance Alternative Parser where
(<|>) = mplus
empty = mzero

遗憾的是,我无法确切地告诉您这是否可行,因为您提供的书籍代码的链接不包含 MonadPlus

哪里可以找到缺失的定义

最简单的方法是使用 hoogle或 hayoo - 正如您在链接中看到的那样,例如 Hoogle 会告诉您它位于 base 包和 Control.Applicative 命名空间

处理倍数

好吧,我又不好了 - 你应该没问题

import Control.Applicative (Alternative())

import qualified Control.Applicative as CA

instance CA.Alternative Parser where ...

或者通过限定所有内容(例如使用 Parsing.many 而不仅仅是 many)

再次抱歉,我无法为您提供 100% 防水的编译解决方案 - 您可能需要测试一下(例如,我对这里的 () 不是 100% 确定 import Control .Applicative (Alternative()) 你也许可以剥离它。

关于haskell - 运行 Literate Haskell 代码时没有 (GHC.Base.Alternative Parser) 错误实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31811149/

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