Created
July 26, 2019 02:21
-
-
Save Xetera/905aae22bbeeb16ad30ff52f403f327b to your computer and use it in GitHub Desktop.
Basic stack implementation in haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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