#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))
When I try this, I am getting the wrong result. What’s the problem here?
> (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
Take (vectorSum A 0 3), when I expanded the recursion, I thought it was supposed to be
+ 1 + VectorSum (1 3)
+ 1 + VectorSum (2, 3)
+ 1 + VectorSum (3, 3)
+ 1 (I hit the first case, there is no more recursion)
= 4
Instead, I get 6. Why?
Thanks.
Look at 0,1 and 1,2 the answers aren’t equal.
Your answer should look like this:
It was a simple mistake – you forgot a couple of parenthesis in this line:
It should have been:
Without those parenthesis, you’re not actually calling the
vector-refprocedure, instead you’re listing some symbols and returning the final one,bin this case. Remember to always surround a procedure call and its arguments between parenthesis, just as you did in theelsepart.