2012-02-13 37 views
3
#lang eopl 

(define (vectorSum V b e) ; b is starting index, and e is ending index 
    (cond 
    [ (eqv? b e) vector-ref V b] 
    [ (> b e) 
     (eopl:error 'vectorSum "starting index must be smaller than or equal to the end index")] 
    [ else (+ (vector-ref V b) (vectorSum V (+ b 1) e))])) 


(define A #(1 1 1 1 1)) 

當我嘗試這個時,我得到了錯誤的結果。這裏有什麼問題?爲什麼這個遞歸添加在Scheme中是錯誤的?

> (vectorSum A 0 4) 
8 
> (vectorSum A 0 1) 
2 
> (vectorSum A 0 3) 
6 
> (vectorSum A 1 3) 
5 
> (vectorSum A 1 2) 
3 

> (vectorSum A 0 1) 
2 
> (vectorSum A 1 2) 
3 

採取(vectorSum A 0 3),當我擴大了遞歸,我認爲這應該是

+ 1 + VectorSum (1 3) 
    + 1 + VectorSum (2, 3) 
     + 1 + VectorSum (3, 3) 
      + 1 (I hit the first case, there is no more recursion) 
= 4 

相反,我得到6.爲什麼?

謝謝。


看看0,1和1,2的答案是不相等的。

回答

2

你的回答應該是這樣的:

(define (vectorSum V b e) 
    (cond ((eqv? b e) 
     (vector-ref V b)) 
     ((> b e) 
     (eopl:error 'partialVectorSum "starting index must be smaller than or equal to the end index")) 
     (else (+ (vector-ref V b) (vectorSum V (+ b 1) e))))) 

這是一個簡單的錯誤 - 你忘了一對夫婦括號這一行:

[ (eqv? b e) vector-ref V b] 

它應該是:

[ (eqv? b e) (vector-ref V b) ] 

沒有這些括號,你實際上並沒有調用vector-ref程序,instea d你列出了一些符號並返回最後一個,在這種情況下爲b。請記住,始終圍繞過程調用及其括號之間的參數,就像您在else部分中所做的那樣。

+0

所以主要原因實際上是在第一種情況下vector-ref中沒有括號。這是如何引起問題的?我怎樣才能跟蹤這個?非常感謝你。 – CppLearner 2012-02-13 01:41:40

+1

如果沒有這些括號,你實際上並不是在調用'vector-ref'過程,而是在列出一些符號並返回最後一個符號,在這種情況下返回最後一個'b'。如何追蹤它?我想不出一種方法來檢測這種錯誤(除了視覺檢查)之外,只要記住圍繞一個過程調用及其在括號之間的參數,就像您在'else'部分所做的那樣。 – 2012-02-13 01:44:48

+0

謝謝奧斯卡!很好趕:) :) – CppLearner 2012-02-13 01:46:08

3

你對遞歸如何展開的理解是正確的。您的問題是,您忘記在第一種情況下將您的呼叫加括號爲vector-ref。你寫的方式vector-ref V b被解釋爲三個獨立的表達式。其中最後一個(b)是表達式的值。因此,在你的例子中b是3,你會得到1 + 1 + 1 + 3 = 6

只需添加圓括號以使其成爲函數調用,並且它將按照您希望的方式工作。

+0

啊。現在我懂了。花了20分鐘,爲什麼。在stackoverflow上問問總是很好的!你們好棒! – CppLearner 2012-02-13 01:43:03