使用深度优先搜索排序将嵌套地图展平为列表

Flatten Nested Map into List with Depth-First Search Ordering

在 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")

这是一个递归的解决方案:

(defn flatten-map [m]
  (flatten
    (for [[k v] m]
      (cons k (flatten-map v)))))

这是一个简单的迭代解决方案(使用 looprecur):

(defn flatten-map [m]
  (loop [in m out []]
    (if-let [[[k v] & ts] (seq in)]
      (recur (concat v ts)
             (conj out k))
      out)))

还有一个 "fancy" 一个(使用 tree-seq function

(defn flatten-map [m]
  (->> [nil m]
       (tree-seq sequential? second)
       (drop 1)
       (map first)))