author | wenzelm |
Thu, 09 Feb 2017 22:40:15 +0100 | |
changeset 65014 | 97a622d01609 |
parent 47060 | e2741ec9ae36 |
permissions | -rw-r--r-- |
28127 | 1 |
(* Title: Pure/General/queue.ML |
2 |
Author: Makarius |
|
3 |
||
4 |
Efficient queues. |
|
5 |
*) |
|
6 |
||
7 |
signature QUEUE = |
|
8 |
sig |
|
9 |
type 'a T |
|
10 |
val empty: 'a T |
|
11 |
val is_empty: 'a T -> bool |
|
12 |
val content: 'a T -> 'a list |
|
13 |
val enqueue: 'a -> 'a T -> 'a T |
|
47060
e2741ec9ae36
prefer explicitly qualified exception List.Empty;
wenzelm
parents:
29606
diff
changeset
|
14 |
val dequeue: 'a T -> 'a * 'a T (*exception List.Empty*) |
28127 | 15 |
end; |
16 |
||
17 |
structure Queue: QUEUE = |
|
18 |
struct |
|
19 |
||
20 |
datatype 'a T = Queue of 'a list * 'a list; |
|
21 |
||
22 |
val empty = Queue ([], []); |
|
23 |
||
24 |
fun is_empty (Queue ([], [])) = true |
|
25 |
| is_empty _ = false; |
|
26 |
||
27 |
fun content (Queue (xs, ys)) = ys @ rev xs; |
|
28 |
||
29 |
fun enqueue x (Queue (xs, ys)) = Queue (x :: xs, ys); |
|
30 |
||
31 |
fun dequeue (Queue (xs, y :: ys)) = (y, Queue (xs, ys)) |
|
32 |
| dequeue (Queue (xs as _ :: _, [])) = let val y :: ys = rev xs in (y, Queue ([], ys)) end |
|
47060
e2741ec9ae36
prefer explicitly qualified exception List.Empty;
wenzelm
parents:
29606
diff
changeset
|
33 |
| dequeue (Queue ([], [])) = raise List.Empty; |
28127 | 34 |
|
35 |
end; |