smith
smith

Reputation: 111

Turning this list into a vector of sets

Does anyone have an idea how to convert this list of vectors into a vector of sets?

([#{2}] [#{1 2 3 4}] [#{5}] [#{3}])

result should be

[#{2} #{1 2 3 4} #{5} #{3}]

Upvotes: 0

Views: 118

Answers (3)

dpassen
dpassen

Reputation: 1306

A way I haven't seen suggested is using into and cat.

(def data '([#{2}] [#{1 2 3 4}] [#{5}] [#{3}]))
(into [] cat data) => [#{2} #{1 4 3 2} #{5} #{3}]

Upvotes: 4

user2609980
user2609980

Reputation: 10484

Multiple ways to accomplish this. It depends on your needs what approach you use:

(def data '([#{2}] [#{1 2 3 4}] [#{5}] [#{3}]))

;; If you have a list of single element lists:
(mapv first data) ;; => [#{2} #{1 2 3 4} #{5} #{3}]

;; If you have a list of multiple element lists:
(vec (apply concat data)) ;; => [#{2} #{1 2 3 4} #{5} #{3}]

;; If you also want to handle multiple levels of nesting:
(vec (flatten data)) ;; => [#{2} #{1 2 3 4} #{5} #{3}]

;; If you ..;
(transduce (map first) conj data) ;; => [#{2} #{1 2 3 4} #{5} #{3}]

Upvotes: 4

schaueho
schaueho

Reputation: 3504

Note that the sets are just elements of the vectors.

So, one way is to iterate (map) over the list of vectors and pick the first element of each vector (i.e. the set). This will build a list of these sets that you can then convert to a vector:

user=> (vec (map first '([#{2}] [#{1 4 3 2}] [#{5}] [#{3}])))
[#{2} #{1 4 3 2} #{5} #{3}]

Upvotes: 1

Related Questions