Dan's Thoughts Thinking somewhat carefully

15Aug/090

Exercise 2.30 of SICP

Exercise 2.30: Define a procedure square-tree analogous to the square-list procedure of exercise 2.21. That is, square-list should behave as follows:

(square-tree
 (list 1
       (list 2 (list 3 4) 5)
       (list 6 7)))
(1 (4 (9 16) 25) (36 49))

Define square-tree both directly (i.e., without using any higher-order procedures) and also by using map and recursion.

(define (map proc items)
  (if (null? items)
    '()
    (cons (proc (car items)) (map proc (cdr items)))))
 
(define (square x) (* x x))
 
(define (square-tree tree)
  (cond ((null? tree) '())
        ((not (pair? tree)) (square tree))
        (else
          (cons (square-tree (car tree))
                (square-tree (cdr tree))))))
 
(define (map-square-tree tree)
  (map (lambda (sub-tree)
           (if (not (pair? sub-tree))
             (square sub-tree)
             (map-square-tree sub-tree)))
         tree))

> (define t (list 1
(list 2 (list 3 4) 5)
(list 6 7)))
> t
(1 (2 (3 4) 5) (6 7))
> (map-square-tree t)
(1 (4 (9 16) 25) (36 49))
> (square-tree t)
(1 (4 (9 16) 25) (36 49))

Filed under: SICP, lisp Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


Spam protection by WP Captcha-Free

No trackbacks yet.