author | wenzelm |
Wed, 31 Dec 2008 18:53:16 +0100 | |
changeset 29270 | 0eade173f77e |
parent 28581 | 6cd2e5d5c6d0 |
child 29606 | fedb8be05f24 |
permissions | -rw-r--r-- |
9413 | 1 |
(* Title: Pure/General/heap.ML |
9095 | 2 |
ID: $Id$ |
9413 | 3 |
Author: Markus Wenzel, TU Muenchen |
9095 | 4 |
|
9413 | 5 |
Heaps over linearly ordered types. See also Chris Okasaki: "Purely |
6 |
Functional Data Structures" (Chapter 3), Cambridge University Press, |
|
7 |
1998. |
|
8 |
*) |
|
9095 | 9 |
|
10 |
signature HEAP = |
|
11 |
sig |
|
9413 | 12 |
type elem |
13 |
type T |
|
14 |
val empty: T |
|
15 |
val is_empty: T -> bool |
|
16 |
val merge: T * T -> T |
|
23179 | 17 |
val insert: elem -> T -> T |
28581 | 18 |
val min: T -> elem (*exception Empty*) |
19 |
val delete_min: T -> T (*exception Empty*) |
|
20 |
val min_elem: T -> elem * T (*exception Empty*) |
|
21 |
val upto: elem -> T -> elem list * T |
|
9095 | 22 |
end; |
23 |
||
9413 | 24 |
functor HeapFun(type elem val ord: elem * elem -> order): HEAP = |
9095 | 25 |
struct |
9413 | 26 |
|
27 |
||
28 |
(* datatype heap *) |
|
9095 | 29 |
|
9413 | 30 |
type elem = elem; |
31 |
datatype T = Empty | Heap of int * elem * T * T; |
|
32 |
||
33 |
||
34 |
(* empty heaps *) |
|
9095 | 35 |
|
9413 | 36 |
val empty = Empty; |
37 |
||
38 |
fun is_empty Empty = true |
|
39 |
| is_empty (Heap _) = false; |
|
40 |
||
9095 | 41 |
|
9413 | 42 |
(* build heaps *) |
43 |
||
44 |
local |
|
45 |
||
46 |
fun rank Empty = 0 |
|
47 |
| rank (Heap (r, _, _, _)) = r; |
|
9095 | 48 |
|
9413 | 49 |
fun heap x a b = |
50 |
if rank a >= rank b then Heap (rank b + 1, x, a, b) |
|
51 |
else Heap (rank a + 1, x, b, a); |
|
52 |
||
53 |
in |
|
54 |
||
55 |
fun merge (h, Empty) = h |
|
56 |
| merge (Empty, h) = h |
|
57 |
| merge (h1 as Heap (_, x1, a1, b1), h2 as Heap (_, x2, a2, b2)) = |
|
58 |
(case ord (x1, x2) of |
|
14472
cba7c0a3ffb3
Removing the datatype declaration of "order" allows the standard General.order
paulson
parents:
9413
diff
changeset
|
59 |
GREATER => heap x2 a2 (merge (h1, b2)) |
9413 | 60 |
| _ => heap x1 a1 (merge (b1, h2))); |
61 |
||
23179 | 62 |
fun insert x h = merge (Heap (1, x, Empty, Empty), h); |
9095 | 63 |
|
9413 | 64 |
end; |
65 |
||
66 |
||
67 |
(* minimum element *) |
|
68 |
||
18134 | 69 |
fun min Empty = raise List.Empty |
9413 | 70 |
| min (Heap (_, x, _, _)) = x; |
71 |
||
18134 | 72 |
fun delete_min Empty = raise List.Empty |
9413 | 73 |
| delete_min (Heap (_, _, a, b)) = merge (a, b); |
74 |
||
28581 | 75 |
fun min_elem h = (min h, delete_min h); |
76 |
||
77 |
||
78 |
(* initial interval *) |
|
79 |
||
80 |
nonfix upto; |
|
81 |
||
82 |
fun upto _ (h as Empty) = ([], h) |
|
83 |
| upto limit (h as Heap (_, x, a, b)) = |
|
84 |
(case ord (x, limit) of |
|
85 |
GREATER => ([], h) |
|
86 |
| _ => upto limit (delete_min h) |>> cons x); |
|
87 |
||
9095 | 88 |
end; |