How to check duplicates on a map in clojure?

So, I have a list similar to the following:

({:name "yellowtail", :quantity 2} {:name "tuna", :quantity 1} 
{:name "albacore", :quantity 1} {:quantity 1, :name "tuna"})

My goal is to search the list of map elements and find duplicate keys, if there are duplicates, and then increase the number. Therefore, in the list, I have two displayed tuna that appear. I want to remove one and just increase the number of the other. Thus, the result should be:

({:name "yellowtail", :quantity 2} {:name "tuna", :quantity 2} 
{:name "albacore", :quantity 1} )

C: the amount of tuna increased to 2. I tried to use recur for this without success, I'm not sure that recur is a good direction to work with. Can someone point me in the right direction?

+4
source share
3 answers

group-by :name , map , .

-

(->> your-list 
  (group-by :name) 
  (map (fn [[k v]] 
         {:name k :quantity (apply + (map :quantity v))})))   

P.S. , , , .

+5

.

(->> data 
     (map (juxt :name :quantity identity)) 
     (reduce (fn [m [key qty _]] 
                (update m key (fnil (partial + qty) 0))) 
             {}) 
     (map #(hash-map :name (key %1) :quantity (val %1))))

identity, , , . ,

(->> data 
     (mapcat #(repeat (:quantity %1) (:name %1))) 
     (frequencies) 
     (map #(hash-map :name (key %1) :quantity (val %1))))
+2

.

({:name "yellowtail", :quantity 2} {:name "tuna", :quantity 1} 
{:name "albacore", :quantity 1} {:quantity 1, :name "tuna"})

...

{"yellowtail" 2, "tuna" 1, "albacore" 1}

multiset. clojure, .

0

Source: https://habr.com/ru/post/1606345/


All Articles