在clojure中,我怎样才能像这样转换嵌套地图:
{"1" {"1.1" {"1.1.1" {}
"1.1.2" {}}
"1.2" {}}
"2" {"2.1" {}
"2.2" {}
"2.3" {}}}
进入这个:
("1" "1.1" "1.1.1" "1.1.2" "1.2" "2" "2.1" "2.2" "2.3")
答案 0 :(得分:3)
这是一个简单的迭代解决方案(使用loop
和recur
):
(defn flatten-map [m]
(loop [in m out []]
(if-let [[[k v] & ts] (seq in)]
(recur (concat v ts)
(conj out k))
out)))
一个"幻想"一个(使用tree-seq
function)
(defn flatten-map [m]
(->> [nil m]
(tree-seq sequential? second)
(drop 1)
(map first)))
答案 1 :(得分:1)
这是一个递归解决方案:
(defn flatten-map [m]
(flatten
(for [[k v] m]
(cons k (flatten-map v)))))