#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