从Clojure记录返回普通地图 [英] Return plain map from a Clojure record

查看:240
本文介绍了从Clojure记录返回普通地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条记录:

(defrecord Point [x y])
(def p (Point. 1 2))

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

Now I want to extract just the map from the record. These ways get the job done. Are these good ways? Are there better ways?

(into {} (concat p))
(into {} (map identity p))
(apply hash-map (apply concat p))

我希望在那里

推荐答案

记录地图

(defrecord Thing [a b])

(def t1 (Thing. 1 2))
(instance? clojure.lang.IPersistentMap t1) ;=> true

因此,一般而言,没有必要将其强制为 APersistentMap 类型。但是,如果需要,您可以将放入

So, in general there is no need to coerce them into a APersistentMap type. But, if desired you do so with into:

(into {} t1) ;=> {:a 1, :b 2}

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

If you want to traverse an arbitrary data structure, including nested records, making this transformation, then use 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}}}])

这篇关于从Clojure记录返回普通地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