Created
August 9, 2024 02:58
-
-
Save YuMingLiao/8cab88ecccc68eeebe15a3a4568890aa to your computer and use it in GitHub Desktop.
A Haskell implementation of priority search queue found on wikipedia
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data PriorityQueue k a = Nil | Branch k a (PriorityQueue k a) (PriorityQueue k a) | |
empty :: Ord k => PriorityQueue k a | |
empty = Nil | |
singleton :: Ord k => k -> a -> PriorityQueue k a | |
singleton k a = Branch k a Nil Nil | |
minKeyValue :: Ord k => PriorityQueue k a -> (k, a) | |
minKeyValue Nil = error "empty queue" | |
minKeyValue (Branch k a _ _) = (k, a) | |
minView :: Ord k => PriorityQueue k a -> Maybe (a, PriorityQueue k a) | |
minView Nil = Nothing | |
minView (Branch _ a l r) = Just (a, union l r) | |
union :: Ord k => PriorityQueue k a -> PriorityQueue k a -> PriorityQueue k a | |
union l Nil = l | |
union Nil r = r | |
union l@(Branch kl _ _ _) r@(Branch kr _ _ _) | |
| kl <= kr = link l r | |
| otherwise = link r l | |
link (Branch k a Nil m) r = Branch k a r m | |
link (Branch k a ll lr) r = Branch k a lr (union ll r) | |
insert :: Ord k => k -> a -> PriorityQueue k a -> PriorityQueue k a | |
insert k a q = union (singleton k a) q |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment