| author | wenzelm | 
| Fri, 15 Aug 2008 17:03:55 +0200 | |
| changeset 27895 | e4f8763b971b | 
| parent 23179 | 8db2b22257bd | 
| child 28581 | 6cd2e5d5c6d0 | 
| 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 | 
| 18134 | 18 | val min: T -> elem (*exception Empty*) | 
| 19 | val delete_min: T -> T (*exception Empty*) | |
| 9095 | 20 | end; | 
| 21 | ||
| 9413 | 22 | functor HeapFun(type elem val ord: elem * elem -> order): HEAP = | 
| 9095 | 23 | struct | 
| 9413 | 24 | |
| 25 | ||
| 26 | (* datatype heap *) | |
| 9095 | 27 | |
| 9413 | 28 | type elem = elem; | 
| 29 | datatype T = Empty | Heap of int * elem * T * T; | |
| 30 | ||
| 31 | ||
| 32 | (* empty heaps *) | |
| 9095 | 33 | |
| 9413 | 34 | val empty = Empty; | 
| 35 | ||
| 36 | fun is_empty Empty = true | |
| 37 | | is_empty (Heap _) = false; | |
| 38 | ||
| 9095 | 39 | |
| 9413 | 40 | (* build heaps *) | 
| 41 | ||
| 42 | local | |
| 43 | ||
| 44 | fun rank Empty = 0 | |
| 45 | | rank (Heap (r, _, _, _)) = r; | |
| 9095 | 46 | |
| 9413 | 47 | fun heap x a b = | 
| 48 | if rank a >= rank b then Heap (rank b + 1, x, a, b) | |
| 49 | else Heap (rank a + 1, x, b, a); | |
| 50 | ||
| 51 | in | |
| 52 | ||
| 53 | fun merge (h, Empty) = h | |
| 54 | | merge (Empty, h) = h | |
| 55 | | merge (h1 as Heap (_, x1, a1, b1), h2 as Heap (_, x2, a2, b2)) = | |
| 56 | (case ord (x1, x2) of | |
| 14472 
cba7c0a3ffb3
Removing the datatype declaration of "order" allows the standard General.order
 paulson parents: 
9413diff
changeset | 57 | GREATER => heap x2 a2 (merge (h1, b2)) | 
| 9413 | 58 | | _ => heap x1 a1 (merge (b1, h2))); | 
| 59 | ||
| 23179 | 60 | fun insert x h = merge (Heap (1, x, Empty, Empty), h); | 
| 9095 | 61 | |
| 9413 | 62 | end; | 
| 63 | ||
| 64 | ||
| 65 | (* minimum element *) | |
| 66 | ||
| 18134 | 67 | fun min Empty = raise List.Empty | 
| 9413 | 68 | | min (Heap (_, x, _, _)) = x; | 
| 69 | ||
| 18134 | 70 | fun delete_min Empty = raise List.Empty | 
| 9413 | 71 | | delete_min (Heap (_, _, a, b)) = merge (a, b); | 
| 72 | ||
| 9095 | 73 | end; |