| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
module type Ordered = sig |
| 14 |
type t |
| 15 |
val compare : t -> t -> int |
| 16 |
end |
| 17 |
|
| 18 |
module type S =sig |
| 19 |
|
| 20 |
|
| 21 |
type t |
| 22 |
|
| 23 |
|
| 24 |
type elt |
| 25 |
|
| 26 |
|
| 27 |
val empty : t |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
val add : elt -> t -> t |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
val maximum : t -> elt |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
val remove : t -> t |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
val iter : (elt -> unit) -> t -> unit |
| 45 |
|
| 46 |
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a |
| 47 |
|
| 48 |
end |
| 49 |
|
| 50 |
exception EmptyHeap |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
module Functional(X : Ordered) = struct |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
type t = |
| 60 |
| Leaf |
| 61 |
| Node of t * X.t * t |
| 62 |
|
| 63 |
type elt = X.t |
| 64 |
|
| 65 |
let empty = Leaf |
| 66 |
|
| 67 |
let rec add x = function |
| 68 |
| Leaf -> |
| 69 |
Node (Leaf, x, Leaf) |
| 70 |
| Node (l, y, r) -> |
| 71 |
if X.compare x y >= 0 then |
| 72 |
Node (add y r, x, l) |
| 73 |
else |
| 74 |
Node (add x r, y, l) |
| 75 |
|
| 76 |
let rec extract = function |
| 77 |
| Leaf -> |
| 78 |
assert false |
| 79 |
| Node (Leaf, y, r) -> |
| 80 |
assert (r = Leaf); |
| 81 |
y, Leaf |
| 82 |
| Node (l, y, r) -> |
| 83 |
let x, l = extract l in |
| 84 |
x, Node (r, y, l) |
| 85 |
|
| 86 |
let is_above x = function |
| 87 |
| Leaf -> true |
| 88 |
| Node (_, y, _) -> X.compare x y >= 0 |
| 89 |
|
| 90 |
let rec replace_min x = function |
| 91 |
| Node (l, _, r) when is_above x l && is_above x r -> |
| 92 |
Node (l, x, r) |
| 93 |
| Node ((Node (_, lx, _) as l), _, r) when is_above lx r -> |
| 94 |
|
| 95 |
Node (replace_min x l, lx, r) |
| 96 |
| Node (l, _, (Node (_, rx, _) as r)) -> |
| 97 |
|
| 98 |
Node (l, rx, replace_min x r) |
| 99 |
| Leaf | Node (Leaf, _, _) | Node (_, _, Leaf) -> |
| 100 |
assert false |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
let rec merge l r = match l, r with |
| 105 |
| _, Leaf -> |
| 106 |
l |
| 107 |
| Node (ll, lx, lr), Node (_, ly, _) -> |
| 108 |
if X.compare lx ly >= 0 then |
| 109 |
Node (r, lx, merge ll lr) |
| 110 |
else |
| 111 |
let x, l = extract l in |
| 112 |
Node (replace_min x r, ly, l) |
| 113 |
| Leaf, _ -> |
| 114 |
assert false |
| 115 |
|
| 116 |
let maximum = function |
| 117 |
| Leaf -> raise EmptyHeap |
| 118 |
| Node (_, x, _) -> x |
| 119 |
|
| 120 |
let remove = function |
| 121 |
| Leaf -> |
| 122 |
raise EmptyHeap |
| 123 |
| Node (l, _, r) -> |
| 124 |
merge l r |
| 125 |
|
| 126 |
let rec iter f = function |
| 127 |
| Leaf -> () |
| 128 |
| Node (l, x, r) -> iter f l; f x; iter f r |
| 129 |
|
| 130 |
let rec fold f h x0 = match h with |
| 131 |
| Leaf -> |
| 132 |
x0 |
| 133 |
| Node (l, x, r) -> |
| 134 |
fold f l (fold f r (f x x0)) |
| 135 |
|
| 136 |
end |