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)))))
((repeat square 2) 5)
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))
Note: This is not linearly iterative as described in the book as a chain of deferred operations is still being built.
The above answer does not follow the book's instructions. The book instructs "Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f." A correct answer is as follows:
(define (repeated f n) (lambda (x) (cond ((= n 0) x) (else ((compose (repeated f (- n 1)) f) x)))))
I think the following solution is more elegant. When we only need to apply the function once, we can just return the function (I'm not doing error-checking here to see of n is smaller than 1).
(define (repeated f n) (if (= n 1) f (compose f (repeated f (- n 1)))))
<< Previous exercise (1.42) | Next exercise (1.44) >>