23 hours ago
my attempt to do the exercises in sicp.
Wednesday, December 15, 2010
sicp exercise 3.55
;; 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 (add-streams s1 s2)
(stream-map + s1 s2))
(define (integers-from-n n)
(cons-stream n (integers-from-n (+ 1 n))))
(define integers (integers-from-n 1))
(define (partial-sum s)
(define result (cons-stream (stream-ref s 0)
(add-streams (stream-cdr s) result)))
result)
(newline)
(display (stream-ref (partial-sum integers) 0))(newline)
(display (stream-ref (partial-sum integers) 1))(newline)
(display (stream-ref (partial-sum integers) 2))(newline)
(display (stream-ref (partial-sum integers) 3))(newline)
(display (stream-ref (partial-sum integers) 4))(newline)
;; Output:
;Loading "sicp_prob_03.55.scm"...
;1
;3
;6
;10
;15
;... done
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment