[pro] The Best Examples of "Code is Data"
Scott L. Burson
Scott at sympoiesis.com
Mon Sep 6 02:31:07 UTC 2010
On Sun, Sep 5, 2010 at 3:56 PM, Luís Oliveira <luismbo at gmail.com> wrote:
> 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.
Okay, it is true that anything that CONSTANTP says "true" on can
fairly be EVALled. But be aware that implementations are not required
to recognize something like '(* 2 (/ 4 2)) as a constant. (Maybe most
of them do.)
-- Scott
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/
>
> _______________________________________________
> pro mailing list
> pro at common-lisp.net
> http://common-lisp.net/cgi-bin/mailman/listinfo/pro
>
More information about the pro
mailing list