我是 Parsec 的新手(以及一般的解析器),我在写这个解析器时遇到了一些问题:
list = char '(' *> many (spaces *> some letter) <* spaces <* char ')'
这个想法是以这种格式解析列表(我正在处理 s-expressions):
(firstElement secondElement thirdElement and so on)
我写了这段代码来测试它:
import Control.Applicative
import Text.ParserCombinators.Parsec hiding (many)
list = char '(' *> many (spaces *> some letter) <* spaces <* char ')'
test s = do
putStrLn $ "Testing " ++ show s ++ ":"
parseTest list s
putStrLn ""
main = do
test "()"
test "(hello)"
test "(hello world)"
test "( hello world)"
test "(hello world )"
test "( )"
这是我得到的输出:
Testing "()":
[]
Testing "(hello)":
["hello"]
Testing "(hello world)":
["hello","world"]
Testing "( hello world)":
["hello","world"]
Testing "(hello world )":
parse error at (line 1, column 14):
unexpected ")"
expecting space or letter
Testing "( )":
parse error at (line 1, column 3):
unexpected ")"
expecting space or letter
如您所见,当列表的最后一个元素和结束的)
. spaces
我不明白为什么我之前放入的空白没有消耗<* char ')'
。我犯了什么愚蠢的错误?