Prolog - Recursion and Structures

This chapter covers recursion and structures.


Recursion is a technique in which one predicate uses itself (may be with some other predicates) to find the truth value.

Let us understand this definition with the help of an example −

So this predicate is recursive in nature. Suppose we say that just_ate(deer, grass), it means is_digesting(deer, grass) is true. Now if we say is_digesting(tiger, grass), this will be true if is_digesting(tiger, grass) :- just_ate(tiger, deer), is_digesting(deer, grass), then the statement is_digesting(tiger, grass) is also true.

There may be some other examples also, so let us see one family example. So if we want to express the predecessor logic, that can be expressed using the following diagram −

Recursion Recursion1

So we can understand the predecessor relationship is recursive. We can express this relationship using the following syntax −


Structures are Data Objects that contain multiple components.

For example, the date can be viewed as a structure with three components — day, month and year. Then the date 9th April, 2020 can be written as: date(9, apr, 2020).

Note − Structure can in turn have another structure as a component in it.

So we can see views as tree structure and Prolog Functors.


Now let us see one example of structures in Prolog. We will define a structure of points, Segments and Triangle as structures.

To represent a point, a line segment and a triangle using structure in Prolog, we can consider following statements −

Note − Structures can be naturally pictured as trees. Prolog can be viewed as a language for processing trees.

Matching in Prolog

Matching is used to check whether two given terms are same (identical) or the variables in both terms can have the same objects after being instantiated. Let us see one example.

Suppose date structure is defined as date(D,M,2020) = date(D1,apr, Y1), this indicates that D = D1, M = feb and Y1 = 2020.

Following rules are to be used to check whether two terms S and T match −

Binary Trees

Following is the structure of binary tree using recursive structures −

Binary Trees

The definition of the structure is as follows −

node(2, node(1,nil,nil), node(6, node(4,node(3,nil,nil), node(5,nil,nil)), node(7,nil,nil))

Each node has three fields, data and two nodes. One node with no child (leaf node) structure is written as node(value, nil, nil), node with only one left child is written as node(value, left_node, nil), node with only one right child is written as node(value, nil; right_node), and node with both child has node(value, left_node, right_node).