此函数适用于多少个参数?

时间:2018-10-22 05:32:32

标签: arguments racket

((lambda (x y) (* x y)) (2 3))

application: not a procedure;
 expected a procedure that can be applied to arguments
  given: 2
  arguments...:
   3
  context...:
   /Applications/Racket v7.0/share/pkgs/sandbox-lib/racket/sandbox.rkt:493:0: call-with-custodian-shutdown
   /Applications/Racket v7.0/collects/racket/private/more-scheme.rkt:148:2: call-with-break-parameterization
   .../more-scheme.rkt:261:28
   /Applications/Racket v7.0/share/pkgs/sandbox-lib/racket/sandbox.rkt:861:5: loop

正确的表达应为

((lambda (x y) (* x y)) 2 3)

但是我还是不太明白错误消息。

Given 2

表示该函数需要2个参数,不是吗? 但是以下是什么意思?

arguments...:
   3

我认为该函数将(2 3)作为一个参数。为什么会告诉3?

1 个答案:

答案 0 :(得分:1)

您看到的错误是不是一个Arity不匹配错误。当您在Racket中应用带有错误数量的参数的函数时,会出现如下错误:

> (define (f x)
    (void))
> (f 1 2)
f: arity mismatch;
 the expected number of arguments does not match the given number
  expected: 1
  given: 2
  arguments...:
   1
   2

请注意,错误消息中提到了函数名称(在这种情况下为f),并明确表示“ arity mismatch”,并包括说明性描述。您问题中的错误消息是另一则错误消息:

application: not a procedure;
 expected a procedure that can be applied to arguments
  given: 2
  arguments...:
   3

让我们细分此消息。

  1. 错误消息未提及任何特定的函数名称。相反,发出此错误消息的一方只是“应用程序”,也就是说,实现功能应用程序的语言部分本身正在引发错误。

  2. 错误消息的简短描述是“不是过程”。这意味着您试图将某些值用作函数,但它根本不是函数。较长的说明对此进行了详细说明:它期望可以应用的功能,但发现了其他内容。

  3. 鉴于上述情况,错误消息的“给定”部分更有意义。消息中的2没有描述一些参数,但实际上是指您尝试应用的 value 。您可以使用稍微简化的示例来重现此内容:

    > (2 3)
    application: not a procedure;
     expected a procedure that can be applied to arguments
      given: 2
      arguments...:
       3
    

    如果我们使用一个不包含数字的示例,则更清楚了,这样就不会混淆其他值:

    > ("not a function" "first arg" "second arg")
    application: not a procedure;
     expected a procedure that can be applied to arguments
      given: "not a function"
      arguments...:
       "first arg"
       "second arg"
    

如果我们返回您的原始程序,则可以清楚出了什么地方出了问题。由于(2 3)周围有一组括号,因此您尝试将2用作函数(因为括号表示在Racket中是函数应用程序),这是不合法的。该错误报告了这种违反情况。