I want to generate named functions with fn and return them from the macro, I tried the following example:
(defmacro getfn [namestr children] `(fn fn-name# [] (println "Recursing" ~namestr) (doall (map (fn [child#] (child#)) ~children)))) (def foo (getfn "foo" [])) (def bar (getfn "bar" [foo])) (defn -main [& args] (bar))
The result usually corresponds to the expected result:
Recursing bar Recursing foo
However, when I run this compiled lead (AOT), I get:
Recursing bar Recursing bar ... Recursing bar Recursing bar Exception in thread "main" java.lang.StackOverflowError
It seemed rather strange to me that the bar continues to call itself instead of foo, the only reasonable reason for this is the generated symbol fn-name# for leakage outside its area. Is this a bug in Clojure or the alleged behavior?
Update: For clarity, it should be mentioned that removing the fn-name# character and introducing an anonymous function fixes this problem. However, in my actual code, I sometimes need to call it recursively, so I need to call it.
source share