I've googled a bit and found a paper on Finger Trees, which can be used to implement a priority queue with proper asymptotic complexity, but they're quite complicated, but still about the simplest thing I could find.
Is there a simple data structure that allows to implement a fast priority queue in Haskell? Think simple as in you could explain it to a novice programmer.
The binary heap is the most efficient method for implementing the priority queue in the data structure.
The priority queue can be implemented in four ways that include arrays, linked list, heap data structure and binary search tree. The heap data structure is the most efficient way of implementing the priority queue, so we will implement the priority queue using a heap data structure in this topic.
The heap provides multiple functions and operations than the priority queue. The priority queue provides queue-related functions. The heap implements abstract data types such as priority queue but priority queue does not implement heap. The priority queue is simpler than the heap data structure.
The default PriorityQueue is implemented with Min-Heap, that is the top element is the minimum one in the heap.
The heap package on Hackage claims to be based on Okasaki's leftist heaps.
From the docs:
Choose MinHeap or MaxHeap if you need a simple minimum or maximum heap (which always keeps the minimum/maximum element at the head of the Heap).
If you wish to manually annotate a value with a priority, e. g. an IO () action with an Int use MinPrioHeap or MaxPrioHeap. They manage (prio, val) tuples so that only the priority (and not the value) influences the order of elements.
If you still need something different, define a custom order for the heap elements by implementing an instance of HeapItem and let the maintainer know what's missing.
The heap that is the simplest to implement in Haskell I know is the Pairing Heap.
It supports insert and merge in constant time (amortised) and logarithmic time to delete elements.
data Heap a = Empty | Heap a [(Heap a)]
deriving Show
findMin :: Heap a -> a
findMin (Heap h _) = h
merge :: Ord a => Heap a -> Heap a -> Heap a
merge Empty h = h
merge h Empty = h
merge h1@(Heap x hs1) h2@(Heap y hs2)
| x < y = Heap x (h2:hs1)
| otherwise = Heap y (h1:hs2)
mergePairs :: Ord a => [Heap a] -> Heap a
mergePairs [] = Empty
mergePairs [h] = h
mergePairs (h1:h2:hs) = merge (merge h1 h2) (mergePairs hs)
insert :: Ord a => a -> Heap a -> Heap a
insert x = merge (Heap x [])
deleteMin :: Ord a => Heap a -> Heap a
deleteMin (Heap x hs) = mergePairs hs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With