2

我正在尝试使用megaparsec.

其中一部分是由分隔符分隔的字符串的重复,我正在使用sepBy它。考虑例如

sepBy (char 'a') (char 's')

这可以正确解析,,,,""..."a"如果"asa"我需要继续使用另一个以我的分隔符开头的解析器进行解析,则会出现问题,如

(,) <$> sepBy (char 'a') (char 's') <*> string "something"

如果我尝试"asasomething"使用此解析器解析字符串,我希望得到("aa", "something"). 相反,我收到一个错误,因为我没有aafter the second s

我也试过了,sepEndBy但结果是一样的

4

1 回答 1

3

我解决了它如下。

sepByused by的实现megapersec

sepBy :: MonadPlus m => m a -> m sep -> m [a]
sepBy p sep = do
  r <- C.optional p
  case r of
    Nothing -> return []
    Just  x -> (x:) <$> many (sep >> p)

我将其修改为

sepBy :: Parser a -> Parser sep -> Parser [a]
sepBy p sep = do
  r <- optional p
  case r of
    Nothing -> return []
    Just  x -> (x:) <$> many (try $ sep >> p)

对其进行专门化以Parsec添加 atry以避免急切的解析

于 2020-02-14T09:51:36.830 回答