USERSFU
USERSFU

Reputation: 69

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

Upvotes: 0

Views: 1933

Answers (2)

Óscar López
Óscar López

Reputation: 236112

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

Upvotes: 3

lioumens
lioumens

Reputation: 120

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

Upvotes: 0

Related Questions