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
editTheloop
macro inANSI Common Lispis anaphoric in binding, where theit
expression refers to the result of the test expression in a clause.[2][3]
Here is an example that sums the value of non-nil
elements, whereit
refers to the values of elements that do not equalnil
:
(loopforelementin'(nil1nil2nilnil346)
whenelementsumit)
;; ⇒ 16
Hereit
is 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
editOne 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
editReferences
edit- ^abChapter 6ofLet over Lambda
- ^22. LOOP for Black BeltsfromPractical Common Lisp
- ^What would be an example of an anaphoric conditional in Lisp?onStackOverflow
- ^6.1.8.1 Examples of clause groupingfrom theCommon Lisp HyperSpec
- ^abChapter 14. Anaphoric MacrosArchivedApril 26, 2012, at theWayback MachineofOn LispbyPaul Graham
External links
edit- Chapter 14. Anaphoric MacrosfromOn LispbyPaul Graham
- Anaphora— an anaphoric macro collection