[plt-scheme] tree regular expression matcher availability?

From: Eli Barzilay (eli at barzilay.org)
Date: Sat Mar 22 22:13:29 EDT 2008

On Mar 22, Charles Duffy wrote:
> Howdy, all.
> 
> I'm trying to use match for processing some data structures with
> optional elements, nested sublists (some of which have additional
> nested sublists in turn), and am finding it somewhat unwieldy --
> handling cases where zero-or-one matches are allowed, for instance,
> seems surprisingly complex.

You can always use an arbitrary predicate:

  (define (length-between lo hi)
    (lambda (l)
      (and (list? l) (<= lo (length l) hi))))
  (match '((1) () (2))
    [(list (? (length-between 0 1)) ...) "ok"])

To grab the result, use an `and' pattern:

  (match '((1) () (2))
    [(list (and (? (length-between 0 1)) x) ...) x])

but the `?' thing allows more patterns to be `and'ed:

  (match '((1) () (2))
    [(list (? (length-between 0 1) x) ...) x])

And finally, you can tie it all up with a match extension:

  (define-match-expander list-between
    (syntax-rules ()
      [(list-between lo hi id) (? (length-between lo hi) id)]))
  (match '((1) () (2)) [(list (list-between 0 1 x) ...) x])

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!


Posted on the users mailing list.