首先,我并不完全理解错误信息,因此我只能使用含糊不清的问题标题
我试图通过GHC运行此代码,我写了
-- Functional parsing library from chapter 13 of Programming in Haskell,
-- Graham Hutton, Cambridge University Press, 2016.
module Parsing (module Parsing, module Control.Applicative) where
import Data.Typeable
import Control.Applicative
import Data.Char
-- Basic definitions
newtype Parser a = P (String -> [(a,String)])
parse :: Parser a -> String -> [(a,String)]
parse (P p) inp = p inp
item :: Parser Char
item = P (\inp -> case inp of
[] -> []
(x:xs) -> [(x,xs)])
-- Sequencing parsers
instance Functor Parser where
-- fmap :: (a -> b) -> Parser a -> Parser b
fmap g p = P (\inp -> case parse p inp of
[] -> []
[(v,out)] -> [(g v, out)])
instance Applicative Parser where
-- pure :: a -> Parser a
pure v = P (\inp -> [(v,inp)])
-- <*> :: Parser (a -> b) -> Parser a -> Parser b
pg <*> px = P (\inp -> case parse pg inp of
[] -> []
[(g,out)] -> parse (fmap g px) out)
instance Monad Parser where
-- (>>=) :: Parser a -> (a -> Parser b) -> Parser b
p >>= f = P (\inp -> case parse p inp of
[] -> []
[(v,out)] -> parse (f v) out)
-- Making choices
instance Alternative Parser where
-- empty :: Parser a
empty = P (\inp -> [])
-- (<|>) :: Parser a -> Parser a -> Parser a
p <|> q = P (\inp -> case parse p inp of
[] -> parse q inp
[(v,out)] -> [(v,out)])
return' :: a -> Parser a
return' v = \inp -> [(v, inp)]
p' :: Parser (Char, Char)
p' = do
x <- item
item
y <- item
return' (x, y)
main = print (p' "123")
代码包含我从给定的演示代码Parsing.hs复制的许多代码,以及与幻灯片相同的p'
函数
运行此代码会导致错误
4.hs:63:15: error:
? Couldn't match expected type ‘[Char] -> a0’
with actual type ‘Parser (Char, Char)’
? The function ‘p'’ is applied to one argument,
but its type ‘Parser (Char, Char)’ has none
In the first argument of ‘print’, namely ‘(p' "123")’
In the expression: print (p' "123")
这个类型似乎有些不对劲,我试过
main = print (item "123")
既没有奏效
但是,当我只删除Parser
的定义时,将其替换为上一张幻灯片中提到的定义
type Parser a = String -> [(a, String)]
item :: Parser Char
item = \inp -> case inp of
[] -> []
(x:xs) -> [(x,xs)]
return' :: a -> Parser a
return' v = \inp -> [(v, inp)]
main = print (item "123")
它只与输出[('1',"23")]
一起工作,我在这里感到困惑。
答案 0 :(得分:0)
newtype
需要构造函数,type
不需要。如果我们想要type
替换newtype
,我们需要在P
类型的任何用法中添加构造函数Parser
;为了解决Parser
问题,我们实施了parse
。
从第二个示例代码开始,我们将获得
newtype Parser a = P (String -> [(a, String)])
parse :: Parser a -> String -> [(a,String)]
parse (P p) inp = p inp
item :: Parser Char
item = P (\inp -> case inp of
[] -> []
(x:xs) -> [(x,xs)])
main = print (parse item "12345")
现在让我们实现您的特殊解析器p
。为了使用do
,我们实现了Monad实例。
我们添加到我们的代码中:
instance Monad Parser where
-- (>>=) :: Parser a -> (a -> Parser b) -> Parser b
p >>= f = P (\inp -> case parse p inp of
[] -> []
[(v,out)] -> parse (f v) out)
-- return :: a -> Parser a
return v = P (\inp -> [(v, inp)])
p :: Parser (Char, Char)
p = do
x <- item
item
y <- item
return (x, y)
我们的main
命令变为:
main = print (parse p "12345")
在我看来,ghc中的错误信息相当广泛,但必须仔细阅读;一个人也必须非常小心使用数据类型。