gpt4 book ai didi

haskell - 很难让 Parsec 解析器正确跳过空格

转载 作者:行者123 更新时间:2023-12-04 13:23:30 27 4
gpt4 key购买 nike

我是 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 ')' 之前输入了.我犯了什么愚蠢的错误?

最佳答案

问题是最终的空间被 spaces 所消耗。在 many 的参数中,

list = char '(' *> many (spaces *> some letter) <* spaces <* char ')'
-- ^^^^^^ that one

然后解析器期望 some letter但找到一个右括号,因此失败。

为了解决这个问题,只在 token 之后使用空格,
list = char '(' *> spaces *> many (some letter <* spaces) <* char ')'

根据需要工作:
$ runghc lisplists.hs 
Testing "()":
[]

Testing "(hello)":
["hello"]

Testing "(hello world)":
["hello","world"]

Testing "( hello world)":
["hello","world"]

Testing "(hello world )":
["hello","world"]

Testing "( )":
[]

关于haskell - 很难让 Parsec 解析器正确跳过空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16047626/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com