Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Last active January 23, 2016 11:00
Show Gist options
  • Save maxdeliso/2d97201503d73ae858f1 to your computer and use it in GitHub Desktop.
Save maxdeliso/2d97201503d73ae858f1 to your computer and use it in GitHub Desktop.
simple haskell stack implementation, work in progress
module AStack(Stack, push, pop, top, size, stackTo) where
data Stack a = Empty
| MkStack a (Stack a)
push :: a -> Stack a -> Stack a
push x s = MkStack x s
size :: Stack a -> Int
size s = length (stkToLst s) where
stkToLst Empty = []
stkToLst (MkStack x s) = x:xs where
xs = stkToLst s
pop :: Stack a -> (a, Stack a)
pop (MkStack x s)
= (x, case s of
r -> i r where i x = x)
top :: Stack a -> a
top (MkStack x s) = x
stackTo :: Int -> Stack Int
stackTo x = foldl (\s n -> push n s) Empty [1..x]
showStack :: (Show a) => Stack a -> String
showStack (MkStack x s) = show x ++ " - " ++ showStack s
showStack Empty = "}"
instance Show a => Show (Stack a) where
show x = showStack x
instance Functor Stack where
fmap f (MkStack x s) = push (f x) $ fmap f s
fmap f Empty = Empty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment