Log in Page Discussion History Go to the site toolbox

Exercise 3.55

From BluWiki

Section 3.5 Exercises

Exercise 3.55

Define a procedure partial-sums that takes as argument a stream S and returns the stream whose elements are S0, S0 + S1, S0 + S1 + S2, .... For example, (partial-sums integers) should be the stream 1, 3, 6, 10, 15, ....

(define (partial-sums stream)
  (cons-stream (stream-car stream)
               (add-streams (stream-cdr stream)
                            (partial-sums stream))))

A simple test:

(define x (partial-sums (integers-starting-from 0)))
;; The nth element of x should be the sum
;; of the first n non-negative integers.
(for-each (lambda (n)
            (newline)
            (display (stream-ref x n)))
          (list 0 1 2 3 4 5))

This prints:

0    ; 0
1    ; 0  + 1
3    ; 1  + 2
6    ; 3  + 3
10   ; 6  + 4
15   ; 10 + 5

A more interesting test: The sum of the first n non-negative integers should be <math>(n/2) * (n+1)</math>.

(- (stream-ref x 135)
   (* (+ 135 1) (/ 135 2)))
0

Site Toolbox:

Personal tools
GNU Free Documentation License 1.2
This page was last modified on 19 October 2007, at 18:19.
Disclaimers - About BluWiki