More Interesting Laziness

While the sequences returned from repeat are impressive at scale, they are also relentlessly boring—just the same value over and over. We can get more interesting sequences with cycle. The cycle function takes a collection and returns a lazy sequence of the items in the collection repeated over and over. So this:

 (take 7 (cycle [1 2 3]))

will give you (1 2 3 1 2 3 1).

We can generate still more interesting sequences with iterate. To use iterate you pass it a function and a starting value:

 (​def​ numbers (iterate inc 1))

The iterate function returns a sequence whose first element is the value you passed in, in our example the 1, so that this:

 (first numbers)

returns 1. The plot thickens with the second item, which ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.