[Haskell-cafe] Attoparsec: Limiting Parsers to N Bytes, or Combing Parsers?

Evan Laforge qdunkan at gmail.com
Sat Sep 24 05:58:00 CEST 2011

> So the question remains: is there a way to limit a parser to a finite chunk
> of input? Perhaps a way to run the 'take n' parser on the input and then run
> another parser on its result? This smells like monadic behavior, but of
> course with different semantics than the Monad instance for Parser.

Oh yeah, well you want to lift the results of the sub-computation into
the current one.  So something like

runSub m input = either throw return $ Attoparsec.parse m input

That's not the right syntax, but you get the idea.  Now you can do:

runSub hexNumber =<< Attoparsec.take 2

I've done stuff like this but with more complicated monads.  You pull
the current state, run the sub-monad then merge its state and results
into the current one.  And this is similar to what ErrorT does in the
'catch' function.

You want to set up the initial state of the sub parser more carefully
of course so you don't get confusing line numbers in error msgs.  And
I imagine it's less efficient than doing the parsing in one go since
you have to deal with stuff twice.

More information about the Haskell-Cafe mailing list