Skip to content

Instantly share code, notes, and snippets.

@pwm
Created June 26, 2017 11:03
Show Gist options
  • Save pwm/a81ca9e0819ac5891d0c6b7b2b6c2709 to your computer and use it in GitHub Desktop.
Save pwm/a81ca9e0819ac5891d0c6b7b2b6c2709 to your computer and use it in GitHub Desktop.
Haskell Queue
-- http://www.randomhacks.net.s3-website-us-east-1.amazonaws.com/2007/02/08/haskell-queues-without-pointers/
{-# OPTIONS_GHC -Wall #-}
module Queue where
-- A queue holding values of type 'a'.
data Queue a = Queue [a] [a]
deriving (Show)
-- Create a new queue.
newQueue :: Queue a
newQueue = Queue [] []
-- Test whether a queue is empty.
empty :: Queue a -> Bool
empty (Queue [] []) = True
empty _ = False
-- Add an item to the back of the queue, returning the updated queue.
enq :: Queue a -> a -> Queue a
enq (Queue xs ys) y = Queue xs (y:ys)
-- Remove an item from the front of the queue, returning the item and the updated queue.
deq :: Queue a -> (a, Queue a)
-- If the queue is empty, raise an error.
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) = deq (Queue (reverse ys) [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment