Created
June 11, 2018 19:59
-
-
Save rnagasam/90d2645271b933d806db588ffe940eaf to your computer and use it in GitHub Desktop.
Multiway Trees
This file contains 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 InstanceSigs #-} | |
-- Rose Trees | |
data Tree a = | |
a :> [Tree a] | |
deriving (Eq, Show) | |
singleton :: a -> Tree a | |
singleton = (:> []) | |
instance Functor Tree where | |
fmap :: (a -> b) -> Tree a -> Tree b | |
fmap f (x :> xs) = (f x) :> fmap (f <$>) xs | |
instance Applicative Tree where | |
pure :: a -> Tree a | |
pure = singleton | |
(<*>) :: Tree (a -> b) -> Tree a -> Tree b | |
(f :> fs) <*> t@(x :> xs) = (f x) :> fxs | |
where | |
fxs = map (f <$>) xs ++ map (<*> t) fs | |
instance Foldable Tree where | |
foldMap :: Monoid m => (a -> m) -> Tree a -> m | |
foldMap f (x :> xs) = f x <> foldMap (foldMap f) xs | |
instance Monad Tree where | |
return :: a -> Tree a | |
return = pure | |
(>>=) :: Tree a -> (a -> Tree b) -> Tree b | |
(x :> xs) >>= f = | |
case f x of | |
x' :> xs' -> x' :> (xs' ++ map (>>= f) xs) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment