Anaphoric Lisp Macros

These macros are from PaulGraham's outstanding book OnLisp. An anaphor is an expression which refers back in the conversation, as in "Get the wrench and put it on the table." These macros allow us to refer back to previously computed values. For example, consider an anaphoric version of if, call it aif. We can refer back to the condition part of the if with the variable it.

(aif (big-long-calculation)
  (foo it))
Here are the macros:

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

(defmacro awhen (test-form &body body) `(aif ,test-form (progn ,@body)))

(defmacro awhile (expr &body body) `(do ((it ,expr ,expr)) ((not it)) ,@body))

(defmacro aand (&rest args) (cond ((null args) t) ((null (cdr args)) (car args)) (t `(aif ,(car args) (aand ,@(cdr args))))))

(defmacro acond (&rest clauses) (if (null clauses) nil (let ((cl1 (car clauses)) (sym (gensym))) `(let ((,sym ,(car cl1))) (if ,sym (let ((it ,sym)) ,@(cdr cl1)) (acond ,@(cdr clauses)))))))


Methinks this is inspired by PerlPronouns? -- DollarUnderscore and the lot.


EditText of this page (last edited July 8, 2013) or FindPage with title or text search