我在一个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做点什么,但我还没有取得任何成功。我已经在main函数中尝试了以下内容:
(let [call-string (read-string "(hello-world-fn)")
func (resolve (symbol (first call-string)))
args (rest call-string)]
(apply func args))没有成功。
有人能(a)给我指出正确的方向;(b)准确地解释当这种情况发生时Clojure阅读器中发生了什么?
发布于 2012-02-07 15:12:28
您可以使用macros以一种非常优雅的方式解决您的挑战。实际上,您可以编写一个模仿eval的宏。
(defmacro my-eval [s] `~(read-string s))
(my-eval "(hello-world-fn)")); "Hello World"它比eval工作得更好,因为s的符号解析发生在调用my-eval的上下文中。感谢@Matthias Benkard的澄清。
您可以在http://clojure.org/reader中阅读有关宏及其语法的内容
发布于 2012-02-06 21:24:57
尝试查看-main中的实际名称空间是什么。
(defn -main [& args]
(prn *ns*)
(eval (read-string "(hello-world-fn)")))它在抛出异常之前输出#<Namespace user>。这暗示着使用lein run执行程序是从user名称空间开始的,该名称空间显然不包含hello-world-fn符号的映射。您需要显式地限定它。
(defn -main [& args]
(eval (read-string "(helloworld/hello-world-fn)")))https://stackoverflow.com/questions/9159268
复制相似问题