सामग्री पर जाएँ

लेसन 24 · Macros

Macro Patterns: with- Macros, Loops and Control Flow

Learn the macro patterns used in real Common Lisp code: with- cleanup macros, while and do- loops, anaphoric macros, defining DSL forms and when to prefer functions.

After you can write a macro, the next skill is recognizing the handful of shapes that cover most macros in real programs. This lesson tours them: cleanup wrappers, custom loops, small control structures and definition macros.

Lisp snippets are read-only (no Common Lisp runtime on this site). The JavaScript examples are stand-ins that model each pattern; they are labelled as such.

Pattern 1: with- macros (set up, run, clean up)

A with- macro acquires a resource, runs your body, and always releases it. The standard with-open-file is the model:

LISP
(with-open-file (in "data.txt")
  (read-line in))

It expands to roughly an open, an unwind-protect around the body and a close. Here is your own version for a lock-like resource:

LISP
(defmacro with-resource ((var open-form) &body body)
  `(let ((,var ,open-form))
     (unwind-protect (progn ,@body)
       (release ,var))))

unwind-protect runs its cleanup forms even if the body signals an error or exits non-locally, which is why the pattern belongs in a macro: callers cannot forget it. A function could not do this nicely, because the body would have to be wrapped in a lambda by every caller.

JS Stand-in: with- pattern using try/finally

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

No output.

The macro version in Lisp has no lambda at the call site; the stand-in shows the same guarantee: cleanup runs on success and on error.

Pattern 2: your own loops

loop and dolist are macros, so you can add iteration constructs. A while loop:

LISP
(defmacro while (test &body body)
  `(loop (unless ,test (return))
         ,@body))

(let ((n 0))
  (while (< n 3)
    (print n)
    (incf n)))      ; prints 0 1 2

This uses plain loop (no keywords), the simple infinite loop whose body is forms, with return exiting. A do- macro that binds a variable:

LISP
(defmacro do-range ((var from to) &body body)
  (let ((limit (gensym "LIMIT")))
    `(let ((,limit ,to))
       (do ((,var ,from (1+ ,var)))
           ((>= ,var ,limit))
         ,@body))))

(do-range (i 1 4) (print i))   ; prints 1 2 3

The gensym for limit follows the previous lesson: to is evaluated exactly once.

JS Stand-in: expanding while and do-range

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

No output.

Pattern 3: small control structures

Macros are how you add if-like syntax. Three examples:

LISP
(defmacro my-unless (test &body body)
  `(if ,test nil (progn ,@body)))

(defmacro aif (test then &optional else)       ; anaphoric: binds IT
  `(let ((it ,test))
     (if it ,then ,else)))

(aif (gethash :k table)
     (format t "found ~a~%" it)
     (format t "missing~%"))

aif deliberately captures it; that is the point. Anaphoric macros are a controversial style: they are short but the capture is invisible at the call site. Use them sparingly and document them. Contrast with the standard when-let style from the Alexandria library, which names the variable explicitly:

LISP
(alexandria:when-let ((v (gethash :k table)))
  (format t "found ~a~%" v))

Pattern 4: definition macros

A defmacro can generate defun, defvar, defclass or a table entry. Typical uses are registries and command tables:

LISP
(defvar *commands* (make-hash-table :test 'equal))

(defmacro define-command (name (&rest args) &body body)
  `(setf (gethash ,(string-downcase (symbol-name name)) *commands*)
         (lambda ,args ,@body)))

(define-command greet (who)
  (format t "Hello, ~a!~%" who))

(funcall (gethash "greet" *commands*) "Ada")   ; prints Hello, Ada!

The user writes a clean declarative form; the macro hides the table. This is the beginning of a domain-specific language (DSL), a topic the project lessons use.

JS Stand-in: define-command registry

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

No output.

Pattern 5: choosing function or macro again

Before writing a macro, try the function plus lambda alternative. If callers do not mind writing (lambda () ...), a function is simpler, composable and debuggable:

LISP
(defun call-with-resource (open-fn body-fn)
  (let ((r (funcall open-fn)))
    (unwind-protect (funcall body-fn r)
      (release r))))

(defmacro with-resource ((var open-form) &body body)
  `(call-with-resource (lambda () ,open-form) (lambda (,var) ,@body)))

This two-layer style, a function call-with-... plus a thin macro with-..., is idiomatic Common Lisp: the function can be passed to mapcar or redefined while the macro supplies pleasant syntax. Redefining the function updates all callers immediately, because the macro only expanded into a call.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why do with- macros use unwind-protect?

    unwind-protect runs its cleanup forms however control leaves the protected form.
  2. 2. What is deliberate about aif?

    Anaphoric macros intentionally capture a name. It is convenient but hidden at the call site, so use sparingly.
  3. 3. What is the benefit of a function call-with-x plus a thin macro with-x?

    Logic lives in a function that is easier to debug and pass around; the macro just removes lambda noise.
  4. 4. In do-range, why is the upper bound bound to a gensym variable?

    Binding once avoids repeated evaluation each iteration, and the uninterned name avoids capture.

Summary

  • with- macros wrap a body in setup and unwind-protect cleanup.
  • Custom loops (while, do-range) are short macros over loop or do.
  • Anaphoric macros capture a name on purpose; use them sparingly and explicitly.
  • Definition macros generate functions or registry entries and are the root of DSLs.
  • Prefer a call-with-... function plus a thin macro; stand-ins above are JavaScript models, not real Lisp.

Next: Reader Macros, Compiler Macros and macrolet

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।