[英]Decompose nested maps into key-value pairs
I would like to decompose a nested map in Clojure into a sequence of key-value pairs. 我想将Clojure中的嵌套映射分解为一系列键值对。 For example, let's have this map:
例如,让我们有这张地图:
{:a :b
:c {:d {:e :f
:g :h}
:i :j}}
This map decomposed should look like this: 这个分解的地图应该如下所示:
[[:a :b]
[:c {:d {:e :f
:g :h}
:i :j}]
[:d {:e :f
:g :h}]
[:e :f]
[:g :h]
[:i :j]]
Order of the output does not matter. 输出顺序无关紧要。
I'm thinking about solving this with a recursive function, tree-seq
, or clojure.walk
. 我正在考虑使用递归函数,
tree-seq
或clojure.walk
解决这个问题。 I suspect I might be missing something from the Clojure standard library. 我怀疑我可能会遗漏Clojure标准库中的某些内容。 What would be the best solution to approach this?
什么是解决这个问题的最佳解决方案?
Here's a solution that uses tree-seq
: 这是一个使用
tree-seq
的解决方案:
(defn decompose [m]
(mapcat (partial tree-seq (comp map? val) val) m))
This produces a sequence of MapEntry
s. 这会产生一系列
MapEntry
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.