You are on page 1of 45

PROLOG

Logic in Computer science


LAB SECTION
CHAPTER 4 - LOGIC PROGRAMMING

Logic is the systematic study of valid rules of inference, i.e., the relations that
lead to the acceptance of one proposition (the conclusion) on the basis of a set of
other propositions (premises). More broadly, logic is the analysis and appraisal of
arguments.
PPROLOG
• Prolog is a logical and a declarative programming language.
• The name itself, Prolog, is short for PROgramming in LOGic.
• Prolog is the major example of a fourth-generation programming language supporting the
declarative programming paradigm.
PROLOG

• This is particularly suitable for programs that involve symbolic or non-numeric


computation.

• Conventionally PROLOG is the suitable language to program a logic, but there is


also another logic programming language including ASP, Janus, Datalog, etc.

• Prolog program is saved as .pl extension.


PROCEDULAR Vs DECLARATIVE LANGUAGES

Procedural languages - is also often referred to as imperative language and it


outlines a specific set of steps that must be taken in order to arrive at the
desired outcome. The language uses a series of functions, variable and conditional
statements to describe what should be done. Essentially, the developer is
providing the device with the logical steps needed to complete a task. Typically,
this is the first language programmers learn, making it the more traditional
option.

Examples of programming languages which support the procedural paradigm


includes C, PHP and all major languages in some sense.
PROCEDULAR Vs DECLARATIVE LANGUAGES

Declarative languages - tells the program what needs to be done and allows the
program to figure out the necessary steps. The focus is on the outcome instead
of how to get there. This helps to create a more flexible program that can be
used in different contexts. As long as the final outcome is clearly specified, the
steps to get there will be automatically generated. By operating at a higher level
of abstract thinking, there is plenty of room for optimization, which has helped to
make this language the new paradigm.

Examples of programming languages which support the declarative paradigm


includes SQL, Prolog, Datalog, ASP and etc.
PROLOG - BASICS

Facts, Rules and Queries − are the building blocks of logic programming.

1. FACTS

We can define fact as an explicit relationship between objects, and properties


these objects might have. So, facts are unconditionally true in nature. Consider
the following statements.

 Tom is a cat. > Man is mortal.

 Kunal loves to eat Pasta. > Hair is black.

> Nawaz loves to play games. > Khalid is lazy.


PROLOG - BASICS

Following are some guidelines to write facts −

 Names of properties/relationships begin with lower case letters.

 The relationship name appears as the first term.

 Objects appear as comma-separated arguments within parentheses.

 A period "." must end a fact.

 Objects also begin with lower case letters. They also can begin with digits (like
1234), and can be strings of characters enclosed in quotes e.g., color (penink,
‘red’). phoneno (agnibha, 1122334455). is also called a predicate or clause.
PROLOG - BASICS

Syntax – facts
relation (object1, object2...).

Example – The following are the example of the above concept.

 cat(tom).
 loves_to_eat(kunal,pasta).
 of_color(hair,black).
 loves_to_play_games(nawaz).
 lazy(khalid).
PROLOG - BASICS

2. RULES

We can define rule as an implicit relationship between objects. So, facts are
conditionally true. So, when one associated condition is true, then the predicate is
also true. Suppose we have some rules as given below −

 Lili is happy if she dances.

 Tom is hungry if he is searching for food.

 Jack and Bili are friends if both of them love to play cricket.

 will go to play if school is closed, and he is free.


PROLOG - BASICS

1. HORN CLAUSES

Prolog program is simply based on predicate logic known as Horn clause. In prolog,
we compose the program using facts and rules and we pose a query-on-query
prompt about the facts and rules we inserted.

Horn Clause: Horn clause consists of head (left hand side) and body (right hand
side). Head can have 0 or 1 predicate and body can have list of predicates. That
means LHS has only single literal and RHS can have more than one literal.
PROLOG - BASICS

1. HORN CLAUSES

Prolog program is simply based on predicate logic known as Horn clause. In prolog,
we compose the program using facts and rules and we pose a query-on-query
prompt about the facts and rules we inserted.

Horn Clause: Horn clause consists of head (left hand side) and body (right hand
side). Head can have 0 or 1 predicate and body can have list of predicates. That
means LHS has only single literal and RHS can have more than one literal.
PROLOG - BASICS

1. HORN CLAUSES – written as

h :- b     ( where b is p1, p2, p3, .., pn and ' :- ' operator is read as 'if')
Read as :-  h is true if b is true. In other words, h is true if all the predicates on
right side are true.

Headless Horn Clauses : Son(john) //Read as : john is son


          son(john, mary).         // Read as : john is son of mary

Headed Horn Clauses:

