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?
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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With