Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Prolog tree traversal


1. Prolog tree traversal

2. Prolog tree traversal
Let is look at how an expression tree represented as a prefix list can be traversed in Prolog.

Here is the Prolog code.

Here is the output of the Prolog code.


3. Difference list
A difference list is used to construct a list from a passed logical variable in a bottom-up manner from the processing of the leaves of the tree. This acts as a tree transform from input (inherited attributes) to output (synthesized attributes).

4. Printing a nested list
In the following code, a return variable is used to get a tree to print and then the predicate prints1 (modified from prints) is used to print the tree.

The cut operator "!" is used to cut off backtracking in the prints1 predicate. Otherwise extraneous output would result. One should never use the cut operator unless one knows what one is doing.

5. Predicates for test data
One way to get data (e.g., for test) in a program is to use multiple treeList predicates and get each in turn (on backtracking).

Notice how the call by pattern matching is used to select which traverse case is to be used.

6. Revised code
Here is the Prolog code.

Here is the output of the Prolog code.


7. End of page