<< Previous exercise (2.34) | Index | Next exercise (2.36) >>
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
My solution is a "tomato-tomato" of above.
Identity-mapping and using recursion in proc.
(define (count-leaves t) (define proc (lambda (x y) (if (pair? x) (+ (count-leaves x) y) (+ 1 y)))) (define init_val 0) (define seq (map (lambda (a) a) t)) (accumulate proc init_val seq))