为什么会出现“ arity mismatch”错误?在SICP中练习1.43

问题描述 投票:2回答:1

我正在从[[exercise 1.43处理The Structure and Interpretation of Computer Programs

练习1.43。如果f

是一个数值函数,而[[n是一个正整数,那么我们可以形成f的第[[n个重复应用,它定义为在[[x处的值为f(f(...(f(x))...))]的函数。例如,如果f是函数x x + 1,则fn重复应用是函数x x + n 。如果f是对数字进行平方运算,则fn重复应用是将其自变量提高到第2 n的函数功率。编写一个过程,该过程将计算f和正整数n的过程作为输入,并返回计算f的第n次重复应用的过程。您的过程应该可以如下使用:((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)))))
racket sicp
1个回答
0
投票
((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)))))))

© www.soinside.com 2019 - 2024. All rights reserved.