Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Loops and Decision Making



In this chapter, we will discuss loops and decision making in Prolog.

Loops

Loop statements are used to execute the code block multiple times. In general, for, while, do-while are loop constructs in programming languages (like Java, C, C++).

Code block is executed multiple times using recursive predicate logic. There are no direct loops in some other languages, but we can simulate loops with few different techniques.

Program (loop.pl)

count_to_10(10) :- write(10),nl.count_to_10(X) :-   write(X),nl,   Y is X + 1,   count_to_10(Y).

Output

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

yes
| ?- count_to_10(3).
3
4
5
6
7
8
9
10

true ? 

(47 ms) yes
| ?- 

Now create a loop that takes lowest and highest values. So, we can use the between() to simulate loops.

Program (loop.pl)

Let us see an example program −

count_down(L, H) :-   between(L, H, Y),   Z is H - Y,   write(Z), nl.
count_up(L, H) :-   between(L, H, Y),   Z is L + Y,   write(Z), nl.

Output

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

yes
| ?- count_down(12,17).
5

true ? ;
4

true ? ;
3

true ? ;
2

true ? ;
1

true ? ;
0

(31 ms) yes
| ?- count_up(5,12).
10

true ? ;
11

true ? ;
12

true ? ;
13

true ? ;
14

true ? ;
15

true ? ;
16

true ? ;
17

(47 ms) yes
| ?- 

Decision Making

The decision statements are If-Then-Else statements. So when we try to match some condition, and perform some task, then we use the decision making statements. The basic usage is as follows >

If <condition> is true, Then <do this>, Else <do this>

In some different programming languages, there are If-Else statements, but in Prolog we have to define our statements in some other manner. Following is an example of decision making in Prolog.

Program (test.pl)

% If-Then-Else statementgt(X,Y) :- X >= Y,write('X is greater or equal').
gt(X,Y) :- X < Y,write('X is smaller').
% If-Elif-Else statementgte(X,Y) :- X > Y,write('X is greater').\
gte(X,Y) :- X =:= Y,write('X and Y are same').
gte(X,Y) :- X < Y,write('X is smaller').

Output

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

yes
| ?- gt(10,100).
X is smaller

yes
| ?- gt(150,100).

no
| ?- gte(10,20).
X is smaller

yes
| ?- gte(100,20).

no
| ?- gte(100,100).
X and Y are same

true ? 

yes
| ?- 
Advertisements