-
Notifications
You must be signed in to change notification settings - Fork 1
/
Exercise 2.28 fringe.rkt
executable file
·68 lines (58 loc) · 1.5 KB
/
Exercise 2.28 fringe.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
#lang racket
; Exercise 2.28. Write a procedure fringe that takes as argument a tree (represented as a
; list) and returns a list whose elements are all the leaves of the tree arranged in
; left-to-right order. For example,
; (define x (list (list 1 2) (list 3 4)))
; (fringe x)
; (1 2 3 4)
; (fringe (list x x))
; (1 2 3 4 1 2 3 4)
; SOLUTION
(define (fringe items)
(cond
; List has no elements, so return it
((null? items) items)
; Not a list, so return it as a single-element list
((not (pair? items)) (list items))
; List is non-empty
(else
(append (fringe (car items)) (fringe (cdr items)))
)
)
)
; Tests
Welcome to DrRacket, version 6.11 [3m].
Language: racket, with debugging; memory limit: 128 MB.
> (define x (list 1 (list 2 3)))
> x
'(1 (2 3))
> (fringe x)
'(1 2 3)
> (define x (list (list 1 2) 3))
> (fringe x)
'(1 2 3)
> (define x (list (list 1 2) (list 3 4)))
> (fringe x)
'(1 2 3 4)
> (fringe (list x x))
'(1 2 3 4 1 2 3 4)
> (define one-through-four (list 1 2 3 4))
> (fringe one-through-four)
'(1 2 3 4)
> (cons (list 1 2) (list 3 4))
'((1 2) 3 4)
> (fringe (cons (list 1 2) (list 3 4)))
'(1 2 3 4)
> (fringe (list 1 3 (list 5 7) 9))
'(1 3 5 7 9)
> (fringe (list (list 7)))
'(7)
> (fringe (list 1 (list 2 (list 3 (list 4 (list 5 (list 6 7)))))))
'(1 2 3 4 5 6 7)
> (fringe (list (list 1 2) (list 3 4)))
'(1 2 3 4)
> (fringe (list (list 3 4) (list 1 2)))
'(3 4 1 2)
> (fringe (list (list 4 3) (list 2 1)))
'(4 3 2 1)
>