sicp-ex-1.44



<< Previous exercise (1.43) | sicp-solutions | Next exercise (1.45) >>


 (define dx 0.00001) 
  
 (define (smooth f) 
   (lambda (x) 
     (/ (+ (f (- x dx)) 
           (f x) 
           (f (+ x dx))) 
        3))) 
  
 (define (n-fold-smooth f n) 
   ((repeated smooth n) f)) 

The above answer for n-fold-smooth is incorrect. The function "repeated" is not used correctly in the function. Repeated should be defined as:

 (define (repeated f n) 
   (lambda (x) (cond ((= n 0) x) 
                     (else 
                      ((compose (repeated f (- n 1)) f) x))))) 

And n-fold-smooth (named "n-smooth" below) should be defined as:

 (define (n-smooth f n x) 
   ((repeated (smooth f) n) x)) 

The first solution is correct

 (define (n-fold-smooth f n)  
   ((repeated smooth n) f))  

and the second is incorrect.

 (define (n-smooth f n x) 
   ((repeated (smooth f) n) x)) 

The input needs only the function and the number of smoothing procedure, so it should not include x. Also in the second solution, we get the n-times composition of (smooth f), instead of the desired n-times composition of (smooth) as a procedure, which is then applied to f.


for example, ((n-fold-smooth square 1) 5) and ((smooth square) 5)

Have to be same. but, first one returns 25 and second one returns 25.666 So We can realize something wrong with above's solution. We have to find another solutions.

 (define (n-fold-smooth2 f n) 
   (if (= n 1) 
       (smooth f) 
       (smooth (n-fold-smooth2 f (- n 1)))))   

this code doesn't use repeated function but It' doesn't caculate inner function repeatedly.

when we use (compose smooth f) instead of (smooth f),

this function returns #<Closure>


gghso

I got the hit from 1.45

 (define (n-fold-smooth3 f n) 
   ((repeated smooth n) (lambda (x) (f x)))) 

I Think this code is the answer