-
Notifications
You must be signed in to change notification settings - Fork 1
/
Exercise 2.30 square-tree.rkt
executable file
·70 lines (61 loc) · 1.51 KB
/
Exercise 2.30 square-tree.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#lang racket
; 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.
; SOLUTION
(define (square-tree tree)
(cond
((null? tree) tree)
((not (pair? tree)) (square tree))
(else
(cons (square-tree (car tree)) (square-tree (cdr tree)))
)
)
)
(define (square-tree-with-map tree)
(map
(lambda (tree)
(cond
((null? tree) tree)
((not (pair? tree)) (square tree))
(else
(square-tree-with-map tree)
)
)
)
tree
)
)
(define (square x)
(* x x)
)
; Tests
Welcome to DrRacket, version 6.11 [3m].
Language: racket, with debugging; memory limit: 128 MB.
> (square-tree
(list 1 (list 2 (list 3 4) 5) (list 6 7))
)
'(1 (4 (9 16) 25) (36 49))
> (square-tree-with-map
(list 1 (list 2 (list 3 4) 5) (list 6 7))
)
'(1 (4 (9 16) 25) (36 49))
> (square-tree (square-tree-with-map
(list 1 (list 2 (list 3 4) 5) (list 6 7))
))
'(1 (16 (81 256) 625) (1296 2401))
> (square-tree-with-map (square-tree-with-map
(list 1 (list 2 (list 3 4) 5) (list 6 7))
))
'(1 (16 (81 256) 625) (1296 2401))
> (square-tree-with-map (square-tree
(list 1 (list 2 (list 3 4) 5) (list 6 7))
))
'(1 (16 (81 256) 625) (1296 2401))
>