I'd like to add all items in a vector in Scheme.
I believe my problem areas are in the way I use lambda (very unsure of this expression's correct usage), assign the length of the vector to variable i and add the value I attempt to get from each of the elements in the vector. Not sure how to fix the error based on the error message.
The error I am getting is just:
#< procedure>
the code:
(define (sum X)
(define length (vector-length X)) ;potential problem area
(lambda (length)
(lambda (total)
(do (
(i length (- i 1))
(a (vector-ref X i)(+ a total)) ; potential problem area
)
((zero? i) total)
)
)
)
)
Revised code (thanks user479988) - I've removed the lambdas, realized I dont need them. And defined the variable i to an initial 0.
The error is now the output is showing 0.
The code:
(define (sum X)
(define length (vector-length X)) ;potential problem area
(define total 0)
(define i 0)
(do (
(i length (- i开发者_Go百科 1))
(a (vector-ref X i)(+ a total)) ; potential problem area
((zero? i) total)
)
)
)
Could you please advise on the i) error ii) logic of the algorithm
Thanks!
I can't really tell the structure of your program because the parenthesis are mismatched and the indentation is hard to read but I think you're not giving the lambdas any input so instead of returning the sum, you return the function you made with the lambdas since you didn't evaluate them.
精彩评论