-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-3-1-mutable-structures.rkt
107 lines (85 loc) · 2.2 KB
/
3-3-1-mutable-structures.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#lang racket
; Mutable cons
(define (cons x y)
(define (set-x! v) (set! x v))
(define (set-y! v) (set! y v))
(define (dispatch m)
(cond [(eq? m 'car) x]
[(eq? m 'cdr) y]
[(eq? m 'set-car!) set-x!]
[(eq? m 'set-cdr!) set-y!]
[else (error "Undefined operation: CONS" m)]))
dispatch)
(define (car z) (z 'car))
(define (cdr z) (z 'cdr))
(define (caar z) ((z 'car) 'car))
(define (set-car! z v)
((z 'set-car!) v)
z)
(define (set-cdr! z v)
((z 'set-cdr!) v)
z)
; Queue with pointers
; Constant complexity
(define (front-ptr queue) (car queue))
(define (rear-ptr queue) (cdr queue))
(define (set-front-ptr! queue item)
(set-car! queue item))
(define (set-rear-ptr! queue item)
(set-cdr! queue item))
(define (empty-queue? queue)
(null? (front-ptr queue)))
(define (make-queue) (cons '() '()))
(define (front-queue queue)
(if (empty-queue? queue)
#f
(car (front-ptr queue))))
(define (insert-queue! queue item)
(let ([new-pair (cons item '())])
(cond
[(empty-queue? queue)
(set-front-ptr! queue new-pair)
(set-rear-ptr! queue new-pair)
queue]
[else
(set-cdr! (rear-ptr queue) new-pair)
(set-rear-ptr! queue new-pair)
queue])))
(define (delete-queue! queue)
(cond
[(empty-queue? queue) #f]
[else
(let ([front (front-ptr queue)])
(set-front-ptr! queue (cdr front))
(car front))]))
(define (print-queue queue)
(define (print items)
(if (null? items)
'end
(begin
(displayln (car items))
(print (cdr items))
'end)))
(print (front-ptr queue)))
; Table with assignment
(define (assoc key records)
(cond
[(null? records) #f]
[(equal? key (caar records)) (car records)]
[else (assoc key (cdr records))]))
(define (lookup table key)
(let ([record (assoc key (cdr table))])
(if record
(cdr record)
#f)))
(define (insert! table key value)
(let ([record (assoc key (cdr table))])
(if record
(set-cdr! record value)
(set-cdr!
table
(cons (cons key value)
(cdr table))))))
(define (make-table)
(cons '*table* '()))
(define t (make-table))