1
\$\begingroup\$

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

I wrote this solution. What do you think?

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

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

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

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

EDIT: This is a much better solution for map-square-tree.

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

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

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

(define a (list 1 1 (list (list 2 3) 1 2)))
\$\endgroup\$
1
\$\begingroup\$

Your direct definition of square-tree is correct.

Your definition using map calls square-tree; to make it properly recursive, call map-square-tree instead. Further, you may recurse on the subtree itself. This will make your code succinct.

(define (map-square-tree tree)
  (map (lambda (subtree)
         ((if (pair? subtree) map-square-tree square) subtree))
       tree))
\$\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.