我想要一个宏this-ns
这样它就会返回调用它的位置的名称空间。例如,如果我有这段代码
(ns nstest.main
(:require [nstest.core :as nstest]))
(defn ns-str [x]
(-> x (.getName) name))
(defn -main [& args]
(println "The ns according to *ns*:" (ns-str *ns*))
(println "The actual ns:" (ns-str (nstest/this-ns))))
我希望打电话lein run
会产生这样的输出:
The ns according to *ns*: user
The actual ns: nstest.main
我想出的实现是以下代码:
(ns nstest.core)
(defmacro this-ns []
(let [s (gensym)]
`(do (def ~s)
(-> (var ~s)
(.ns)))))
它似乎确实有效,但感觉很hacky。值得注意的是,在上面的例子中它将扩展到def
被调用inside the -main
感觉功能不是很干净。
我的问题: 有没有更好的实现方法this-ns
获取命名空间,其中this-ns
叫做?
这是另一种变体:
(defmacro this-ns []
`(->> (fn []) str (re-find #"^.*?(?=\$|$)") symbol find-ns))
问题是匿名函数被编译为一个名为类似的类playground.core$_main$fn__181@27a0a5a2
,因此它以函数编译所在的实际命名空间的名称开头。
不能说它看起来不那么老套,那么你的变体,仍然避免了副作用,由def
在你的情况下。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)