X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=Data%2FTree.hs;h=f2a55f59d28e32ef5ea75804fdc609aa12b4c4ac;hb=a14a8400e73713d5ac8c1b3405ac13f4cfe86acf;hp=113bc4c1ceb5d05bb4b601c58c9c4f49e4961d88;hpb=fde33aa064e87cf823a501ac5c909e93d169fe37;p=haskell-directory.git diff --git a/Data/Tree.hs b/Data/Tree.hs index 113bc4c..f2a55f5 100644 --- a/Data/Tree.hs +++ b/Data/Tree.hs @@ -28,13 +28,18 @@ module Data.Tree( import Prelude #endif +import Control.Applicative (Applicative(..), (<$>)) import Control.Monad +import Data.Monoid (Monoid(..)) import Data.Sequence (Seq, empty, singleton, (<|), (|>), fromList, ViewL(..), ViewR(..), viewl, viewr) -import qualified Data.Sequence as Seq (foldl) +import Data.Foldable (Foldable(foldMap), toList) +import Data.Traversable (Traversable(traverse)) import Data.Typeable -#include "Typeable.h" +#ifdef __GLASGOW_HASKELL__ +import Data.Generics.Basics (Data) +#endif -- | Multi-way trees, also known as /rose trees/. data Tree a = Node { @@ -42,21 +47,30 @@ data Tree a = Node { subForest :: Forest a -- ^ zero or more child trees } #ifndef __HADDOCK__ +# ifdef __GLASGOW_HASKELL__ + deriving (Eq, Read, Show, Data) +# else deriving (Eq, Read, Show) +# endif #else /* __HADDOCK__ (which can't figure these out by itself) */ instance Eq a => Eq (Tree a) instance Read a => Read (Tree a) instance Show a => Show (Tree a) +instance Data a => Data (Tree a) #endif type Forest a = [Tree a] +#include "Typeable.h" INSTANCE_TYPEABLE1(Tree,treeTc,"Tree") instance Functor Tree where - fmap = mapTree + fmap f (Node x ts) = Node (f x) (map (fmap f) ts) + +instance Traversable Tree where + traverse f (Node x ts) = Node <$> f x <*> traverse (traverse f) ts -mapTree :: (a -> b) -> (Tree a -> Tree b) -mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts) +instance Foldable Tree where + foldMap f (Node x ts) = f x `mappend` foldMap (foldMap f) ts -- | Neat 2-dimensional drawing of a tree. drawTree :: Tree String -> String @@ -123,9 +137,7 @@ unfoldTreeM_BF f b = liftM getElement $ unfoldForestQ f (singleton b) -- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/, -- by Chris Okasaki, /ICFP'00/. unfoldForestM_BF :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a) -unfoldForestM_BF f = liftM toRevList . unfoldForestQ f . fromList - where toRevList :: Seq c -> [c] - toRevList = Seq.foldl (flip (:)) [] +unfoldForestM_BF f = liftM toList . unfoldForestQ f . fromList -- takes a sequence (queue) of seeds -- produces a sequence (reversed queue) of trees of the same length