I'm using scheme. I'm having no problems in finding the sum of a certain list but I'm quite having trouble in adding the sum when a list has a list in it or AKA Nested List.
(define (my-summation li)
(if (null? li)
0
((if (list? (car li)) (my-summation (car li))
(+ (car li) (my-summation (cdr li)))))))
This was my input and this was the result of the error. Scheme is my weakness since it involves recursion but I can't seem to find the problem.
> (my-summation '(6 3 -2 5 '(4 2 -3) 4 ))
function call: expected a function after the open parenthesis, but received -3
Its in the parentheses, you have an extra set around the if
. Also you don't need to quote a list when it is in a quoted list. And the (list? (car li))
case was incorrect, it should sum the element and the rest of the list.
(define (my-summation li)
(if (null? li)
0
(if (list? (car li))
(+ (my-summation (car li)) (my-summation (cdr li)))
(+ (car li) (my-summation (cdr li))))))
(my-summation '(6 3 -2 5 (4 2 -3) 4))
Results in a sum of 19
.
An alternative solution:
(define (sum-list xs)
(define (loop sum-so-far xs)
(cond
[(null? xs) sum-so-far] ; no-more-elements
[(pair? (car xs)) (loop (+ sum-so-far (sum-list (car xs))) ; the first element is a sublist
(cdr xs))] ; so sum-list computes its sum
[else (loop (+ sum-so-far (car xs)) ; the first element is a number
(cdr xs))])) ; so it is added directly
(loop 0 xs))
(sum-list '(6 3 -2 5 (4 2 -3) 4)) ; note: no quote in the middle
; ==> 19
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.