Skip to content

Commit a5b5a9d

Browse files
committed
Added exercises 3.16 and 3.17
1 parent 7343b11 commit a5b5a9d

File tree

2 files changed

+51
-17
lines changed

2 files changed

+51
-17
lines changed

3.0/3.16.scm

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
;; x -> [a][]
1616
;; z -> [x][] -> [x][]
17-
;; output 5
17+
;; output 4
1818

1919
;; x -> [a][]
2020
;; y -> [x][x]

3.0/3.17.scm

+50-16
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,69 @@
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))
613

14+
(define (unvisited-pair? p)
15+
(if (and (pair? p)
16+
(not ((ds 'in-list) p)))
17+
#t
18+
#f))
19+
720
(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))))
1027

1128
(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+
1633
(define (in-list? l e)
1734
(cond ((null? l) #f)
18-
((eq? (cdr l) e) #t)
35+
((eq? (car l) e) #t)
1936
(else (in-list? (cdr l) e))))
2037

2138
(define (make-pair-list plist)
2239
(define (append value)
23-
(append! plist value))
40+
(append! plist (list value)))
2441
(define (in-list value)
2542
(in-list? plist value))
2643
(define (dir-plist) plist)
2744
(define (dispatch m)
2845
(cond ((eq? m 'append) append)
2946
((eq? m 'in-list) in-list)
3047
((eq? m 'state) dir-plist)
31-
(else (error "unknown request -- make-list-pair"
32-
m))))
48+
(else (error "unknown request -- make-list-pair" m))))
3349
dispatch)
3450

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

Comments
 (0)