Convert nested lists to list sets in Clojure?

A list of lists of the same size, for example:

(def d [["A" "B"] ["A" "C"] ["H" "M"]]) 

How can it be transformed into a list of sets, each of which is indicated for the indices above:

 [#{"A" "H"} #{"B" "C" "M"}] 
+7
source share
3 answers
 (map set (apply map vector d)) 

" (apply map vector) " is what is called "zip" in other languages ​​such as Python. It calls vector for the first element of each element d , then the second element for each element, etc.

Then we call set in each of these collections.

+17
source

If the hash set allows duplicate keys, you can use:

 (apply map hash-set d) 

instead you can do more ugly

 (apply map (fn [& s] (set s)) d) 
+4
source

I would suggest the following:

 (reduce (fn [sets vals] (map conj sets vals)) (map hash-set (first d)) (rest d)) 
+1
source

All Articles