omega
omega

Reputation: 43833

scheme recursion

I am trying to create a scheme recursive function deep_count that counts the sum of the numbers even if it's nested in sub lists.

(define deep_count
  (lambda (xs)
    (cond 
      ((empty? xs) 0)
      ((list? (first xs)) (+ 
                           (deep_count (first xs)) 
                           (deep_count (rest xs))))
      (else (+ 1 (deep_count (rest xs)))))))

(deep_count '(1 2 3 (4 5 6) ((7 8 9) 10 (11 (12 13)))))

But I am getting 13 instead of 91. Whats wrong here?

EDIT: never mind, I know why.

Upvotes: 1

Views: 212

Answers (1)

Óscar López
Óscar López

Reputation: 235984

There's a small mistake at the end. Change this:

(+ 1 (deep_count (rest xs)))

... For this, and you're all set:

(+ (first xs) (deep_count (rest xs)))

Upvotes: 2

Related Questions