haskellHQ
haskellHQ

Reputation: 1047

"count 3" in ReadP parses 3 occurrences. How do I parse between 3 and 8 occurrences?

ReadP has this function:

count :: Int -> ReadP a -> ReadP [a]

-- Usage:
count 3 $ satisfy (== 'c')

I'm wondering if there is a similar function to parse between 3 and 8 occurrences:

count_between 3 8 $ satisfy (== 'c')

If I have to create my own, how would you do that?

Upvotes: 3

Views: 58

Answers (1)

Gurkenglas
Gurkenglas

Reputation: 2317

count_between a b p = (++) <$> count a p <*> count_upto (b - a) p

count_upto 0 _ = pure []
count_upto b p = ((:) <$> p <*> count_upto (b-1) p) +++ pure []

Note the similarity to many. A munching variant would use <++ instead of +++.

Upvotes: 4

Related Questions