Visualize a tree

From Fōrmulæ wiki
Jump to: navigation, search

This page is the answer to the task Visualize a tree in the Rosetta Code.

Description (from Rosetta Code)

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.

Solution

Fōrmulæ trees

Fōrmulæ is a homoiconic language using expression trees as its fundamental structure, so managing trees is very natural.

A tree is an expression defined recursively: A tree is a (main) node that can contain zero o more trees.

In Fōrmulæ, every kind of expression has one (or more) visualizers. Currently there are two visualizers for expression trees (and hence there is no need to write code to visualize expression trees):

A visualizer to show trees in horizontal form:

VisualizeTree1.png

A visualizer to show trees in vertical form:

VisualizeTree2.png

Creating trees from expressions

The ToTree expression creates a tree from a given expression. see the following examples:

VisualizeTree3.png

Be aware the the expression expression will be first reduced, like the following:

VisualizeTree4.png

It order to avoid the reduction, the use of the Protect expression is recommended:

VisualizeTree5.png

Here is another example:

VisualizeTree6.png

In the following example, it is shown that a matrix is a list containing (same cardinality) lists:

VisualizeTree9.png

In the following example, it is shown that, according to the Fōrmulæ arithmetic canon, a negative number is a Math.Arithmetic.Negative expression containing a Math.Number expression:

VisualizeTree10.png

In the next example, it is shown that a function has exactly two subexpressions: the function itself and arguments. The arguments of the functions is a list of symbols:

VisualizeTree11.png

Creating trees programatically

The tree, like any other expression in Fōrmulæ is a first-class citizen of the language. Fōrmulæ also supports high-order functions, so trees can be set as parameters of functions, or retrieved from functions.

The following example shows a function that produces a Fibonacci tree, a tree that shows the calls of a recursive Fibonacci numbers:

VisualizeTree7.png

VisualizeTree8.png