3

我正在尝试在 Graham Hutton 的《Haskell 编程》一书中执行示例(http://www.cs.nott.ac.uk/~gmh/book.html)。即使这些示例是在 literate haskell 中,我也可以启动 ghci 来加载示例;例如ghci cipher.lhshttp://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 ...
4

2 回答 2

5

就在您发布的链接中:

GHC 说没有 (Alternative ...) 的实例

AMP 的一个副作用是 Alternative 成为 MonadPlus 的超类。简单的补救措施:

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而不是 just many

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

于 2015-08-04T14:03:14.830 回答
1

我也偶然发现了这个问题。对于那些想要修改模块版本的人,parsing.lhs只需将其放在导入部分:

> import qualified Control.Applicative as CA

在类型解析器定义之后,这段代码:

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

或在此处获取模块的改编版本https://gist.github.com/myshov/85badeb087c51631aee3

于 2016-01-31T17:35:56.497 回答