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

Nathan Hüsken nathan.huesken at posteo.de
Mon Dec 17 11:28:22 CET 2012


On 12/17/2012 07:45 AM, Karl Voelker wrote:
(...)
> 
> 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.)

Ok, I would choose 3 because performance is not the issue and it seems
to be the most simple.
Still ... I can not do it with "endBy", can I? Do it so:

file = do
  res <- many $ try (do {c <- cell; char ','; return c})
  l   <- lastCell
  eof
  return res

cell = many1 (noneOf ",")
lastCell = many1 (noneOf "\n")

works. But I wonder if I also could have used a clearer combinator from
parsec.

Regards,
Nathan



More information about the Beginners mailing list