[Haskell-cafe] [Parsec] Backtracking with try does not work for me?

Udo Stenzel u.stenzel at web.de
Mon Jul 31 06:57:04 EDT 2006


Stephane Bortzmeyer wrote:
> 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?

Because 'try' can only help you if its argument fails.  If the argument to
'try' succeeds, then it behaves as if it wasn't there.  Now 'optional x'
always succeeds, so the 'try' is useless where you placed it.  You need
to 'try' the argument to 'optional':

> minilang = do
>        char 'a'
>        optional (try (do {comma ; char 'b'}))
>        optional (do {comma ; char 'c'})
>        eof
>        return "OK"

You could also factor your grammar or use ReadP, where backtracking is not
an issue.


Udo.
-- 
Ours is a world where people don't know what they want and are willing
to go through hell to get it. -- Don Marquis
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20060731/ae68a4e8/attachment-0001.bin


More information about the Haskell-Cafe mailing list