3.67 Exercise 3.67
To get all of the pairs of integers (i, j) including those where i > j, you can consider the pairs meeting the new condition as a new stream to mix in. This stream can be constructed in the same way as the pairs were constructed in the original definition of pairs, but with the pair elements switched.
The only complication is that we need to be careful not to include the pairs (i, j) where i = j twice. This can be done by applying a simple filter to one of the pair streams.
I have also added a base case to handle empty streams, as the pairs and all-pairs procedures don’t need to be called on empty streams. If we ever reach a case where one of the two streams passed in is empty, then there are no more elements in the stream we are creating.
(define (all-pairs s t) (if (or (stream-null? s) (stream-null? t)) the-empty-stream (let ((car-s (stream-car s)) (car-t (stream-car t)) (cdr-s (stream-cdr s)) (cdr-t (stream-cdr t))) (cons-stream (list car-s car-t) (interleave (stream-map (lambda (x) (list car-s x)) (stream-filter (lambda (y) (not (= y car-s))) cdr-t)) (interleave (stream-map (lambda (x) (list x car-s)) cdr-t) (pairs cdr-s cdr-t)))))))
> (display-stream (take-stream (all-pairs integers integers) 20))
(1 1)
(1 2)
(2 1)
(1 3)
(2 2)
(1 4)
(3 1)
(1 5)
(2 3)
(1 6)
(4 1)
(1 7)
(3 3)
(1 8)
(5 1)
(1 9)
(2 4)
(1 10)
(6 1)
(1 11)
'done