Visualize a tree: Difference between revisions
Content added Content deleted
(Added Fōrmulæ) |
(→Functional composition: Python 3 pylint. Tidying) |
||
Line 2,087: | Line 2,087: | ||
Using the same tree structure (including tree node constructor and accessors) as in the [[Tree_traversal|Tree Traversal]] task: |
Using the same tree structure (including tree node constructor and accessors) as in the [[Tree_traversal|Tree Traversal]] task: |
||
{{Works with|Python|3}} |
|||
⚫ | |||
<lang python>'''Vizualize a tree''' |
|||
⚫ | |||
from operator import (add) |
from operator import (add) |
||
Line 2,093: | Line 2,096: | ||
# drawTree :: Tree a -> String |
# drawTree :: Tree a -> String |
||
def drawTree(tree): |
def drawTree(tree): |
||
'''ASCII diagram of a tree.''' |
|||
return '\n'.join(draw(tree)) |
return '\n'.join(draw(tree)) |
||
Line 2,098: | Line 2,102: | ||
# draw :: Tree a -> [String] |
# draw :: Tree a -> [String] |
||
def draw(node): |
def draw(node): |
||
'''List of the lines of an ASCII |
|||
diagram of a tree.''' |
|||
def shift(first, other, xs): |
def shift(first, other, xs): |
||
return list(starmap( |
return list(starmap( |
||
Line 2,128: | Line 2,134: | ||
# main :: IO () |
# main :: IO () |
||
def main(): |
def main(): |
||
'''Test''' |
|||
# tree :: Tree Int |
# tree :: Tree Int |
||
Line 2,146: | Line 2,153: | ||
print(drawTree(tree)) |
print(drawTree(tree)) |
||
# GENERIC ------------------------------------------------- |
# GENERIC ------------------------------------------------- |
||
Line 2,152: | Line 2,160: | ||
# Node :: a -> [Tree a] -> Tree a |
# Node :: a -> [Tree a] -> Tree a |
||
def Node(v): |
def Node(v): |
||
'''Contructor for a Tree node which connects a |
|||
value of some kind to a list of zero or |
|||
more child trees.''' |
|||
return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} |
return lambda xs: {'type': 'Node', 'root': v, 'nest': xs} |
||
Line 2,157: | Line 2,168: | ||
# nest :: Tree a -> [Tree a] |
# nest :: Tree a -> [Tree a] |
||
def nest(tree): |
def nest(tree): |
||
'''Accessor function for children of tree node''' |
'''Accessor function for children of tree node.''' |
||
return tree['nest'] if 'nest' in tree else None |
return tree['nest'] if 'nest' in tree else None |
||
# root :: Dict -> a |
# root :: Dict -> a |
||
def root( |
def root(dct): |
||
'''Accessor function for data of tree node''' |
'''Accessor function for data of tree node.''' |
||
return |
return dct['root'] if 'root' in dct else None |
||