my attempt to do the exercises in sicp.

Sunday, December 19, 2010

sicp exercise 3.60

;; Exercise 3.60.  With power series represented as streams of coefficients as in exercise 3.59, adding series is implemented by add-streams. Complete the definition of the following procedure for multiplying series:

;; (define (mul-series s1 s2)
;;  (cons-stream <??> (add-streams <??> <??>)))

;; You can test your procedure by verifying that sin^2 x + cos^2 x = 1, using the series from exercise 3.59.

(define (integrate-series s)
  (define (integrate-series-i s n)
    (cons-stream  (/ (stream-car s) n)
                  (integrate-series-i (stream-cdr s) (+ 1 n))))
  (integrate-series-i s 1))

(define (mul-stream s1 s2)
  (stream-map * s1 s2))

(define minus-one
  (cons-stream -1 minus-one))

(define cosine-series
  (cons-stream 1 (mul-stream minus-one (integrate-series sine-series))))

(define sine-series
  (cons-stream 0 (integrate-series cosine-series)))

(define (scale-stream stream factor)
  (stream-map (lambda (x) (* x factor)) stream))

(define (add-streams s1 s2)
  (cons-stream (+ (stream-car s1) (stream-car s2))
               (add-streams (stream-cdr s1)(stream-cdr s2))))

(define (mul-series s1 s2)
    (* (stream-car s1)
       (stream-car s2))
       (add-streams (scale-stream (stream-cdr s1) (stream-car s2))
                    (scale-stream (stream-cdr s2) (stream-car s1)))
       (cons-stream 0 (mul-series (stream-cdr s1) (stream-cdr s2))))))

(define test (add-streams (mul-series sine-series sine-series)
                          (mul-series cosine-series cosine-series)))

(display (stream-ref test 0))(newline)
(display (stream-ref test 1))(newline)
(display (stream-ref test 2))(newline)
(display (stream-ref test 3))(newline)
(display (stream-ref test 4))(newline)
(display (stream-ref test 5))(newline)

;Loading "sicp_prob_03.60.scm"...
;... done

No comments: