Skip to content

Instantly share code, notes, and snippets.

@Xetera
Created July 26, 2019 02:21
Show Gist options
  • Select an option

  • Save Xetera/905aae22bbeeb16ad30ff52f403f327b to your computer and use it in GitHub Desktop.

Select an option

Save Xetera/905aae22bbeeb16ad30ff52f403f327b to your computer and use it in GitHub Desktop.
Basic stack implementation in haskell
data Stack a
= Nil
| Stack a (Stack a)
instance Functor Stack where
fmap f s =
case s of
Stack e next ->
Stack (f e) $ fmap f next
Nil -> Nil
instance Foldable Stack where
foldr f current rest =
case rest of
Stack item next ->
foldr f (f item current) next
Nil -> current
instance Show a => Show (Stack a) where
show st = "Stack: " <> show (foldr (:) [] st)
stack :: a -> Stack a
stack a = Stack a Nil
push :: Stack a -> a -> Stack a
push Nil item = Stack item Nil
push next item = Stack item next
pop :: Stack a -> (Maybe a, Stack a)
pop (Stack item next) = (Just item, next)
pop Nil = (Nothing, Nil)
main :: IO ()
main = print $ foldl push (stack 2) [1..10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment