Queue.hs

-- | Abstract Data Type Example: Efficient Queues
-- Functional Programming course 2018.
-- Thomas Hallgren

{-
This started as a skeleton, the definitions were filled in
during the lecture.
-}

--------------------------------------------------------------------------------
module Queue(Q,empty,add,isEmpty,front,remove) where

-- | Queue representation.
-- Invariant: the front queue should not be empty when the queue is nonempty
data Q a = Q [a] [a]           deriving (Show)
           --fs  bs

smartQ :: [a] -> [a] -> Q a
smartQ [] bs = Q (reverse bs) []
smartQ fs bs = Q fs bs

-- | An empty queue
empty   :: Q a
empty = smartQ [] []

-- | Add an element at the back
add     :: a -> Q a -> Q a
add x (Q fs bs) = smartQ fs (x:bs)

-- | Check if the queue is empty
isEmpty :: Q a -> Bool
isEmpty (Q [] _) = True
isEmpty _        = False

-- | Inspect the front element
front   :: Q a -> a
front (Q (x:fs) bs) = x

-- | Remove an element from the front
remove  :: Q a -> Q a
remove (Q (x:fs) bs) = smartQ fs bs


--instance Eq a => Eq (Q a) where


Plain-text version of Queue.hs | Valid HTML?