Clojure:如何获取函数的元数据?

时间:2009-11-17 12:03:05

标签: clojure

我正在尝试获取所有内置Clojure函数的元数据。

previous question中我了解到这可以通过^#'func_name之类的东西来实现(获取var对象的元数据)。但我没有设法以编程方式进行,其中func-name事先不知道。

例如,尝试获取clojure.core中最后一个函数的元数据:

user=> (use 'clojure.contrib.ns-utils)
nil
user=> (def last-func (last (vars clojure.core)))

user=> last-func
zipmap

;The real metadata (zipmap is hardcoded)
user=> ^#'zipmap
{:ns #<Namespace clojure.core>, :name zipmap, :file "clojure/core.clj", :line 1661, :arglists ([keys vals]), :doc "Returns a map .."}

;Try to get programmatically, but get shit
user=> ^#'last-func
{:ns #<Namespace user>, :name last-func, :file "NO_SOURCE_PATH", :line 282}

怎么做?我已经尝试了很多变化,但没有任何诀窍。

2 个答案:

答案 0 :(得分:9)

您正在寻找metans-resolve

user=> (let [fun "map"] (meta (ns-resolve 'clojure.core (symbol fun))))
{:ns #<Namespace clojure.core>, :name map, :file "clojure/core.clj", :line 1705, :arglists ([f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls]), :doc "Returns a lazy sequence consisting of the result of applying f to the\n  set of first i tems of each coll, followed by applying f to the set\n  of second items in each coll, until any one of the colls is\n  exhausted.  Any remaining items in other colls are ignored. Function\n  f should accept number-of-colls arguments."}

答案 1 :(得分:3)

技术上目前Clojure中的函数不能包含元数据:

http://www.assembla.com/spaces/clojure/tickets/94-GC--Issue-90---%09-Support-metadata-on-fns

然而,绑定到函数的变量可能,并且看起来就像你用ns-resolve找到的那样。 (meta last-func)也会起作用。由于last-func是var本身,^#'last-func(这是(meta(var(quote last-func)))的简写())有一个冗余的var dereferencing。

相关问题