How can I get the nested keys of a map in clojure?

后端 未结 11 1136
梦如初夏
梦如初夏 2020-12-15 10:59

if my structure is

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

I

11条回答
  •  [愿得一人]
    2020-12-15 11:18

    Got a similar question, wasn't satisfied by current solutions:

    "Naive" recursive approach

    (require '[clojure.set :as set])
    
    (defn all-paths
      ([m current]
       ;; base case: map empty or not a map
       (if (or (not (map? m)) (empty? m))
         #{current}
       ;; else: recursive call for every (key, value) in the map
         (apply set/union #{current}
                (map (fn [[k v]]
                       (all-paths v (conj current k)))
                     m))))
      ([m]
       (-> m (all-paths []) (disj []))))
    
    
    (all-paths {:a 1
                :b 2
                :c {:ca 3
                    :cb {:cba 4
                         :cbb 5}}
                :d {:da 6
                    :db 7}})
    => #{[:a] [:b] [:c] [:d] [:c :ca] [:c :cb] [:d :da] [:d :db] [:c :cb :cba] [:c :cb :cbb]}
    

提交回复
热议问题