Skip to content

Instantly share code, notes, and snippets.

@AndrasKovacs
Created March 22, 2013 15:57
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 AndrasKovacs/5222409 to your computer and use it in GitHub Desktop.
Save AndrasKovacs/5222409 to your computer and use it in GitHub Desktop.
import Data.Function (on)
data Leftist a = Empty | Node {_rank :: Int, val :: a, lch, rch :: (Leftist a)}
rank :: Leftist a -> Int
rank (Node r _ _ _) = r
rank _ = 0
singleton :: a -> Leftist a
singleton a = Node 1 a Empty Empty
merge :: (a -> a -> Bool) -> Leftist a -> Leftist a -> Leftist a
merge _ a Empty = a
merge _ Empty b = b
merge p a b = Node (1 + rank l') (val a') l' r' where
(a', b') = if on p val b a then (b, a) else (a, b)
(l, r) = (lch a', merge p (rch a') b')
(l', r') = if on (<) rank r l then (r, l) else (l, r)
insert :: (a -> a -> Bool) -> a -> Leftist a -> Leftist a
insert p = merge p . singleton
pop :: (a -> a -> Bool) -> Leftist a -> Maybe (a, Leftist a)
pop p (Node _ a l r) = Just (a, merge p l r)
pop _ _ = Nothing
fromList :: (a -> a -> Bool) -> [a] -> Leftist a
fromList p = mergeAll . map singleton where
pairs (a:b:xs) = merge p a b: pairs xs
pairs x = x
mergeAll [] = Empty
mergeAll [x] = x
mergeAll x = mergeAll (pairs x)
pqSort :: (a -> a -> Bool) -> [a] -> [a]
pqSort p = toList p . fromList p
toList :: (a -> a -> Bool) -> Leftist a -> [a]
toList _ Empty = []
toList p (Node _ i l r) = i : toList p (merge p l r)
main = print $ pqSort (<) [3, 7, 8, 1, 432, 2, 9, 6, 4, 5, 5454, 1, 78678, 54]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment