[Haskell-cafe] [Parsec] A combinator to match between M and N times?

Tomasz Zielonka tomasz.zielonka at gmail.com
Tue Aug 29 09:11:09 EDT 2006


On Tue, Aug 29, 2006 at 03:05:39PM +0200, Stephane Bortzmeyer wrote:
> Parsec provides "count n p" to run the parser p exactly n times. I'm
> looking for a combinator "countBetween m n p" which will run the
> parser between m and n times. It does not exist in Parsec.

> Much to my surprise, it seems quite difficult to write it myself and,
> until now, I failed (the best result I had was with the "option"
> combinator, which unfortunately requires a dummy value, returned when
> the parser fails).
 
How about this?

    countBetween m n p = do
        xs <- count m p
        ys <- count (n - m) $ option Nothing $ do
            y <- p
            return (Just y)
        return (xs ++ catMaybes ys)

Assuming n >= m.

> Does anyone has a solution? Preferrably one I can understand, which
> means not yet with liftM :-)

No liftM, as requested :-)

Best regards
Tomasz


More information about the Haskell-Cafe mailing list