Executing code stored as a list
-
05-07-2019 - |
Question
After understanding (quote), I'm curious as to how one might cause the statement to execute. My first thought was
(defvar x '(+ 2 21))
`(,@x)
but that just evaluates to (+ 2 21)
, or the contents of x
. How would one run code that was placed in a list?
Solution
(eval '(+ 2 21))
OTHER TIPS
@Christián Romo:
Backtick example: you can kinda implement apply using eval and backtick, because you can splice arguments into a form. Not going to be the most efficient thing in the world, but:
(eval `(and ,@(loop for x from 1 upto 4 collect `(evenp ,x))))
is equivalent to
(eval '(and (evenp 1) (evenp 2) (evenp 3) (evenp 4)))
Incidentally, this has the same result as the (much more efficient)
(every 'evenp '(1 2 3 4))
Hope that satisfies your curiosity!
Take a look at funny Lisp tutorial at http://lisperati.com/. There are versions for Common Lisp and Emacs Lisp, and it demonstrates use of quasiquote and macros.