fail "illegal" -6ren">
gpt4 book ai didi

haskell - 秒差距负匹配

转载 作者:行者123 更新时间:2023-12-01 12:08:21 25 4
gpt4 key购买 nike

parseIdent :: Parser (String)
parseIdent = do
x <- lookAhead $ try $ many1 (choice [alphaNum])
void $ optional endOfLine <|> eof
case x of
"macro" -> fail "illegal"
_ -> pure x

我正在尝试解析一个字母数字字符串,该字符串只有在不匹配预定值(在本例中为 macro)时才会成功。


但是以下是给我一个错误:

*** Exception: Text.ParserCombinators.Parsec.Prim.many: combinator 'many' is applied to a parser that accepts an empty string.

哪个没有意义,many1(choice [alphaNum])如何接受一个空字符串?


如果我删除 lookAhead $ try,这个错误就会消失。但它因非法而“失败”:

...
*** Exception: (line 6, column 36):
unexpected " "
expecting letter or digit or new-line
illegal

我的做法是否正确?还是有另一种技术来实现否定搜索?

最佳答案

你几乎拥有它:

import Text.Parsec
import Text.Parsec.Char
import Text.Parsec.String
import Control.Monad

parseIdent :: Parser (String)
parseIdent = try $ do
x <- many1 alphaNum
void $ optional endOfLine <|> eof
case x of
"macro" -> fail "illegal"
_ -> pure x

那么,为什么您的代码不起作用?

  • try 在错误的位置。此处真正的回溯部分是在您取回字母数字词检查它不是“macro”
  • 后回溯
  • lookAhead 与此无关。如果您最终得到了您想要的词,您确实希望从输入中使用该词。 try 已经负责将您的输入流重置为之前的状态

关于haskell - 秒差距负匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54379342/

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