简体   繁体   中英

scheme sum of the numbers in a list

I am writing a function which give the sum of all the number in a list neglecting words or alphabets.

(define (sum-list ls)
  (cond ((null? ls) 0)
        ((not (number? (car ls))) (sum-list(cdr ls)))
        (else (+ (car ls) (sum-list (cdr ls))))
        )
  )

(deep-sum '(a 2 (b (1 c)) 3)) => ; should return 6.

but i am getting 5. that mean my code is not reaching in the inner loop

That's not the way to traverse a list of lists, it goes more like this:

(define (deep-sum ls)
  (cond ((null? ls) 0)
        ((not (pair? ls))            ; only add atoms
         (if (number? ls) ls 0))     ; only add numbers
        (else (+ (deep-sum (car ls)) ; advance recursion on both car and car
                 (deep-sum (cdr ls))))))

Now it works as expected:

(deep-sum '(a 2 (b (1 c)) 3))
=> 6

If you want to check nested lists, you must have another condition that checks if the element is a list, and then call sum-list recursively.

Adding this line below the null? condition should do it.

((list? (car ls)) (+ (sum-list (car ls)) (sum-list (cdr ls))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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