Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Advanced Operations in Tree Data Structures



Now let us define some advanced operations on the same tree data structure.

Advances TDS

Here we will see how to find the height of a node, that is, the length of the longest path from that node, using the Prolog built-in predicate setof/3. This predicate takes (Template, Goal, Set). This binds Set to the list of all instances of Template satisfying the goal Goal.

We have already defined the tree before, so we will consult the current code to execute these set of operations without redefining the tree database again.

We will create some predicates as follows −

  • ht(Node,H). − This finds the height. It also checks whether a node is leaf or not, if so, then sets height H as 0, otherwise recursively finds the height of children of Node, and add 1 to them.

  • max([X|R], M,A). − This calculates the max element from the list, and a value M. So if M is maximum, then it returns M, otherwise, it returns the maximum element of list that is greater than M. To solve this, if given list is empty, return M as max element, otherwise check whether Head is greater than M or not, if so, then call max() using the tail part and the value X, otherwise call max() using tail and the value M.

  • height(N,H). − This uses the setof/3 predicate. This will find the set of results using the goal ht(N,Z) for the template Z and stores into the list type variable called Set. Now find the max of Set, and value 0, store the result into H.

Now let us see the program in execution −

Program (case_tree_adv.pl)

height(N,H) :- setof(Z,ht(N,Z),Set), max(Set,0,H).
ht(Node,0) :- leaf_node(Node),!.
ht(Node,H) :- Node is_parent Child, ht(Child,H1), H is H1 + 1.
max([],M,M).
max([X|R],M,A) :- (X > M -> max(R,X,A) ; max(R,M,A)).

Output

| ?- consult('D:/TP Prolog/Sample Codes/case_tree_adv.pl').
compiling D:/TP Prolog/Sample Codes/case_tree_adv.pl for byte code...
D:/TP Prolog/Sample Codes/case_tree_adv.pl compiled, 4 lines read - 2059 bytes written, 4 ms

(16 ms) yes
| ?- ht(c,H).

H = 1 ? a

H = 3

H = 3

H = 2

H = 2

(31 ms) yes
| ?- max([1,5,3,4,2],10,Max).

Max = 10

(16 ms) yes
| ?- max([1,5,3,40,2],10,Max).

Max = 40

yes
| ?- setof(H, ht(c,H),Set).

Set = [1,2,3]

yes
| ?- max([1,2,3],0,H).

H = 3

yes
| ?- height(c,H).

H = 3

yes
| ?- height(a,H).

H = 4

yes
| ?- 
prolog_tree_data_structure.htm
Advertisements