【问题标题】:Why do I get an "arity mismatch" error? Exercise 1.43 in SICP为什么我会收到“arity mismatch”错误? SICP中的练习1.43
【发布时间】:2020-09-30 12:56:42
【问题描述】:

我正在处理来自 The Structure and Interpretation of Computer Programsexercise 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)))))

【问题讨论】:

    标签: racket sicp


    【解决方案1】:

    先看你怎么称呼它:

    ((repeated square 2) 5)
    

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

    ((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)))))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-13
      • 2012-07-05
      • 2011-11-05
      • 2017-02-03
      • 2010-12-26
      • 2012-12-15
      • 2021-05-23
      • 1970-01-01
      相关资源
      最近更新 更多