Created
May 10, 2019 16:46
-
-
Save SamirTalwar/6d3149a1777134672ac3adee4cedd2e3 to your computer and use it in GitHub Desktop.
A tree 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
module Tree where | |
data Tree a | |
= Node [Tree a] | |
| Leaf a | |
deriving (Eq, Show) | |
instance Functor Tree where | |
f `fmap` Leaf value = Leaf $ f value | |
f `fmap` Node children = Node $ fmap (fmap f) children | |
instance Applicative Tree where | |
pure = Leaf | |
Leaf f <*> x = f <$> x | |
Node trees <*> x = Node $ map (<*> x) trees | |
instance Monad Tree where | |
Leaf value >>= f = f value | |
Node children >>= f = Node $ map (>>= f) children | |
instance Foldable Tree where | |
foldr accumulate initial (Leaf value) = accumulate value initial | |
foldr accumulate initial (Node children) = | |
foldr (flip (foldr accumulate)) initial children | |
instance Traversable Tree where | |
traverse f (Leaf value) = Leaf <$> f value | |
traverse f (Node children) = Node <$> traverse (traverse f) children |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment