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