Haskell解析器、Monad和MonadPlus

Haskell解析器、Monad和MonadPlus,haskell,monads,applicative,monadplus,Haskell,Monads,Applicative,Monadplus,编辑// 现在的代码是: Parser.hs:56:10: No instance for (Applicative Parser) arising from the superclasses of an instance declaration In the instance declaration for ‘Monad Parser’ Parser.hs:60:10: No instance for (GHC.Base.Alternative Parse

编辑//

现在的代码是:

Parser.hs:56:10:
    No instance for (Applicative Parser)
      arising from the superclasses of an instance declaration
    In the instance declaration for ‘Monad Parser’

Parser.hs:60:10:
    No instance for (GHC.Base.Alternative Parser)
      arising from the superclasses of an instance declaration
    In the instance declaration for ‘MonadPlus Parser’
你可以跟着。它简单明了:将
return
的定义移动到
pure
,添加
的样板定义,并从monad实例中删除
return

Parser.hs:64:10:
Not in scope: type constructor or class ‘MonadPlus’
工作守则作为一个整体:

instance Alternative Parser where 
    (<|>) = mplus 
    empty = mzero
模块解析器,其中
进口管制
导入标记器(标记、令牌)
导入控制
newtype解析器a=解析器([(令牌,标记)]->[(a,[(令牌,标记)])]
parse::Parser a->[(令牌,标记)]->[(a,[(令牌,标记)])]
解析(解析器p)=p
实例函子解析器,其中
fmap=liftM
实例应用程序解析器,其中
纯a=解析器(\cs->[(a,cs)])
()=ap
实例Monad解析器,其中
p>>=f=Parser(\cs->concat[parse(fa)cs'|(a,cs')parse p cs++parse q cs)
mzero=解析器(常量[])
实例替代解析器,其中
()=mplus
空=零

您可以按照迁移指南进行操作:我想您仍然需要Applicative的手动实例(这将非常简单)还有其他选择。谢谢你的建议!@zakyggaps我尝试按照你链接上的说明进行操作,但不幸的是,现在出现了新的错误,我不确定该如何修复。我可能还需要更改一些内容?在你原来对“>>=”的定义中,你有参数“p”和“f”。但是在你对“*>”的定义中你不再有这些参数了。如果你用“p*>f”替换“(*>)”会发生什么?你对“>>=”的新定义中也有类似的混淆。你确定你理解运算符语法的工作原理吗?@PaulJohnson我替换了它,现在它不再抱怨它们了,谢谢!现在它只抱怨a(56)、p(66)和q(66)。我对Haskell还是非常陌生,没有经常使用它,所以有时我还是会对很多事情感到困惑。我正在尽最大努力学习,但它非常不同。那么“纯”的定义中的“a”是什么?@PaulJohnson抱歉,已修复。此修复仅给出错误“解析器”。hs:56:29:不在范围内:“a”现在,pure=Parser(\cs->[(a,cs)]似乎存在某种问题还是什么?我对这个很陌生,不知道问题的根源在哪里。@katyp你不应该删除
MonadPlus
实例。
Alternative
的定义取决于它。@zakyggaps非常感谢你的帮助!现在ghci仍然给出了MonadPlus的编译错误。我编辑了原始帖子
Parser.hs:64:10:
Not in scope: type constructor or class ‘MonadPlus’
instance Functor Parser where
    fmap = liftM

instance Applicative Parser where
    pure a = Parser (\cs -> [(a,cs)])
    (<*>) = ap

instance Monad Parser where
    p >>= f = Parser (\cs -> concat [parse (f a) cs' | (a,cs') <- parse p cs])
instance Alternative Parser where 
    (<|>) = mplus 
    empty = mzero
module Parser where

import           Control.Monad
import           Tagger        (Tag, Token)
import           Control.Applicative

newtype Parser a = Parser ([(Token, Tag)] -> [(a, [(Token, Tag)])])

parse :: Parser a -> [(Token, Tag)] -> [(a, [(Token, Tag)])]
parse (Parser p) = p

instance Functor Parser where
    fmap = liftM

instance Applicative Parser where
    pure a = Parser (\cs -> [(a,cs)])
    (<*>) = ap

instance Monad Parser where
    p >>= f = Parser (\cs -> concat [parse (f a) cs' | (a,cs') <- parse p cs])

instance MonadPlus Parser where
    p `mplus` q = Parser (\cs -> parse p cs ++ parse q cs)
    mzero = Parser (const [])

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