eval a list into a let on clojure

2019-06-26 06:50发布

问题:

My problem is the next, i try to evaluate a list with some vars using a let to asign values to this vars

if i do (def a (list * 'x 'y)) and (let [x 3 y 3] (eval a)) I have a CompilerException java.lang.RuntimeException: Unable to resolve symbol: x in this context, compiling:(NO_SOURCE_PATH:6)

but if I run (def x 4) (def y 4) and (eval a) i have a 16, anyway if I run again (let [x 3 y 3] (eval a)) again I have 16,

exist a method to binding the x and y correctly and eval the list?

ty!

回答1:

Well, you could also eval the let expression, See if this is what you need:

(eval '(let [x 3 y 3] (* x y)))

EDIT :

According to the comments, this will work for your case:

(def a (list (list * 'x 'y)))
(eval (concat '(let [x 3 y 3]) a))

Even better, use quasiquoting:

(def a (list * 'x 'y))
(eval `(let ~'[x 3 y 3] ~a))


回答2:

let defines lexically scoped bindings that are not accessible from the body of the eval function. This is no different than any other function. However, the bindings created with def are accessible because they are namespace global. All functions have access to namespace global variables, as long as they are public.



回答3:

(def ^:dynamic x 4) (def ^:dynamic y 4)
user=> (binding [x 3 y 3] (eval a))
9
user=> (eval a)
16