Search code examples
lispcommon-lispsyntactic-sugar

Can one use the "it" command outside of a loop in Lisp?


I know that in a Lisp loop, one can use the special variable "it", as in this example from Gigamonkeys:

(loop for key in some-list when (gethash key some-hash) collect it)

I was wondering if there was any equivalent concept outside of a loop besides using let to store it explicitly, something like this:

(let ((result (foo input)))
     (when result (push result acc)))

I can use let, but I was just curious as to whether there was some syntactic sugar that can make my code a little more concise.


Solution

  • The lisp-y answer is, who cares if there isn't syntax, just add your own.

    (defmacro awhen (test &body body)
        `(let ((it ,test))
              (when it ,@body)))
    

    and then use it

    (awhen (expensive-computation)
           (format t "~a~%" it))
    

    This class of macros are often prefixed with an "a" for anaphoric. See aif for Paul Graham's examples in On Lisp.