boy(john) :- son(john, mary).   // Read as : john is a boy if he is son of mary 


PROLOG – BASICS

Syntax – Rules

Rule_name (object1, object2, ...) :-fact/rule(object1, object2, ...)

Examples:-
•happy(lili) :- dances(lili).
•hungry(tom) :- search_for_food(tom).
•friends(jack, bili) :- lovesCricket(jack), lovesCricket(bili).
•goToPlay(ryan) :- isClosed(school), free(ryan).
PROLOG - BASICS

1. RELATIONS

Relationship is one of the main features that we have to properly mention in


Prolog. These relationships can be expressed as facts and rules. In Prolog
programs, it specifies relationship between objects and properties of the objects.

Consider the fact, Chala loves hawi. This fact will be written as ‘loves(chala, hawi).’
in prolog. In this prolog fact, the word ‘loves’ is a relation.

Examples - Chala can drives a car. ----- can_drives (chala, car).


PROLOG - BASICS

1. Comment in Prolog

Single-line or Multi-line comments begin with /* and end with */  , but cannot be


nested.  % is also used only for single line comment, but it should be at the
starting of the line.

3. QUERIES

Queries are some questions on the relationships between objects and object
properties. So, question can be anything, as given below −
PROLOG - BASICS

Examples

 Is tom a cat?

 Does Kunal love to eat pasta?

 Is Lili happy?

 Will Ryan go to play?

So according to these queries, Logic programming language can find the answer
and return them.
PROLOG – KNOWLEDGE BASE

Knowledge base is a collection of facts and rules.

Example:- KB1
loves(chala, hawi).
loves(bonsa, gelane).
loves(bonsa, hawi).
loves(hawi, bonsa).
dates(chala, hawi) :- loves(chala, hawi) , loves(hawi, chala).
dates(hawi, bonsa) :- loves(bonsa, hawi), NOT(loves(bonsa, gelane)).
fight(hawi, gelane) :- loves(hawi, bonsa) , loves(gelane, bonsa).
The above statements are knowledge base, they’re a collection of facts and rules.
PROLOG OPERATORS

1. Comparison Operations

Operator Meaning Compute the following queries


X>Y X is greater than Y
 1+2=:=2+1.
X<Y X is less than Y
 1+A=B+2.
X >= Y X is greater than or equal to Y
 5<10.
X =< Y X is less than or equal to Y  10=\=100.
X =:= Y the X and Y values are equal

X =\= Y the X and Y values are not equal Activity:


1+2=2+1. and 1+2=:=2+1. returns different
output. Why?
PROLOG OPERATORS

2. Arithmetic Operation Example


calc :- X is 100 + 200,write('100 + 200 is '),write(X),nl,
Y is 400 - 150,write('400 - 150 is '),write(Y),nl,
Operator Meaning
Z is 10 * 300,write('10 * 300 is '),write(Z),nl,
+ Addition

- Subtraction
A is 100 / 30,write('100 / 30 is '),write(A),nl,

* Multiplication B is 100 // 30,write('100 // 30 is '),write(B),nl,


/ Division C is 100 ** 2,write('100 ** 2 is '),write(C),nl,
** Power D is 100 mod 30,write('100 mod 30 is '),write(D),nl.
// Integer division
Hint: To run use the query ‘calc.’
mod Modulus
• Then compute the following queries-
 X is 10**2, 100 =:=X.
 X is 100//3, Y is 100/3, X =< Y.
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) Now Compute the ff queries
 count_to_10(3).
count_to_10(10):- write(10),nl.  count_to_10(8).
count_to_10(X) :- write(X),nl,
Y is X + 1,count_to_10(Y).  count_to_10(0).
PROLOG – DECISION MAKING

The decision statements are If-Then-Else statements. So, when we try to match
some condition, and perform some tasks, then we use the decision-making
statements. If <condition> is true, Then <do this>, Else

% 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').
PROLOG – DECISION MAKING

Save the above program as decision.pl, and compute the following queries.

1. gt(10,100).
2. gt(150,100).
3. gte(10,20).
4. gte(100,20).
5. gte(100,100).
PROLOG – CONJUNCTION AND DISJUNCTION

• Conjunction
Conjunction (AND logic) can be implemented using the comma (,) operator. So two
predicates separated by comma are joined with AND statement. Suppose we have
a predicate, parent(jhon, bob), which means “Jhon is parent of Bob”, and another
predicate, male(jhon), which means “Jhon is male”. So we can make another
predicate that father(jhon,bob), which means “Jhon is father of Bob”. We can
define predicate father, when he is parent AND he is male.
PROLOG – CONJUNCTION AND DISJUNCTION

