Search code examples
clojuresequences

Getting a lazy list of the first n items of a lazy list


In Clojure, I have a list

[a, b, c, d]

and I want to pull out of it a new infinite list of tuples

[ [a,b,c], [b,c,d], [c,d,a], [d,a,b], [a,b,c] ... ]

I'm trying to figure out how to do this in a purely functional way with the built-in seq functions.

Is this straightforward and I haven't cracked it yet? Or is it actually some kind of hard problem? (In other languages I'd write my own circular iterators and keep track of a lot of state.)

Update : Also, why is someone voting this down?


Solution

  • This can be accomplished using a combination of cycle and partition

    (take 5 (partition 3 1 (cycle '(a b c d))))
    ;; => ((a b c) (b c d) (c d a) (d a b) (a b c))