aeter
aeter

Reputation: 12700

Transformation of nested lists into a list of sets in Clojure?

Having a list of equally sized lists, e.g.:

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

How can it be transformed into a list of sets, each set for the indexes above:

[#{"A" "H"} #{"B" "C" "M"}]

Upvotes: 7

Views: 1410

Answers (3)

mikera
mikera

Reputation: 106351

I'd suggest the following:

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

Upvotes: 1

dfan
dfan

Reputation: 5814

(map set (apply map vector d))

"(apply map vector)" is what is called "zip" in other languages like Python. It calls vector on the first item of each element of d, then the second item of each element, etc.

Then we call set on each of those collections.

Upvotes: 17

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17773

if hash-set allowed duplicate keys, you could use:

(apply map hash-set d)

instead, you can do the uglier

(apply map (fn [& s] (set s)) d)

Upvotes: 4

Related Questions