An anaphoric macro is a type of programming macro that deliberately captures some form supplied to the macro which may be referred to by an anaphor (an expression referring to another). Anaphoric macros first appeared in Paul Graham's On Lisp and their name is a reference to linguistic anaphora—the use of words as a substitute for preceding words.
Here is an example that sums the value of non-
nil elements, where
it refers to the values of elements that do not equal
(loop for element in '(nil 1 nil 2 nil nil 3 4 6) when element sum it) ;; ⇒ 16
it is bound to the output of
(and (> number 3) number) when true, collecting numbers larger than 3:
(loop for number from 1 to 6 when (and (> number 3) number) collect it) ; IT refers to (and (> number 3) number). ;; ⇒ (4 5 6)
Defining anaphoric macrosEdit
(defmacro aif (test-form then-form &optional else-form) `(let ((it ,test-form)) (if it ,then-form ,else-form))) (aif (+ 2 7) (format nil "~A does not equal NIL." it) (format nil "~A does equal NIL." it)) ;; ⇒ "9 does not equal NIL."
(defmacro alambda (parms &body body) `(labels ((self ,parms ,@body)) #'self)) ;; Factorial function defined recursively where `self' refers to the alambda function (alambda (n) (if (= n 0) 1 (* n (self (1- n)))))
- Chapter 6 of Let over Lambda
- 22. LOOP for Black Belts from Practical Common Lisp
- What would be an example of an anaphoric conditional in Lisp? on StackOverflow
- 184.108.40.206 Examples of clause grouping from the Common Lisp HyperSpec
- Chapter 14. Anaphoric Macros Archived April 26, 2012, at the Wayback Machine of On Lisp by Paul Graham