## **Note: this wiki is now retired and will no longer be updated!**

**The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.**

# SICP exercise 2.30

From Drewiki

## Problem

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)))

*Output:*

`
`

(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.

## Solution

Without higher-order procedures:

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

Test:

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

*Output:*

`
`

(1 (4 (9 16) 25) (36 49))

With `map`:

(define (square-tree tree) (map (lambda (sub-tree) (if (pair? sub-tree) (square-tree sub-tree) (square sub-tree))) tree))

Test:

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

*Output:*

`
`

(1 (4 (9 16) 25) (36 49))