diff --git a/ex-3_63-xx.scm b/ex-3_63-xx.scm index 0672c86..2ac9bec 100644 --- a/ex-3_63-xx.scm +++ b/ex-3_63-xx.scm @@ -101,4 +101,42 @@ (display "\nex-3.66\n") -; (display "\nex-3.67\n") +(define (pairs s t) + (cons-stream + (list (stream-car s) (stream-car t)) + (interleave + (stream-map (lambda (x) (list (stream-car s) x)) + (stream-cdr t)) + (pairs (stream-cdr s) (stream-cdr t))))) + +(define int-pairs (pairs integers integers)) + +(define prime-pairs + (stream-filter + (lambda (pair) (prime? (+ (car pair) (cadr pair)))) + int-pairs)) + +(define (stream-append s1 s2) + (if (stream-null? s1) + s2 + (cons-stream (stream-car s1) + (stream-append (stream-cdr s1) s2)))) + +(define (interleave s1 s2) + (if (stream-null? s1) + s2 + (cons-stream (stream-car s1) + (interleave s2 (stream-cdr s1))))) + +(assert (find (list 2 5) prime-pairs) 6) +(assert (find (list 3 3) int-pairs) 6) +(assert (find (list 1 100) int-pairs) 197) +;(assert (find (list 99 100) int-pairs) 1000) +;(assert (find (list 100 100) int-pairs) 10) + +; I haven't been able to figure out the relationship by myself. +; The explanations on Schemewiki are good, though: +; http://community.schemewiki.org/?sicp-ex-3.66 + +(display "\nex-3.67\n") + diff --git a/util.scm b/util.scm index 3d79690..4d787c3 100644 --- a/util.scm +++ b/util.scm @@ -74,6 +74,13 @@ (cons (stream-car xs) (take (- n 1) (stream-cdr xs))))) +(define (find item stream) + (define (iter n stream) + (if (equal? (stream-car stream) item) + n + (iter (+ n 1) (stream-cdr stream)))) + (iter 0 stream)) + (define (display-stream s) (stream-for-each display-line s)) @@ -97,4 +104,8 @@ (define (add-streams s1 s2) (stream-map + s1 s2)) +(define ones (cons-stream 1 ones)) + +(define integers (cons-stream 1 (add-streams ones integers))) + 'util-loaded