Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make an infinite, repeating sequence in clojure?

I want to take a sequence or vector and create an infinite, looping, lazy version of it. This is what I tried:

(def test-seq '(1 2 3))
(take 5 (repeat test-seq))

And I got

((1 2 3) (1 2 3) (1 2 3) (1 2 3) (1 2 3))

When what I wanted was

(1 2 3 1 2)

I know this works

(take 5 (flatten (repeat test-seq)))

but that seems a bit unsatisfying and flabby. I'm assuming re-structuring a sequence of sequences is expensive but I may well be wrong :)

like image 282
Gary Liddon Avatar asked Aug 01 '13 15:08

Gary Liddon


1 Answers

You're looking for cycle:

(take 5 (cycle '(1 2 3))) ;; => (1 2 3 1 2)
like image 177
mtyaka Avatar answered Oct 13 '22 14:10

mtyaka