Clojure 中的元数据保存

Metadata Preservation in Clojure

来自ClojureScript Unraveled

As long as the functions that derive new data structures return collections with the same type, metadata will be preserved; this is not true if the types change due to the transformation.

(def v (with-meta [0 1 2 3] {:foo :bar}))
;; => [0 1 2 3]

(def sv (subvec v 0 2))
;; => [0 1]

(meta sv)
;; => nil ; where did the metadata?

为什么元数据丢失了? subvec return 不是和 v 类型相同的集合,即向量吗?

在这种情况下,您需要保留元信息,subvec returns 一个全新的向量,与之前的向量无关,并在此过程中删除元信息。

(def sv (with-meta (subvec v 0 2) (meta v)))

大多数函数将以您使用 subvec 的方式保留元信息。

正如@muhuk 指出的那样:

https://github.com/funcool/clojurescript-unraveled/blob/master/src/language-advanced.adoc#values