2016-02-01 55 views
0

我是Scheme的新手,我已经花了大约一周的时间了。顶级列表中所有数字的总和

编写一个Lisp函数列表,其中包含一个列表并返回列表中所有数字之和的顶级函数。因此, (sumlist'(1 2(3)(4a)nil b 5))应该返回1 + 2 + 5 = 8。数字3和4不在顶层。使用数字?检查的事情是一个数字。”

这是我到目前为止,它可以识别的东西是否是一个数字或没有,但我不能得到它仅加起来的数字顶级

(define (sumlist lst) 
    (cond ((null? lst) 0) 
     ((number? lst) lst) 
     ((list? lst) 
     (+ (sumlist (car lst)) (sumlist (cdr lst)))) 
     (#t 0))) 
; no values returned 
> (sumlist '(1 2 (3) (4 a) nil b 5)) 
15 

任何帮助表示赞赏

编辑:。。无论绝地的和丹尼尔的回答工作,谢谢两位非常

+2

如果您只关心顶层,则不需要递归到“(汽车1)”。 – Barmar

回答

2
(define (sumlist lst) 
(cond ((null? lst) 0) ;; list is empty, we're done ;; 
    ((number? (car lst)) (+ (car lst) (sumlist (cdr lst)))) ;; the first item is a number, so we add it to the rest 
    (else (sumlist (cdr lst))) ;; the first item was not a number, we just check the rest of the list 
)) 
3

我认为这可能是一个有点更简单:

(define (sumlist lst) 
    (cond 
     ((null? lst) 0) 
     ((number? (car lst)) (+ (car lst) (sumlist (cdr lst)))) 
     (else (sumlist (cdr lst))))) 

既然你只关心一个元素是否是数字,那么你只有三种情况。

相关问题