-
Notifications
You must be signed in to change notification settings - Fork 460
/
Copy pathqueue.res
142 lines (122 loc) · 2.65 KB
/
queue.res
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
/* ************************************************************************ */
/* */
/* OCaml */
/* */
/* Francois Pottier, projet Cristal, INRIA Rocquencourt */
/* Jeremie Dimino, Jane Street Europe */
/* */
/* Copyright 2002 Institut National de Recherche en Informatique et */
/* en Automatique. */
/* */
/* All rights reserved. This file is distributed under the terms of */
/* the GNU Lesser General Public License version 2.1, with the */
/* special exception on linking described in the file LICENSE. */
/* */
/* ************************************************************************ */
exception Empty
type rec cell<'a> =
| Nil
| Cons({content: 'a, mutable next: cell<'a>})
type t<'a> = {
mutable length: int,
mutable first: cell<'a>,
mutable last: cell<'a>,
}
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,
})
switch q.last {
| 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 =>
switch q.first {
| Nil => raise(Empty)
| Cons({content}) => content
}
let top = peek
let take = q =>
switch q.first {
| Nil => raise(Empty)
| Cons({content, next: Nil}) =>
clear(q)
content
| Cons({content, next}) =>
q.length = q.length - 1
q.first = next
content
}
let pop = take
let copy = {
let rec copy = (q_res, prev, cell) =>
switch cell {
| Nil =>
q_res.last = prev
q_res
| Cons({content, next}) =>
let res = Cons({content, next: Nil})
switch prev {
| Nil => q_res.first = res
| Cons(p) => p.next = res
}
copy(q_res, res, next)
}
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) =>
switch cell {
| Nil => ()
| Cons({content, next}) =>
f(content)
iter(f, next)
}
(f, q) => iter(f, q.first)
}
let fold = {
let rec fold = (f, accu, cell) =>
switch cell {
| Nil => accu
| Cons({content, next}) =>
let accu = f(accu, content)
fold(f, accu, next)
}
(f, accu, q) => fold(f, accu, q.first)
}
let transfer = (q1, q2) =>
if q1.length > 0 {
switch q2.last {
| 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)
}
}