Parsec <|> choice in parser, Error throws but does not go to next parser

本秂侑毒 提交于 2019-12-02 02:15:45

From the documentation for <|>:

The parser is called predictive since q is only tried when parser p didn't consume any input (i.e.. the look ahead is 1).

In your case both the parses consume "#\\" before failing, so the other alternative can't be evaluated. You can use try to ensure backtracking works as expected:

The parser try p behaves like parser p, except that it pretends that it hasn't consumed any input when an error occurs.

Something like the next:

try parseSpecialCharNotation <|> parseSingleChar

Side note: is it better to extract "#\\" out of the parsers because otherwise you are doing the same work twice. Something like the next:

do
  string "#\\"
  try parseSpecialCharNotation <|> parseSingleChar

Also, you can use string combinator instead of a series of char parsers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!