fec58569b2fc39148b90a7dd08b502c3c46933ff
[haskell-directory.git] / Data / Tree.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Tree
4 -- Copyright   :  (c) The University of Glasgow 2002
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  portable
10 --
11 -- Multi-way trees (/aka/ rose trees) and forests.
12 --
13 -----------------------------------------------------------------------------
14
15 module Data.Tree(
16         Tree(..), Forest,
17         -- * Two-dimensional drawing
18         drawTree, drawForest,
19         -- * Extraction
20         flatten, levels,
21         -- * Building trees
22         unfoldTree, unfoldForest,
23         unfoldTreeM, unfoldForestM,
24         unfoldTreeM_BF, unfoldForestM_BF,
25     ) where
26
27 #ifdef __HADDOCK__
28 import Prelude
29 #endif
30
31 import Control.Applicative (Applicative(..))
32 import Control.Monad
33 import Data.Monoid (Monoid(..))
34 import Data.Sequence (Seq, empty, singleton, (<|), (|>), fromList,
35                         ViewL(..), ViewR(..), viewl, viewr)
36 import Data.Foldable (Foldable(foldMap), toList)
37 import Data.Traversable (Traversable(traverse))
38 import Data.Typeable
39
40 #ifdef __GLASGOW_HASKELL__
41 import Data.Generics.Basics (Data)
42 #endif
43
44 -- | Multi-way trees, also known as /rose trees/.
45 data Tree a   = Node {
46                 rootLabel :: a,         -- ^ label value
47                 subForest :: Forest a   -- ^ zero or more child trees
48         }
49 #ifndef __HADDOCK__
50 # ifdef __GLASGOW_HASKELL__
51   deriving (Eq, Read, Show, Data)
52 # else
53   deriving (Eq, Read, Show)
54 # endif
55 #else /* __HADDOCK__ (which can't figure these out by itself) */
56 instance Eq a => Eq (Tree a)
57 instance Read a => Read (Tree a)
58 instance Show a => Show (Tree a)
59 instance Data a => Data (Tree a)
60 #endif
61 type Forest a = [Tree a]
62
63 #include "Typeable.h"
64 INSTANCE_TYPEABLE1(Tree,treeTc,"Tree")
65
66 instance Functor Tree where
67   fmap = mapTree
68
69 mapTree              :: (a -> b) -> (Tree a -> Tree b)
70 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
71
72 instance Traversable Tree where
73   traverse f (Node x ts) = Node <$> f x <*> traverse (traverse f) ts
74
75 instance Foldable Tree where
76   foldMap f (Node x ts) = f x `mappend` foldMap (foldMap f) ts
77
78 -- | Neat 2-dimensional drawing of a tree.
79 drawTree :: Tree String -> String
80 drawTree  = unlines . draw
81
82 -- | Neat 2-dimensional drawing of a forest.
83 drawForest :: Forest String -> String
84 drawForest  = unlines . map drawTree
85
86 draw :: Tree String -> [String]
87 draw (Node x ts0) = x : drawSubTrees ts0
88   where drawSubTrees [] = []
89         drawSubTrees [t] =
90                 "|" : shift "`- " "   " (draw t)
91         drawSubTrees (t:ts) =
92                 "|" : shift "+- " "|  " (draw t) ++ drawSubTrees ts
93
94         shift first other = zipWith (++) (first : repeat other)
95
96 -- | The elements of a tree in pre-order.
97 flatten :: Tree a -> [a]
98 flatten t = squish t []
99   where squish (Node x ts) xs = x:foldr squish xs ts
100
101 -- | Lists of nodes at each level of the tree.
102 levels :: Tree a -> [[a]]
103 levels t = map (map rootLabel) $
104                 takeWhile (not . null) $
105                 iterate (concatMap subForest) [t]
106
107 -- | Build a tree from a seed value
108 unfoldTree :: (b -> (a, [b])) -> b -> Tree a
109 unfoldTree f b = let (a, bs) = f b in Node a (unfoldForest f bs)
110
111 -- | Build a forest from a list of seed values
112 unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a
113 unfoldForest f = map (unfoldTree f)
114
115 -- | Monadic tree builder, in depth-first order
116 unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
117 unfoldTreeM f b = do
118         (a, bs) <- f b
119         ts <- unfoldForestM f bs
120         return (Node a ts)
121
122 -- | Monadic forest builder, in depth-first order
123 #ifndef __NHC__
124 unfoldForestM :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
125 #endif
126 unfoldForestM f = mapM (unfoldTreeM f)
127
128 -- | Monadic tree builder, in breadth-first order,
129 -- using an algorithm adapted from
130 -- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
131 -- by Chris Okasaki, /ICFP'00/.
132 unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
133 unfoldTreeM_BF f b = liftM getElement $ unfoldForestQ f (singleton b)
134   where getElement xs = case viewl xs of
135                 x :< _ -> x
136                 EmptyL -> error "unfoldTreeM_BF"
137
138 -- | Monadic forest builder, in breadth-first order,
139 -- using an algorithm adapted from
140 -- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
141 -- by Chris Okasaki, /ICFP'00/.
142 unfoldForestM_BF :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
143 unfoldForestM_BF f = liftM toList . unfoldForestQ f . fromList
144
145 -- takes a sequence (queue) of seeds
146 -- produces a sequence (reversed queue) of trees of the same length
147 unfoldForestQ :: Monad m => (b -> m (a, [b])) -> Seq b -> m (Seq (Tree a))
148 unfoldForestQ f aQ = case viewl aQ of
149         EmptyL -> return empty
150         a :< aQ -> do
151                 (b, as) <- f a
152                 tQ <- unfoldForestQ f (foldl (|>) aQ as)
153                 let (tQ', ts) = splitOnto [] as tQ
154                 return (Node b ts <| tQ')
155   where splitOnto :: [a'] -> [b'] -> Seq a' -> (Seq a', [a'])
156         splitOnto as [] q = (q, as)
157         splitOnto as (_:bs) q = case viewr q of
158                 q' :> a -> splitOnto (a:as) bs q'
159                 EmptyR -> error "unfoldForestQ"