Exercise 1.43
If f f f is a numerical function and n n n is a positive integer, then we can form the n t h n^{th} nth repeated application of f f f, which is defined to be the function whose value at x x x is f ( f ( . . . ( f ( x ) ) . . . ) ) f (f (...(f (x)). . .)) f(f(...(f(x))...)). For example, if f f f is the function x → x + 1 x\rightarrow x + 1 x→x+1, then the n t h n^th nth repeated application of f f f is the function x → x + n x\rightarrow x+n x→x+n. If f f f is the operation of squaring a number, then the n t h n^{th} nth repeated application of f f f is the function that raises its argument to the 2 n 2^n 2n-th power. Write a procedure that takes as inputs a procedure that computes f f f and a positive integer n n n and returns the procedure that computes the n t h n^{th} nth repeated application of f f 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.
这道题稍微复杂一点,要用一个循环来实现重复调用目标函数 n n n 次。
; f 表示函数,参数只有一个且为数值;n 表示要嵌套执行多少次 f 函数
(define (repeated f n)
(if (= n 1)
(lambda (x) (f x))
(compose f (repeated f (- n 1)))))
((repeated square 2) 5)
((repeated inc 10) 5)
; 执行结果
625
15