Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - More on Tree Data Structure



Here, we will see some more operations that will be performed on the above given tree data structure.

Let us consider the same tree here −

Node

We will define other operations −

  • path(Node)

  • locate(Node)

As we have created the last database, we will create a new program that will hold these operations, then consult the new file to use these operations on our pre-existing program.

So let us see what is the purpose of these operators −

  • path(Node) − This will display the path from the root node to the given node. To solve this, suppose X is parent of Node, then find path(X), then write X. When root node a is reached, it will stop.

  • locate(Node) − This will locate a node (Node) from the root of the tree. In this case, we will call the path(Node) and write the Node.

Program

Let us see the program in execution −

path(a).                             
/* Can start at a.*/path(Node) :- Mother is_parent Node, /* Choose parent, */ path(Mother), /* find path and then */write(Mother),write(' --> ').
/* Locate node by finding a path from root down to the node */locate(Node) :- path(Node), write(Node), nl.

Output

| ?- consult('D:/TP Prolog/Sample Codes/case_tree_more.pl').
compiling D:/TP Prolog/Sample Codes/case_tree_more.pl for byte code...
D:/TP Prolog/Sample Codes/case_tree_more.pl compiled, 2 lines read - 872 bytes written, 3 ms

yes
| ?- path(n).
a --> c --> h --> 

true ? 

no
| ?- path(n).
a --> c --> h --> 

true ? 

yes
| ?- path(s).
a --> d --> j --> 

true ? 

yes
| ?- path(w).

no
| ?- locate(n).
a --> c --> h --> n

true ? 

(16 ms) yes
| ?- locate(s).
a --> d --> j --> s

true ? 

yes
| ?- 
prolog_tree_data_structure.htm
Advertisements