Exercise 2.35

Read Exercise 2.35 ~ Solution


(define (count-leaves t)
  (accumulate +
              0 
              (map (lambda (root)
                     (if (leaf? root)
                         1
                         (count-leaves root)))
                   t)))

(define x (cons (list 1 2) (list 3 4)))
(count-leaves x)
4
(count-leaves (list x x))
8

3 thoughts on “Exercise 2.35

  1. I found a little strange to force the use of map in this definition. The only solution I could think of was

    (define (count-leaves-enum t)
    (accumulate (lambda (x y) (+ 1 y))
    0
    (enumerate-tree t)))

    which, for me at least, seems a lot simpler.

    1. Yes. Even simpler is just (length (enumerate-tree t)). I think the point is to give us some practice with – and get us to think more deeply about – using the higher order primitives map and accumulate.

Leave a comment