Clojure: Summing Values ​​in a Map Set

I am trying to summarize the values ​​of a map collection by their common keys. I have this snippet:

(def data [{:a 1 :b 2 :c 3} {:a 1 :b 2 :c 3}] (for [xs data] (map xs [:a :b])) ((1 2) (1 2)) Final result should be ==> (2 4) 

Basically, I have a list of maps. Then I carry out a list of concepts to take only the keys that I need.

My question now is how can I sum these values? I tried using reduce, but it only works on sequences, not collections.

Thanks.

=== EDIT ====

Using the suggestion from Joost I, the following came out:

 (apply merge-with + (for [x data] (select-keys x [:col0 :col1 :col2])) 

Iterates over the collection and summarizes the selected keys. The added part of "select-keys" is necessary, first of all, to avoid trouble when the cards in the collection contain literals, and not just numbers.

+4
source share
1 answer

If you really want to summarize the values ​​of shared keys, you can do the whole conversion in one step:

 (apply merge-with + data) => {:a 2, :b 4, :c 6} 

To summarize subsequences, you have:

 (apply map + '((1 2) (1 2))) => (2 4) 
+11
source

All Articles