如果我的结构是
{ :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-map
与 my-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/