Download code

Jump to: navigation, search

Back to Priority_Queue_(Haskell)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

PriorityQueue.hs

 1 {- The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Priority_Queue_(Haskell)?oldid=19189
14 -}
15 
16 module PriorityQueue (
17     PriorityQueue,
18     empty,
19     minKey,
20     minKeyValue,
21     insert,
22     deleteMinAndInsert
23 ) where
24  
25 import Prelude
26 
27 -- Declare the data type constructors.
28 data Ord k => PriorityQueue k a = Nil | Branch k a (PriorityQueue k a) (PriorityQueue k a)
29  
30 
31 -- Declare the exported interface functions.
32 -- Return an empty priority queue.
33 empty :: Ord k => PriorityQueue k a
34 empty = Nil
35 
36 -- Return the highest-priority key.
37 minKey :: Ord k => PriorityQueue k a -> k
38 minKey = fst . minKeyValue
39 
40 -- Return the highest-priority key plus its associated value.
41 minKeyValue :: Ord k => PriorityQueue k a -> (k, a)
42 minKeyValue Nil              = error "empty queue"
43 minKeyValue (Branch k a _ _) = (k, a)
44 
45 -- Insert a key/value pair into a queue.
46 insert :: Ord k => k -> a -> PriorityQueue k a -> PriorityQueue k a
47 insert k a q = union (singleton k a) q
48 
49 -- Delete the highest-priority key/value pair and insert a new key/value pair into the queue.
50 deleteMinAndInsert :: Ord k => k -> a -> PriorityQueue k a -> PriorityQueue k a
51 deleteMinAndInsert k a Nil              = singleton k a
52 deleteMinAndInsert k a (Branch _ _ l r) = union (insert k a l) r
53 
54 -- Declare the private helper functions.
55 -- Join two queues in sorted order.
56 union :: Ord k => PriorityQueue k a -> PriorityQueue k a -> PriorityQueue k a
57 union l Nil = l
58 union Nil r = r
59 union l@(Branch kl _ _ _) r@(Branch kr _ _ _)
60     | kl <= kr  = link l r
61     | otherwise = link r l
62 
63 -- Join two queues without regard to order.
64 -- (This is a helper to the union helper.)
65 link (Branch k a Nil m) r = Branch k a r m
66 link (Branch k a ll lr) r = Branch k a lr (union ll r)
67 
68 -- Return a queue with a single item from a key/value pair.
69 singleton :: Ord k => k -> a -> PriorityQueue k a
70 singleton k a = Branch k a Nil Nil


hijacker
hijacker
hijacker
hijacker