[Haskell-beginners] Parsec, comma sperated list with special last element

Karl Voelker ktvoelker at gmail.com
Mon Dec 17 07:45:41 CET 2012


On Sun, Dec 16, 2012 at 8:55 AM, Nathan Hüsken <nathan.huesken at posteo.de>wrote:

> I am assuming this is because the lastCell is comsumed by a "cell" parser.
>

Yes. Parsec does not backtrack automatically, which means once the cell
parser has consumed the input that you were hoping would be consumed by
lastCell, your program is never going to go back and reconsider that part
of the input, even if doing so is the only way to make the file parser
succeed.


> lastCell and cell look pretty similar, so the cell parser can does not
> fail when presented the <lastCell>.
>
> Can I still do this with "endBy" or is there a better combinator?
>

Using endBy is not the problem. There are many different solutions:

1. Factor out the common prefix of cell and lastCell, and restructure the
file parser to avoid committing to either cell or lastCell until the next
input symbol is one which definitively identifies which alternative the
parser is looking at.

2. Replace cell and lastCell with a single parser that matches either one.
Parse out a list of cellOrLastCell results and then do some post-processing
to treat the last one specially.

3. Use the "try" combinator. You apply this combinator to a parser, and get
back a parser which consumes no input if it fails. When using this
combinator, you should consider whether this will have an unacceptable
impact on the performance of your parser. (Performance is one of the
reasons Parsec does not just backtrack automatically.)

-Karl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20121216/98980271/attachment-0001.htm>


More information about the Beginners mailing list