Created
May 7, 2020 01:33
-
-
Save emptyflask/6b4584adda621a9ce0f4c2421eedeb06 to your computer and use it in GitHub Desktop.
haskell trees
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
import Data.Monoid | |
import Data.Foldable | |
data Tree a = Empty | |
| Node (Maybe a) | |
(Tree a) | |
(Tree a) | |
deriving (Show) | |
instance Foldable Tree where | |
foldMap f Empty = mempty | |
foldMap f (Node a l r) = foldMap f a | |
<> foldMap f l | |
<> foldMap f r | |
instance Functor Tree where | |
fmap f Empty = Empty | |
fmap f (Node a l r) = Node (fmap f a) | |
(fmap f l) | |
(fmap f r) | |
tree :: Tree Integer | |
tree = Node (Just 3) | |
(Node (Just 2) | |
Empty | |
(Node (Just 5) | |
Empty | |
Empty | |
) | |
) | |
(Node Nothing Empty Empty) | |
main :: IO () | |
main = do | |
putStrLn $ "sum: " <> show (sum tree) | |
putStrLn $ "fmap: " <> show ((*2) <$> tree) |
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
{-# LANGUAGE DeriveFoldable #-} | |
{-# LANGUAGE DeriveFunctor #-} | |
import Data.Monoid | |
import Data.Foldable | |
data Tree a = Empty | |
| Node (Maybe a) | |
(Tree a) | |
(Tree a) | |
deriving (Show, Functor, Foldable) | |
tree :: Tree Integer | |
tree = Node (Just 3) | |
(Node (Just 2) | |
Empty | |
(Node (Just 5) | |
Empty | |
Empty | |
) | |
) | |
(Node Nothing Empty Empty) | |
main :: IO () | |
main = do | |
putStrLn $ "sum: " <> show (sum tree) | |
putStrLn $ "fmap: " <> show ((*2) <$> tree) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment