git.iko.soy/rowtype-yoga/purescript-yoga-tree
on master help sign in
Add 'showForest' and 'drawForest' functions
commit4f246a0a662193791eb2a59855db5d466018b2c7 authorJordan Martinez <jordanalex.martinez@gmail.com> dateWed 17 Apr 2019, 20:21 (7 years ago) parentbce8f4f
1 file changed+31−7
src/Data/Tree.purs+31−7
src/Data/Tree.purs+31−7
@@ -19,18 +19,42 @@ mkTree = mkCofree
1919
2020-- | Draw a 2D `String` representation of a `Tree String`.
2121drawTree :: Tree String -> String
22−drawTree t = tailRec go {level: 0, drawn: (head t) <> "\n", current: (tail t)}
22+drawTree = drawTree' 0
23+
24+-- | Draw a 2D `String` representation of a `Tree String`,
25+-- | starting the indent at the given level
26+drawTree' :: Int -> Tree String -> String
27+drawTree' level t =
28+ let
29+ treeRoot = (power " " level) <> "|----> " <> (head t) <> "\n"
30+ treeChildren = drawForest' (level + 1) (tail t)
31+ in treeRoot <> treeChildren
32+
33+-- | Draw a 2D `String` representation of a `Forest String`,
34+drawForest :: Forest String -> String
35+drawForest = drawForest' 0
36+
37+-- | Draw a 2D `String` representation of a `Forest String`,
38+-- | starting the indent at the given level
39+drawForest' :: Int -> Forest String -> String
40+drawForest' level forest = tailRec goForest { level: level, drawn: "", current: forest }
2341 where
24− go :: { current :: Forest String , drawn :: String , level :: Int } -> Step { current :: Forest String , drawn :: String , level :: Int } String
25− go {level: l, drawn: s, current: Nil} = Done s
26− go {level: l, drawn: s, current: c:cs } =
27− let drawn = (power " " l) <> "|----> " <> (head c) <> "\n" in
28− Loop {level: l, drawn: s <> drawn <> (tailRec go {level: l + 1, drawn: "", current: (tail c)}) , current: cs}
42+ goForest :: { current :: Forest String , drawn :: String , level :: Int }
43+ -> Step { current :: Forest String , drawn :: String , level :: Int } String
44+ goForest {level: l, drawn: s, current: Nil} = Done s
45+ goForest {level: l, drawn: s, current: c:cs } =
46+ let drawnTree = drawTree' l c in
47+ Loop {level: l, drawn: s <> drawnTree, current: cs}
2948
3049-- | Draw a 2D `String` representation of a `Tree` composed of `Show`able
3150-- | elements.
3251showTree :: forall a. Show a => Tree a -> String
33−showTree = drawTree <<< (map show)
52+showTree tree = drawTree (show <$> tree)
53+
54+-- | Draw a 2D `String` representation of a `Forest` composed of `Show`able
55+-- | elements.
56+showForest :: forall a. Show a => Forest a -> String
57+showForest forest = drawForest ((\tree -> show <$> tree) <$> forest)
3458
3559-- | Scan a `Tree`, accumulating values of `b` there are constant across `Node`s
3660-- | that have the same parent.