乐正

Actions speak louder than words.

Sicp-ex3-55

问题

请定义函数partial-sums,它以流S作为参数,返回的流中的元素是$S_0, S_0 + S_1, S_0 + S_1 + S_2, \cdots$。例如,(partial-sums integers)应该生成流$1, 3, 6, 10, 15, \cdots$。

解答

1
2
3
4
(define (partial-sums s)
  (cons-stream (stream-car s)
               (add-streams (partial-sums s)
                            (stream-cdr s))))

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(define s (partial-sums integers))
;Value: s

(stream-ref s 0)
;Value: 1

(stream-ref s 1)
;Value: 3

(stream-ref s 2)
;Value: 6

(stream-ref s 3)
;Value: 10

(stream-ref s 4)
;Value: 15

draft

« sicp-ex3-54 sicp-ex3-56 »

Comments