2013-09-26 34 views
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)))))))) 

回答

5

在這一行,你打電話multBins(cons 0 x)(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 -------------+ 

推測的unapplicable值'(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,其定義我沒有,並與firstrest定義),DrRacket凸顯違規調用的位置:

bad code highlighted in DrRacket IDE

雖然我指出的兩個有問題的調用都需要修復,但您現在看到的錯誤發生在二者中的第二個。

+1

優秀和徹底的解釋。去年春天,我和博士博士做了一些工作,並且有一個很好的把手,但我忘了這個皺紋。簡短的答案是不要使用太多括號! – smirciat

相關問題