Skip to content

Adding 2 new combinators #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion Text/Parsec/Combinator.hs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

module Text.Parsec.Combinator
( choice
, count
, count, countUpTo, countFromTo
, between
, option, optionMaybe, optional
, skipMany1
Expand Down Expand Up @@ -165,6 +165,22 @@ count :: (Stream s m t) => Int -> ParsecT s u m a -> ParsecT s u m [a]
count n p | n <= 0 = return []
| otherwise = sequence (replicate n p)

-- | @countUpto n p@ parses zero to @n@ occurrences of @p@. If @n@ is smaller or
-- equal to zero, the parser equals to @return []@. Returns a list of up to
-- @n@ values returned by @p@.
countUpTo :: Stream s m t => Int -> ParsecT s u m a -> ParsecT s u m [a]
countUpTo n p
| n <= 0 = return []
| otherwise = option [] (liftM2 (:) p (countUpTo (pred n) p))

-- | @countUpto m n p@ parses @m@ to @n@ occurrences of @p@. If @n@ is smaller or
-- equal to zero, the parser equals to @return []@. Returns a list of @m@ to
-- @n@ values returned by @p@.
countFromTo :: Stream s m t => Int -> Int -> ParsecT s u m a -> ParsecT s u m [a]
countFromTo l r p
| r < l = return []
| otherwise = liftM2 (++) (count l p) (countUpTo (r - l) p)

-- | @chainr p op x@ parses /zero/ or more occurrences of @p@,
-- separated by @op@ Returns a value obtained by a /right/ associative
-- application of all functions returned by @op@ to the values returned
Expand Down