Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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"}]
like image 567
aeter Avatar asked Mar 14 '11 20:03

aeter


3 Answers

(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.

like image 55
dfan Avatar answered Oct 01 '22 21:10

dfan


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)
like image 45
Joost Diepenmaat Avatar answered Oct 01 '22 22:10

Joost Diepenmaat


I'd suggest the following:

(reduce
  (fn [sets vals]
    (map conj sets vals))
  (map hash-set (first d))
  (rest d))
like image 33
mikera Avatar answered Oct 01 '22 22:10

mikera