遍历嵌套地图的所有键 [英] Iterate over all keys of nested map

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

问题描述

给出:

{:o {:i1 1
     :i2 {:ii1 4}}}

我想从根开始以绝对形式遍历地图的键向量。所以我想:

I'd like to iterate over the keys of the map in "absolute" form from the root as a vector. So I'd like:

{
 [:o :i1] 1
 [:o :i2 :ii1] 4
}

因此。

推荐答案

一个我认为更好的版本,使用 for 而不是 mapcat

A version that I think is rather nicer, using for instead of mapcat:

(defn flatten-keys [m]
  (if (not (map? m))
    {[] m}
    (into {}
          (for [[k v] m
                [ks v'] (flatten-keys v)]
            [(cons k ks) v']))))

该函数自然是递归的,对于非映射而言,最方便的基本情况是此值,没有keyeq导致。对于地图,您可以仅对地图中的每个值调用 flatten-keys ,然后将其键放在生成的地图的每个keyseq之前。

The function is naturally recursive, and the most convenient base case for a non-map is "this one value, with no keyseq leading to it". For a map, you can just call flatten-keys on each value in the map, and prepend its key to each keyseq of the resulting map.

这篇关于遍历嵌套地图的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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