Implement till 3.69
This commit is contained in:
@@ -138,5 +138,55 @@
|
|||||||
; The explanations on Schemewiki are good, though:
|
; The explanations on Schemewiki are good, though:
|
||||||
; http://community.schemewiki.org/?sicp-ex-3.66
|
; 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")
|
||||||
|
|||||||
Reference in New Issue
Block a user