简体   繁体   English

方案 - 列表总和

[英]Scheme - sum of list

I'm trying to implement a function which calc sum of list , its name is sum -我正在尝试实现一个函数,它 calc sum of list ,它的名字是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 ?我在这里做错了什么?

I think you swapped the then and the else part of the if :我认为你换了,然后和的其他部分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.在原始函数中,对于每个非空列表,返回0

You can also use apply您也可以使用apply

(define (sum elemList) (apply + elemList))

Should give you the same results应该给你相同的结果

Please refer by this link for more details.请参考此链接了解更多详情。 - http://groups.umd.umich.edu/cis/course.des/cis400/scheme/listsum.htm - 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))))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM