1
- ; ;; TODO not completed
2
-
3
- ; ;; Exercise 3.17. Devise a correct version of the count-pairs procedure of exercise 3.16 that returns the number of distinct pairs
4
- ; ;; in any structure. (Hint: Traverse the structure, maintaining an auxiliary data structure that is used to keep track of which pairs
5
- ; ;; have already been counted.)
1
+ (define (count-pairs p )
2
+ (if (unvisited-pair? p)
3
+ (let (
4
+ (tmp (+ (count-pairs (car p))
5
+ (count-pairs (cdr p))
6
+ 1 ))
7
+ ; ; more init
8
+ )
9
+ (begin
10
+ ((ds 'append ) p)
11
+ tmp))
12
+ 0 ))
6
13
14
+ (define (unvisited-pair? p )
15
+ (if (and (pair? p)
16
+ (not ((ds 'in-list ) p)))
17
+ #t
18
+ #f ))
19
+
7
20
(define (append! plist value )
8
- (set-cdr! (last-pair plist) value)
9
- plist)
21
+ (cond ((null? value) plist)
22
+ ((not (pair? value)) plist)
23
+ ((eq? (last-pair plist) null?) plist)
24
+ (else (begin
25
+ (set-cdr! (last-pair plist) value)
26
+ plist))))
10
27
11
28
(define (last-pair x )
12
- (if ( null? ( cdr x) )
13
- x
14
- ( last-pair (cdr x))))
15
-
29
+ (cond (( null? x) x )
30
+ (( null? ( cdr x)) x)
31
+ ( else ( last-pair (cdr x) ))))
32
+
16
33
(define (in-list? l e )
17
34
(cond ((null? l) #f )
18
- ((eq? (cdr l) e) #t )
35
+ ((eq? (car l) e) #t )
19
36
(else (in-list? (cdr l) e))))
20
37
21
38
(define (make-pair-list plist )
22
39
(define (append value )
23
- (append! plist value))
40
+ (append! plist ( list value) ))
24
41
(define (in-list value )
25
42
(in-list? plist value))
26
43
(define (dir-plist ) plist)
27
44
(define (dispatch m )
28
45
(cond ((eq? m 'append ) append)
29
46
((eq? m 'in-list ) in-list)
30
47
((eq? m 'state ) dir-plist)
31
- (else (error " unknown request -- make-list-pair"
32
- m))))
48
+ (else (error " unknown request -- make-list-pair" m))))
33
49
dispatch)
34
50
35
- (define pair-list (make-pair-list (list 'head )))
51
+ (define ds (make-pair-list (list (list 'head ))))
52
+ (define x (cons 'a ()))
53
+ (define z (cons x (cons x ())))
54
+
55
+ ; ; (count-pairs z) outputs 3
56
+
57
+ (define x (cons 'a ()))
58
+ (define y (cons x x))
59
+ (define z (cons y y))
60
+
61
+ ; ; (count-pairs z) outputs 3
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
0 commit comments