## **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.31

From Drewiki

## Problem

Abstract your answer to exercise 2.30 to produce a procedure `tree-map` with the property
that `square-tree` could be defined as

(define (square-tree tree) (tree-map square tree))

## Solution

Here's one way to do it:

(define nil (quote ())) (define (square x) (* x x)) (define (tree-map f tree) (map (lambda (sub-tree) (if (pair? sub-tree) (tree-map f sub-tree) (f 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))