Advertisement
NLinker

Basic heap structure

Jul 29th, 2017
420
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- The basic heap data structure
  2. data Heap a
  3.   = E
  4.   | H a [Heap a]
  5.   deriving (Show)
  6.  
  7. extractMin :: Ord a => Heap a -> Maybe (a, Heap a)
  8. extractMin E = Nothing
  9. extractMin h@(H t _) = Just (t, deleteMin h)
  10.  
  11. isEmpty :: Heap a -> Bool
  12. isEmpty E = True
  13. isEmpty _     = False
  14.  
  15. findMin :: Ord a => Heap a -> Maybe a
  16. findMin (H h _) = Just h
  17. findMin E      = Nothing
  18.  
  19. merge :: Ord a => Heap a -> Heap a -> Heap a
  20. merge E h = h
  21. merge h E = h
  22. merge h1@(H x hs1) h2@(H y hs2)
  23.   | x < y = H x (h2 : hs1)
  24.   | otherwise = H y (h1 : hs2)
  25.  
  26. mergePairs :: Ord a => [Heap a] -> Heap a
  27. mergePairs []         = Empty
  28. mergePairs [h]        = h
  29. mergePairs (h1:h2:hs) = merge (merge h1 h2) (mergePairs hs)
  30.  
  31. insert :: Ord a => a -> Heap a -> Heap a
  32. insert x = merge (H x [])
  33.  
  34. deleteMin :: Ord a => Heap a -> Heap a
  35. deleteMin (H _x hs) = mergePairs hs
  36. deleteMin E        = error "heap is empty: invalid operation deleteMin"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement