【问题标题】:Clojure: How to get meta-data of functions?Clojure:如何获取函数的元数据?
【发布时间】:2009-11-17 12:03:05
【问题描述】:

我正在尝试获取所有内置 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}

怎么做?我已经尝试了很多变体,但没有任何效果。

【问题讨论】:

    标签: clojure


    【解决方案1】:

    您正在寻找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."}

    【讨论】:

    • 谢谢!确实,^(ns-resolve 'clojure.core last-func) 实现了这一点
    • 我找到了另一种使用“intern”函数的方法:^(intern 'clojure.core last-func)
    • 这是一个危险的解决方案:
      user=&gt; (meta (intern 'clojure.core (with-meta 'count :meta :data}))) {:ns #, :name count, :meta :data}
      所以要小心你的符号来自哪里。我仍然会推荐 ns-resolve 而不是实习生。
    【解决方案2】:

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

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

    但是,绑定到函数的 var 可能,看起来这就是您使用 ns-resolve 找到的。 (meta last-func) 也可以。由于 last-func 是 var 本身,所以 ^#'last-func (它是 (meta (var (quote last-func)))) 的简写)有一个冗余的 var 解引用。

    【讨论】:

    • 没有。 (meta last-func) 不起作用。自己试试看。它返回 nil
    • clojure.contrib.ns-utils/vars 返回符号列表而不是变量列表,这就是它不起作用的原因。
    猜你喜欢
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多