Clojure: I have a lot of sorted cards and you want to reduce the values ​​of the key super-maps & # 8594; vector

I saw this one , but I can’t understand how to apply it (not a pun) to my situation.

I have a sorted list of such cards: (note that there can be more than two keys on a card) ({name1 3, name2 7}, {name1 35, name2 7}, {name1 0, name2 3})

What I need is a data structure afterwards:

({: name1 [3,35,0]}, {: name2 [7,7,3]})

I struggled with this for a while and seemed unable to get close.

Caveats: the data should remain sorted, and I have N keywords for more than two.

+4
source share
3 answers

I would go for merge-with with the addition of some preprocessing:

 (def maps [{:a :b :e :f} {:a :c} {:a :d :e :g}]) (apply merge-with concat (for [m maps [kv] m] {k [v]})) >>> {:e (:f :g), :a (:b :c :d)} 
+2
source

I think the function you want is combined with:

 user=> (def x {:a 1 :b 2}) user=> (def y {:a 3 :b 4}) user=> (merge-with vector xy) {:a [1 3], :b [2 4]} user=> user=> (def z {:a 5 :b 6 :c 7}) user=> (merge-with vector xyz) {:a [[1 3] 5], :c 7, :b [[2 4] 6]} ; oops user=> (merge-with #(vec (flatten (vector %1 %2))) xyz) {:a [1 3 5] :b [2 4 6] :c 7} user=> 
+1
source

This is my attempt to solve this problem. It is not as elegant as the decision of Raphael.

 (def maps [{:a :b :e :f} {:a :c} {:a :d :e :g}]) (apply merge-with #(if (list? %1) (conj %1 %2) (list %1 %2)) maps) >>> {:a (:d :b :c), :e (:f :g)} 
0
source

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


All Articles