The simplest way to add all the elements in a list would be to use apply
:
(apply + lista)
=> 3 11/20
But I guess you want to implement this from scratch. Your procedure has lots of parentheses errors, and the way you're iterating over the list (using list-ref
) is not idiomatic - in Scheme we use recursion to traverse lists, not indexes. Fixing it requires quite a bit of work:
(define suma
(lambda ()
(let s ((i 0))
(if (= i (- l 1))
(list-ref lista i)
(+ (list-ref lista i)
(s (+ i 1)))))))
But still, even if we were to solve this problem using explicit recursion, the above is not idiomatic. A solution more in the spirit of Scheme would look as follows, and notice the template for traversing a list:
(define (suma lst) ; pass the list as a parameter
(if (null? lst) ; is the list empty? then
0 ; we've reached the base case, return 0
(+ (car lst) ; otherwise add the current element
(suma (cdr lst))))) ; and advance the recursion
Alternatively, we could use tail recursion to write a more efficient solution:
(define (suma lst)
(let s ((lst lst) ; list to traverse
(acc 0)) ; accumulated result
(if (null? lst) ; if the list is empty
acc ; return the accumulator
(s (cdr lst) ; otherwise advance recursion
(+ (car lst) acc))))) ; and update accumulator
Either way, we pass the input list as parameter and it works as expected:
(suma lista)
=> 3 11/20