[Haskell-cafe] Re: Parsec lookahead and <|>

Job Vranish jvranish at gmail.com
Thu Aug 20 15:34:25 EDT 2009


try works in this case, but it won't if we are using a parser which can
consume and then fail (instead of char 'a'). In which case we may want it to
fail without exploring the second option.

Hmmm though you might be right. Having lookAhead return Consumed is only a
problem if the parser passed to lookAhead succeeds, but the parser following
lookAhead fails without consuming, which seems like a fairly rare case.

Although, it would be a problem for cases where the lookAhead is checking
for a negation.  For example:
parseStuff = (lookAhead parseNotCapital >> identifier) <|> number
wouldn't work if lookAhead returned Consumed on success, and try doesn't
save us either.

Even if returning "Consumed" is the desired behavior I'd still say it at
least deserves a note in the docs.

Martijn, how did you encounter this problem?

- Job


On Thu, Aug 20, 2009 at 2:21 PM, Christian Maeder
<Christian.Maeder at dfki.de>wrote:

> Daniel Fischer wrote:
> > Am Donnerstag 20 August 2009 13:44:15 schrieb Martijn van Steenbergen:
> >> Goedemiddag café,
> >>
> >> Consider the following function, using parsec-3.0.0:
> >>> la :: Parsec String () (Maybe Char)
> >>> la = lookAhead (optionMaybe anyChar)
> >> *Lookahead> parseTest (char 'a' <|> char 'b') "a"
> >> 'a'
> >> *Lookahead> parseTest (char 'a' <|> char 'b') "b"
> >> 'b'
> >> *Lookahead> parseTest (la *> char 'a' <|> char 'b') "a"
> >> 'a'
> >> *Lookahead> parseTest (la *> char 'a' <|> char 'b') "b"
> >> parse error at (line 1, column 2):
> >> unexpected "b"
> >> expecting "a"
> >>
> >> The first three work fine and as expected, but the fourth example fails
> >> where I would expect success. I know <|> won't try the rhs if the lhs
> >> consumed input, but lookAhead's documentation promises not to consume
> >> any input. Is this a bug in Parsec or am I missing something?
> >
> > Bad bug in Parsec (from the beginning, the same happens in parsec-2), I'd
> say.
>
> I'd say, its a feature. lookAhead returns whatever its argument returns.
>  So in this case it returns "Consumed" without consuming.
>
> You can always wrap around a "try" to force the alternative:
>
>  parseTest (try (la >> char 'a') <|> char 'b') "b"
>
> Cheers Christian
>
> Maybe it should have been:
>
>  la >> (char 'a' <|> char 'b')
>
> in the first place.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090820/019ae1e6/attachment.html


More information about the Haskell-Cafe mailing list