Dan's Thoughts Thinking somewhat carefully

13Jul/090

Exercise 1.43 of SICP

Exercise 1.43: If f is a numerical function and n is a positive integer, then we can form the nth repeated application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, if f is the function x \mapsto  x + 1, then the nth repeated application of f is the function x \mapsto  x + n. If f is the operation of squaring a number, then the nth repeated application of f is the function that raises its argument to the 2nth power. 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. Your procedure should be able to be used as follows:

((repeated square 2) 5)
625

Hint: You may find it convenient to use compose from exercise 1.42.

(define (compose f g)
  (lambda (x) 
    (f (g x))))
 
(define (square n) (* n n))
(define (repeated fn n)
  (if (= n 1)
    fn
    (compose 
      fn (repeated fn (- n 1)))))

> ((repeated square 2) 5)
625

> ((repeated square 3) 5)
390625

> ((repeated (lambda (x) (+ x 1)) 3) 5)
8

Filed under: lisp, SICP Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

Spam protection by WP Captcha-Free

No trackbacks yet.