From 4c4d9fe8ba50bdea74d1cc130f5f99f0b73a1e80 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Thu, 7 Jan 2021 12:14:27 -0500 Subject: [PATCH] Implement till 3.69 --- ex-3_63-xx.scm | 52 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/ex-3_63-xx.scm b/ex-3_63-xx.scm index 2ac9bec..1b28643 100644 --- a/ex-3_63-xx.scm +++ b/ex-3_63-xx.scm @@ -138,5 +138,55 @@ ; The explanations on Schemewiki are good, though: ; http://community.schemewiki.org/?sicp-ex-3.66 -(display "\nex-3.67\n") +(display "\nex-3.67 - all-pairs\n") +(define (all-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 t))) + (stream-cdr s))) + (all-pairs (stream-cdr s) (stream-cdr t))))) + +(define int-pairs (all-pairs integers integers)) + +(assert (stream-ref int-pairs 10) '(3 4)) + +(display "\nex-3.68 - non-lazy pairs\n") +(display "[answered]\n") + +(define (bad-pairs s t) + (interleave + (stream-map (lambda (x) (list (stream-car s) x)) + t) + (pairs (stream-cdr s) (stream-cdr t)))) + +; MIT-Scheme uses applicative-order evluation. Hence, pairs gets evaluated +; recursively. Since there is no delay this implementation results in an +; endless loop. + +(display "\nex-3.69 - triples\n") + +(define (triples a b c) + (cons-stream + (list (stream-car a) (stream-car b) (stream-car c)) + (interleave + (stream-map (lambda (pairs) (cons (stream-car a) pairs)) + (pairs b (stream-cdr c))) + (triples (stream-cdr a) (stream-cdr b) (stream-cdr c))))) + +(define (pythagorean? a b c) + (= (+ (* a a) (* b b)) (* c c))) + +(define pythagorean-triples + (stream-filter (lambda (ts) (apply pythagorean? ts)) + (triples integers integers integers))) + +(assert (stream-ref pythagorean-triples 1) '(6 8 10)) + +(display "\nex-3.70\n") + +; (display "\nex-3.71\n")