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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
exception Empty
type 'a cell =
| Nil
| Cons of { content: 'a; mutable next: 'a cell }
type 'a t = {
mutable length: int;
mutable first: 'a cell;
mutable last: 'a cell
}
let create () = {
length = 0;
first = Nil;
last = Nil
}
let clear q =
q.length <- 0;
q.first <- Nil;
q.last <- Nil
let add x q =
let cell = Cons {
content = x;
next = Nil
} in
match q.last with
| Nil ->
q.length <- 1;
q.first <- cell;
q.last <- cell
| Cons last ->
q.length <- q.length + 1;
last.next <- cell;
q.last <- cell
let push =
add
let peek q =
match q.first with
| Nil -> raise Empty
| Cons { content } -> content
let peek_opt q =
match q.first with
| Nil -> None
| Cons { content } -> Some content
let top =
peek
let take q =
match q.first with
| Nil -> raise Empty
| Cons { content; next = Nil } ->
clear q;
content
| Cons { content; next } ->
q.length <- q.length - 1;
q.first <- next;
content
let take_opt q =
match q.first with
| Nil -> None
| Cons { content; next = Nil } ->
clear q;
Some content
| Cons { content; next } ->
q.length <- q.length - 1;
q.first <- next;
Some content
let pop =
take
let copy =
let rec copy q_res prev cell =
match cell with
| Nil -> q_res.last <- prev; q_res
| Cons { content; next } ->
let res = Cons { content; next = Nil } in
begin match prev with
| Nil -> q_res.first <- res
| Cons p -> p.next <- res
end;
copy q_res res next
in
fun q -> copy { length = q.length; first = Nil; last = Nil } Nil q.first
let is_empty q =
q.length = 0
let length q =
q.length
let iter =
let rec iter f cell =
match cell with
| Nil -> ()
| Cons { content; next } ->
f content;
iter f next
in
fun f q -> iter f q.first
let fold =
let rec fold f accu cell =
match cell with
| Nil -> accu
| Cons { content; next } ->
let accu = f accu content in
fold f accu next
in
fun f accu q -> fold f accu q.first
let transfer q1 q2 =
if q1.length > 0 then
match q2.last with
| Nil ->
q2.length <- q1.length;
q2.first <- q1.first;
q2.last <- q1.last;
clear q1
| Cons last ->
q2.length <- q2.length + q1.length;
last.next <- q1.first;
q2.last <- q1.last;
clear q1
(** {1 Iterators} *)
let to_seq q =
let rec aux c () = match c with
| Nil -> Seq.Nil
| Cons { content=x; next; } -> Seq.Cons (x, aux next)
in
aux q.first
let add_seq q i = Seq.iter (fun x -> push x q) i
let of_seq g =
let q = create() in
add_seq q g;
q