structure IntHeap = struct type item = int val initial = 0 fun leq(p : item, q : item) : bool = p <= q infix leq fun max(p,q) = if p leq q then q else p and min(p,q) = if p leq q then p else q datatype tree = L of item | N of item * tree * tree exception InitHeap fun initHeap n = if n < 1 then raise InitHeap else if n = 1 then L initial else let val t = initHeap(n - 1) in N (initial, t, t) end fun top(L i) = i | top(N(i,_,_)) = i fun isHeap (L _) = true | isHeap (N(i,l,r)) = i leq top l andalso i leq top r andalso isHeap l andalso isHeap r fun depth (L _) = 1 | depth (N(i,l,r)) = 1 + max(depth l,depth r) fun replace (i,h) = (top h, insert(i,h)) and insert (i, L _) = L i | insert (i, N(_,l,r)) = if i leq min(top l,top r) then N(i,l,r) else if (top l) leq (top r) then N(top l,insert(i,l),r) else N(top r,l,insert(i,r)) fun size (L _) = 1 | size (N(_,l,r)) = 1 + size l + size r fun maxHeap (L i) = i | maxHeap (N(_,l,r)) = max(maxHeap l, maxHeap r) end