Reputation: 588
I'm trying to write a procedure that takes 2 streams and that puts together their pairs and then interleaves them. Right now it's not producing the correct output. Here's the code I have:
(define (interleave-pairs s t)
(cons-stream (cons (stream-car s) (stream-car t))
(cons-stream
(stream-map (lambda (x) (cons (stream-car s) x))
(stream-cdr t))
(interleave-pairs t (stream-cdr s)))))
To obtain the values I wrote a procedure:
(define (take n s)
(if (= n 0)
'()
(cons (stream-car s) (take (- n 1) (stream-cdr s)))))
And this is for the stream of integers:
(define integers (cons-stream 1 (add-streams ones integers)))
So when I call
(take 6 (pairs integers integers))
I'm getting:
((1 . 1)
((1 . 2) . #<promise>)
(1 . 2)
((1 . 3) . #<promise>)
(2 . 2)
((2 . 3) . #<promise>))
Whereas I want (1 1) (1 1) (1 2) (1 3) (2 2) (2 3)
Upvotes: 0
Views: 1005
Reputation: 236004
The base case in your procedure is missing (what happens if one of the streams ends before the other?). The procedure is rather simple, just take one pair of elements (one from each stream) and then interleave them, no need to use stream-map
here:
(define (pairs s1 s2)
(if (stream-null? s1)
s2
(stream-cons (list (stream-car s1) (stream-car s2))
(pairs s2 (stream-cdr s1)))))
Upvotes: 2