Prolog Tutorial¶
Prolog, as the name itself suggests, is the short form of LOGical PROgramming. It is a logical and declarative programming language. Before diving deep into the concepts of Prolog, let us first understand what exactly logical programming is.
Logic Programming¶
Logic Programming is one of the computer programming paradigms in which program statements express facts and rules about different problems within a system of formal logic.
Rules are written in the form of logical clauses, where a head and a body
are present. For example, if H is the head and B1, B2, B3 are the
elements of the body, then the rule states that H is true when B1,
B2, and B3 are all true.
Facts are similar to rules but do not have a body.
What Is Prolog?¶
Prolog (PROgramming in LOGics) is a logical and declarative programming language. It is a major example of a fourth-generation language that supports the declarative programming paradigm.
Prolog is particularly suitable for programs involving symbolic or non-numeric computation. For this reason, it is widely used in Artificial Intelligence, where symbol manipulation and inference are fundamental tasks.
Installing Prolog¶
To install Prolog on a Debian-based system:
sudo apt update
sudo apt install gprolog
To start Prolog:
gprolog
Begin by practicing a basic Hello World program directly in the terminal:
write('Hello World').
Note
Use single quotes, not double quotes, and end each command with a period.
Important
The command halt. exits the Prolog environment.
Creating Prolog Files¶
File Naming Convention¶
file_name.pl
Each file should begin with:
:- initialization(main).
Write your code below this line.
To compile and load the file:
consult('file_name.pl').
Theory¶
Knowledge Base¶
The knowledge base is one of the fundamental parts of logic programming. It stores facts and rules that describe relationships and properties within a problem domain.
Facts, Rules, and Queries¶
Facts, rules, and queries are the building blocks of logic programming.
Facts¶
Facts define explicit relationships between objects and properties. Facts are unconditionally true.
Examples:
Tom is a cat
Kunal loves to eat pasta
Hair is black
Nawaz loves to play games
Pratyusha is lazy
Syntax:
relation(object1, object2, ...).
Example:
cat(tom).
loves_to_eat(kunal, pasta).
of_color(hair, black).
loves_to_play_games(nawaz).
lazy(pratyusha).
Rules¶
Rules define implicit relationships between objects. They are conditionally true: if the conditions on the right-hand side (Body) are true, then the left-hand side (Head) is also true.
Examples:
Lili is happy if she dances
Tom is hungry if he searches for food
Jack and Bili are friends if both love cricket
He will go to play if school is closed and he is free
Syntax notes:
:-is read as if or is implied byLeft-hand side is the Head
Right-hand side is the Body
Comma (,) represents conjunction
Semicolon (;) represents disjunction
rule_name(object1, object2, ...) :-
fact_or_rule(object1, object2, ...).
Queries¶
Queries ask questions about relationships or properties.
Examples:
Is Tom a cat?
Does Kunal love to eat pasta?
Is Lili happy?
Will Ryan go to play?
Prolog evaluates queries and returns answers based on the knowledge base.
Program Examples¶
Consider a knowledge base where Priya, Tiyasha, and Jaya are girls, and Priya can cook.
girl(priya).
girl(tiyasha).
girl(jaya).
can_cook(priya).
Note
Names must be lowercase. Identifiers beginning with uppercase letters are treated as variables in Prolog.
Example queries:
Is Priya a girl? → Yes
Is Jamini a girl? → No
Can Priya cook? → Yes
Can Jaya cook? → No
Another example using rules:
sing_a_song(ananya). %fact
listens_to_music(rohit). %fact
listens_to_music(ananya) :- sing_a_song(ananya). %rule
happy(ananya) :- sing_a_song(ananya). %rule
happy(rohit) :- listens_to_music(rohit). %rule
playes_guitar(rohit) :- listens_to_music(rohit). %rule
Interpretation:
Ananya sings → she listens to music
Rohit listens to music → he is happy
Queries resolve automatically based on defined rules
Knowledge Base with Variables¶
Variables begin with uppercase letters. When querying, Prolog returns results
one at a time. Press ; to see the next result.
Code¶
can_cook(priya).
can_cook(jaya).
can_cook(tiyasha).
likes(priya,jaya) :- can_cook(jaya).
likes(priya,tiyasha) :- can_cook(tiyasha).
Command-Line Output¶
| ?- consult('D:/TP Prolog/Sample Codes/kb3.pl').
| ?- can_cook(X).
X = priya ? ;
X = jaya ? ;
X = tiyasha.
| ?- likes(priya, X).
X = jaya ? ;
X = tiyasha.
Relations in Prolog¶
Prolog expresses relationships between objects and their properties.
For example, the statement Amit has a bike expresses ownership. A query such as Does Amit own a bike? searches for that relationship.
Relationships may be explicitly stated as facts or inferred through rules.
Example: defining a brother relationship.
Conditions:
Both are male
They share a parent
parent(sudip, piyush).
parent(sudip, raj).
male(piyush).
male(raj).
brother(X, Y) :-
parent(Z, X),
parent(Z, Y),
male(X),
male(Y),
X \= Y.
Family Tree Example¶
Code¶
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):- parent(X,Y),male(X).
haschild(X):- parent(X,_).
sister(X,Y):- parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
Command-Line Output¶
| ?- parent(X, jim).
X = pat ? ;
X = peter.
| ?- mother(X, Y).
X = pam,
Y = bob ? ;
X = pat,
Y = jim ? ;
Data Objects¶
![digraph data_objects {
rankdir=TB;
node [shape=box];
"Data Objects" -> "Simple Objects";
"Data Objects" -> "Structures";
"Simple Objects" -> "Constants";
"Simple Objects" -> "Variables";
"Constants" -> "Atoms";
"Constants" -> "Numbers";
}](../../../_images/graphviz-c0d4d3d0eb0b4dd6c529339ee5119cca7d3d27a0.png)
Atoms and Variables¶
Atoms¶
Atoms are constants representing names or objects.
Rules for atoms:
Begin with a lowercase letter
May include letters, digits, and underscores
Examples:
azaharb59b_59ABantara_sarkar
Numbers¶
Numbers are another form of constants. Examples:
1004-81
Typical integer range: -16383 to 16383
Variables¶
Variables begin with an uppercase letter or underscore.
Examples:
XSumStudent_List_Temp
Loops and Decision Making¶
Loops¶
Prolog does not use traditional loop constructs like for or while.
Instead, repetition is achieved using recursion and predicates.
Example loop using recursion:
count_to_10(10) :- write(10),nl.count_to_10(X) :- write(X),nl, Y is X + 1, count_to_10(Y).
Output¶
| ?- count_to_10(3).
3
4
5
6
7
8
9
10
true ?
(47 ms) yes
| ?-
Loops Using between/3¶
The between/3 predicate can simulate looping with a range.
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¶
Decision-making statements are commonly expressed as If–Then–Else logic. When a condition is matched and a task must be performed based on that condition, decision-making constructs are used.
The general idea is:
If <condition> is true, Then <do this>, Else <do this>
In many programming languages, this logic is implemented using explicit if-else statements. In Prolog, however, decision-making is achieved using rules and predicates, rather than traditional control-flow structures.
The following example demonstrates decision-making in Prolog.
If Else Code¶
% If-Then-Else statement
gt(X, Y) :- X >= Y, write('X is greater or equal').
gt(X, Y) :- X < Y, write('X is smaller').
% If-Elif-Else statement
gte(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
| ?-
Conjunction¶
Conjunction represents logical AND. In Prolog, conjunction is implemented using the comma (,) operator. When two predicates are separated by a comma, both predicates must succeed for the rule to be true.
For example:
parent(jhon, bob)means Jhon is the parent of Bobmale(jhon)means Jhon is male
Using conjunction, we can define a new predicate father(jhon, bob), which is true only when Jhon is both a parent and male.
Disjunction¶
Disjunction represents logical OR. In Prolog, disjunction is implemented using the semicolon (;) operator. When predicates are separated by a semicolon, the rule succeeds if either predicate is true.
For example:
father(jhon, bob)means Jhon is Bob’s fathermother(lili, bob)means Lili is Bob’s mother
A predicate child_of(X, Y) can be defined so that it succeeds when either the father or mother relationship exists.
Program: Disjunction¶
% If-Then-Else statement
gt(X, Y) :- X >= Y, write('X is greater or equal').
gt(X, Y) :- X < Y, write('X is smaller').
% If-Elif-Else statement
gte(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/conj_disj.pl').
compiling D:/TP Prolog/Sample Codes/conj_disj.pl for byte code...
D:/TP Prolog/Sample Codes/conj_disj.pl compiled, 10 lines read - 1513 bytes written, 3 ms
(16 ms) yes
| ?- father(jhon, bob).
yes
| ?- child_of(jhon, bob).
true ? yes
| ?- child_of(lili, bob).
yes
| ?-