News

muvee Reveal - the latest incarnation of muvee's flagship product - has just been released on 11 June 2008! The behaviours of the 8 bundled styles are specified using muSE, in addition to all the styles developed for the now discontinued muvee autoProducer 6.1.

Tuesday, September 12, 2006

Pattern matching bind

muSE uniformly uses pattern matching to bind symbols to values. It is used in fn, case and let expressions - which therefore differ slightly from standard Scheme. Not only was it easier to use the same technique in all three expressions, it has resulted in greater expressive power for let and case, obviating the need to do first, rest and such destructuring operations on lists.

muSE's pattern matching bind can deconstruct lists and match constants such as numbers, strings and symbols. Here's an example using fn and case - Suppose we need to create a function that adds up the pair-wise product of its arguments. i.e -

> (f 1 2 3 4 5 6)
should yield -
1 * 2 + 3 * 4 + 5 * 6
= 45

We can write f like this -


(define f
(fn args
(case args
(() 0)
((x y . etc) (+ (* x y) (apply f etc))))))

Note that args is used by itself without an enclosing parentheses to get the arguments of the function as a list - this itself is a pattern match. Also note that NIL can be notated as () without a quote character.

Similarly, let also allows you to deconstruct lists. Apart from that, the behaviour of let in muSE is similar to let* in Scheme. There are no other kinds of let in muSE because so far this one has been sufficient.

3 comments:

Unknown said...

Can you pattern match types other than lists? e.g. vectors? Does it match literals? Is there a "don't care" wild card such as "_"?

Kumar said...

Pattern matching vectors and such isn't supported. Partly because you can't (or its hard) to notate vectors as recursive types. Same for a hash table. That prevents you from doing a "..and the rest of the structure" kind of match.

It matches literals, though. Strings, numbers and quoted symbols will have to match explicitly. The case construct uses this feature to do a pattern-based branch. For an example, see the literal macro which nearly duplicates the functionality of the backquote notation of scheme and lisp.

Kumar said...

There is no particular wild card symbol, but a symbol in a pattern willmatch anything in its place. And since "_" is itself a symbol, you're free to use it like a wild card :) I do use this convention myself.