Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure, concat multiple sequences into one

Tags:

clojure

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

like image 953
o'aoughrouer Avatar asked Oct 25 '13 16:10

o'aoughrouer


2 Answers

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])
like image 156
noisesmith Avatar answered Nov 12 '22 04:11

noisesmith


(take 8 (cycle [2 3]))
;; => (2 3 2 3 2 3 2 3)
like image 6
Leon Grapenthin Avatar answered Nov 12 '22 06:11

Leon Grapenthin