6
\$\begingroup\$

Exercise 2.35. Redefine count-leaves from section 2.2.2 as an accumulation:

(define (count-leaves t) (accumulate <??> <??> (map <??> <??>)))

I wrote the following:

(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence)
          (accumulate op initial (cdr sequence)))))

(define (count-leaves t)
  (accumulate +
              0
              (map (lambda (subtree)
                     (if (pair? subtree) 
                         (count-leaves subtree)
                         1))
                   t)))

(define a (list 1 2 (list 1) (list 1 2 (list 2 (list 1 2)))))

What do you think?

\$\endgroup\$
2
\$\begingroup\$

The code doesn't handle the case of only a single leaf, i.e.

 (count-leaves 'leaf)

but I guess that's a side-effect of the original problem formulation. A cleaner solution would be

(define (count-leaves t)
  (if (pair? t)
      (accumulate + 0 (map count-leaves t))
      1)))

also because it's shorter but this doesn't fit the pattern of the original exercise.

Incidentally, in this case the standard Scheme procedure apply would be enough because the Scheme + routine takes in an arbitrary number of arguments, and you could write just:

(define (count-leaves t)
  (if (pair? t)
      (apply + (map count-leaves t))
      1)))
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.