Skip to content

Instantly share code, notes, and snippets.

@SamirTalwar
Created May 10, 2019 16:46
Show Gist options
  • Save SamirTalwar/6d3149a1777134672ac3adee4cedd2e3 to your computer and use it in GitHub Desktop.
Save SamirTalwar/6d3149a1777134672ac3adee4cedd2e3 to your computer and use it in GitHub Desktop.
A tree implementation in Haskell.
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