Chapter 2, Building Abstractions with Data

Section - 2.2 - Hierarchical Data and the Closure Property

Exercise 2.30


  • Without using map:
1
2
3
4
5
6
7
8
9
10
11
12
#lang sicp

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

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
> (display 
   (square-tree
       (list 
            1
            (list 
                 2 
                 (list 3 4)
                 5
            )
            (list 6 7)
       )
   )
)

(1 (4 (9 16) 25) (36 49))
 
  • With using map:
1
2
3
4
5
6
7
8
9
10
11
12
13
#lang sicp

(define (square-tree tree)
(map
    (lambda (x)
       (if (not (pair? x))
           (* x x)
           (square-tree x)             
       )
    )  
    tree
)
)