Ananaphoric macrois a type ofprogramming macrothat deliberately captures some form supplied to the macro which may be referred to by ananaphor(an expression referring to another). Anaphoric macros first appeared inPaul Graham'sOn Lisp[1]and their name is a reference tolinguistic anaphora[1]—the use of words as a substitute for preceding words.

Examples

edit

Theloopmacro inANSI Common Lispis anaphoric in binding, where theitexpression refers to the result of the test expression in a clause.[2][3]

Here is an example that sums the value of non-nilelements, whereitrefers to the values of elements that do not equalnil:

(loopforelementin'(nil1nil2nilnil346)
whenelementsumit)
;; ⇒ 16

Hereitis bound to the output of(and (> number 3) number)when true, collecting numbers larger than 3:[4]

(loopfornumberfrom1to6
when(and(>number3)number)
collectit);IT refers to (and (> number 3) number).
;; ⇒ (4 5 6)

Defining anaphoric macros

edit

One example is an anaphoric version of theif-then-else construct,which introduces ananaphorit,bound to the result of the test clause:[5]

(defmacroaif(test-formthen-form&optionalelse-form)
`(let((it,test-form))
(ifit,then-form,else-form)))

(aif(+27)
(formatnil"~A does not equal NIL."it)
(formatnil"~A does equal NIL."it))
;; ⇒ "9 does not equal NIL."

Another example is an anaphoric version of theλ-function,which binds the function itself to theanaphorself,allowing it torecur:[5]

(defmacroalambda(parms&bodybody)
`(labels((self,parms,@body))
#'self))

;; Factorial function defined recursively where `self' refers to the alambda function
(alambda(n)
(if(=n0)
1
(*n(self(1-n)))))

See also

edit

References

edit
edit