o'aoughrouer
o'aoughrouer

Reputation: 445

Clojure, concat multiple sequences into one

The following line: (repeat 4 [2 3])

gives me this: ([2 3] [2 3] [2 3] [2 3])

How do I create one vector or list from the above list of vectors so that I get this?: [2 3 2 3 2 3 2 3]

Thanks

Upvotes: 5

Views: 3141

Answers (4)

Stephen Cagle
Stephen Cagle

Reputation: 14554

Pedantically speaking, you asked for a vector, so:

(->> [2 3] cycle (take 8) vec)

I feel cycle is a little more appropriate than concat (though it uses concat itself) as it indicates "cycle through the elements of this sequence" rather than "concatenate the following sequences together". Just my two cents, matter of opinion.

Upvotes: 2

noisesmith
noisesmith

Reputation: 20194

concat is in fact exactly the function you want

user> (apply concat (repeat 4 [2 3]))
(2 3 2 3 2 3 2 3)

this even works with lazy input:

user> (take 8 (apply concat (repeat [2 3])))
(2 3 2 3 2 3 2 3)

This is an alternative:

user> (def flatten-1 (partial mapcat identity))
#'user/flatten-1
user> (flatten-1 (repeat 4 [2 3]))
(2 3 2 3 2 3 2 3)

it is compatible with laziness and unlike flatten preserves any substructure (only doing one level of flattening)

user> (take 12 (flatten-1 (repeat [2 3 [4]])))
(2 3 [4] 2 3 [4] 2 3 [4] 2 3 [4])

Upvotes: 20

Leon Grapenthin
Leon Grapenthin

Reputation: 9276

(take 8 (cycle [2 3]))
;; => (2 3 2 3 2 3 2 3)

Upvotes: 6

user235273
user235273

Reputation:

(flatten x)
Takes any nested combination of sequential things (lists, vectors, etc.) and returns their contents as a single, flat sequence.
(flatten nil) returns nil.

(flatten (repeat 4 [2 3]))  ;(2 3 2 3 2 3 2 3)

Upvotes: 2

Related Questions