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

后端 未结 11 1108
梦如初夏
梦如初夏 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:26

    Obligatory zippers version

    (require '[clojure.zip :as z])
    
    (defn keys-in [m] 
      (letfn [(branch? [[path m]] (map? m)) 
              (children [[path m]] (for [[k v] m] [(conj path k) v]))] 
        (if (empty? m) 
          []
          (loop [t (z/zipper branch? children nil [[] m]), paths []] 
            (cond (z/end? t) paths 
                  (z/branch? t) (recur (z/next t), paths) 
                  :leaf (recur (z/next t), (conj paths (first (z/node t)))))))))
    

提交回复
热议问题