-- | Abstract Data Type Example: Efficient Queues -- Functional Programming course 2017. -- 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: queue not empty => front list not empty data Q a = Q [a] [a] -- Q front back deriving (Show) -- | A smart constructor to enforce the invariant 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 fs bs) = null fs -- | Inspect the front element front :: Q a -> a front (Q (f:fs) bs) = f -- | Remove an element from the front remove :: Q a -> Q a remove (Q (f:fs) bs) = smartQ fs bs --instance Eq a => Eq (Q a) where {- Below are the tests we ran in GHCi: :l Queue.hs :browse empty it empty add 1 it add 2 it add 3 it add 4 it remove it remove it remove it remove it remove it xs = [1..100] ys = 0:xs -}