data Stack a
= S
(Queue a
) (Queue a
) deriving (Show)
newStack = S newQueue newQueue
pop :: Stack a -> (a, Stack a)
pop (S main help) = if empty main
else (x, S newMain help)
where (x, newMain) = deq main
push :: a -> Stack a -> Stack a
push a (S main help) = S newMain help
where newHelp = move main help --move items from main queue to help queue
newTop = enq a newQueue --enqueue the item to be pushed to an empty queue
newMain = move newHelp newTop --move items from help queue to the queue with the pushed item
-- helper function to move the contents of q1 to q2
move :: Queue a -> Queue a -> Queue a
move q1 q2 = if empty q1
then q2
else move newQ1 (enq x q2)
where (x, newQ1) = deq q1
main = do
let testStack = push 1 $ push 2 $ push 3 newStack
let popped
= snd $ pop testStack
print $ push
10 $ push
20 popped
-- This implementation is taken from
-- http://w...content-available-to-author-only...s.net/2007/02/08/haskell-queues-without-pointers/
-- except showQueue
data Queue a = Queue [a] [a]
newQueue = Queue [] []
empty (Queue [] []) = True
empty _ = False
enq :: a -> Queue a -> Queue a
enq y (Queue xs ys) = Queue xs (y:ys)
deq :: Queue a -> (a, Queue a)
deq (Queue [] []) =
error "Can't deq from an empty queue" -- If there's at least one item in the front
-- part of the queue, return it.
deq (Queue (x:xs) ys) = (x, Queue xs ys)
-- If the front part is empty, reverse the
-- back part, move it to the front, and try
-- again.
deq (Queue [] ys) =
showQueue (Queue [] []) = "Q:[]"
showQueue
(Queue xs ys
) = "Q:" ++ (show $ xs
++ ys
)
instance (Show a
) => Show (Queue a
) where