23 hours ago
my attempt to do the exercises in sicp.
Wednesday, July 16, 2008
sicp exercise 2.30
;
; Exercise 2.30. 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.
;
(define square-tree (lambda (tree)
(cond ((null? tree) (list))
((pair? tree) (cons (square-tree (car tree)) (square-tree (cdr tree))))
(else (* tree tree)))))
(define square-tree-map (lambda (tree)
(map (lambda (sub-tree)
(if (pair? sub-tree)
(square-tree-map sub-tree)
(* sub-tree sub-tree))) tree)))
(define x (list (list 1 2 (list 3 4 (list 10 19)) 4 (list 10))))
(display (square-tree x)) (newline)
(display (square-tree-map x)) (newline)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment