sicp-ex-1.43


Define some primitives:

         (define (square x) (* x x)) 
         (define (compose f g) (lambda (x) (f (g x)))) 

Define the procedure:

 (define (repeat f n) 
    (if (< n 1) 
        (lambda (x) x) 
        (compose f (repeat f (- n 1))))) 

Test with:

         ((repeat square 2) 5) 

Output:

         625 

Another solution using the linear iterative way.

  
 (define (repeat f n) 
   (define (iter n result) 
     (if (< n 1) 
         result 
         (iter (- n 1) (compose f result)))) 
   (iter n identity)) 

<< Previous exercise (1.42) | Next exercise (1.44) >>