Using recursion, it's possible to do it with map and without enumerate-tree the following way.
(define (count-leaves-recursive t) (accumulate + 0 (map (lambda (node) (if (pair? node) (count-leaves-recursive node) 1)) t))) ;; Usage (count-leaves-recursive tree) ;; => 7
The previous solution counts the empty list as a leaf:
(count-leaves-recursive (quote (1 () () (() ()) () () 2))) ;; Value: 8
This can easily be remedied by using more conditions:
(define (count-leaves-recursive t) (accumulate + 0 (map (lambda (t) (cond ((null? t) 0) ((pair? t) (count-leaves-recursive t)) (else 1))) t))) ;; which gives (count-leaves-recursive '(1 2 () () (3 () ()))) ;; Value: 3
<< Previous exercise (2.34) | Index | Next exercise (2.36) >>