I'm trying to create some dynamic code within clojure. In the function below, the idea is that the conditions for the (and) macro will be dynamically generated.
(defn matching-keys [rec match-feed keys]
(> (count (clojure.set/select #(and (for [k keys]
(= (% k) (rec k))))
(set match-feed)))
0))
So if it worked!! then this code would produce an (and) something like this when passed keys of [:tag :attrs]
:
(and (= (% :tag) (rec :tag))
(= (% :attrs) (rec :attrs)))
I've been messing around with various `` and
~` operators to try to make it work, and am now in a state of confusion.开发者_C百科 Any guidance is welcome.
Thanks,
Colin
You don't need dynamically generated code for this. Changing the anonymous function to #(every? (fn [k] (= (% k) (rec k))) keys)
should do what you want without generating code at runtime.
The ability to use higher-order functions means that you should hardly ever need to dynamically generate code.
You can use eval to evaluate a dynamically built form, e.g.:
(eval '(= 2 3))
Keep in mind that a dynamically evaluated form will have no access to the lexical context. It means that:
(let [a 1 b 2]
(eval '(+ a b)))
will not work.
However, it is still possible to use a dynamic environment:
(def a nil)
(def b nil)
(binding [a 1 b 2]
(eval '(+ a b)))
精彩评论