问题
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 ?
回答1:
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.
来源:https://stackoverflow.com/questions/15019498/scheme-sum-of-list