从 Clojure 记录返回普通地图

Dav*_* J. 4 records clojure

我有一个记录:

(defrecord Point [x y])
(def p (Point. 1 2))
Run Code Online (Sandbox Code Playgroud)

现在我只想从记录中提取地图。这些方法可以完成工作。这些是好方法吗?有更好的方法吗?

(into {} (concat p))
(into {} (map identity p))
(apply hash-map (apply concat p))
Run Code Online (Sandbox Code Playgroud)

我希望可能有一种更简洁的方法,也许内置于记录的概念中。

A. *_*ebb 6

记录就是地图

(defrecord Thing [a b])

(def t1 (Thing. 1 2))
(instance? clojure.lang.IPersistentMap t1) ;=> true
Run Code Online (Sandbox Code Playgroud)

所以,一般没有必要将它们强制转换为一个APersistentMap类型。但是,如果需要,您可以这样做into

(into {} t1) ;=> {:a 1, :b 2}
Run Code Online (Sandbox Code Playgroud)

如果要遍历任意数据结构,包括嵌套记录,进行此转换,请使用 walk

(def t2 (Thing. 3 4))
(def t3 (Thing. t1 t2))
(def coll (list t1 [t2 {:foo t3}]))

(clojure.walk/postwalk #(if (record? %) (into {} %) %) coll)
;=> ({:a 1, :b 2} [{:a 3, :b 4} {:foo {:a {:a 1, :b 2}, :b {:a 3, :b 4}}}])
Run Code Online (Sandbox Code Playgroud)