Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 816
interstar Avatar asked Nov 25 '25 20:11

interstar


2 Answers

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))
like image 99
Kyle Avatar answered Nov 28 '25 13:11

Kyle


Without using partition:

(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))
like image 31
orend Avatar answered Nov 28 '25 13:11

orend



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!