将嵌套映射分解为键值对 [英] Decompose nested maps into key-value pairs

查看:81
本文介绍了将嵌套映射分解为键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Clojure中的嵌套映射分解为一系列键值对。例如,让我们看这张地图:

I would like to decompose a nested map in Clojure into a sequence of key-value pairs. 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]]

输出的顺序无关紧要。

我正在考虑使用递归函数 tree-seq code>或 clojure.walk 。我怀疑我可能缺少Clojure标准库中的某些内容。

I'm thinking about solving this with a recursive function, tree-seq, or clojure.walk. I suspect I might be missing something from the Clojure standard library. What would be the best solution to approach this?

推荐答案

这里是使用 tree-seq

(defn decompose [m]
  (mapcat (partial tree-seq (comp map? val) val) m))

这将生成一个 MapEntry序列 s。

这篇关于将嵌套映射分解为键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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