-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.30.rkt
33 lines (29 loc) · 922 Bytes
/
2.30.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#lang sicp
;; Exercise 2.30:
;; Define a procedure square-tree analogous to the square-list procedure of Exercise 2.21. That is, square-tree 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 tree)
(map (lambda (sub-tree)
(if (pair? sub-tree)
(square-tree sub-tree)
(* sub-tree sub-tree)))
tree))
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))
(define (square-tree tree)
(cond ((null? tree) nil)
((not (pair? tree))
(square tree))
(else (cons (square-tree (car tree))
(square-tree (cdr tree))))))
(define (square n) (* n n))