我有一个Clojure文件,其中包含以下内容:
(ns helloworld
(:gen-class
:main -main))
(defn hello-world-fn []
(println "Hello World"))
(defn -main [& args]
(eval (read-string "(hello-world-fn)")))
我正在运行它,并且使用以下内容:
lein run helloworld
我遇到了以下错误:
Exception in thread "main" java.lang.RuntimeException: Unable to resolve symbol:
helloworld in this context, compiling:(helloworld.clj:12)
我有一种感觉需要使用ns-resolve
或resolve
来做些什么,但是我没有成功。在主函数中,我尝试过以下方法:
(let [call-string (read-string "(hello-world-fn)")
func (resolve (symbol (first call-string)))
args (rest call-string)]
(apply func args))
没有成功。
有人能否(a)指引我正确的方向;(b)解释当发生这种情况时Clojure阅读器中正在发生什么?
(hello-world-fn)
时,它可以正常工作。为什么它的行为与eval
不同呢? - viebelhello-world-fn
将在编译时解析,所以源文件顶部附近的命名空间声明是相关的。 另一方面,"(hello-world-fn)"
只是一个字符串。 编译器不会查看字符串以对其进行命名空间限定,因为这样做是错误的。 因此,在运行时执行的eval
需要通过查看*ns*
变量来解析名称引用。 - Matthias Benkard