dictionary - 如何在 clojure 中获取映射的嵌套键?

标签 dictionary recursion clojure functional-programming

如果我的结构是

{ :a :A
  :b :B
  :c {
       :d :D
     }
  :e {
       :f {
            :g :G
            :h :H
          }
     }
}

我想要一个名为 keys-in 的函数,它返回如下内容:

[[:a] [:b] [:c :d] [:e :f :g] [:e :f :h]]

那么我可以做类似的事情:

(not-any? nil? (map #(get-in my-other-map %1) (keys-in my-map)))

所以我可以确定 my-other-mapmy-map 具有相同的键

最佳答案

(defn keys-in [m]
  (if (map? m)
    (vec 
     (mapcat (fn [[k v]]
               (let [sub (keys-in v)
                     nested (map #(into [k] %) (filter (comp not empty?) sub))]
                 (if (seq nested)
                   nested
                   [[k]])))
             m))
    []))

;; tests
user=> (keys-in nil)
[]
user=> (keys-in {})
[]
user=> (keys-in {:a 1 :b 2}))
[[:a] [:b]]
user=> (keys-in {:a {:b {:c 1}}})
[[:a :b :c]]
user=> (keys-in {:a {:b {:c 1}} :d {:e {:f 2}}})
[[:a :b :c] [:d :e :f]]

关于dictionary - 如何在 clojure 中获取映射的嵌套键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21768802/

相关文章:

clojure - 命名空间限定记录字段访问器

clojure - 惰性序列的实现时机

clojure - 应用 Clojure

c++ - 我可以依靠 std::map::operator[] 来触摸吗?

python - 使用 enumerate 遍历列表字典以提取信息

c++ - 在二叉树中插入 4 或 5 个数字,但在输出中只得到 3 个数字

java - 为什么这会导致堆栈溢出错误?有向图

java - 计算序列中尾随零的数量

python - 将 dict 值四舍五入为 2 位小数

python - 合并字典而不覆盖以前的值,其中值是一个列表