[project @ 2005-12-03 17:32:01 by jpbernardy]
[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 #include "Typeable.h"
41
42 -- | Multi-way trees, also known as /rose trees/.
43 data Tree a   = Node {
44                 rootLabel :: a,         -- ^ label value
45                 subForest :: Forest a   -- ^ zero or more child trees
46         }
47 #ifndef __HADDOCK__
48   deriving (Eq, Read, Show)
49 #else /* __HADDOCK__ (which can't figure these out by itself) */
50 instance Eq a => Eq (Tree a)
51 instance Read a => Read (Tree a)
52 instance Show a => Show (Tree a)
53 #endif
54 type Forest a = [Tree a]
55
56 INSTANCE_TYPEABLE1(Tree,treeTc,"Tree")
57
58 instance Functor Tree where
59   fmap = mapTree
60
61 mapTree              :: (a -> b) -> (Tree a -> Tree b)
62 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
63
64 instance Traversable Tree where
65   traverse f (Node x ts) = Node <$> f x <*> traverse (traverse f) ts
66
67 instance Foldable Tree where
68   foldMap f (Node x ts) = f x `mappend` foldMap (foldMap f) ts
69
70 -- | Neat 2-dimensional drawing of a tree.
71 drawTree :: Tree String -> String
72 drawTree  = unlines . draw
73
74 -- | Neat 2-dimensional drawing of a forest.
75 drawForest :: Forest String -> String
76 drawForest  = unlines . map drawTree
77
78 draw :: Tree String -> [String]
79 draw (Node x ts0) = x : drawSubTrees ts0
80   where drawSubTrees [] = []
81         drawSubTrees [t] =
82                 "|" : shift "`- " "   " (draw t)
83         drawSubTrees (t:ts) =
84                 "|" : shift "+- " "|  " (draw t) ++ drawSubTrees ts
85
86         shift first other = zipWith (++) (first : repeat other)
87
88 -- | The elements of a tree in pre-order.
89 flatten :: Tree a -> [a]
90 flatten t = squish t []
91   where squish (Node x ts) xs = x:foldr squish xs ts
92
93 -- | Lists of nodes at each level of the tree.
94 levels :: Tree a -> [[a]]
95 levels t = map (map rootLabel) $
96                 takeWhile (not . null) $
97                 iterate (concatMap subForest) [t]
98
99 -- | Build a tree from a seed value
100 unfoldTree :: (b -> (a, [b])) -> b -> Tree a
101 unfoldTree f b = let (a, bs) = f b in Node a (unfoldForest f bs)
102
103 -- | Build a forest from a list of seed values
104 unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a
105 unfoldForest f = map (unfoldTree f)
106
107 -- | Monadic tree builder, in depth-first order
108 unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
109 unfoldTreeM f b = do
110         (a, bs) <- f b
111         ts <- unfoldForestM f bs
112         return (Node a ts)
113
114 -- | Monadic forest builder, in depth-first order
115 #ifndef __NHC__
116 unfoldForestM :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
117 #endif
118 unfoldForestM f = mapM (unfoldTreeM f)
119
120 -- | Monadic tree builder, in breadth-first order,
121 -- using an algorithm adapted from
122 -- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
123 -- by Chris Okasaki, /ICFP'00/.
124 unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
125 unfoldTreeM_BF f b = liftM getElement $ unfoldForestQ f (singleton b)
126   where getElement xs = case viewl xs of
127                 x :< _ -> x
128                 EmptyL -> error "unfoldTreeM_BF"
129
130 -- | Monadic forest builder, in breadth-first order,
131 -- using an algorithm adapted from
132 -- /Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design/,
133 -- by Chris Okasaki, /ICFP'00/.
134 unfoldForestM_BF :: Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
135 unfoldForestM_BF f = liftM toList . unfoldForestQ f . fromList
136
137 -- takes a sequence (queue) of seeds
138 -- produces a sequence (reversed queue) of trees of the same length
139 unfoldForestQ :: Monad m => (b -> m (a, [b])) -> Seq b -> m (Seq (Tree a))
140 unfoldForestQ f aQ = case viewl aQ of
141         EmptyL -> return empty
142         a :< aQ -> do
143                 (b, as) <- f a
144                 tQ <- unfoldForestQ f (foldl (|>) aQ as)
145                 let (tQ', ts) = splitOnto [] as tQ
146                 return (Node b ts <| tQ')
147   where splitOnto :: [a'] -> [b'] -> Seq a' -> (Seq a', [a'])
148         splitOnto as [] q = (q, as)
149         splitOnto as (_:bs) q = case viewr q of
150                 q' :> a -> splitOnto (a:as) bs q'
151                 EmptyR -> error "unfoldForestQ"