• Disjunction
Disjunction (OR logic) can be implemented using the semi-colon (;) operator. So
two predicates separated by semi-colon are joined with OR statement. Suppose
we have a predicate, father(jhon, bob). This tells that “Jhon is father of Bob”,
and another predicate, mother(lili,bob), this tells that “lili is mother of bob”. If
we create another predicate as child(), this will be true when father(jhon, bob) is
true OR mother(lili,bob) is true.
PROLOG – CONJUNCTION AND DISJUNCTION

• Program(logic.pl)
parent(jhon,bob).
parent(lili,bob). • Now compute this queries
male(jhon).
female(lili).  father(jhon,bob).
 child_of(jhon,bob).
% Conjunction Logic  child_of(lili,bob).
father(X,Y) :- parent(X,Y),male(X).  mother(john,lili).
mother(X,Y) :- parent(X,Y),female(X).

% Disjunction Logic
child_of(X,Y) :- father(X,Y);mother(X,Y).
PROLOG LISTS
PROLOG – LISTS

List is a data structure that can be used in different cases for non-numeric programming.
Lists are used to store the atoms as a collection.

• Presentation of Lists

The list is a simple data structure that is widely used in non-numeric programming. List
consists of any number of items, for example, red, green, blue, white, dark. It will be
represented as, [red, green, blue, white, dark]. The list of elements will be enclosed with
square brackets.
PROLOG – LISTS

A list can be either empty or non-empty. In the first case, the list is simply written as a
Prolog atom, []. In the second case, the list consists of two things as given below −
 The first item, called the head of the list;
 The remaining part of the list, called the tail.
Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail is
[green, blue, white, dark]. So, the tail is another list.
Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also
write the list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts.
PROLOG – LISTS

So, the following list representations are also valid −


 [a, b, c] = [x | [b, c]]
 [a, b, c] = [a, b | [c]]
 [a, b, c] = [a, b, c | [ ]]
For these properties we can define the list as −
A data structure that is either empty or consists of two parts − a head and a tail. The tail
itself has to be a list.
PROLOG – LISTS

• Basic Operation On List

Operations Definitions

Membership Checking During this operation, we can verify whether a given element is member of specified list or
not?
Length Calculation With this operation, we can find the length of a list.

Concatenation Concatenation is an operation which is used to join/add two lists.

Delete Items This operation removes the specified element from a list.

Append Items Append operation adds one list into another (as an item).

Insert Items This operation inserts a given item into a list.


PROLOG – LISTS

1. Membership Operation
During this operation, we can check whether a member X is present in list L or not? So how
to check this? Well, we have to define one predicate to do so. Suppose the predicate name
is list_member(X,L). The goal of this predicate is to check whether X is present in L or
not.

To design this predicate, we can follow these observations. X is a member of L if either −

 X is head of L, or

 X is a member of the tail of L


PROLOG – Membership Operation

Program: -
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).

Save the above program as list_member.pl, and compute the following queries.

• list_member(b,[a,b,c]).
• list_member(b,[a,[b,c]]). Try, list_member(X,[a,b,c,d]).
• list_member([b,c],[a,[b,c]]).
• list_member(d,[a,b,c]).
PROLOG – LISTS

2. Length Calculation
This is used to find the length of list L. We will define one predicate to do this task.
Suppose the predicate name is list_length(L,N). This takes L and N as input argument. This
will count the elements in a list L and instantiate N to their number. As was the case with
our previous relations involving lists, it is useful to consider two cases −

 If list is empty, then length is 0.

 If the list is not empty, then L = [Head|Tail], then its length is 1 + length of Tail.
PROLOG – Length Calculation

Program: -
list_length([],0).
list_length([_|TAIL],N) :- list_length(TAIL,N1), N is N1 + 1.

Save the above program as list_length.pl, consult and compute the following queries.

• list_length([a,b,c,d,e,f,g,h,i,j],Len).
• list_length([],Len).
• list_length([[a,b],[c,d],[e,f]],Len).
PROLOG – LISTS

3. Concatenation
Concatenation of two lists means adding the list items of the second list after the first
one. So if two lists are [a,b,c] and [1,2], then the final list will be [a,b,c,1,2]. So to do this
task we will create one predicate called list_concat(), that will take first list L1, second list
L2, and the L3 as resultant list. There are two observations here.

 If the first list is empty, and second list is L, then the resultant list will be L.

 If the first list is not empty, then write this as [Head|Tail], concatenate Tail with L2
recursively, and store into new list in the form, [Head|New List].

 its length is 1 + length of Tail.


PROLOG – Concatenation

Program: -
list_concat([],L,L).
list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3).

