This is the mail archive of the kawa@sources.redhat.com mailing list for the Kawa project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Here's a pattern matching macro (was Re: Spec of syntax-case)


I've put a pattern-matching macro up at
http://www.ifs.org.uk/~popx/match.html . It's a bit like the one Marco
Vezzoli posted on 13 May (for which, thanks, Marco!), but allows you not
only to destructure lists into their components and bind these to
variables, but also to write tests against literals, type tests, and calls
to arbitrary predicates in the patterns. Though I say it myself, I think
it's quite elegant: it works by converting patterns into boolean
functions, which may, as a side effect, bind the pattern variables. It
ought to be fairly easy to extend.

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)
        ; Binds t to the tail of the list.
    )
    ( (list (or (= 'b) (= 'c)) (?? 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)
        ; Binds h and h2 to the first two elements, and t to the
        ; remainder.
    )
    ( (cons (? a) (? b))
        (format "A cons: ~s ~s" a b)
    )
  )
)

I did this only using syntax-rules. The notation isn't as compact as I'd
like: I'd prefer to be able to write <TYPE> in place of (type <TYPE>),
CONSTANT in place of (= CONSTANT), and VARIABLE in place of (? VARIABLE).  
But these need syntax-case, so that the macro can test what kind of an
expression a pattern is, and as discussed in earlier postings, that isn't
working.

Jocelyn Paine
http://www.ifs.org.uk/~popx/
+44 (0)7768 534 091 



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]