my attempt to do the exercises in sicp.

Sunday, January 2, 2011

sicp exercise 3.76

;; Exercise 3.76.  Eva Lu Ator has a criticism of Louis's approach in exercise 3.75. The program he wrote is not modular, because it intermixes the operation of smoothing with the zero-crossing extraction. For example, the extractor should not have to be changed if Alyssa finds a better way to condition her input signal. Help Louis by writing a procedure smooth that takes a stream as input and produces a stream in which each element is the average of two successive input stream elements. Then use smooth as a component to implement the zero-crossing detector in a more modular style.

(define (display-line str)
  (display str)

(define (display-stream str num)
  (define (internal index)
    (if (> index num) 'printed
          (display-line (stream-ref str index))
          (internal (+ 1 index)))))
  (internal 0))

(define (make-zero-crossings input-stream last-value)
  (let ((avpt (/ (+ (stream-car input-stream) last-value) 2)))
    (cons-stream (sign-change-detector avpt last-value)
                 (make-zero-crossings (stream-cdr input-stream)

(define (avg x y)(/ (+ x y) 2))

(define (smooth s)
  (define (iter x y str)
    (cons-stream (avg x y)
                 (iter y (stream-car str) (stream-cdr str))))
  (iter (stream-car s)
        (stream-car (stream-cdr s))
        (stream-cdr (stream-cdr s))))

(define (integers-from-n n)
  (cons-stream n (integers-from-n (+ 1 n))))

(define integers (integers-from-n 0))

(define (make-zero-crossings input-stream last-value)
   (sign-change-detector (stream-car input-stream) last-value)
   (make-zero-crossings (stream-cdr input-stream)
                        (stream-car input-stream))))

(define zero-crossings (make-zero-crossings (smooth (cons-stream 0 sense-data)) 0))

No comments: