我正在尝试编写一个简单的Parser,所以所有的声明都列在下面的图片中,但是当我尝试编译这个模块时它会失败。 我正在按照此来源提供的教程进行操作 - > Haskell lessons suggested by official site,特别是Erik Meijer博士(Lesson on Parser with "do" construct)的视频。
问题在于我认为“do”构造能够以递减的方式“连接”前一个函数的输出,但是这个p函数的工作方式对我来说似乎很神奇。什么是正确的实施?
-- Generic Parser.
type Parser a = String -> [(a, String)]
-- A simple Parser that captures the first char of the string, puts it in
-- the first position of the couple and then puts the rest of the string into
-- the second place of the couple inside the singleton list.
item :: Parser Char
item = \inp -> case inp of
[] -> []
(x:xs) -> [(x, xs)]
-- Simple parser that always fails.
failure :: Parser a
failure = \inp -> []
-- Returns the type of the parser without operating on the input.
return1 :: a -> Parser a
return1 v = \inp -> [(v, inp)]
-- Explicit call to parse.
parse :: Parser a -> String -> [(a, String)]
parse p inp = p inp
-- Some kind of "or" operator that if the first parser fails (returning an empty list) it
-- parses the second parser.
(+++) :: Parser a -> Parser a -> Parser a
p +++ q = \inp -> case p inp of
[] -> parse q inp
[(v, out)] -> [(v, out)]
-- The function within I'm having troubles.
p :: Parser (Char,Char)
p = do
x <- item
item
y <- item
return1 (x, y)
答案 0 :(得分:4)
您的Parser
只是函数的类型同义词。您在使用中看到的友好解析器都是自己的正确类型,包括Functor
和Applicative
个实例,以及(在大多数情况下)Alternative
,{{1} }和Monad
个实例。您可能需要看起来像以下(未经测试,从未编译过)的版本。
MonadPlus