common-lisp Anaphoric Macros


An Anaphoric Macro is a macro that introduces a variable (often IT) that captures the result of a user-supplied form. A common example is the Anaphoric If, which is like a regular IF, but also defines the variable IT to refer to the result of the test-form.

(defmacro aif (test-form then-form &optional else-form)
  `(let ((it ,test-form))
     (if it ,then-form ,else-form)))

(defun test (property plist)
  (aif (getf plist property)
       (format t "The value of ~s is ~a.~%" property it)
       (format t "~s wasn't in ~s!~%" property plist)))

(test :a '(:a 10 :b 20 :c 30))
; The value of :A is 10.
(test :d '(:a 10 :b 20 :c 30))
; :D wasn't in (:A 10 :B 20 :C 30)!