方案-清单总和 [英] Scheme - sum of list

查看:84
本文介绍了方案-清单总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个计算list之和的函数,其名称为sum-

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 ?

推荐答案

我认为您交换了if then else 部分:

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)))
  )
)

在原始函数中,对于每个非空列表,都返回0.

In the original function, for every non-empty list, 0 is returned.

这篇关于方案-清单总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