Visualize a tree: Difference between revisions
→Functional composition: Python 3 pylint. Tidying
(Added Fōrmulæ) |
(→Functional composition: Python 3 pylint. Tidying) |
||
Line 2,087:
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>from itertools import (repeat, starmap)▼
<lang python>'''Vizualize a tree'''
from operator import (add)
Line 2,093 ⟶ 2,096:
# drawTree :: Tree a -> String
def drawTree(tree):
'''ASCII diagram of a tree.'''
return '\n'.join(draw(tree))
Line 2,098 ⟶ 2,102:
# draw :: Tree a -> [String]
def draw(node):
'''List of the lines of an ASCII
diagram of a tree.'''
def shift(first, other, xs):
return list(starmap(
Line 2,128 ⟶ 2,134:
# main :: IO ()
def main():
'''Test'''
# tree :: Tree Int
Line 2,146 ⟶ 2,153:
print(drawTree(tree))
# GENERIC -------------------------------------------------
Line 2,152 ⟶ 2,160:
# Node :: a -> [Tree a] -> Tree a
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}
Line 2,157 ⟶ 2,168:
# nest :: Tree a -> [Tree a]
def nest(tree):
'''Accessor function for children of tree node.'''
return tree['nest'] if 'nest' in tree else None
# root :: Dict -> a
def root(
'''Accessor function for data of tree node.'''
return
|