顶级列表中所有数字的总和
Sum of all numbers in a list at the top level
我是 Scheme 的新手,我已经花了大约一个星期的时间。
Write a Lisp function sumlist which takes a list and returns the sum of all the numbers in the list, at the top level. Thus,
(sumlist '(1 2 (3) (4 a) nil b 5)) should return 1+2+5=8. The numbers 3 and 4 are not at the top level. Use number? to check if a thing is a number."
这就是我目前所拥有的。它可以识别某物是否是数字,但是我无法让它只将顶层的数字相加。
(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
感谢任何帮助。
编辑:Jedi 和 Daniel 的回答都有效。非常感谢你们。
我觉得可以再简单一点:
(define (sumlist lst)
(cond
((null? lst) 0)
((number? (car lst)) (+ (car lst) (sumlist (cdr lst))))
(else (sumlist (cdr lst)))))
因为你只关心一个元素是不是数字,所以你只有3种情况。
(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
))
我是 Scheme 的新手,我已经花了大约一个星期的时间。
Write a Lisp function sumlist which takes a list and returns the sum of all the numbers in the list, at the top level. Thus, (sumlist '(1 2 (3) (4 a) nil b 5)) should return 1+2+5=8. The numbers 3 and 4 are not at the top level. Use number? to check if a thing is a number."
这就是我目前所拥有的。它可以识别某物是否是数字,但是我无法让它只将顶层的数字相加。
(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
感谢任何帮助。
编辑:Jedi 和 Daniel 的回答都有效。非常感谢你们。
我觉得可以再简单一点:
(define (sumlist lst)
(cond
((null? lst) 0)
((number? (car lst)) (+ (car lst) (sumlist (cdr lst))))
(else (sumlist (cdr lst)))))
因为你只关心一个元素是不是数字,所以你只有3种情况。
(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
))