Reputation: 11012
I'm trying to implement a function which calc sum of list , its name is sum
-
(define (sum elemList)
(if
(null? elemList)
(+ (car elemList) (sum (cdr elemList)))
0
)
)
The above implementation gives wrong result , for example -
> (sum (list 1 2 3 4 ))
0
What I did wrong here ?
Upvotes: 3
Views: 18368
Reputation: 11
Please refer by this link for more details. -http://groups.umd.umich.edu/cis/course.des/cis400/scheme/listsum.htm
(define(list-sum lst)
(cond
((null ? lst)
0)
((pair? (car lst))
(+(list-sum (car lst)) (list-sum (cdr lst))))
(else
(+ (car lst) (list-sum (cdr lst))))))
Upvotes: 0
Reputation: 1703
You can also use apply
(define (sum elemList) (apply + elemList))
Should give you the same results
Upvotes: 3
Reputation: 20950
I think you swapped the then and the else part of the if
:
(define (sum elemList)
(if
(null? elemList)
0
(+ (car elemList) (sum (cdr elemList)))
)
)
In the original function, for every non-empty list, 0
is returned.
Upvotes: 8