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
repeattakes&body bodyand expands into adotimesaround it.gensymsupplies a fresh counter name so the expansion cannot capture a caller's variable.- Backquote quotes the template,
,timesdrops in one value, and,@bodysplices the forms.
Keywords and builtins used here
declaredefmacrodefvardotimesformatgensymignorableincflet
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.
Step 2 of 3 in Format & macros, step 23 of 27 in Language basics.