-
Notifications
You must be signed in to change notification settings - Fork 14
/
iqueue.sml
executable file
·62 lines (50 loc) · 1.45 KB
/
iqueue.sml
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
structure IQueue :> IQUEUE =
struct
datatype 'a qbody =
Null
| Node of 'a * 'a qptr
withtype 'a qptr = 'a qbody ref
type 'a iqueue = 'a qptr ref * 'a qptr ref
(* Invariant:
An iqueue has the form (head, tail) where !head is a pointer to the first cell
and !tail is a pointer just past the last cell. Thus, !tail is always ref Null.
*)
fun iqueue () =
let val ptr = ref Null
in
(ref ptr, ref ptr)
end
fun reset (head, tail) =
let val ptr = ref Null
in
head := ptr;
tail := ptr
end
fun isEmpty (head, tail) =
(case !(!head) of
Null => true
| Node _ => false)
fun insert (head, tail) x =
let val lastptr = !tail
val lastptr' = ref Null
in
lastptr := Node (x, lastptr');
tail := lastptr'
end
exception Empty
fun front (head, tail) =
(case !(!head) of
Null =>
raise Empty
| Node (x, ptr) =>
x)
fun remove (head, tail) =
(case !(!head) of
Null =>
raise Empty
| Node (x, ptr) =>
(
head := ptr;
x
))
end