# sicp-ex-2.31

jz

Pretty nice.

```
(define (tree-map proc tree)
(define nil '())
(map (lambda (subtree)
(cond ((null? subtree) nil)
((not (pair? subtree)) (proc subtree))
(else (tree-map proc subtree))))
tree))

;; Usage:
(define my-tree (list (list 1 2) 3 (list 4 5)))
(tree-map square my-tree)
(tree-map (lambda (x) (+ x 1)) my-tree)

```

jwc

my way:

```
(define (tree-map proc tree)
(cond ((null? tree) nil)
((pair? tree)
(cons
(tree-map proc (car tree))
(tree-map proc (cdr tree))))
(else (proc tree))))
```

bishboria

my way. For me this is more succinct than using cond and there's no need to check for nil explicitly (or define it):

```
(define (tree-map proc tree)
(map (lambda (sub-tree)
(if (pair? sub-tree)
(tree-map proc sub-tree)
(proc sub-tree)))
tree))
```

akaucher

own map implementation without cons

```
(define (tree-map proc tree)
(if (null? tree)
'()
(if (pair? tree)
(cons (tree-map proc (car tree))
(tree-map proc (cdr tree)))
(proc tree))))

```

pritesh

using map

```
(define (tree-map f tree)
(map  (lambda (x)
(if (pair? x)
(tree-map f x)
(f x)
)
)
tree
)
)

```

master

As I mentioned in the previous exercise, I think the idea of mapping over a tree is better expressed in the following way (although admittedly it's slightly more complex in the case where the procedure being mapped is not a unary procedure):

``` (define (tree-map f tree)
(if (not (pair? tree))
(f tree)
(map (lambda (subtree) (tree-map f subtree)) tree)))
```