
I'm trying to write a Parsec parser for a language which authorizes (this is a simplified example) "a" or "a,b,c" or "a,c" or "a,b". (I can change the grammar but not the language.) The first attempt was: ***** CUT HERE **** import Text.ParserCombinators.Parsec import System (getArgs) comma = char ',' minilang = do char 'a' optional (do {comma ; char 'b'}) optional (do {comma ; char 'c'}) eof return "OK" run parser input = case (parse parser "" input) of Left err -> putStr ("parse error at " ++ (show err) ++ "\n") Right x -> putStr (x ++ "\n") main = do args <- getArgs run minilang (head args) ***** CUT HERE **** Of course, it fails for "a,c": parse error at (line 1, column 3): unexpected "c" expecting "b" for a reason explained in Parsec's documentation (the parser "optional (do {comma ; char 'b'})" already consumed the input, do note the column number). What puzzles me is that the solution suggested in Parsec's documentation does not work either: ********* CUT HERE ******************* minilang = do char 'a' try (optional (do {comma ; char 'b'})) optional (do {comma ; char 'c'}) eof return "OK" ********* CUT HERE ******************* parse error at (line 1, column 2): unexpected "c" expecting "b" Apparently, "try" was used (do note that the column number indicates that there was backtracking) but the parser still fails for "a,c". Why?