Executing a dynamically bound function in Clojure

Posted by Carl Smotricz on Stack Overflow See other posts from Stack Overflow or by Carl Smotricz
Published on 2010-04-04T17:31:09Z Indexed on 2010/04/04 17:33 UTC
Read the original article Hit count: 346

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about clojure

Related posts about binding