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

Matthias Fischmann fis at wiwi.hu-berlin.de
Mon Jul 31 04:59:14 EDT 2006



On Mon, Jul 31, 2006 at 09:04:32AM +0200, Stephane Bortzmeyer wrote:
> 
> minilang = do
>        char 'a'
>        try (optional (do {comma ; char 'b'}))
>        optional (do {comma ; char 'c'})
>        eof
>        return "OK"
> 
> 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?

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


The (return 'x') is needed for type consistency.  The (try) combinator
doesn't spare you the error, it merely resets the cursor on the input
stream.  To catch the parse error, you need to name a throwaway
alternative.

cheers,
matthias



-- 
Institute of Information Systems, Humboldt-Universitaet zu Berlin

web:      http://www.wiwi.hu-berlin.de/~fis/
e-mail:   fis at wiwi.hu-berlin.de
tel:      +49 30 2093-5742
fax:      +49 30 2093-5741
office:   Spandauer Strasse 1, R.324, 10178 Berlin, Germany
pgp:      AD67 CF64 7BB4 3B9A 6F25  0996 4D73 F1FD 8D32 9BAA
-------------- 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/f5068ca0/attachment.bin


More information about the Haskell-Cafe mailing list