4
\$\begingroup\$

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?

\$\endgroup\$
2
\$\begingroup\$

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))
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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