Anaphoric macro

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[1] and their name is a reference to linguistic anaphora[1]—the use of words as a substitute for preceding words.

Examples

The loop macro in ANSI Common Lisp is anaphoric in binding it to the result of the test expression in a clause.[2][3]

Here is an example that sums the value of non-nil elements, where it refers to the values of elements that do not equal nil:

 (loop for element in '(nil 1 nil 2 nil nil 3 4 6)
       when element sum it)
 ;; ⇒ 16

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

 (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 macros

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

 (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."

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

 (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)))))
gollark: Not really.
gollark: The only infinite scroll thing on my website is the infinite lorem ipsum page, as a joke which probably will eat all your RAM.
gollark: Not deleting the top entries you've scrolled past, or something.
gollark: Lazy loading doesn't stop it from using lots of RAM. They just programmed it poorly, I guess.
gollark: I run Discord in the browser, personally, to mildly reduce RAM use and data gathering, and use old reddit because new reddit is just terrible.

See also

References

This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.