The other day I had a realization that suddenly made syntax-case seem a lot less magic.
All the tutorials, papers and documentation I had read about syntax-case only showed examples where syntax-case evaluated immediately to a syntax object, and it was always embedded inside with-syntax or define-syntax or some other thing that ended in "-syntax". They never showed any examples like this one:
(define (is-nil? stx)
(syntax-case stx ()
(() #t)
(_ #f)))
This example defines a function that takes a syntax object and returns a boolean indicating whether or not the syntax object is the empty list. Note that the return value of this function is not a syntax object. Note also that is-nil? is defined using regular old define, not define-syntax. It doesn't even have to be called at expand time. For example, (is-nil? (syntax ()) returns #t, and (is-nil? (syntax 1)) returns #f.
The point is that syntax-case is nothing more than a way to destructure syntax objects, just like the case statement in haskell. Until I realized this, I had thought that there was some weird requirement that it only be used to define "syntax transformers" (which is just a concise way of saying "a function that takes a syntax object and produces a syntax object"). I also wondered whether there was some weird requirement that meant syntax-case could only be used at expand time, or could only be used inside a define-syntax form. Neither of these restrictions is necessary.
Anyway, there's my my little addition to the global knowledge web. Hopefully it will help someone else see through the aura of macro magic to realize that syntax-objects are really just an abstract data type and syntax-case is just a destructuring form.
Posted on May 28, 2006 10:34 AM
More languages articles
Intriguing. What is syntax-case?
Posted by: John Bachir at May 28, 2006 12:08 PMsyntax-case is a more powerful version of syntax-rules. syntax-rules is an essential part of Scheme's hygienic macro facility. If you're only mildly curious, you might try reading Syntax-rules Primer for the Merely Eccentric or Introduction to the art of metaprogramming. If you're really curious, the definitive source is Syntactic Abstraction in Scheme.
Posted by: Kim at May 29, 2006 11:24 AM