Scheme - sum of list

喜你入骨 提交于 2020-01-02 13:57:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!