A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming.

It's often helpful to visually examine such a structure.

There are many ways to represent trees to a reader, such as:

   indented text   (à la unix  tree  command)
   nested HTML tables
   hierarchical GUI widgets
   2D   or   3D   images
   etc.
Task

Write a program to produce a visual representation of some tree.

The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.

Make do with the vague term "friendly" the best you can.




import "/dynamic" for Struct
import "random" for Random
 
var Stem = Struct.create("Stem", ["str", "next"])
 
var SDOWN = "  |"
var SLAST = "  `"
var SNONE = "   "
 
var rand = Random.new()
 
var tree // recursive
tree = Fn.new { |root, head|
    var col = Stem.new(null, null)
    var tail = head
    while (tail) {
        System.write(tail.str)
        if (!tail.next) break
        tail = tail.next
    }
    System.print("--%(root)")
    if (root <= 1) return
    if (tail && tail.str == SLAST) tail.str = SNONE
    if (!tail) {
        tail = head = col
    } else {
        tail.next = col
    }
    while (root != 0) { // make a tree by doing something random
        var r = 1 + rand.int(root)
        root = root - r
        col.str = (root != 0) ? SDOWN : SLAST
        tree.call(r, head)
    }
    tail.next = null
}
 
var n = 8
tree.call(n, null)