Clojure - (读取字符串字符串调用函数

haw*_*eye 3 clojure resolve

我在clojure文件中有以下内容:

(ns helloworld
  (:gen-class
    :main -main))

(defn hello-world-fn []
  (println "Hello World"))

(defn -main [& args]
  (eval (read-string "(hello-world-fn)")))
Run Code Online (Sandbox Code Playgroud)

而且我正在运行它

lein run helloworld
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Exception in thread "main" java.lang.RuntimeException: Unable to resolve symbol:
 helloworld in this context, compiling:(helloworld.clj:12)
Run Code Online (Sandbox Code Playgroud)

我有一种感觉,我需要做的东西ns-resolveresolve但我还没有成功.我在main函数中尝试了以下内容:

(let [call-string  (read-string "(hello-world-fn)")
      func (resolve  (symbol (first call-string)))
      args (rest call-string)]
   (apply func args))
Run Code Online (Sandbox Code Playgroud)

没有成功.

有人(a)可以指出我正确的方向; (b)准确解释Clojure读者在发生这种情况时会发生什么?

Dan*_*nus 6

试着看看你的实际命名空间是什么-main.

(defn -main [& args]
  (prn *ns*)
  (eval (read-string "(hello-world-fn)")))
Run Code Online (Sandbox Code Playgroud)

#<Namespace user>在轰炸之前输出,但有例外.这暗示lein run了在user命名空间中开始执行程序,这显然不包含hello-world-fn符号的映射.您需要明确限定它.

(defn -main [& args]
  (eval (read-string "(helloworld/hello-world-fn)")))
Run Code Online (Sandbox Code Playgroud)