(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
(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
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.
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.
[…] Several of the other answers I looked at used recursion instead of enumerate-tree. Here’s one I liked: […]