stchang / parsack

A basic Parsec-like monadic parser combinator library implementation in Racket.
MIT License
50 stars 10 forks source link

"between X and Y occurences of p" #54

Open Arteneko opened 3 years ago

Arteneko commented 3 years ago

I was wondering if there was a clean way to write a parser that would do "between x and y occurrences of p".

Basically, to allow, for example, "between 1 and 5 spaces".

JwanMan commented 1 year ago

If you still need it, I'm using the following:

(define (ntimes p from (to from))
  (cond [(> from 0) (>>= p
                         (λ (x)
                             (>>= (ntimes p (- from 1) (- to 1))
                                  (λ (y)
                                    (return (cons x y))))))]
        [(> to 0) (<any> (>>= p
                              (λ (x)
                                (>>= (ntimes p 0 (- to 1))
                                     (λ (y) (return (cons x y))))))
                         (return '()))]
        [else (return '())]))

Unfortunately, I don't have the time right now to make a proper pull request (with docs and tests and a more generic interface), but I might make one when I do.