问题描述
我在clojure文件中有以下内容:
(ns helloworld
:main -main))
(defn hello-world-fn []
(printlnHello World))
main [& args]
(eval(read-string(hello-world-fn)))
我用它运行
lein run helloworld
,我收到以下错误:
线程main中的异常java.lang.RuntimeException:无法解析符号:
helloworld在此上下文中,编译:(helloworld.clj:12)
我有一种感觉需要用
ns-resolve
或解决
,但我没有取得任何成功。我试过在主函数中的以下:(let [call-string -fn))
func(resolve(symbol(first call-string)))
args(rest call-string)]
(apply func args))
没有成功。
有人(a)指向正确的方向;
解决方案你可以解决你的挑战,在这种情况下,一个非常优雅的方式,使用
宏
。事实上,你可以写一个模仿eval
的宏。def macro my-eval [s]`〜(read-string s))
(my-eval(hello-world-fn))); Hello World
它的效果更好,
eval
因为s
的符号解析发生在调用my-eval
的上下文中。感谢@Matthias Benkard的澄清。
您可以在
I've got the following in a clojure file:
(ns helloworld (:gen-class :main -main)) (defn hello-world-fn [] (println "Hello World")) (defn -main [& args] (eval (read-string "(hello-world-fn)")))
and I'm running it with
lein run helloworld
and I'm getting the following error:
Exception in thread "main" java.lang.RuntimeException: Unable to resolve symbol: helloworld in this context, compiling:(helloworld.clj:12)
I have a feeling I need to do something with
ns-resolve
orresolve
but I haven't had any success. I've tried the following in the main function:(let [call-string (read-string "(hello-world-fn)") func (resolve (symbol (first call-string))) args (rest call-string)] (apply func args))
Without success.
Can someone (a) point me in the right direction; and (b) explain precisely what is going on in the Clojure reader when this occurs?
解决方案You can solve your challenge, in a very elegant way, using
macros
. In fact, you can write a macro that mimicseval
.(defmacro my-eval [s] `~(read-string s)) (my-eval "(hello-world-fn)")); "Hello World"
It works better that
eval
because the symbol resolution ofs
occurs in the context that callsmy-eval
. Thanks to @Matthias Benkard for the clarifications.You can read about macros and their syntax in http://clojure.org/reader
这篇关于Clojure - (读字符串字符串调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!