2015/12/15

# SICP 問題 3.67

``````;; interleave
(define (pairs s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(interleave (stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(stream-map (lambda (x) (list x (stream-car s)))
(stream-cdr t)))
(pairs (stream-cdr s) (stream-cdr t)))))
``````
``````gosh> (stream-head (pairs integers integers) 20)
(1 1)
(1 2)
(2 2)
(2 1)
(2 3)
(1 3)
(3 3)
(3 1)
(3 2)
(1 4)
(3 4)
(4 1)
(2 4)
(1 5)
(4 4)
(5 1)
(4 2)
(1 6)
(4 3)
(6 1)
done``````
``````;; 三つのストリームを混ぜるinterleave
(define (interleave3 s1 s2 s3)
(if (stream-null? s1)
(interleave s2 s3)
(cons-stream (stream-car s1)
(interleave3 s2 s3 (stream-cdr s1)))))

;; interleave3を使う
(define (pairs s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave3
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(stream-map (lambda (x) (list x (stream-car s)))
(stream-cdr t))
(pairs (stream-cdr s) (stream-cdr t)))))
``````
``````gosh> (stream-head (pairs integers integers) 20)
(1 1)
(1 2)
(2 1)
(2 2)
(1 3)
(3 1)
(2 3)
(1 4)
(4 1)
(3 2)
(1 5)
(5 1)
(3 3)
(1 6)
(6 1)
(2 4)
(1 7)
(7 1)
(4 2)
(1 8)
done``````