28127
|
1 |
(* Title: Pure/General/queue.ML
|
|
2 |
ID: $Id$
|
|
3 |
Author: Makarius
|
|
4 |
|
|
5 |
Efficient queues.
|
|
6 |
*)
|
|
7 |
|
|
8 |
signature QUEUE =
|
|
9 |
sig
|
|
10 |
type 'a T
|
|
11 |
val empty: 'a T
|
|
12 |
val is_empty: 'a T -> bool
|
|
13 |
val content: 'a T -> 'a list
|
|
14 |
val enqueue: 'a -> 'a T -> 'a T
|
|
15 |
val dequeue: 'a T -> 'a * 'a T
|
|
16 |
end;
|
|
17 |
|
|
18 |
structure Queue: QUEUE =
|
|
19 |
struct
|
|
20 |
|
|
21 |
datatype 'a T = Queue of 'a list * 'a list;
|
|
22 |
|
|
23 |
val empty = Queue ([], []);
|
|
24 |
|
|
25 |
fun is_empty (Queue ([], [])) = true
|
|
26 |
| is_empty _ = false;
|
|
27 |
|
|
28 |
fun content (Queue (xs, ys)) = ys @ rev xs;
|
|
29 |
|
|
30 |
fun enqueue x (Queue (xs, ys)) = Queue (x :: xs, ys);
|
|
31 |
|
|
32 |
fun dequeue (Queue (xs, y :: ys)) = (y, Queue (xs, ys))
|
|
33 |
| dequeue (Queue (xs as _ :: _, [])) = let val y :: ys = rev xs in (y, Queue ([], ys)) end
|
|
34 |
| dequeue (Queue ([], [])) = raise Empty;
|
|
35 |
|
|
36 |
end;
|