I have a file which contains some trusted clojure source code:
((+ a b) (* a b) (- a b))
For each of the items in the list I want to generate an anonymous function:
(fn [a b] (+ a b))
(fn [a b] (* a b))
(fn [a b] (- a b))
If I call the following marco
(defmacro create-fn
[args exprs]
`(fn ~args ~exprs))
directly with some clojure code it works perfectly:
user=> (macroexpand-1 '(create-fn [a b] (* a b)))
(clojure.core/fn [a b] (* a b))
But when I bind the context of the file to a local and try to map my macro it will not work. On access of the first generated function I get the error message "java.lang.RuntimeException: Unable to resolve symbol: a in this context"
(Please note that I had to put an extra eval
into the macro to get the value of the symbol e
which is used in the anonymous function used by map)
(defmacro create-fn
[args exprs]
`(let [e# (eval ~exprs)]
(fn ~args
e#)))
(let [exprs (read-string "((+ a b) (* a b) (- a b))")
fns (map
(fn [e] (create-fn [a b] e))
exprs)]
(first fns))
Any help is very much appreciated!