[pro] The Best Examples of "Code is Data"

Daniel Weinreb dlw at itasoftware.com
Tue Sep 7 22:15:20 UTC 2010


What happens if you do

(defun foo (x)
  (plus x 3))

?

Luís Oliveira wrote:
> On Sun, Sep 5, 2010 at 9:59 PM, Scott L. Burson <Scott at sympoiesis.com> wrote:
>   
>> As tempting as it is to call EVAL for various purposes, the reality is that
>> correct uses of EVAL are quite rare.  In fact, unless you're writing your
>> own read-eval-print loop of some kind, the best rule of thumb is that if
>> you're calling EVAL explicitly, you've made a mistake.  I have trouble
>> coming up with any exceptions to this rule other than a REPL.
>>     
>
> One of the many tricks I've picked up from James Bielman (I hope he's
> subscribed to this mailing list :-)) was using CONSTANTP and EVAL in
> compiler macros. Here's a simple example:
>
>     (defun plus (x y)
>       (+ x y))
>
>     (define-compiler-macro plus (&whole form x y)
>       (if (and (constantp x) (constantp y))
>           (+ (eval x) (eval y))
>           form))
>
> Execution examples:
>
>     (compiler-macroexpand-1 '(plus 1 1)) => 2
>
>     (compiler-macroexpand-1 '(plus '1 '1)) => 3
>
>     (compiler-macroexpand-1 '(plus (* 2 (/ 4 2)) (+ 3 2))) => 9
>
>     (defconstant +1+ 1)
>     (compiler-macroexpand-1 '(plus +1+ 2)) => 3
>
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.common-lisp.net/pipermail/pro/attachments/20100907/4d5d1c5a/attachment.html>


More information about the pro mailing list