<< Previous exercise (3.54) | Index | Next exercise (3.56) >>
Must have self-reference to avoid recalculation:
(define (partial-sums s)
(define ps (add-streams s (cons-stream 0 ps)))
ps)
My solution:
(define (partial-sums S)
(cons-stream (stream-car S)
(add-streams (partial-sums (stream-cdr S))
S)))
dekuofa1995's solution is wrong. For his, (partial-sums integers) returns 1, 3, 7, 12... correct solution should return (partial-sums integers) => 1, 3, 6, 10...
(define (partial-sums s)
(cons-stream (stream-car s)
(add-streams (partial-sums s)
(stream-cdr s))))
(define (partial-sums s) (cons-stream (stream-car s) (add-streams (stream-cdr s) (partial-sums s))))
dzy
this will cause recalculation.
LisScheSic
More specifically, "Defining streams implicitly" all use something like (define a (cons-stream first a)) if using recursion up to this exercise. Notice in this form 2 a's are the same variable.
But in the above definition, the call of (partial-sums s) inside itself will create one totally new env in the global environment and can't reuse the calculation with each other. You can check this by doing something like (trace add-streams):
---
Also see http://community.schemewiki.org/?sicp-ex-3.63 as xdavidliu says in http://community.schemewiki.org/?sicp-ex-3.61.