迭代嵌套映射的所有键 [英] Iterate over all keys of nested map

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

问题描述

给定:

{: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
}

结果.基本上只获取叶子节点.

As the result. Basically only get the leaf nodes.

推荐答案

我认为更好的一个版本,使用 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,并将其键添加到结果映射的每个键序列中.

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天全站免登陆