1

I've got a couple of infinite sequences. I want to take one of each other per step. What's the idiomatic way of doing that? In other words, assume that there's a finite, realized sequence iss that contains lazy, infinite sequences. How to print out the first elements of every infinite sequence, then the second element of every infinite sequence, and so on?

user100464
  • 17,331
  • 7
  • 32
  • 40
Mate Varga
  • 3,144
  • 2
  • 14
  • 17

2 Answers2

3

I'd use a simple map vector. It returns a lazy sequence of applications of vector to the first elements of all the sequences, then the second elements and so on. Until you force realization, nothing get's mapped.

Try it for yourself (note that (range) returns an infinite lazy seq):

(def lazy-zipped (map vector (range) (drop 10 (range)) (drop 20 (range))))

(take 5 lazy-zipped)

prints

([0 10 20] [1 11 21] [2 12 22] [3 13 23] [4 14 24])
soulcheck
  • 36,297
  • 6
  • 91
  • 90
  • That looks good -- I've ended up writing a 'flip' function that converts a sequence of sequences (with dimensions X*infinity) into another (infinity*X): `(defn flip [seq-of-seqs]` `(cons` `(map first seq-of-seqs)` `(lazy-seq (flip (map rest seq-of-seqs)))))` -- and iterating through that is easy. – Mate Varga Oct 02 '14 at 16:39
1

Maybe this?

user=> (def seq1 (iterate inc 1))
#'user/seq1
user=> (def seq2 (iterate inc 10))
#'user/seq2
user=> (take 10 (partition 2 (interleave seq1 seq2)))
((1 10) (2 11) (3 12) (4 13) (5 14) (6 15) (7 16) (8 17) (9 18) (10 19))
user100464
  • 17,331
  • 7
  • 32
  • 40