如何在clojure中获取地图的嵌套键? [英] How can I get the nested keys of a map in clojure?
本文介绍了如何在clojure中获取地图的嵌套键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我的结构是
{:a:A
:b:B
:c {
:d:D
}
:e {
:f {
:g:G
:h:H
} b $ b}
}
我想要一个名为keys-in的函数返回如下:
[[:a] [:b] [:c:d] [:e:f:g ] [:e:f:h]]
所以我可以这样做:
(不是任何?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 [[kv]]
(let [sub(keys-in v)
nested(map#(into [k]%) )
nested
[[k]])))
m))
[]))
tests
user => (keys-in nil)
[]
user => (keys-in {})
[]
user => (键入{:a 1:b 2}))
[[:a] [:b]]
user => (keys-in {:a {:b {:c 1}}})
[[:a:b:c]]
user => (键入{:a {:b {:c 1}}:d {:e {:f 2}}}
[[:a:b:c] [:d:e:f] ]
if my structure is
{ :a :A
:b :B
:c {
:d :D
}
:e {
:f {
:g :G
:h :H
}
}
}
I would like to get a function called keys-in that returns something like:
[[:a] [:b] [:c :d] [:e :f :g] [:e :f :h]]
so then I can do something like:
(not-any? nil? (map #(get-in my-other-map %1) (keys-in my-map)))
So I can be sure that my-other-map has the same keys that 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]]
这篇关于如何在clojure中获取地图的嵌套键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文