(wat-aro)

無職から有職者にランクアップしました

SICP 問題 2.35

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

;;enumerate-tree
(define (enumerate-tree tree)
  (cond ((null? tree) nil)
        ((not (pair? tree)) (list tree))
        (else (append (enumerate-tree (car tree))
                      (enumerate-tree (cdr tree))))))

;;count-leaves
(define (count-leaves tree)
  (accumulate + 0 (map (lambda (x) 1)
                       (enumerate-tree tree))))
gosh> (count-leaves (list 1 2 (list 3) (list 4 5 (list 6)) 7))
7