Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Macros and Languages

Syntax-rules Macros

Write pattern-based macros with define-syntax-rule and syntax-rules: patterns, templates, ellipses, literals, recursive macros, and a JavaScript pattern-expander stand-in.

A macro is a function that runs at compile time. It receives a piece of code, rewrites it, and the compiler then compiles the result. Macros let you add new control structures (unless, my-while, for/sum) to the language without changing the compiler. In Scheme and Racket the simplest way to write one is pattern matching: you give a pattern for the code you want to recognize and a template for what to produce.

This lesson covers define-syntax-rule (Racket) and syntax-rules (standard Scheme), ellipses, literals and recursive macros. You should be comfortable with quasiquote and code as data; the idea is similar, but the matching and substitution are done for you.

Macro code runs in the Racket or Scheme expander, which our site does not have. The Racket code here is read-only. The runnable block is a JavaScript stand-in that matches and expands patterns on nested arrays.

define-syntax-rule

The shortest form defines a macro with one pattern:

RACKET
(define-syntax-rule (swap! a b)
  (let ([tmp a])
    (set! a b)
    (set! b tmp)))

(define x 1)
(define y 2)
(swap! x y)
(list x y) ; => '(2 1)

(swap! a b) is the pattern: swap! is the keyword, a and b are pattern variables that match any expression. The second part is the template. Wherever a or b appears there, the code the user wrote is pasted in. A function could not do this, because set! must see the variable names, not their values. Macros operate on code before it runs, so they can control when and whether arguments are evaluated.

A classic example is my-unless, which must not evaluate its body when the test is true. As a function, both arguments would be evaluated first:

RACKET
(define-syntax-rule (my-unless test body ...)
  (if test (void) (begin body ...)))

Ellipses: repetition

The ... after a pattern variable means "zero or more of these". In the template, body ... pastes every matched expression. Pattern variables followed by ... in the pattern must be followed by ... in the template.

RACKET
(define-syntax-rule (my-or2 e ...)
  (list e ...))

(my-or2 1 2 3)  ; => '(1 2 3)

Ellipses can be nested for lists of lists:

RACKET
(define-syntax-rule (my-let ([name val] ...) body ...)
  ((lambda (name ...) body ...) val ...))

(my-let ([a 1] [b 2]) (+ a b))  ; => 3

Here each [name val] pair is matched, then name ... and val ... are expanded separately into the lambda parameters and the arguments. This reimplements let using lambda, which is exactly how let can be defined.

Several rules and literals

Standard Scheme's syntax-rules (also in Racket) lets you list several pattern/template clauses, tried in order. Literals are keywords that must appear verbatim, such as else:

RACKET
(define-syntax my-cond
  (syntax-rules (else)
    [(_ [else result]) result]
    [(_ [test result] clause ...)
     (if test result (my-cond clause ...))]))

(my-cond [(> 1 2) 'a]
         [(< 1 2) 'b]
         [else 'c])   ; => 'b

Recursion works because the macro's output can contain another use of the same macro, which is then expanded in turn. The first clause stops the recursion. The _ stands for the macro keyword and is ignored in the pattern.

flowchart TD
  A["(my-cond [t1 r1] [t2 r2] [else r3])"] --> B["(if t1 r1 (my-cond [t2 r2] [else r3]))"]
  B --> C["(if t1 r1 (if t2 r2 (my-cond [else r3])))"]
  C --> D["(if t1 r1 (if t2 r2 r3))"]

Each expansion step peels off one clause until only else remains.

A stand-in expander

The block below implements the core of pattern-based expansion in JavaScript on nested arrays. A pattern variable is a string starting with ?; the last element of a list pattern can be ["?x", "..."]-style repetition (here written "?x..."). It is a simplified model, but the matching, binding and substitution steps are the same as in a real expander.

JS Stand-in: a tiny pattern-based macro expander

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that expand is called again on the result, so one macro can produce uses of another. That is the same fixed-point loop the real expander performs.

When to use macros

Use a macro when a function cannot do the job: controlling evaluation (my-unless), binding new names (my-let), or defining new syntax (for/sum). Prefer functions otherwise, because they can be passed around and are easier to debug. Macros cannot be passed to map: (map my-unless ...) is a syntax error. A good rule: write a function first; reach for a macro only when evaluation order or binding forces it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can't swap! be an ordinary function?

    A function gets copies of values. A macro gets the code (the variable names), so it can generate set! forms that change them.
  2. 2. What does the ellipsis body ... mean in a pattern?

    ... repeats the preceding pattern element for any number of matches.
  3. 3. In (syntax-rules (else) ...), what is else?

    Names in the literals list are matched exactly instead of binding to anything.
  4. 4. How does a recursive macro stop expanding?

    The expander keeps rewriting until no macro use remains; the base-case clause produces output without another use.

Summary

  • A macro rewrites code at compile time; define-syntax-rule handles the one-pattern case.
  • Pattern variables bind code, not values, so macros control evaluation and binding.
  • ... matches repetition; literals match exact keywords; multiple clauses are tried in order.
  • Macros can expand into uses of other macros, including themselves.
  • Prefer functions unless evaluation order or new binding forms require a macro.

Next: Hygiene and syntax-case