【发布时间】:2020-09-30 12:56:42
【问题描述】:
我正在处理来自 The Structure and Interpretation of Computer Programs 的 exercise 1.43。
练习 1.43. 如果 f 是一个数值函数,而 n 是一个正整数,那么我们可以形成 nf的第一次重复应用,它被定义为在x处的值为f(f(...(f(x))的函数)...))。例如,如果f是函数x ↦ x + 1,那么f的第n次重复应用是函数 x ↦ x + n。如果 f 是一个数的平方运算,那么 f 的第 n 次重复应用是将其参数提升到 2n次幂。编写一个过程,将计算 f 和一个正整数 n 的过程作为输入,并返回计算第 n 个重复应用的过程f。您的程序应该可以按如下方式使用:
((repeated square 2) 5) 625提示:您可能会发现在exercise 1.42 中使用
compose会很方便。
我这样写代码:
(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)))))
【问题讨论】: