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

pro*_*eek 3 haskell literate-programming

我正在尝试在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
Run Code Online (Sandbox Code Playgroud)

但是有一些例子,由于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 
Run Code Online (Sandbox Code Playgroud)

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

Not in scope: type constructor or class ‘Alternative’
Run Code Online (Sandbox Code Playgroud)

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

添加此代码可以正常工作:

import qualified Control.Applicative as CA
instance CA.Alternative Parser where ...
Run Code Online (Sandbox Code Playgroud)

Car*_*ten 5

从您发布的链接开始:

GHC说没有实例(替代...)

AMP的副作用是Alternative成为了超级MonadPlus.简单的补救措施:

实例Alternative Foo其中(<|>)= mplus empty = mzero

所以这里应该是:

import Control.Applicative

instance Alternative Parser where
    (<|>) = mplus
    empty = mzero
Run Code Online (Sandbox Code Playgroud)

遗憾的是,我不能确切地告诉你这是否会这样做,因为你提供的书籍代码的链接不包括实例 MonadPlus

哪里找到缺少的定义

最简单的方法是使用hoogle或hayoo - 正如你可以在链接中看到的那样Hoogle会告诉你base包中的名字Control.Applicative 命名空间

处理倍数

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

import Control.Applicative (Alternative())
Run Code Online (Sandbox Code Playgroud)

要么

import qualified Control.Applicative as CA

instance CA.Alternative Parser where ...
Run Code Online (Sandbox Code Playgroud)

或通过限定所有的东西(如使用Parsing.many而不是仅仅many)

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