Skip to content

Instantly share code, notes, and snippets.

@ZacharyKamerling
Created January 18, 2015 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZacharyKamerling/425ca21169061e41f7c8 to your computer and use it in GitHub Desktop.
Save ZacharyKamerling/425ca21169061e41f7c8 to your computer and use it in GitHub Desktop.
data Heap a = Tree !Int !a (Heap a) (Heap a) | Leaf
empty :: Heap a
empty = Leaf
push :: Heap a -> Int -> a -> Heap a
push tree@(Tree p n l r) p2 n2 =
if p2 < p
then Tree p2 n2 tree Leaf
else Tree p n r (merge (Tree p2 n2 Leaf Leaf) l)
push Leaf p n = Tree p n Leaf Leaf
pop :: Heap a -> Maybe (Heap a, a)
pop (Tree _ n l r) = Just (merge l r, n)
pop Leaf = Nothing
merge :: Heap a -> Heap a -> Heap a
merge l@(Tree p1 n1 l1 r1) r@(Tree p2 n2 l2 r2) =
if p1 < p2
then Tree p1 n1 r1 (merge l1 r)
else Tree p2 n2 r2 (merge l2 l)
merge l Leaf = l
merge Leaf r = r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment