sicp 2.35

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

 

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

 

 

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

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

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

 

8

你可能感兴趣的:(SICP)