Search code examples
clojuremapsiteration

In Clojure, how do I make a nested map return a map with an inner map all set to 0?


So basically how do I make a function given the input {:A 1 :B 2 :C {:X 5 :Y 5 :Z 5} :D 1} and the key :C return {:A 1 :B 2 :C {:X 0 :Y 0 :Z 0} :D 1}? It's the same mapping but with the nested map all set to 0. Given that we know that the key :C has the nested values.

I'm very new to clojure and I'm struggling with loops and iterations so any help would be appreciated.

Thanks.


Solution

  • (defn with-zero-vals-at-key
      [m k]
      (update m k (fn [m2] (zipmap (keys m2) (repeat 0)))))
    
    (with-zero-vals-at-key {:A 1 :B 2 :C {:X 5 :Y 5 :Z 5} :D 1} :C)
    ;; => {:A 1, :B 2, :C {:X 0, :Y 0, :Z 0}, :D 1}
    
    ;; OR
    
    (defn with-zero-vals
      [m]
      (zipmap (keys m) (repeat 0)))
    
    (update {:A 1 :B 2 :C {:X 5 :Y 5 :Z 5} :D 1}
            :C
            with-zero-vals)
    ;; => {:A 1, :B 2, :C {:X 0, :Y 0, :Z 0}, :D 1}