我正在从[[exercise 1.43处理The Structure and Interpretation of Computer Programs。
是一个数值函数,而[[n是一个正整数,那么我们可以形成f的第[[n个重复应用,它定义为在[[x处的值为f(f(...(f(x))...))]的函数。例如,如果f是函数x x + 1,则f的n重复应用是函数x x + n 。如果f是对数字进行平方运算,则f的n重复应用是将其自变量提高到第2 n的函数功率。编写一个过程,该过程将计算f和正整数n的过程作为输入,并返回计算f的第n次重复应用的过程。您的过程应该可以如下使用:练习1.43。如果f
((repeated square 2) 5)
625
提示:您可能会发现使用compose
中的exercise 1.42很方便。我写了这样的代码:(define (repeated f n)
(lambda (x)
(if (= n 1)
(f x)
(f ((repeated f (- n 1)))))))
错误:
> ((repeated square 2) 5) ...p/1.3.4-mine.rkt:22:2: arity mismatch; the expected number of arguments does not match the given number expected: 1 given: 0
为什么我的代码不起作用?正确答案是:
(define (repeated f n)
(if (= n 1)
f
(lambda (x)
(f ((repeated f (- n 1)) x)))))
((repeated f (- n 1)))
repeated
返回一个带有一个自变量的过程,因此,不带自变量调用结果应表示Arity错误。
正确的答案是在递归调用中传递一个必需的参数。在现实生活中,尽管您不会在每个步骤上都重新创建过程,但是可能使用了一个命名为let
:
(define (repeated f n) (if (= n 1) f (lambda (x) (let loop ((acc x) (n n)) (if (zero? n) acc (loop (f acc) (- n 1)))))))