Search code examples
parsinghaskellfunctional-programmingparsec

How to combine many parsers?


Why this parser fails and how to fix it?

λ> str1 = string "elif "
λ> str2 = string "else "
λ> strs = (,) <$> many str1 <*> optionMaybe str2
λ> parse strs "" "elif elif elif else "
Left (line 1, column 16):
unexpected "s"
expecting "elif "

How to combine a many parser and an optionalMaybe parser?


Solution

  • The problem is that string "elif " will eat the el in else, and since it has consumed input it will not backtrack and instead complain about an unexpected s

    The easiest fix is to allow backtracking with try:

    str1 = try $ string "elif "