gpt4 book ai didi

racket - 为什么会出现 "arity mismatch"错误? SICP 练习 1.43

转载 作者:行者123 更新时间:2023-12-03 23:06:35 27 4
gpt4 key购买 nike

我正在研究 exercise 1.43来自 The Structure and Interpretation of Computer Programs .

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 ↦ x + 1, then the nth repeated application of f is the function x ↦ 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 (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 square 2) 5)

看看你是如何进行递归的:

((repeated f (- n 1)))

repeated 返回一个接受一个参数的过程,因此调用不带参数的结果应该表示一个元数错误。

在正确的答案中,它在递归调用中传递了一个必需的参数。在现实生活中,您不会在每一步都重新创建过程,但可能会使用一个命名的 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)))))))

关于racket - 为什么会出现 "arity mismatch"错误? SICP 练习 1.43,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62314940/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com