-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbag_fifo.mz
50 lines (43 loc) · 972 Bytes
/
bag_fifo.mz
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
(* Data type definitions. *)
data mutable cell a =
Cell { value_: a; next: dynamic }
data mutable bag a =
Empty { head: (); tail: () }
| NonEmpty { head: dynamic; tail: dynamic }
adopts cell a
(* The real functions. *)
val create [a] (): bag a =
Empty { head = (); tail = () }
val insert [a] (consumes x: a, b: bag a): () =
let c = Cell {
value_ = x; next = ()
} in
c.next <- c;
give c to b;
match b with
| Empty ->
tag of b <- NonEmpty;
b.head <- c;
b.tail <- c
| NonEmpty { tail } ->
take tail from b;
tail.next <- c;
give tail to b;
b.tail <- c
end
val retrieve [a] (b: bag a): option a =
match b with
| Empty ->
none
| NonEmpty { head; tail } ->
take head from b;
if head == tail then begin
tag of b <- Empty;
b.head <- ();
b.tail <- ()
end else begin
b.head <- head.next
end;
let x = head.value_ in
some x
end