typestar

defmacro in Lisp

A macro rewrites source into other source before any of it is evaluated.

;; A macro rewrites source before evaluation; backquote builds the new form.

(defmacro repeat (times &body body)
  "Evaluate BODY TIMES times and return nil."
  (let ((counter (gensym "COUNT")))
    `(dotimes (,counter ,times)
       (declare (ignorable ,counter))
       ,@body)))

(defvar *ticks* 0)

(repeat 3
  (incf *ticks*)
  (format t "tick ~d~%" *ticks*))

(format t "expansion: ~s~%" (macroexpand-1 '(repeat 2 (chime))))

How it works

  1. repeat takes &body body and expands into a dotimes around it.
  2. gensym supplies a fresh counter name so the expansion cannot capture a caller's variable.
  3. Backquote quotes the template, ,times drops in one value, and ,@body splices the forms.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
404
Tokens
78
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 2 of 3 in Format & macros, step 23 of 27 in Language basics.

← Previous Next →