Dan's Thoughts Thinking somewhat carefully

16Aug/090

Exercise 2.31 of SICP

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

> (define t (list 1
(list 2 (list 3 4) 5)
(list 6 7)))
> t
(1 (2 (3 4) 5) (6 7))
> (square-tree t)
(1 (4 (9 16) 25) (36 49))

Filed under: lisp, SICP Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

Spam protection by WP Captcha-Free

No trackbacks yet.