Kawa pattern-matching macro

[ Jocelyn Ireson-Paine's Home Page | Free software | Publications ]

This is a simple but elegant pattern match macro. It works like case, but allows you to match against patterns. These can destructure lists and pairs by binding their elements to variables, and can also contain tests against literals, type tests, and calls to arbitrary predicates in the patterns. The matcher should be easy to extend: it works by converting patterns into boolean functions which may, as a side effect, bind variables declared in the patterns.

Here's an example, defining a function test-match which calls the macro:

(define (test-match E)
  (match E
    ( (= 1)
        "The number 1"
    )
    ( (or (= 2) (= 3))
        "The number 2 or 3"
    )
    ( (and (type <int>) (test > 100))
        "A number greater than 100"
    )
    ( (and (type <int>) (test > 20) (test < 30))
        "A number greater than 20 and less than 30"
    )
    ( (list (= 'a) (?? t))
        (format "A list starting with the symbol 'a: ... ~s" t)
    )
    ( (list (or (= 'b) (= 'b)) (?? t))
        (format "A list starting with the symbols 'b or 'c: ... ~s" t)
    )
    ( (list (? h) (? h2) (?? t))
        (format "A list of at least 2 elements: ~s ~s ~s" h h2 t)
    )
    ( (cons (? a) (? b))
        (format "A cons: ~s ~s" a b)
    )
  )
)

The macros are here, as a plain text file. If you prefer them in a zip file, it's here

22nd May 2002

[ Jocelyn Ireson-Paine's Home Page | Free software | Publications ]