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

In Clojure I have a list

[a, b, c, d]

      

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

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

      

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

Is this straight forward and I haven't cracked it yet? Or is it really some kind of difficult problem? (In other languages, I would write my own looping iterators and keep track of a lot of state.)

Update: Also, why would anyone vote for this?

+3


source to share


2 answers


This can be accomplished with 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))

      

+10


source


Without using a section:



(defn next-rotation [coll]
  (take (count coll) (drop 1 (cycle coll))))

(defn tuples [n coll]
  (lazy-seq (cons (take n coll) (tuples n (next-rotation coll)))))

;; (take 5 (tuples 3 '(a b c d))) ;; =>
;; ((a b c) (b c d) (c d a) (d a b) (a b c))

      

+1


source







All Articles