我有一个简单的球拍定义,用于将二进制数相乘。它使用经过充分测试的“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))))))))