SICP solution exercise 2.35

Solution for exercise 2.35 of SICP:

(define nil '())

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

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

(define x (cons (list 5 6) (cons (list 7 8 ) (list 9 10))))
(define y (list (list 4 5) (list 6 7)))
(define z (cons (list 11 12) (list 13 14)))
(define t (list 15 16))
(define s (cons (list 17 18) (cons (list (list 19 20) (list 21 22)) (list 23 24))))

x
y
z
t
s

(count-leaves x)
(count-leaves y)
(count-leaves z)
(count-leaves t)
(count-leaves s)

This entry was posted in SICP and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>