How do I get the sum of all elements in a given list using chez scheme? -


(define lista (list 1/2 2/3 3/4 4/5 5/6)) (define l (length lista))  (define suma ( lambda() (     (let s((i 0))         (if (= l 1)             (list-ref lista i)             (   (if(< (- l 2))                     (+ (list-ref lista i) (s (+ 1)))                       )             )         )     ) )    ) ) 

i following error when run (suma):

attempt apply non-procedure #<void>.

new @ please help. thank you!

the simplest way add elements in list use apply:

(apply + lista) => 3 11/20 

but guess want implement scratch. procedure has lots of parentheses errors, , way you're iterating on list (using list-ref) not idiomatic - in scheme use recursion traverse lists, not indexes. fixing requires quite bit of work:

(define suma   (lambda ()     (let s ((i 0))       (if (= (- l 1))           (list-ref lista i)           (+ (list-ref lista i)              (s (+ 1))))))) 

but still, if solve problem using explicit recursion, above not idiomatic. solution more in spirit of scheme follows, , notice template traversing list:

(define (suma lst)           ; pass list parameter   (if (null? lst)            ; list empty?       0                      ; we've reached base case, return 0       (+ (car lst)           ; otherwise add current element          (suma (cdr lst))))) ; , advance recursion 

alternatively, use tail recursion write more efficient solution:

(define (suma lst)   (let s ((lst lst)              ; list traverse           (acc 0))               ; accumulated result     (if (null? lst)              ; if list empty         acc                      ; return accumulator         (s (cdr lst)             ; otherwise advance recursion            (+ (car lst) acc))))) ; , update accumulator 

either way, pass input list parameter , works expected:

(suma lista) => 3 11/20 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -