SICP solution exercise 2.30

Solution for exercise 2.30 of SICP:

;Define square-tree directly (i.e., without using any
;higher-order procedures) 
(define nil '())

(define (square-tree-direct tree)
  (cond ((null? tree) nil)
        ((not (pair? tree))
         (* tree tree))
        (else (cons (square-tree-direct (car tree))
                    (square-tree-direct (cdr tree))))))

(square-tree-direct
 (list 1
       (list 2 (list 3 4) 5)
       (list 6 7)))

;Define square-tree by using map and recursion.
(define (square-tree-map tree)
  (map (lambda (subtree)
         (if (pair? subtree)
             (square-tree-map subtree)
             (* subtree subtree)))
  tree))

(square-tree-map
 (list 1
       (list 2 (list 3 4) 5)
       (list 6 7)))


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>