Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic code with clojure

Tags:

clojure

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. Any guidance is welcome.

Thanks,

Colin

like image 288
colinf Avatar asked Nov 18 '25 00:11

colinf


2 Answers

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.

like image 103
Brian Avatar answered Nov 20 '25 15:11

Brian


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)))
like image 33
aav Avatar answered Nov 20 '25 17:11

aav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!