Executing a dynamically bound function in Clojure
- by Carl Smotricz
I'd like to pre-store a bunch of function calls in a data structure and later evaluate/execute them from within another function.
This works as planned for functions defined at namespace level with defn (even though the function definition comes after my creation of the data structure) but will not work with functions defined by let [name (fn or letfn inside the function.
Here's my small self-contained example:
(def todoA '(funcA))
(def todoB '(funcB))
(def todoC '(funcC))
(def todoD '(funcD)) ; unused
(defn funcA [] (println "hello funcA!"))
(declare funcB funcC)
(defn runit []
(let [funcB (fn [] (println "hello funcB"))]
(letfn [(funcC [] (println "hello funcC!"))]
(funcA)
(eval todoA) ; OK
(funcB) ; OK
(eval todoB) ; "Unable to resolve symbol: funcB in this context" at line 2
(funcC) ; OK
(eval todoC) ; "Unable to resolve symbol: funcC in this context" at line 3
)))
Is there a simple fix I could undertake to get eval'd quoted calls to functions to work for functions defined inside another function?