Scheme macros with syntax-rules
last modified November 24, 2026 Guile 3.0
A macro extends the syntax of Scheme. Before a program runs, the
macro expander replaces each use of a macro with new code, built from a
template. Macros can do what procedures cannot: they decide which of their
arguments are evaluated, how many times, and in which order, and they can
assign to the variables they are given. This article writes macros with
syntax-rules, the pattern language of the Scheme standard. The
examples run with GNU Guile 3.0.7.
A first macro
define-syntax binds a name to a macro, and
syntax-rules describes the macro as a list of rules. Each rule
has a pattern, which is matched against the use of the macro, and
a template, which is the code that replaces it.
(define-syntax swap!
(syntax-rules ()
((swap! a b)
(let ((tmp a))
(set! a b)
(set! b tmp)))))
(define left "port")
(define right "starboard")
(swap! left right)
(display left)
(newline)
(display right)
(newline)
The pattern (swap! a b) matches a use of the macro with two
arguments, and binds the pattern variables a and
b to the pieces of code found there. In the template, the
pattern variables are replaced by those pieces, so (swap! left
right) becomes a let that saves left and two
set! forms. A procedure could not do this: it receives the
values of its arguments, not the variables, and cannot assign to them. The
empty list after syntax-rules holds the literals, explained
later.
$ guile swap.scm starboard port
Macros and evaluation
The arguments of a procedure are evaluated before the call. The arguments of a macro are pieces of code, and the template decides whether they are evaluated at all. This makes macros the tool for new control structures.
(define (unless-proc test value)
(if test #f value))
(define-syntax my-unless
(syntax-rules ()
((_ test body ...)
(if test #f (begin body ...)))))
(define (loud x)
(display "evaluating ")
(display x)
(newline)
x)
(define stock 0)
(display "procedure:")
(newline)
(unless-proc (= stock 0) (loud "order more"))
(display "macro:")
(newline)
(my-unless (= stock 0) (loud "order more"))
(my-unless (> stock 0) (loud "out of stock"))
unless-proc is a procedure, so its second argument is evaluated
even when the test is true, and the message is printed although the result is
discarded. my-unless is a macro that expands to an
if, so its body runs only when the test is false. The first
element of a pattern is always the macro keyword, and it is commonly written
as _. body ... matches any number of expressions,
which the template wraps in a begin. Guile has a built-in
unless; the macro shows how such forms are
made.
$ guile unless.scm procedure: evaluating order more macro: evaluating out of stock
Several patterns
A macro can have several rules. The expander tries the patterns in order and uses the template of the first one that matches. A template may use the macro itself, so a macro can process its arguments one at a time.
(define-syntax my-or
(syntax-rules ()
((_) #f)
((_ e) e)
((_ e rest ...)
(let ((t e))
(if t t (my-or rest ...))))))
(define-syntax my-and
(syntax-rules ()
((_) #t)
((_ e) e)
((_ e rest ...)
(if e (my-and rest ...) #f))))
(write (my-or))
(newline)
(write (my-or #f (memv 3 (list 1 2 3 4)) (car '())))
(newline)
(write (my-and))
(newline)
(write (my-and 1 2 "three"))
(newline)
(write (my-and (number? 'x) (car '())))
(newline)
my-or handles no arguments, one argument, and more than one. In
the last case it evaluates the first expression once, stores it in
t, and returns it if it is true; otherwise it expands to
my-or of the remaining expressions. my-and works
the other way round. Both stop as soon as the result is known, so
(car '()), which would fail, is never evaluated. The macros
behave like the built-in or and and described in
the booleans and equality article.
$ guile clauses.scm #f (3 4) #t "three" #f
The ellipsis
The ellipsis ... after a pattern element matches zero or more
repetitions of that element. In the template, an element followed by an
ellipsis is repeated once for each match. The repeated element may be a
whole subpattern, such as a (name value) pair.
(define-syntax my-let
(syntax-rules ()
((_ ((name value) ...) body1 body2 ...)
((lambda (name ...) body1 body2 ...) value ...))))
(my-let ((x 3) (y 4))
(display (+ (* x x) (* y y)))
(newline))
(define-syntax show-all
(syntax-rules ()
((_ e ...)
(begin
(begin (write 'e) (display " = ") (write e) (newline))
...))))
(define price 12)
(show-all (* price 3) (string-append "a" "b") (list price 'eur))
(define-syntax pairs
(syntax-rules ()
((_ (key value) ...)
(list (cons 'key value) ...))))
(write (pairs (name "Tomas") (age (+ 30 1)) (city "Kosice")))
(newline)
my-let rebuilds let from lambda: the
pattern ((name value) ...) collects the names and the values into
two sequences, and the template puts the names in a parameter list and the
values in the call. body1 body2 ... requires at least one body
expression. In show-all, a whole begin form is
repeated for each expression; 'e quotes the code itself, so each
line shows an expression next to its value. The quoted symbol
'eur is written in its long form (quote eur).
pairs turns each key into a quoted symbol and builds an
association list.
$ guile ellipsis.scm 25 (* price 3) = 36 (string-append "a" "b") = "ab" (list price (quote eur)) = (12 eur) ((name . "Tomas") (age . 31) (city . "Kosice"))
Literals
The list after syntax-rules names the literals:
identifiers that must appear in the use of the macro exactly as written,
instead of being pattern variables. Literals let a macro have keywords of its
own.
(define-syntax for
(syntax-rules (in from to)
((_ x in lst body ...)
(for-each (lambda (x) body ...) lst))
((_ i from start to end body ...)
(let loop ((i start))
(when (<= i end)
body ...
(loop (+ i 1)))))))
(for c in (list "red" "green" "blue")
(display c)
(display " "))
(newline)
(for i from 1 to 5
(display (* i i))
(display " "))
(newline)
(define words (list "sun" "moon"))
(for w in words
(display (string-upcase w))
(newline))
for has two forms, distinguished by the literals
in, from, and to. The first form
iterates over a list with for-each; the loop variable becomes the
parameter of a lambda that wraps the body. The second form
counts from start to end with a
named let. Without the literals,
in would be a pattern variable and would match anything, and the
first rule would also take the counting form.
$ guile literals.scm red green blue 1 4 9 16 25 SUN MOON
A while loop
Scheme has no while loop in the standard, but one is easy to
write. The macro expands into a named let that tests the
condition, runs the body, and calls itself.
(define-syntax while
(syntax-rules ()
((_ test body ...)
(let loop ()
(when test
body ...
(loop))))))
(define-syntax repeat
(syntax-rules (times)
((_ n times body ...)
(let loop ((k n))
(when (> k 0)
body ...
(loop (- k 1)))))))
(define n 27)
(define steps 0)
(while (not (= n 1))
(set! n (if (even? n) (quotient n 2) (+ (* 3 n) 1)))
(set! steps (+ steps 1)))
(display "steps: ")
(display steps)
(newline)
(repeat 3 times
(display "tick "))
(newline)
(define balance 100)
(while (> balance 30)
(display balance)
(display " ")
(set! balance (- balance 25)))
(newline)
The first loop counts the steps of the Collatz sequence from 27 to 1, and the
second takes amounts off a balance. repeat uses the literal
times only to make its uses read naturally. The recursive call
(loop) is a tail call, so the loops run in constant space. Guile
already has a while form of its own; the definition in the file
replaces it without a warning.
$ guile while.scm steps: 111 tick tick tick 100 75 50
Hygiene
The templates above introduce their own variables, such as tmp
and t. If the expansion simply pasted the text, a user variable
with the same name would clash with them. Macros made with
syntax-rules are hygienic: names introduced by a
template never capture names from the use site, and free names in a template
refer to the bindings visible where the macro was defined.
(define-syntax swap!
(syntax-rules ()
((_ a b)
(let ((tmp a))
(set! a b)
(set! b tmp)))))
(define-syntax my-or
(syntax-rules ()
((_) #f)
((_ e) e)
((_ e rest ...)
(let ((t e))
(if t t (my-or rest ...))))))
(define tmp 1)
(define other 2)
(swap! tmp other)
(write (list tmp other))
(newline)
(define t 5)
(write (my-or #f t))
(newline)
(define-syntax my-unless
(syntax-rules ()
((_ test body ...)
(if test #f (begin body ...)))))
(let ((if list))
(write (my-unless #f 'safe))
(newline)
(write (if 1 2 3))
(newline))
swap! exchanges two variables even when one of them is called
tmp, and (my-or #f t) returns the user's
t, not the internal one. In the last part, if is
locally bound to list. The if in the template of
my-unless still means the real conditional, while
(if 1 2 3) written in the body of the let calls
list. Hygiene lets macros be used anywhere without knowing how
they are written.
$ guile hygiene.scm (2 1) 5 safe (1 2 3)
Looking at the expansion
Guile's macroexpand expands a form and returns it in
Tree-IL, the internal language of the compiler.
tree-il->scheme from the (language tree-il)
module turns it back into readable Scheme.
(use-modules (language tree-il))
(define-syntax swap!
(syntax-rules ()
((_ a b)
(let ((tmp a))
(set! a b)
(set! b tmp)))))
(define-syntax my-unless
(syntax-rules ()
((_ test body ...)
(if test #f (begin body ...)))))
(define (show-expansion form)
(write form)
(display " =>")
(newline)
(display " ")
(write (tree-il->scheme (macroexpand form)))
(newline))
(show-expansion '(swap! x y))
(show-expansion '(let ((tmp 1) (y 2)) (swap! tmp y)))
(show-expansion '(my-unless (null? xs) (display (car xs)) (newline)))
show-expansion prints a quoted form and its expansion. The second
form shows hygiene at work: the expander renamed the tmp of the
template to tmp-1, because the code around it already has a
tmp. The expansion of my-unless shows the
begin created by the template. Expanding a form by hand like this
is the quickest way to find out why a macro does not do what was intended.
The output is Guile's view of the code and may simplify it, so it is a
debugging aid rather than an exact copy of the template.
$ guile expand.scm (swap! x y) => (let ((tmp x)) (set! x y) (set! y tmp)) (let ((tmp 1) (y 2)) (swap! tmp y)) => (let ((tmp 1) (y 2)) (let ((tmp-1 tmp)) (set! tmp y) (set! y tmp-1))) (my-unless (null? xs) (display (car xs)) (newline)) => (if (null? xs) #f (begin (display (car xs)) (newline)))
Recursive macros
A macro that calls itself in its template can transform its input step by step. Many derived forms of Scheme are defined this way in terms of simpler ones.
(define-syntax my-let*
(syntax-rules ()
((_ () body1 body2 ...)
(let () body1 body2 ...))
((_ ((name value) rest ...) body1 body2 ...)
(let ((name value))
(my-let* (rest ...) body1 body2 ...)))))
(my-let* ((width 4)
(height (* width 2))
(area (* width height)))
(display (list width height area))
(newline))
(define-syntax my-cond
(syntax-rules (else)
((_ (else e1 e2 ...))
(begin e1 e2 ...))
((_ (test e1 e2 ...))
(when test e1 e2 ...))
((_ (test e1 e2 ...) clause ...)
(if test
(begin e1 e2 ...)
(my-cond clause ...)))))
(define (grade points)
(my-cond ((>= points 90) 'a)
((>= points 75) 'b)
((>= points 50) 'c)
(else 'f)))
(write (map grade (list 95 80 51 12)))
(newline)
my-let* turns sequential bindings into nested let
forms, one for each binding, so each value can use the names before it. The
empty binding list ends the recursion. my-cond turns a list of
clauses into nested if forms. The literal else
marks the default clause, and a last clause without else uses
when, which returns an unspecified value when its test is false.
$ guile recursive.scm (4 8 32) (a b c f)
A test macro
Macros can see the source code of their arguments, which a procedure never does. A test macro uses this to print the expression that was checked next to the result.
(define-syntax check
(syntax-rules (=>)
((_ expr => expected)
(let ((actual expr))
(if (equal? actual expected)
(begin
(display "ok: ")
(write 'expr)
(newline)
#t)
(begin
(display "FAILED: ")
(write 'expr)
(display " gave ")
(write actual)
(display ", expected ")
(write expected)
(newline)
#f))))))
(define-syntax check-all
(syntax-rules (=>)
((_ (expr => expected) ...)
(let ((results (list (check expr => expected) ...)))
(display (length (filter (lambda (r) r) results)))
(display " of ")
(display (length results))
(display " passed")
(newline)))))
(define (average . xs)
(/ (apply + xs) (length xs)))
(check-all
((average 2 4 6) => 4)
((average 1 2) => 3/2)
((string-upcase "tatra") => "TATRA")
((reverse (list 1 2 3)) => (list 3 2 1))
((average 10) => 1))
check evaluates the expression once, compares the result with
equal?, and writes the quoted expression in its report. The
literal => separates the expression from the expected value
and has no other meaning. check-all expands into a list of
check calls and counts the true results. The last test is wrong
on purpose: the average of the single value 10 is 10.
$ guile check.scm ok: (average 2 4 6) ok: (average 1 2) ok: (string-upcase "tatra") ok: (reverse (list 1 2 3)) FAILED: (average 10) gave 10, expected 1 4 of 5 passed
Source
Syntax-rules — GNU Guile Reference Manual
Revised7 Report on the Algorithmic Language Scheme
In this article we have defined macros with define-syntax and
syntax-rules, compared macros with procedures, written macros
with several patterns, repeated code with the ellipsis, given macros keywords
with literals, built while and for loops, seen how
hygiene keeps names apart, inspected expansions with
macroexpand, written recursive macros, and made a small test
macro. The advanced macros article
continues with syntax-case, and the
quasiquote article builds code from
templates at run time.
Author
List all Scheme tutorials.