Monday, March 07, 2005

Pattern Matching Macros

If I were to teach macros, I would want to separate some of the pieces and introduce them one at a time. Consequently, I think syntax-rules would not be the best way to start. I think the first conceptual hurdle is understanding the phase distinction, and learning to read a program that contains embedded meta-programming. But pattern matching is a whole different topic, and one that people may not be familiar with. For ML and Haskell programmers, it might be no problem. But I remember being terrified by those mysterious ellipses when I first saw Scheme macros.

I might even start with defmacro, except I'm not sure how I feel about starting people with a broken macro system. At any rate, I'd want a system that simply allowed the novice to get used to metaprogramming without having to learn pattern matching at the same time.

But pattern matching has a clear software engineering advantage: it's more abstract than explicit selectors. When an expression contains 5 subexpressions, and you add another one at the beginning, you have to change every single selector for all subsequent subexpressions; with pattern matching, by giving names to the subexpressions and referring to them by name from then on, only the matching code needs to be changed. In other words, patterns are abstract with respect to the positions of their elements.

This reminds me of one of my favorite properties of abstraction. Traditionally people talk about being able to change the implementation without affecting the clients. But another way to put this is making software more amenable to change. The more abstract your code, the greater your ability to refactor.

1 comment:

Leon Smith said...

As an SML and Haskell programmer, "" first thing I hunted down when I first played with Scheme.

Why do you think that pattern matching is pedagogically difficult?