Save the above program as list_concat.pl, and compute the following queries.
• list_concat([1,2],[a,b,c],NewList).
• list_concat([],[a,b,c],NewList).
• list_concat([[1,2,3],[p,q,r]],[a,b,c],NewList).
PROLOG – LISTS

3. Delete From List


Suppose we have a list L and an element X, we have to delete X from L. So, there are three cases
•If X is the only element, then after deleting it, it will return empty list.
 its length is 1 + length of Tail.
•If X is head of L, the resultant list will be the Tail part.
•If X is present in the Tail part, then delete from there recursively.
Save the above program as list_delete.pl,
and compute the following queries.
Program: -
list_delete(X, [X], []). • list_delete(a,[a,e,i,o,u],NewList).
• list_delete(a,[a],NewList).
list_delete(X,[X|L1], L1). • list_delete(X,[a,e,i,o,u],[a,e,o,u]).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).
PROLOG – LISTS

4. Append into List


Appending two lists means adding two lists together, or adding one list as an item. Now if the item
is present in the
 its length is 1list, thenofthe
+ length Tail.append function will not work. So we will create one predicate
namely, list_append(L1, L2, L3). The following are some observations −

 Let A is an element, L1 is a list, the output will be L1 also, when L1 has A already.

 Otherwise, new list will be L2 = [A|L1].


Save the above program as list_append.pl, and
Program: - compute the following queries.
list_member(X,[X|_]). • list_append(a,[e,i,o,u],NewList).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
• list_append(e,[e,i,o,u],NewList).
list_append(A,T,T) :- list_member(A,T),!.
list_append(A,T,[A|T]). • list_append([a,b],[e,i,o,u],NewList).
PROLOG – LISTS

4. Insert into List


This method is used to insert an item X into list L, and the resultant list will be R. So the
predicate will be in this form list_insert(X, L, R). So this can insert X into L in all possible
 its length is 1 + length of Tail.
positions. If we see closer, then there are some observations.

 If we perform list_insert(X,L,R), we can use list_delete(X,R,L), so delete X from R and make


new list L.

Program: - Save the above program as list_insert.pl, and


list_delete(X, [X], []). compute the following queries.
list_delete(X,[X|L1], L1).
list_delete(X, [Y|L2], [Y|L1]) :- list_delete(X,L2,L1).
• list_insert(a,[e,i,o,u],NewList).
list_insert(X,L,R) :- list_delete(X,R,L). • list_insert([a,x],[e,i,o,u],NewList).
PROLOG – INPUTS AND OUTPUTS

So far, we have seen that we can write a program and the query on the console to execute.
In some cases, we print something on the console, that are written in our prolog code. So
here we will see that writing and reading tasks in more detail using prolog. So, this will be
the input and output handling techniques.

1. The write() Predicate

To write the output we can use the write() predicate. This predicate takes the parameter
as input, and writes the content into the console by default. write() can also write in files.
Let us see some examples of write() function.
PROLOG – INPUTS AND OUTPUTS

Example – Compute the following line of codes individually and understand the output.

• write(56).
• write('hello’).
• write('hello'),nl,write('world’).
• write("ABCDE")

we can see that the write() predicate can write the contents into the console. We can use ’nl’ to
create a new line. And from this example, it is clear that, if we want to print some string on the
console, we have to use single quotes (‘string‘). But if we use double quote (“string”), then it will
return a list of ASCII values.
PROLOG – INPUTS AND OUTPUTS

2. The read() Predicate Program: -


cube :-

The read() predicate is used to read from write('Write a number: '),


read(Number),
console. User can write something in the
process(Number).
console, that can be taken as input and process(stop) :- !.
process it. The read() is generally used to process(Number) :-
C is Number * Number * Number,
read from console, but this can also be
write('Cube of '),write(Number),write(': '),write(C),nl, cube.
used to read from files. Now let us see Save the above program as cube.pl, consult and understand
one example to see how read() works. how the input and output works.
PROLOG – INPUTS AND OUTPUTS

2. The tab() Predicate

The tab() is one additional predicate that can be used to put some blank-spaces while we
write something. So, it takes a number as an argument, and prints those many numbers of
blank spaces.

Programs:-
write('hello'),tab(15),write('world’).
write('We'),tab(5),write('will'),tab(5),write('use'),tab(5),write('tabs').
QUIZ
Look at the following knowledge base.
result(amin, 'Computer Science').

result(jack, 'Statistics'). Write a prolog code that asks you to


result(sheikha, 'Software Engineering').
enter the name of the student, and
result(abrham, 'Information Technology').
then returns their department.
result(kerima, 'Law').
Thank you!

You might also like