Skip to content

Instantly share code, notes, and snippets.

@TheSeamau5
Created December 25, 2014 00:03
Show Gist options
  • Save TheSeamau5/218a29c86afff572b777 to your computer and use it in GitHub Desktop.
Save TheSeamau5/218a29c86afff572b777 to your computer and use it in GitHub Desktop.
Stacks and Queues
-- STACKS
type Stack a = Bottom | Element a (Stack a)
push : a -> Stack a -> Stack a
push element stack =
Element element stack
pop : Stack a -> (Maybe a, Stack a)
pop stack =
case stack of
Bottom -> (Nothing, stack)
Element element innerStack -> (Just element, innerStack)
justPop : Stack a -> Stack a
justPop = snd << pop
peek : Stack a -> Maybe a
peek stack =
case stack of
Bottom -> Nothing
Element element _ -> Just element
-- QUEUES
type Queue a = Queue (List a)
emptyQueue : Queue a
emptyQueue = Queue []
enqueue : a -> Queue a -> Queue a
enqueue element (Queue xs) = Queue (xs ++ [element])
dequeue : Queue a -> (Maybe a, Queue a)
dequeue (Queue list) =
case list of
[] -> (Nothing, emptyQueue)
x :: xs -> (Just x, Queue xs)
justDequeue : Queue a -> Queue a
justDequeue = snd << dequeue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment