1 -----------------------------------------------------------------------------
4 -- Copyright : (c) The University of Glasgow 2002
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
11 -- Queues with constant time operations, from
12 -- /Simple and efficient purely functional queues and deques/,
13 -- by Chris Okasaki, /JFP/ 5(4):583-592, October 1995.
15 -----------------------------------------------------------------------------
19 -- * Primitive operations
20 -- | Each of these requires /O(1)/ time in the worst case.
21 emptyQueue, addToQueue, deQueue,
23 listToQueue, queueToList
26 import Prelude -- necessary to get dependencies right
29 -- | The type of FIFO queues.
30 data Queue a = Q [a] [a] [a]
33 INSTANCE_TYPEABLE1(Queue,queueTc,"Queue")
35 -- Invariants for Q xs ys xs':
36 -- length xs = length ys + length xs'
37 -- xs' = drop (length ys) xs -- in fact, shared (except after fmap)
38 -- The queue then represents the list xs ++ reverse ys
40 instance Functor Queue where
41 fmap f (Q xs ys xs') = Q (map f xs) (map f ys) (map f xs')
42 -- The new xs' does not share the tail of the new xs, but it does
43 -- share the tail of the old xs, so it still forces the rotations.
44 -- Note that elements of xs' are ignored.
48 emptyQueue = Q [] [] []
50 -- | Add an element to the back of a queue.
51 addToQueue :: Queue a -> a -> Queue a
52 addToQueue (Q xs ys xs') y = makeQ xs (y:ys) xs'
54 -- | Attempt to extract the front element from a queue.
55 -- If the queue is empty, 'Nothing',
56 -- otherwise the first element paired with the remainder of the queue.
57 deQueue :: Queue a -> Maybe (a, Queue a)
58 deQueue (Q [] _ _) = Nothing
59 deQueue (Q (x:xs) ys xs') = Just (x, makeQ xs ys xs')
62 -- length ys <= length xs + 1
63 -- xs' = drop (length ys - 1) xs
64 -- construct a queue respecting the invariant.
65 makeQ :: [a] -> [a] -> [a] -> Queue a
66 makeQ xs ys [] = listToQueue (rotate xs ys [])
67 makeQ xs ys (_:xs') = Q xs ys xs'
69 -- Assuming length ys = length xs + 1,
70 -- rotate xs ys zs = xs ++ reverse ys ++ zs
71 rotate :: [a] -> [a] -> [a] -> [a]
72 rotate [] (y:_) zs = y : zs -- the _ here must be []
73 rotate (x:xs) (y:ys) zs = x : rotate xs ys (y:zs)
75 -- | A queue with the same elements as the list.
76 listToQueue :: [a] -> Queue a
77 listToQueue xs = Q xs [] xs
79 -- | The elements of a queue, front first.
80 queueToList :: Queue a -> [a]
81 queueToList (Q xs ys _) = xs ++ reverse ys