Search code examples
clojure

Clojure - calculating a value for a map key


I have a vector of maps. Each map has three keys :x, :y and :z. I want that the value of :z would be the sum of the values of keys :x and :y. How should I do this? i.e.

[{x: 5 :y 10 :z (+ :x :y)} {...} {...}]

In the above example, the first map's :z value should then be (+ 5 10) = 15.

Thanks for helping!


Solution

  • It may help to parameterize this logic by extracting it out into a function if you plan on repeatedly doing this, although I would just create the :z key at the time you create the map, since you will presumably have access to x and y at that time.

    Barring that, here is an alterative to the fine solutions presented already, just generalized for different arguments.

    (def ms  [{:x 5 :y 10} {:x 5 :y 12} {:x 8 :y 10}])
    
    (defn assoc-from-existing [m k & ks]
      (assoc m k (->> (select-keys m ks) vals (apply +))))
    
    (mapv #(assoc-from-existing % :z :x :y) ms)