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

Udo Stenzel u.stenzel at web.de
Tue Aug 29 12:24:10 EDT 2006

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.

infixr 2 <:>
(<:>) = ap . ap (return (:))

countBetween 0 0 _ = return []
countBetween 0 n p = p <:> countBetween   0   (n-1) p <|> return []
countBetween m n p = p <:> countBetween (m-1) (n-1) p

(Shortest solution yet, I think.  Is primitive recursion somehow out of
fashion?  Should I rewrite it as two folds?)

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

As requested, though I believe a quick 'liftM2' would have been easier
than two 'ap's.  But if you prefer:

a <:> b = do x <- a
             y <- b
             return (a:b)

or what I'd ordinarily use:

(<:>) = liftM2 (:)

As Will Rogers would have said, "There is no such thing as a free
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20060829/c7baf158/attachment.bin

More information about the Haskell-Cafe mailing list