Parsec
document says the following about <|>
This combinator implements choice. The parser p <|> q first applies p. If it succeeds, the value of p is returned. If p fails without consuming any input, parser q is tried. This combinator is defined equal to the mplus member of the MonadPlus class and the (Control.Applicative.<|>) member of Control.Applicative.Alternative.
How to implement back-tracking version of <|>
? It backtracks when p
consumes any-input such the q
can be applied to full input again.
To enable backtracking, you simply need to use try
, e.g. try p <|> q
.
However, note that excessive use of try
can hurt the performance of your parser. Consider left factoring your grammar instead to eliminate common prefixes where possible.