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

Luís Oliveira luismbo at gmail.com
Sun Sep 5 22:56:37 UTC 2010


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

-- 
Luís Oliveira
http://r42.eu/~luis/




More information about the pro mailing list