Lab Manual
Lab Manual
Lab # 1
Objectives:
Introduction to PROLOG.
How to get PROLOG
PROLOG installation and launching.
First PROLOG program
.
Theory:
Introduction.
Prolog was invented in the early seventies at the University of Marseille. Prolog stands for
PROgramming in LOGic. It is a logic language that is particularly used by programs that use non-
numeric objects. For this reason it is a frequently used language in Artificial Intelligence where
manipulation of symbols is a common task.
Prolog differs from the most common programming languages because it is declarative
language. Traditional programming languages are said to be procedural and the programmer
must specify the details of how to solve the problem. This means that the programmer specify
how to solve a problem. In declarative languages the programmers only specifies the goal to be
achieved and the Prolog system works out how to achieve it.
Prolog’s fast incremental development cycle and rapid prototyping capabilities have encouraged
to use of it as a tool for solving AI problems. Its feature include interface to other languages and
database products and more recently support for object oriented and constraint based
programming has also been introduced.
Constrains replace Prolog’s usual pattern matching mechanism with a more general operation
called constraint satisfaction. Constrains are powerful way to reduce the size of search space
and increase the efficiency of the scheduler.
Applications of Prolog.
● Intelligent data base retrieval.
● Natural language understating.
● Expert systems.
● Machine learning.
● Problem solving.
● Automated reasoning.
Relations in Prolog.
Prolog programs specify relationships among objects and properties of objects. When it is said
that “Ali has a Car”, an ownership relationship is being declared between two objects: Ali and
the Car, and when it is asked “Does Ali own a Car?” then we are trying to find out about the
relationship.
The Program.
The program, sometimes called Database is a text file (*.pl) that contain the facts and rules that
will be used by the user of the program. It contains all the relations that make this program.
Query Mode.
When you launch a program you are in query mode. This mode is represented by the sign ? - at
the beginning of the line. In query mode you ask questions about relations described in the
program.
Loading a program.
First you have to launch your Prolog compiler. When Prolog is launched the ?- should appear
meaning you are in query mode. The manner to launch a program depends of your compiler. We
can load a program by typing the command consult[filename]. When you have done this you can
use all the facts and rules that are contained in the program.
Official Website
This is the official GNU Prolog website where we can see all the necessary details about
GNU Prolog, and also get the download link.
http://www.gprolog.org/
Installation Guide
Download the exe file and run it.
Select proper directory where you want to install the software, otherwise let it be installed
on the default directory. Then click on next.
You can verify the below screen, and check/uncheck appropriate boxes, otherwise you
can leave it as default. Then click on next.
In the next step, you will see the below screen, then click on Install.
Page | 1
Artificial Intelligence & Expert Systems CT-361
Exercise:
1. Write the latest release of prolog?
4. Relationships can also depict rules. Give 2 examples (other than those specified in Lab-1).
Page | 2
Artificial Intelligence & Expert Systems CT-361
Lab # 2
Object:
Let’s learn more about Facts, Rules and Queries.
.
Theory:
Introduction.
In Prolog program facts are declared describing explicit relationships between objects and their
properties such as Sara likes ice-cream, Hair is black, NED is a university, Tom is a cat,
Shahzad teaches Harris.
Rules are declared defining implicit relationships between objects such as brother relationship
and/or rules define implicit object properties i.e. A is a child of B if B is parent of A.
The system can then be used to generate queries by asking questions about relationships and/or
about the object properties such as does Sara like ice-cream? , Asad is parent of whom?
Facts.
Facts are properties of objects or relationship between objects such as Zaheer has phone
number 12345678. It will be written in prolog as:
phoneno(zaheer, 12345678).
It should be noted that:
● Names of properties/relationships begin with lowercase letters.
● The relationship name appears as the first term.
● Objects appear as comma separated arguments inside parentheses.
● A period “.” must terminate the fact.
● Objects also begin with lower case letters. They can also begin with digits and can be strings
enclosed within quotes.
● phoneno(zaheer,12345678) is also called predicate or clause.
Example
Person X teaches course Y.
teaches (X, Y).
teaches (sana, crs01).
teaches (amir, crs02).
Together these facts will form Prolog’s database also called Knowledge Base.
Rules.
Consider the following case which produces a general rule:
Teacher will guide a student if that student is enrolled in the course which that teacher teaches.
Page | 3
Artificial Intelligence & Expert Systems CT-361
Facts are unit clauses whereas rules are non-unit clauses. Variable name will start with a capital
letter.
Syntax of a Clause.
:- means “if” or “is implied by”, also called neck symbol. The left hand side of the neck is
called the head and the right hand side is called the body. The comma stands for and also
called conjunction and semicolon stands for or also called disjunction.
Goal or Query.
Queries are based on facts and rules. Questions can be asked based on the stored information.
Queries are terminated by full stop. To answer a query Prolog consults its database to see if it
is a known fact or not.
If answer is Yes/True the query succeeded else if the answer is No/False then query failed.
A program of prolog consists of clauses, which are of three types: facts, rules and questions.
A procedure is a set of clauses about the same relation.
Example.
P:-Q:R. can be written as P:-Q. P:-R.
P:-Q,R;S,T,U. can be written as P:-(Q,R);(S,T,U). OR P:- Q,R. P:-S,T,U.
Page | 4
Artificial Intelligence & Expert Systems CT-361
Exercise:
1. What are the advantages and limitations of Prolog?
2. Enter the above program into Prolog and execute the queries shown below:
Facts & Rules
ring(Person, Number) :- location(Person, Place), phone_number(Place, Number).
location(Person, Place) :- at(Person, Place).
location(Person,Place) :- visiting(Person, Someone), location(Someone, Place).
phone_number(rm303g, 5767).
phone_number(rm303a, 5949).
at(dr_jones, rm303g).
at(dr_mike, rm303a).
visiting(dr_mike, dr_jones).
Queries.
?- location(dr_bottaci, Pl).
?- ring(dr_mike, Number).
?- ring(Person, 5767).
?- ring(Person, Number).
?- ring(dr_jones, 999).
Page | 5
Artificial Intelligence & Expert Systems CT-361
Lab # 3
Object:
Family relationship in Prolog.
.
Theory:
pam tom
Facts.
parent(pam,bob).
parent(tom,bob).
parent(bob,ann).
parent(bob,pat). bob
ann pat
The parent relation has been defined by stating the n-tuples of objects based on given info in
family tree. The user can easily query the Prolog system about relations defined in the program.
The arguments of relations can be concrete objects or constants such as pat and ann or general
objects such as X and Y. Objects of first kind are called atoms and second kind are called
variables and questions to the system consists of one or more goals.
Additional Facts.
male(pat).
male(tom).
male(bob).
female(pam).
female(ann).
Relationship.
Mother mother(X, Y) :- parent(X,Y), female(X).
Father father(X, Y) :- parent(X,Y), male(X).
Sister sister(X.Y) :- parent(Z,X), parent(Z,Y),female(X),X\==Y.
Brother brother(X.Y) :- parent(Z,X), parent(Z,Y),male(X),X\==Y.
Has child haschild(X) :- parent(X,_).
More Relationships
grandparent(X,Y) :- parent(X,Z),parent(Z,Y).
grandmother(X,Z) :- mother(X,Y),parent(Y,Z).
grandfather(X,Z) :- fatger(X,Y),parent(Y,Z).
wife(X,Y) :- parent(X,Z), parent(Y,Z),female(X),male(Y).
uncle(X,Z) :- brother(X,Y), parent(Y,Z).
Page | 6
Artificial Intelligence & Expert Systems CT-361
Exercise:
1. Write a prolog program to create a family tree by creating facts and rules based on the
information given below:
2. Write a prolog program to create an administration tree by creating facts and rules based
your imagination [Hint: Consider the administrative positions of different people around you].
Page | 7
Artificial Intelligence & Expert Systems CT-361
Lab # 4
Object:
Data Objects in Prolog.
.
Theory:
data objects
constants variables
numbers atoms
Examples:
Atoms.
Atoms can be constructed in three ways:
1. Strings of letters, digits and the underscore ‘_’ starting with a lower case. Such as azhar.
b59,b59_a etc.
2. Strings of special characters. Such as 🡨->, ===🡨, :: etc. when using atoms of this form
some care is to be taken as some special character already have predefined meaning. As :-
3. Strings of characters enclosed in single quotes. This is useful when an atom needs to start
with a capital letter. By enclosing it in quotes it gets distinguished from variable. Such as
‘Azhar’, ‘Prolog’
Numbers.
● Numbers can be Integers and Real.
● Integer numbers can be represented as 100 4 -87 1020
● The normal range of inter numbers is -16383 to 16383.
● The real number treatment depends on the implementation of Prolog. Examples of real
numbers are 3.141 -0.00062 450.18
● Real numbers are not very much in Prolog programming as it is primarily a language for
symbolic, non-numeric computation. In symbolic computation inters are often used.
Variables.
Variables are strings of letters, digits and underscore characters. They start with an upper case
letter or an underscore character. Such as X, Sum, Member_name, Student_list, _a50 etc.
In a clause when a variable is used only once then the variable name can be replaced by so
called anonymous variable which is written as a single underscore.
Page | 8
Artificial Intelligence & Expert Systems CT-361
Structures.
Structured data objects or structures are objects that can have multiple components. The
components can in turn be structures.
Example: the date can be viewed as structure with three components day, month and year. The
date 9th June 2018 can be written as date(9, june, 2018).
Structures can be naturally represented as trees. Prolog can be viewed as a language for
processing trees.
The root of the tree is called the functor and the sub-trees are called arguments. Each functor
is defined with two things: the name whose syntax is that of atom and the arity or the number
of arguments.
Page | 9
Artificial Intelligence & Expert Systems CT-361
Exercise:
Write program in prolog to implement all data types you have studied above
Page | 10
Artificial Intelligence & Expert Systems CT-361
Lab # 5
Object:
Unifications.
Theory:
Simples unifications.
How can we ask something like ''what does Fred eat?'' If we have the following program:
eats(fred,oranges).
How do we ask what fred eats ? We could write something like this :
?- eats(fred,what).
But Prolog will say no. The reason is that Prolog can't find the relation eats(fred,what) in its
database. In this case we have to use a variable which will be unified to match a relation given
in the program. This process is known as unification.
Variables are distinguished from atoms by starting with a capital letter. Here are some examples
of variables:
X /* a single capital letter*/
VaRiAbLe /* a word beginning with an upper case letter */
Two_words /* two words separated with an underscore */
Now that we know how to use a variable, we can ask the same question as before using the
variable what instead of an atom.
?- eats(fred,What)
What=oranges
Yes
In this case Prolog try to unified the variable with an atom. ''What=oranges'' means that the
query is successful when what is unified with oranges.
With the same program if we ask:
?- eats(Who,oranges).
In this example we ask who eats oranges. To this query Prolog should answer :
?- eats(Who,oranges).
Who=fred
yes
Now if we ask:
?- eats(Who,apple).
No
Prolog answer no because he can't find in his database any atom than can match with this
relation. Now if we only want to know if something is eated by anyone and we don't care about
that person we can use the underscore. The '_' can be used like any variable. For example if we
ask eats(fred,_) the result will be:
?- eats(fred,_).
Yes
Page | 11
Artificial Intelligence & Expert Systems CT-361
The result will be yes because Prolog can find a relation of eat between fred and something.
But Prolog will not tell use the value of '_'.
Now if we have the following program:
eats(fred,apple).
eats(fred,oranges).
Now if we ask:
?- eats(fred,What).
The first answer will be ''What=apple'' because that is the unification that match the first
relation of eats with fred in the database. Then prolog will be waiting for you to press a key. If
you press enter Prolog will be ready for a new query. In most implementation if you press the
key '';'' then Prolog will try to find if there is any other successful unification. Prolog will give
the second result ''What=orange'' because this the second one in the program. If you press again
the key '';'' then Prolog will try to find a third unification. The result will be ''no'' because he is
not able to find any other successful unification.
?- eats(fred,What).
What=apple;
What=oranges;
no
Now if we want to know if we have a book from the author2 we can ask:
?- book(_,_,author2).
yes
Page | 12
Artificial Intelligence & Expert Systems CT-361
Exercise:
1. Write a program to implement the following:
likes(fred,cola).
likes(fred,cheap_cigars).
likes(fred,monday_night_football).
likes(sue,jogging).
likes(sue,yogurt).
likes(sue,bicycling).
likes(sue,noam_chomsky).
likes(mary,jogging).
likes(mary,yogurt).
likes(mary,bicycling).
likes(mary,george_bush).
Queries:
?- likes(fred,cola).
?- likes(fred,X).
?- likes(fred,X).
?- likes(Y,jogging).
Page | 13
Artificial Intelligence & Expert Systems CT-361
Lab # 6
Object:
Input & Output Commands.
Theory:
At this time we have seen how we can communicate with prolog using the keyboard and the
screen. We will now see how we can communicate with prolog using files.
Prolog can read and write in a file. The file where Prolog read is called input and the file where
Prolog write is called output. When you run Prolog the default output is your screen (the shell)
and the input is your keyboard. If you want to use files for that you have to tell it to Prolog
using commands.
Examples.
Calculating the cube of an integer.
If we have the following program:
cube(C,N) :- C is N * N * N
If you ask something like cube(X,3) then Prolog would respond X=9. Suppose that we want to
ask for other values than 3, we could write this program like this:
cube :-
read(X), calc(X). /* read X then query calc(X). */
calc(stop) :- !. /* if X = stop then it ends */
calc(X) :- C is X * X * X, write(C),cube. /* calculate C and write it then ask again
cube. */
Now if we ask Prolog cube, Prolog will ask use a value and give us the result until we
write stop.
ASCII characters.
It is of course possible to use ASCII code in Prolog. For example if you type:
?- put(65), put(66), put(67).
Page | 14
Artificial Intelligence & Expert Systems CT-361
Tab.
The built-in predicate tab(N) causes N spaces to be output:
?- write(hi), tab(1), write(there),nl.
hi there
true.
Page | 15
Artificial Intelligence & Expert Systems CT-361
Exercise:
1. Write code in prolog to generate the following output:
5 plus 8 is 13.
X=13
3 multiply by 3 is 9.
X = 9.
Page | 16
Artificial Intelligence & Expert Systems CT-361
Lab # 7
Object:
Operators – Arithmetic and Comparison.
Theory:
For the arithmetic operators, prolog has already a list of predefined predicates. These are:
=, is, <, >, =<, >=, ==, =:=, /, *, +, -, mod, div
In Prolog, the calculations are not written like we have learned. They are written as a binary
tree. That is to say that:
y*5+10*x is written in Prolog as +(*(y,5),*(10,x)).
But Prolog accept our way of writing calculations. Nevertheless, we have to define the rules of
priority for the operators. For instance, we have to tell Prolog that * has higher priority than
+..Prolog allows the programmer to define his own operators with the relations next:
Op(P, xfy, name).
where P is the priority of the operators(between 1 and 1200), xfy indicates if the operator is
infix(xfx,xfy,yfx) or postfix(fx,fy).The name is, of course, the name of the operator. Note that
the prior operator has the lowest priority. Prolog has already these predefined operators:
Op(1200,xfx,':-').
Op(1200,fx,[:-,?-]).
Op(1100,xfy,';').
Op(1000,xfy,',').
Op(700,xfx,[=,is,<,>,=<,>=,==,=:=]).
Op(500,yfx,[+.-]).
Op(500,fx,[+,-,not]).
Op(400,yfx,[*,/,div]).
Op(300,xfx,mod).
Arithmetic Operators
Prolog use the infix operator 'is' to give the result of an arithmetic operation to a variable.
X is 3 + 4.
Prolog responds.
X=7
yes
When the goal operator 'is' is used the variables on the right must have been unified to numbers
before. Prolog is not oriented calculations, so, after a certain point, it approximates the
Page | 17
Artificial Intelligence & Expert Systems CT-361
Comparison Operators.
Comparison operators can be classified into Arithmetic and term comparison operators.
Page | 18
Artificial Intelligence & Expert Systems CT-361
Example:
?- 2>=1.
yes
?- 2>=3.
No
?- 3+4>=7.9.
no
?- 7.5>=7+0.5.
yes
Equals to (=:=).
Compares Arg1 to Arg2, succeeding if Arg1 and Arg2 are equal. Both the arguments must be
a number (integer or float) or arithmetic expression.
Arg1=:= Arg2
Example:
?- 1=:=1.
yes
?- 1=:=2.
no
Page | 19
Artificial Intelligence & Expert Systems CT-361
?- 2+3=:=5.
yes
?- 12=:=6*2.
yes
Exercise:
Write a program to compare ages by defining facts and rules from the information provided
below. Use appropriate operators where necessary.
Age of aslam is 11 years.
Age of asif is 13 years.
Age of afsheen is 17 years.
Age of manal is 16 years.
Age of amir is 30 years.
Age of falak is 33 years.
Age of sobia is 40 years.
Age of sheheryar is 44 years.
Age of rehan is 52 years.
Age of erum is 64 years
Page | 20
Artificial Intelligence & Expert Systems CT-361
Lab # 8
Object:
Lists in Prolog.
Theory:
The list is a simple data structure widely used in non-numeric programming. List consists of
any number of items. It can be represented in prolog as
[red, green, blue, white, dark]
A list can be either empty or non-empty. In first case the list is simply written as a Prolog
atom i.e. []. In second case the list can be viewed as consisting of two things:
The first item is called the head of the list and the remaining part of the list is called tail. The
tail itself has to be a list.
In the list [red, green, blue, white, dark], red is the head while rest of the elements are the tail.
List Membership.
To check whether an object X is member of list L or not.
list_member(X,L). where X is an object and L is a list.
Example
list_member(b, [a, b, c]) is true,
list_member(b, [a, [b, c]]) is not true,
list_member([b,c], [a,[ b, c]]) is true,
The program for the membership relation can be based on the following:
X is a member of L if either X is head of L or X is member of the tail of L.
list_member(X, [X | _ ]).
list_member(X, [_ | TAIL]) :- list_member(X,TAIL).
list_length([], 0).
Page | 21
Artificial Intelligence & Expert Systems CT-361
Exercise:
Write a program in Prolog and implement the member and length calculation clauses using
your own data. Also write down the output.
Page | 22
Artificial Intelligence & Expert Systems CT-361
Lab # 9
Object:
More Lists Operations
Theory:
Concatenation.
concatenation([], L,L).
concatenation([X1 | L1], L2, [X1 | L3] ):- concatenation(L1,L2,L3).
Operations in words.
interm(0,zero).
interm(1,one).
interm(2,two).
interm(3,three).
interm(4,four).
interm(5,five).
interm(6,six).
interm(7,seven).
interm(8,eight).
interm(9,nine).
inwords([], []).
inwords([X | TAIL], [T | Z]) :- interm(X,T), interm(TAIL, Z).
Delete an item.
There can be two cases; if X is the head of the list then result after deletion is tail and if X is
in the tail then it is deleted from there.
del(Y, [Y],[]).
del(X,[X | LIST1],LIST1).
del(X,[Y | LIST], [Y | LIST1]) :- del(X,LIST,LIST1).
Append.
list_member(X, [X | _ ]).
list_member(X, [_ | TAIL]) :- list_member(X,TAIL).
list_append(A,T,T) :-list_member(A,T), !
list_append(A,TAIL,[A |TAIL])..
Insert
list_insert(X,L,R) :- list_delete(X,R,L).
list_delete(X, [X|LIST1], LIST1).
list_delete(X, [Y|LIST], [Y|LIST1]) :- list_delete(X,LIST,LIST1)..
Reverse
list_reverse([], []).
list_reverse([First | Rest], Reversed) :- list_reverse(Rest, ReversedRest),
concatenation(ReservedRest, [First], Reserved).
concatenation([], L,L).
concatenation([X1 | L1], L2, [X1 | L3] ):- concatenation(L1,L2,L3).
Page | 23
Artificial Intelligence & Expert Systems CT-361
Exercise:
Write a program in Prolog and implement the operations learned in this lab using your own
data. Also write down the output.
Page | 24
Artificial Intelligence & Expert Systems CT-361
Lab # 10
Object:
Backtracking in Prolog.
Theory:
Backtracking is a process. When a sub-goal fails, the Prolog system traces its steps backwards
to the previous goal and tries to satisfy it.
This means that all variables that were bound to a value when that goal was satisfied are now
made free again. Then the Prolog system tries to satisfy that goal by matching with the next
clause starting at the clause just after the one that matched the sub-goal. This continues until
either the sub-goal is satisfied, or until the program database has been exhausted, at which point
Prolog backtracks yet again to the sub-goal that was before the current sub-goal.
Example.
person(alice).
person(mark).
likes(alice, coke).
likes(alice, sprite).
likes(alice, fanta).
likes(mark, pepsi).
likes(mark, coffee)
Name = alice.
Drink = coke.
Name = alice.
Drink = sprite.
Name = alice.
Drink = fanta.
Name = mark.
Drink = pepsi
Name = mark.
Drink = coffee.
Example.
Find maximum of two given numbers.
max(X, Y, Max).
where max = X if X >=Y and max = Y if X <Y.
Page | 25
Artificial Intelligence & Expert Systems CT-361
They are mutually exclusive i.e. only one can succeed. More feasible formulation of rules
using cut will be:
max(X, Y, Max)
where if X>-Y then Max = X
otherwise Max = Y.
In prolog:
max(X,Y,X) :- X >=Y, !.
max(X,Y,Y).
max_call(X,Y,Max) :- X>=Y, !, Max = X ; Max = Y.
Page | 26
Artificial Intelligence & Expert Systems CT-361
Exercise:
Write a program in Prolog to find if number is positive or negative using backtracking and cut.
Page | 27
Artificial Intelligence & Expert Systems CT-361
Lab # 11
Object:
Negation as failure in Prolog.
Theory:
The cut-fail combination seems to be offering us some form of negation. It is called Negation
as failure, and is defined as follows:
Second clause makes sure neg succeeds if Goal was not satisfied in the first clause (i.e. ! was
not triggered)
Example
Mary likes animals but snakes. Mary likes X if X is an animal but if X is a snake Mary likes X
will not be true. In prolog this will be written as:
animal(dog).
animal(cat).
animal(elephant).
snake(cobra).
snake(python).
animal(dog).
animal(cat).
animal(elephant).
snake(cobra).
snake(python).
Negation as failure is not logical negation. Changing the order of the goals in the program gives
a different behavior.
Page | 28
Artificial Intelligence & Expert Systems CT-361
Exercise:
Write a program in Prolog to implement Jack likes fruits but bananas use negation as failure
also.
Page | 29
Artificial Intelligence & Expert Systems CT-361
Lab # 12
Object:
Input and Output handling using a data file in Prolog.
Theory:
Many applications require that output be written to a file rather than to the screen. In order to
write to a file create one (or open an existing one) and associate a stream with it. Streams can
be thought of connections to files.
Write to File.
In order to print the string ’Hogwarts’ to the file hogwarts.txt:
open(’hogwarts.txt’, write, Stream),
write(Stream, ’Hogwarts’), nl (Stream),
close(Stream).
First the built-in predicate open is used to create the file hogwarts.txt. The second argument of
open indicates that we want to open a new file (overwriting any existing file with the same
name). The third argument of open returns the name of the stream.
Second, ’Hogwarts’ is written on the stream and issue a newline command as well. After this
close the stream, using the built-in close.
In order to avoid overwriting an existing file but append to an existing one choose a different
mode when opening the file: instead of write, use append as value for the second argument of
open. If a file of the given name doesn’t exist, it will be created.
First the built-in predicate open is used to open the file hogwarts.txt. The second argument of
open indicates that we want to open any existing file and read data from it. The third argument
of open returns the name of the stream.
Second, get_char(Stream,Char1) reads a character as a one character atom and also returns end
of file when the end of file is reached. After this close the stream, using the built-in close.
Example.
write_file:-
open('hogwarts.txt', write, Stream),
write(Stream, 'Hogwarts.'), nl(Stream),
close(Stream).
read_from_file:-
open('hogwarts.txt', read, Stream),
get_char(Stream,Char1),
process_the_stream(Char1,Stream),
close(Stream).
Page | 30
Artificial Intelligence & Expert Systems CT-361
process_the_stream(end_of_file, _):- !.
process_the_stream(Char,Stream):-
write(Char),
get_char(Stream,Char2),
process_the_stream(Char2,Stream).
Page | 31
Artificial Intelligence & Expert Systems CT-361
Exercise:
Write a program in Prolog to create a data file named sample.txt and write the names of
countries entered by user in that file and then read them also.
Page | 32
Artificial Intelligence & Expert Systems CT-361
Lab # 13
Object:
Implementation of Bubble Sort in Prolog.
Theory:
The bubble sort algorithm operates supposedly as reminiscent of bubbles floating up in a glass
of spa rood. This algorithm works as follows:
Go through the list from left to right until you find a pair of consecutive elements that are
ordered the wrong way round. Swap them. Repeat the above until you can go through the full
list without encountering such a pair. Then the list is sorted
The procedure will take a list as input in first argument and then sort that list using bubble sort
algorithm and produce the output as the second argument.
bubblesort(SortList, SortList).
printlist( [ ] ) :- !.
Page | 33
Artificial Intelligence & Expert Systems CT-361
Exercise:
Write a program in Prolog to implement insertion sort.
Page | 34
Artificial Intelligence & Expert Systems CT-361
Lab # 14
Object:
A relational database in Prolog
Theory:
Basically, PROLOG programs are about defining relation among objects in a domain. As
storing data as instances of relations is the essential feature, PROLOG is very good in
performing this sort of operations on data, which many normally associate with a relational
database management system.
For example, consider salary (scale, amount) which is the sort of relation defined in a relational
data model. Scale and amount are referred to as attributes, whereas specific instances of this
relation are called tuples.
A relational database contains tuples defined according to the data model. Retrieving data
stored in the database according to particular constraints on the attributes is called querying the
database.
The database (PROLOG database in this case) includes the following tuples (facts),
salary (1,1000). salary (2,1500). salary (3,2000). salary (4,2500). salary (5,3000). salary
(6,3500). salary (7,4000). salary (8,4500). salary (9,5000).
Relational database offers a number of useful operations which can be carried out to extract
information from a given database. The result of these operations is a new relation, i.e. a new
set of tuples. Typical examples of such database operations are selection, projection and the
join. Below are simple PROLOG implementations of the selection, projection and join.
The purpose of a selection is to request tuples which fulfil certain conditions with respect to
their attribute values. Consider, for example, the query:
‘select all employees from department 1 with a salary higher than scale 2.'
Expressed as a PROLOG query, the purpose is to select tuples satisfying the following
condition:
?- employee(Name,Department_N,Scale), Department_N = 1,Scale > 2.
Page | 35
Artificial Intelligence & Expert Systems CT-361
By entering the ';' operator is it again possible to find out whether there are any alternative
solutions, as PROLOG will then backtrack, and will check whether there are any other
employees satisfying the conditions. Note that, in fact, a functionally complete implementation
of the selection operator has not yet been produced, as only a single tuple is selected from the
database. Recall the trick considered before, where the fail predicate was used in order to
enforce backtracking. Here this trick is used again. This gives the following implementation
of the selection operator:
selection (X,Y) call(X), call(Y), write(X), nl, fail. selection (_,_).
The predicate call generates a sub goal determined by the binding of its variable argument. It
is assumed that the first argument of selection represents the relation from which tuples are to
be selected; the second argument contains the set of selection conditions which should be
satisfied by the selected tuples. For example, all employees in department 1 with a salary scale
higher than 2 are selected by the following query:
?- selection (employee (Name, Department_N, Scale), (Departments_N = 1,Scale > 2)) .
The projection operator in relational database theory is used to select some attributes (or
columns in the corresponding tables) from a relation. For example, the query ‘give for all
Employees only the name and scale', in SQL-like notation:
SELECT name,scale FROM employee.
However, the PROLOG query does again give rise to the selection of a single tuple:
?- employee(Name,_,Scale).
But, as already known, by using the ';' operator the other tuples can be selected as well.
As seen, the resulting PROLOG implementation of the projection operator is quite similar to
the implementation of the selection operator discussed above.
Projection (X,Y) call(X), write(Y), nl, fail. projection (_,_).
The first argument of projection should be the relation that is being projected; the second
argument lists the attributes on which the relationship must be projected. For example, name
and scale of employees are obtained as follows:
?- projection(employee(Name, Department_N, Scale), (Name, Scale)).
Note that this is still not a complete implementation of the projection, as the resulting relation
may not include doubles. As incorporating this in the program as well would make it quite
a bit more complicated, hardly worth the effort for small databases.
It is now quite straightforward to combine selection and projection. This would imply not only
specifying the attributes used in projecting a relation, but also giving the conditions on the
attributes which need to be satisfied by the selected tuples.
Consider, for example, the following query ‘Print the name and scale of those employees in
department 1, with a salary higher than scale 2'. In SQL-like notation:
Page | 36
Artificial Intelligence & Expert Systems CT-361
The final database operation which to be considered is the join. The join simply merges tuples
in relations based on a join condition. Suppose that one would like to obtain a list of employees,
with for every employee the salary included. For this purpose, we need information from two
different relations: employee and salary. For every employee we need to find the salary
corresponding to the salary scale. Hence, the join condition in this case is equality of tuples in
the two relations concerning the attribute scale. In SQL-like notation:
JOIN employee WITH salary WHERE employee.scale = salary.scale
The first and second arguments represent relations; the third argument is used to specify join
conditions. For example:
?- join(employee(Name,Department_N,Scale1), salary(Scale2,Amount), (Scale1 =
Scale2)).
Page | 37
Artificial Intelligence & Expert Systems CT-361
Exercise:
Write a program in Prolog to implement relational database and execute all queries.
Page | 38