#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的答案是不相等的。
所以主要原因實際上是在第一種情況下vector-ref中沒有括號。這是如何引起問題的?我怎樣才能跟蹤這個?非常感謝你。 – CppLearner 2012-02-13 01:41:40
如果沒有這些括號,你實際上並不是在調用'vector-ref'過程,而是在列出一些符號並返回最後一個符號,在這種情況下返回最後一個'b'。如何追蹤它?我想不出一種方法來檢測這種錯誤(除了視覺檢查)之外,只要記住圍繞一個過程調用及其在括號之間的參數,就像您在'else'部分所做的那樣。 – 2012-02-13 01:44:48
謝謝奧斯卡!很好趕:) :) – CppLearner 2012-02-13 01:46:08