my attempt to do the exercises in sicp.

Wednesday, July 16, 2008

sicp exercise 2.31

;  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 square (lambda (x) (* x x)))
(define (scale fact) (lambda (x) (* x fact)))

(define tree-map (lambda (proc tree)
  (cond ((null? tree) (list))
        ((pair? tree) (cons (tree-map proc (car tree)) (tree-map proc (cdr tree))))
        (else (proc tree)))))

(define x (list (list 3 4) (list 1 9 (list 4 8) 3)))
(display x) (newline)
(display (tree-map square x)) (newline)
(display (tree-map (scale 10) x)) (newline)

No comments: