4

我有一个简单的球拍定义,用于将二进制数相乘。它使用经过充分测试的“addWithCarry”定义,该定义采用三个参数:两个列表和一个进位数字并返回二进制和。二进制数以相反的顺序表示为列表。

我用调试器逐步完成了测试线,它正确地通过了递归。每次适当地缩小 y 列表时,它都会执行 multBins,然后按预期执行 addWithCarry 函数。当它返回堆栈时,它突然抛出一个异常“应用程序:不是一个过程,期望一个可以应用于参数的过程”,参数为'(0 0 0 1 0 1 1),这是最高的值“x”添加到总数中。我知道当您尝试将函数的结果作为带参数的函数应用时,可能会发生此错误,但我在这里看不到。看着调试器,一切似乎都在完美运行,直到最后。有任何想法吗?

(define (multBins x y)
  (cond
    ((null? y)       '() )
    ((= (first y) 0) ((multBins (cons 0 x) (rest y))))
    (#t              ((addWithCarry x (multBins (cons 0 x) (rest y)) 0)))))  
(test (multBins '(1 0 1 1)'(1 1 0 1))'(1 1 1 1 0 0 0 1))

这是 addWithCarry 定义:

(define (addWithCarry x y carry)
  (cond
    ((and (null? x)(null? y)) (if (= carry 0) '() '(1)))
    ((null? x) (addWithCarry '(0) y carry))
    ((null? y) (addWithCarry x '(0) carry))
    ( #t  (let ((bit1 (first x))
            (bit2 (first y)))
               (cond
                 ((= (+ bit1 bit2 carry) 0) (cons 0 (addWithCarry (rest x) (rest y) 0)))
                 ((= (+ bit1 bit2 carry) 1) (cons 1 (addWithCarry (rest x) (rest y) 0)))
                 ((= (+ bit1 bit2 carry) 2) (cons 0 (addWithCarry (rest x) (rest y) 1)))
                 (   #t                     (cons 1 (addWithCarry (rest x) (rest y) 1))))))))
4

1 回答 1

5

在这一行中,您multBins使用(cons 0 x)and调用(rest y),并得到一些结果r,然后尝试调用r

((= (first y) 0) ((multBins (cons 0 x) (rest y))))
;                ^                              ^
;                +--- function application -----+

同样的事情发生在下一行,你addWithCarry用一些参数调用,得到一个结果r,然后尝试调用r

(#t              ((addWithCarry x (multBins (cons 0 x) (rest y)) 0)))))
;                ^                                                 ^
;                +-------------- function application -------------+

推测'(0 0 0 1 0 1 1)其中之一正在返回不适用的值。

在一个非常简单的例子中,考虑一下 DrRacket REPL 的这个成绩单:

> (define (value)        ; a function that returns the 
    '(0 0 0 1 0 1 1))    ; same value that yours should

> (value)                ; calling it produces the value 
(0 0 0 1 0 1 1)

> ((value))              ; calling it and then calling
                         ; return value causes the same
                         ; error that you're seeing
; application: not a procedure;
; expected a procedure that can be applied to arguments
;  given: (0 0 0 1 0 1 1)
;  arguments...: [none]

您没有提到您使用的是什么编辑器/IDE/调试器,但有些应该让这更容易被发现。例如,当我加载您的代码时(减去对 的调用test,我没有它的定义,并且定义了firstand rest),DrRacket 会突出显示有问题的调用的位置:

DrRacket IDE 中突出显示的错误代码

虽然我指出的两个有问题的调用都需要修复,但您现在看到的错误发生在两者中的第二个。

于 2013-09-26T12:10:51.623 回答