Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Exercise 2.31. 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))

I wrote the following solution:

(define (square x) (* x x))

(define (tree-map f tree)
  (cond ((null? tree) null)
        ((pair? tree)
         (cons (tree-map f (car tree))
               (tree-map f (cdr tree))))
        (else (f tree))))

(define (map-tree-map f tree)
  (map (lambda (subtree)
         (if (pair? subtree)
             (cons (map-tree-map f (car subtree))
                   (map-tree-map f (cdr subtree)))
             (f subtree)))
         tree))

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

(define a (list 1 1 (list (list 2 3) 1 2)))

Can this be improved in any way?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Your direct definition of tree-map looks good.

The version using map may be written more succinctly (with the recursive portion factored out) as follows:

(define (tree-map f tree)
  (define (rec tree)
    (map (lambda (subtree)
           ((if (pair? subtree) rec f) subtree))
         tree))
  (rec tree))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.