module Parser where
import Control.Monad (MonadPlus, mplus, mzero)
import Tagger (Tag, Token)
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 f p = do
result <- p
return (f result)
instance Monad Parser where
return a = Parser (\cs -> [(a,cs)])
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 [])
{-
这是我的解析器代码。显然我已经完成了“旧方式”并且无法真正让它以新方式工作。您能告诉我需要修复哪些问题才能使其正常工作吗?我阅读了这篇文章(https://wiki.haskell.org/Functor-Applicative-Monad_Proposal)并尝试更改我的代码,但我认为我在这里做错了。
我得到的编译错误:
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’
编辑 //
现在的代码:
module Parser where
import Control.Applicative
import Control.Monad (mplus, mzero, liftM, ap)
import Tagger (Tag, Token)
-- type Token = String
-- type Tag = String
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 --64
p `mplus` q = Parser (\cs -> parse p cs ++ parse q cs)
mzero = Parser (const [])
instance Alternative Parser where
(<|>) = mplus
empty = mzero
(+++) :: Parser a -> Parser a -> Parser a
p +++ q = Parser (\cs -> case parse (p `mplus` q) cs of
[] -> []
(x:_) -> [x])
错误:
Parser.hs:64:10:
Not in scope: type constructor or class ‘MonadPlus’