1 -----------------------------------------------------------------------------
4 -- Copyright : (c) The University of Glasgow 2002
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : experimental
9 -- Portability : portable
11 -- Multi-way trees (/aka/ rose trees) and forests.
13 -----------------------------------------------------------------------------
21 -- | Multi-way trees, also known as /rose trees/.
22 data Tree a = Node a (Forest a) -- ^ a value and zero or more child trees.
24 deriving (Eq, Read, Show)
25 #else /* __HADDOCK__ (which can't figure these out by itself) */
26 instance Eq a => Eq (Tree a)
27 instance Read a => Read (Tree a)
28 instance Show a => Show (Tree a)
30 type Forest a = [Tree a]
32 instance Functor Tree where
35 mapTree :: (a -> b) -> (Tree a -> Tree b)
36 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
38 -- | Neat 2-dimensional drawing of a tree.
39 drawTree :: Show a => Tree a -> String
40 drawTree = unlines . draw . mapTree show
42 -- | Neat 2-dimensional drawing of a forest.
43 drawForest :: Show a => Forest a -> String
44 drawForest = unlines . map drawTree
46 draw :: Tree String -> [String]
47 draw (Node x ts0) = grp this (space (length this)) (stLoop ts0)
48 where this = s1 ++ x ++ " "
50 space n = replicate n ' '
53 stLoop [t] = grp s2 " " (draw t)
54 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
56 rsLoop [] = error "rsLoop:Unexpected empty list."
57 rsLoop [t] = grp s5 " " (draw t)
58 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
60 grp fst0 rst = zipWith (++) (fst0:repeat rst)
62 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
64 -- | The elements of a tree in pre-order.
65 flatten :: Tree a -> [a]
66 flatten t = squish t []
67 where squish (Node x ts) xs = x:foldr squish xs ts
69 -- | Lists of nodes at each level of the tree.
70 levels :: Tree a -> [[a]]
71 levels t = map (map root) $ takeWhile (not . null) $ iterate subforest [t]
72 where root (Node x _) = x
73 subforest f = [t | Node _ ts <- f, t <- ts]