在Clojure中附加元数据

时间:2015-01-30 21:53:02

标签: clojure

我了解如何附加元数据,例如:

(def x ^{:foo true} [1 2])

但Youtube上的Clojure视频使用了这个例子:

(def ^{:foo true} x [1 2])

(meta)不返回Youtube示例中的元数据。

将元数据附加到什么位置,为什么要这样做以及如何返回元数据?感谢。

1 个答案:

答案 0 :(得分:4)

^reader macro,"首先读取元数据并将其附加到下一个表单"

将元数据附加到向量[1 2]

(def x ^{:foo true} [1 2])
(meta x) ;; x resolves to the vector, `meta` retrieves the metadata attached to it

将元数据附加到var x

(def ^{:foo true} x [1 2])
(meta #'x) ;; retrieve the metadata from the var `x`

考虑这个repl会话,我们将元数据附加到var和值:

user=> (def ^{:var-foo true} x ^{:val-foo true} [1 2])
#'user/x
user=> (meta x)
{:val-foo true}
user=> (meta #'x)
{:ns #<Namespace user>, :name x, :file "NO_SOURCE_PATH", :var-foo true, :column 1, :line 1}