0% found this document useful (0 votes)
43 views36 pages

Chapter 04 PCPF

Uploaded by

shubham060505
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views36 pages

Chapter 04 PCPF

Uploaded by

shubham060505
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Chapter 04

Declarative Programming Paradigm: Logic Programming


Logic Programming with PROLOG - Resolution and Unification, Lists,
Arithmetic execution order,
imperative control flow, database manipulation,
PROLOG facilities and deficiencies.
Self-Learning Topic: Identification of different application domains for use of Prolog and Logic
Programming
===========================================================================

Logic Programming

Logic Programming is the name given to a distinctive style of programming, very different from that of
conventional programming languages such as C++ and Java. Fans of Logic Programming would say that
'different' means clearer, simpler and generally better!

Although there are other Logic Programming languages, by far the most widely used is Prolog. The name
stands for Programming in Logic. Prolog is based on research by computer scientists in Europe in the
1960s and 1970s, notably at the Universities of Marseilles, London and Edinburgh. The first
implementation was at the University of Marseilles in the early 1970s. Further development at the
University of Edinburgh led to a de facto standard version, now known as Edinburgh Prolog. Prolog has
been widely used for developing complex applications, especially in the field of Artificial Intelligence.

Although it is a general-purpose language, its main strengths are for symbolic rather than for numerical
computation.

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 is one of the Computer Programming Paradigm, in which the program statements
express the facts and rules about different problems within a system of formal logic. Here, the rules are
written in the form of logical clauses, where head and body are present. For example, H is head and B1,
B2, B3 are the elements of the body. Now if we state that “H is true, when B1, B2, B3 all are true”, this is
a rule. On the other hand, facts are like the rules, but without any body. So, an example of fact is “H is
true”.

Some logic programming languages like Datalog or ASP (Answer Set Programming) are known as purely
declarative languages. These languages allow statements about what the program should accomplish.
There is no such step-by-step instruction on how to perform the task. However, other languages like
Prolog, have declarative and also imperative properties. This may also include procedural statements like
“To solve the problem H, perform B1, B2 and B3”.

Some logic programming languages are given below −

​ ALF (algebraic logic functional programming language).


​ ASP (Answer Set Programming)
​ CycL
​ Datalog
​ FuzzyCLIPS
1
​ Janus
​ Parlog
​ Prolog
​ Prolog++
​ ROOP

Logic and Functional Programming


We will discuss about the differences between Logic programming and the traditional functional
programming languages. We can illustrate these two using the below diagram −

From this illustration, we can see that in Functional Programming, we have to define the procedures, and
the rule how the procedures work. These procedures work step by step to solve one specific problem
based on the algorithm. On the other hand, for the Logic Programming, we will provide knowledge base.
Using this knowledge base, the machine can find answers to the given questions, which is totally different
from functional programming.

In functional programming, we have to mention how one problem can be solved, but in logic
programming we have to specify for which problem we actually want the solution. Then the logic
programming automatically finds a suitable solution that will help us solve that specific problem.

Now let us see some more differences below −

Functional Programming Logic Programming

2
Functional Programming follows the Logic Programming uses abstract model, or
Von-Neumann Architecture, or uses the deals with objects and their relationships.
sequential steps.

The syntax is actually the sequence of The syntax is basically the logic formulae
statements like (a, s, I). (Horn Clauses).

The computation takes part by executing the It computes by deducting the clauses.
statements sequentially.

Logic and controls are mixed together. Logics and controls can be separated.

Logic Programming with PROLOG

What is Prolog?
Prolog or PROgramming in LOGics is a logical and declarative programming language. It is one major
example of the fourth generation language that supports the declarative programming paradigm. This is
particularly suitable for programs that involve symbolic or non-numeric computation. This is the main
reason to use Prolog as the programming language in Artificial Intelligence, where symbol
manipulation and inference manipulation are the fundamental tasks.

In Prolog, we need not mention the way how one problem can be solved, we just need to mention what the
problem is, so that Prolog automatically solves it. However, in Prolog we are supposed to give clues as the
solution method.

Prolog language basically has three different elements −

Facts − The fact is predicate that is true, for example, if we say, “Tom is the son of Jack”, then this is a
fact.

Rules − Rules are extinctions of facts that contain conditional clauses. To satisfy a rule these conditions
should be met. For example, if we define a rule as −

grandfather(X, Y) :- father(X, Z), parent(Z, Y)

This implies that for X to be the grandfather of Y, Z should be a parent of Y and X should be father of Z.

Questions − And to run a prolog program, we need some questions, and those questions can be answered
by the given facts and rules.

History of Prolog
The heritage of prolog includes the research on theorem provers and some other automated deduction
system that were developed in 1960s and 1970s. The Inference mechanism of the Prolog is based on

3
Robinson’s Resolution Principle, that was proposed in 1965, and Answer extracting mechanism by Green
(1968). These ideas came together forcefully with the advent of linear resolution procedures.

The explicit goal-directed linear resolution procedures, gave impetus to the development of a general
purpose logic programming system. The first Prolog was the Marseille Prolog based on the work by
Colmerauer in the year 1970. The manual of this Marseille Prolog interpreter (Roussel, 1975) was the
first detailed description of the Prolog language.

Prolog is also considered as a fourth generation programming language supporting the declarative
programming paradigm. The well-known Japanese Fifth-Generation Computer Project, that was
announced in 1981, adopted Prolog as a development language, and thereby grabbed considerable
attention on the language and its capabilities.

Some Applications of Prolog


Prolog is used in various domains. It plays a vital role in automation system. Following are some other
important fields where Prolog is used −

​ Intelligent Database Retrieval


​ Natural Language Understanding
​ Specification Language
​ Machine Learning
​ Robot Planning
​ Automation System
​ Problem Solving

The different topics that will be covered in this chapter are −

Knowledge Base − This is one of the fundamental parts of Logic Programming. We will see in detail
about the Knowledge Base, and how it helps in logic programming.

Facts, Rules and Queries − These are the building blocks of logic programming. We will get some
detailed knowledge about facts and rules, and also see some kind of queries that will be used in logic
programming.

Here, we will discuss about the essential building blocks of logic programming. These building blocks are
Facts, Rules and the Queries.

Facts
We can define fact as an explicit relationship between objects, and properties these objects might have. So
facts are unconditionally true in nature. Suppose we have some facts as given below −

​ Tom is a cat
​ Kunal loves to eat Pasta
​ Hair is black
​ Nawaz loves to play games

4
​ Pratyusha is lazy.

So these are some facts, that are unconditionally true. These are actually statements, that we have to
consider as true.

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.

Syntax
The syntax for facts is as follows −

relation(object1,object2...).

Example
Following is an example of the above concept −

cat(tom).
loves_to_eat(kunal,pasta).
of_color(hair,black).
loves_to_play_games(nawaz).
lazy(pratyusha).

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.

So these are some rules that are conditionally true, so when the right hand side is true, then the left hand
side is also true.

5
Symbols
Here the symbol ( :- ) will be pronounced as “If”, or “is implied by”. This is also known as neck symbol,
the LHS of this symbol is called the Head, and right hand side is called Body. Here we can use comma (,)
which is known as conjunction, and we can also use semicolon, that is known as disjunction.

Using the following truth-functional symbols, the Prolog expressions are comprised. These
symbols have the same interpretation as in the predicate calculus.

English Predicate Calculus Prolog

If --> :-

Not ~ Not

Or V ;

and ^ ,

Syntax
rule_name(object1, object2, ...) :- fact/rule(object1,
object2, ...)
Suppose a clause is like :
P :- Q;R.
This can also be written as
P :- Q.
P :- R.

If one clause is like :


P :- Q,R;S,T,U.

Is understood as
P :- (Q,R);(S,T,U).
Or can also be written as:
P :- Q,R.
P :- S,T,U.

6
Example
happy(lili) :- dances(lili).
hungry(tom) :- search_for_food(tom).
friends(jack, bili) :- lovesCricket(jack), lovesCricket(bili).
goToPlay(ryan) :- isClosed(school), free(ryan).

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

​ 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.

Knowledge Base in Logic Programming


In this section, we will see what knowledge base in logic programming is.

Well, as we know there are three main components in logic programming − Facts, Rules and Queries.
Among these three if we collect the facts and rules as a whole then that forms a Knowledge Base. So we
can say that the knowledge base is a collection of facts and rules.

Knowledge Base Example:

dog(fido).
dog(rover).
dog(henry).
cat(felix).
cat(michael).
cat(jane).
animal(X):-dog(X).

The first three lines are facts, with the obvious interpretation that fido, rover and henry are all dogs.
The next three facts say that felix, michael and jane are all cats.
The final line is a rule saying that anything (let us call it X) is an animal if it is a dog. Cat lovers may feel
that cats can also claim to be called animals, but the program is silent about this.
Having loaded the program, the user is then faced with the two character symbol ?- which is called the
system prompt. To check whether fido is a dog all that is necessary is to type the query dog(fido) followed
by a full stop and press the 'return' key, which indicates to the system that a response is needed. This gives
the complete dialogue:
?- dog(fido).
Yes

7
The user can enter a series of queries at the prompt, asking for further
information.
?-dog(jane).
no
[Is jane a dog? No - a cat]

?- animal(fido).
yes

[Is fido an animal?]


[yes - because it is a dog and any dog is an animal]

?- dog(X).
X = fido ;
X = rover ;
X = henry

[Is it possible to find anything, let us call it X, that is a dog?]


[All 3 possible answers are provided]

?-animal(felix).
No

This type of reasoning is fundamental to theorem proving in Mathematics and


to writing programs in Prolog.

—---------------------------------------------------------
Data Objects in Prolog: Prolog Terms
The data objects in Prolog are called terms. Examples of terms that have been used in Prolog programs so
far in this book are fido, dog(henry), X and cat(X). There are several different types of term, which are
listed below.

(1) Numbers
All versions of Prolog allow the use of integers (whole numbers). They are written as any sequence of
numerals from 0 to 9, optionally preceded by a + or - sign, for
example:
623
-47
+5
025
Most versions of Prolog also allow the use of numbers with decimal points.
They are written in the same way as integers, but contain a single decimal point, anywhere except before
an optional + or - sign, e.g.
6.43
-.245
+256.

(2) Atoms
8
Atoms are constants that do not have numerical values. There are three ways in which atoms can be
written.
(a) Any sequence of one or more letters (upper or lower case), numerals and underscores, beginning
with a lower case letter, e.g.
john
today_is_Tuesday
fred_jones
a32_BCD
but not
Today
today-is-Tuesday
32abc
(b) Any sequence of characters enclosed in single quotes, including spaces and upper case letters,
e.g.
'Today is Tuesday'
'today-is-Tuesday'
'32abc'
(c) Any sequence of one or more special characters from a list that includes the Following
+-*/><=&#@:

Examples
+++
>=
>
+--
(3) Variables
In a query a variable is a name used to stand for a term that is to be determined,
e.g. variable X may stand for atom dog, the number 12.3, or a compound term or a list (both to be
described below). The meaning of a variable when used in a rule or fact
The name of a variable is denoted by any sequence of one or more letters (upper or lower case), numerals
and underscores, beginning with an upper case letter or underscore, e.g.
X
Author
Person_A
_123A
but not
45_ABC
Person-A
Author

(4) Compound Terms


Compound terms are of fundamental importance in writing Prolog programs. A compound term is a
structured data type that begins with an atom, known here as a functor. The functor is followed by a
sequence of one or more arguments, which are enclosed in brackets and separated by commas. The
general form is functor(t1,t2, ... ,tn) n≥1
If you are familiar with other programming languages, you may find it helpful to think of a compound
term as representing a record structure. The functor represents the name of the record, while the arguments
represent the record fields.
The number of arguments a compound term has is called its arity. Some examples of compound terms are:

9
likes(paul,prolog)
read(X)

dog(henry)
cat(X)
>(3,2)
person('john smith',32,doctor,london)
Each argument of a compound term must be a term, which can be of any kind including a compound term.
Thus some more complex examples of compound
terms are:
likes(dog(henry),Y)
pred3(alpha,beta,gamma,Q)
pred(A,B,likes(X,Y),-4,pred2(3,pred3(alpha,beta,gamma,Q)))

(5) Lists
A list is often considered to be a special type of compound term, but in this book it
will be treated as a separate type of data object.
Lists are written as an unlimited number of arguments (known as list elements)
enclosed in square brackets and separated by commas, e.g. [dog,cat,fish,man].
Unlike the arity of a compound term, the number of elements a list has does not
have to be decided in advance when a program is written, as will be explained in
Chapter 9. This can be extremely useful.
At this stage, all that it is necessary to know is that an element of a list may be a
term of any kind, including a compound term or another list, e.g.
[dog,cat,y,mypred(A,b,c),[p,q,R],z]
[[john,28],[mary,56,teacher],robert,parent(victoria,albert),[a,b,[c,d,e],f],29]
[[portsmouth,edinburgh,london,dover],[portsmouth,london,edinburgh],[glasgow]]
A list with no elements is known as the empty list. It is written as [].

Clauses and Predicates


In Prolog, the program contains a sequence of one or more clauses. The clauses can run over
many lines. Using a dot character, a clause can be terminated. This dot character is followed by at
least one 'white space' character. The clauses are of two types: facts and rules.

Facts are specified in the form of the head. Head is known as the clause head. It will take in the
same way as the goal entered at the prompt by the user. The head of a clause must be a
compound term or an atom. Compound terms and atoms are collectively called as call terms.

Examples of facts are as follows:

holi.

likes(Russell, angelina).

likes(A, prolog).

cat(sphynx).

Rules are specified in the form:

10
head:- t1, t2, t3,….., tk. Where k>=1

The head is known as the clause of head.

:- is known as the clause neck. It is read as 'if'. The body of the clause is specified by t1, t2, t3,
tk. It contains one or more components, and it can be separated using the commas. The goal
represents the components. The command is represented by 'and'.

A rule will be read as ' head is true if t1, t2, t3,…., tk are all true'.

Examples of rules are as follows:

corona_virus(A) :- virus(A), corona(A).


grandparent(A, B) :- father(A, C), parent(C, B).
go :- write('welcome to Prolog'), nl.

Here is another version of the animals program, which includes both facts and
rules.
/* Animals Program 2 */
dog(fido). large(fido).
cat(mary). large(mary).
dog(rover). dog(jane).
dog(tom). large(tom). cat(harry).
dog(fred). dog(henry).
cat(bill). cat(steve).
small(henry). large(fred).
large(steve). large(jim).
large(mike).
large_animal(X):- dog(X),large(X).
large_animal(Z):- cat(Z),large(Z).

fido, mary, jane etc. are atoms, i.e. constants, indicated by their initial lower case letters. X and Y
are variables, indicated by their initial capital letters.
The first 18 clauses are facts. The final two clauses are rules.

Predicates
The following simple program has five clauses. For each of the first three clauses, the head is a compound
term with functor parent and arity 2 (i.e. two arguments).

parent(victoria,albert).
parent(X,Y):-father(X,Y).
parent(X,Y):-mother(X,Y).
father(john,henry).
mother(jane,henry).

11
It is possible (although likely to cause confusion) for the program also to include clauses for which the
head has functor parent, but a different arity, for example

parent(john).
parent(X):-son(X,Y).
/* X is a parent if X has a son Y */

It is also possible for parent to be used as an atom in the same program, for example in the fact
animal(parent).

but this too is likely to cause confusion.

All the clauses (facts and rules) for which the head has a given combination of functor and arity
comprise a definition of a predicate.
The clauses do not have to appear as consecutive lines of a program but it makes programs easier to read
if they do.
The clauses given above define two predicates with the name parent, one with arity two and the other with
arity one. These can be written (in textbooks, reference manuals etc., not in programs) as parent/2 and
parent/1, to distinguish between them. When there is no risk of ambiguity, it is customary to refer to a
predicate as just dog, large_animal etc.

Prolog - Operators
Arithmetic in Prolog
In the previous sections, the examples are non-numerical. In this section, we will use is/2 built-in
predicate. This predicate is predefined as an infix operator. The is/2 predicate is placed between
the two arguments.

If the first argument is an unbound variable, the predicate is/2 are mostly used. The goal A is -4.2
which shows that A is bound to number -4.2, and the goal succeed.

Arithmetic expression or number can be expressed by the second argument.

For example

A = 6 * B + C - 3.2 + S - T / 4

In arithmetic expression, any variables must already be bound. The value of these variables must
be numerical. The value of arithmetic expression bounds the variable of first argument. If it is
not, an error message will be generated as result.

?- A is 5.7 + 2.9 * 3
A = 14.4

12
?- B is 6, C is B + 2.
B = 6,
C=8

In arithmetic expression, + - * / symbols are special type of infix operator, and these operators are
also known as arithmetic operators. In Prolog, operators are used as predicates but here operators
are functions and these operators return a numerical value.

Arithmetic expressions can include variables, numbers, operators, and arithmetic functions.
These will be written in parentheses with their arguments. These will return numerical values just
like the arithmetic operators.

For example: Square bracket of 25.

?- A is sqrt(25).

A=5

The minus(-) arithmetic operator is used as a binary infix operator, which is used to describe the
difference of two numerical values like A - 2. It is also used as a unary prefix operator, which is
used to describe the negative of a numerical value like

?- A is 7, B is -A - 3.

A = 7,

B = -10

Arithmetic functions and Arithmetic operators available in Prolog are shown as following :

X+Y the sum of X and Y

X-Y the difference of X and Y

X*Y the product of X and Y

X/Y the quotient of X and Y

X//Y the 'integer quotient' of X and Y (the result is truncated to the

nearest integer between it and zero)

X^Y X to the power of Y

-X the negative of X

abs(X) the absolute value of X

sin(X) the sine of X (for X measured in degrees)

cos(X) the cosine of X (for X measured in degrees)


13
max(X,Y) the larger of X and Y

sqrt(X) the square root of X

Example:

?- A is 30, B is 3, C is A + B + A * B + sin(A).

A = 30,

B = 3,

C = 123.5

The is predicate is used in the normal way. The first argument can be a bound variable or a
number with numerical value. In two arguments, the numerical values are calculated. If these
values are equal, the goal succeeds. It fails if these values are not equal.

?- A is 5, A is 4+1.
A=7

?- 15 is 9 + 6 - 13 + 20
no

?- 22 is 9 + 6 - 13 + 20
yes

The goal A is A + 1 will always fail, whether or not A is bound.

?- A is 7, A is A + 1.
no

A different approach is used to increase a value by one.

/* Incorrect Version */

increase(S) :- -S is S + 1.

?- increase(4).
No

/* Correct version */

Increase(S, T) :- -T is S + 1.

?- increase(4, A).

A=5

calc :- X is 100 + 200,write('100 + 200 is '),write(X),nl,

Y is 400 - 150,write('400 - 150 is '),write(Y),nl,

14
Z is 10 * 300,write('10 * 300 is '),write(Z),nl,

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

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

C is 100 ** 2,write('100 ** 2 is '),write(C),nl,

D is 100 mod 30,write('100 mod 30 is '),write(D),nl.

| ?- calc.

100 + 200 is 300

400 - 150 is 250

10 * 300 is 3000

100 / 30 is 3.3333333333333335

100 // 30 is 3

100 ** 2 is 10000.0

100 mod 30 is 10

yes

Relational Operators

The relational operators are =:=, >, <, >=, =/=, =<. The relational operators compare the values of
two arguments. If the first argument's value is equal to, greater than, less than, greater than or
equal to, not equal to, less than or equal to the value of second argument, the goal succeeds. Both
arguments can be arithmetic expression, bound variable or numbers.

?- 60 - 5 + 10 =:= 85 - 10*2.
yes

?- 59=\=63.
yes

Equality Operators in Prolog


To test the equality and inequality, Prolog has three types of relational operators. The value of
arithmetic expression can be compared by the first type of relational operator. The terms can be
compared by other two types of relational operator.

Equality Operator (=:=)


15
Given Arithmetic expression

E1 =:= E2

If E1 and E2 evaluate to the same value, the above E1 =:= E2 succeed.

For example:

?- 10+3 =:= 5*4-7.


yes
?- sqrt(25)+10 =:= 3*7-6
yes

Prolog uses checkeven/1 predicate to identify whether an integer is odd or even.

checkeven(X) :- Y is X//2, X =:= Y*2.


?- checkeven(7).
no
?- checkeven(18)
yes
?- checkeven(-27)
no
?- checkeven(-10)
yes

The // is the division operator. It divides the first argument to the second argument and the result
of this division truncates to the nearest integer between it and zero. So 7//2 is 3, 18//2 is 9, -27//2
is -13, -10//2 is -5. Divide the integer by 2 and multiplies it by 2 will give the original integer if it
is even, otherwise it is not.

Inequality Operator (=\=)

Given arithmetic expression

1. E1 =\= E2

If E1 and E2 do not evaluate to the same value, arithmetic expression E1 =\= E2 succeeds.

For example:

?- 24 =\= 17+4
yes

Terms Identical

Given Goal

1. Term1 == Term2

16
In the infix operator ==, both arguments must be terms. If Term1 and Term2 are identical, the
above goal succeeds.

For example:

?- likes(A, prolog) == likes(A, prolog)


A=_

?- likes(A, prolog) == likes(B, prolog)


no
(Variables A and B are different)

?- A is 25, pred1(A) == pred1(25).


A = 25

?- A == 0.
no

?- 5+4 == 2+7.
no

When the arithmetic expression value is used with is/2, the arithmetic expression value can
only evaluate. Here the term is defined by 5+4 with arguments 5 and 4 and functor +. This
term is totally different from 2+7 term.

Term Not Identical (\==)

Given goal

1. Term1 \== Term 2

The above goal is used to test whether Term1 and Term2 are not identical. If Term1 ==
Term2 fails, the Term1 \== Term2 succeeds. Otherwise the goal fails.

For example:

1. ?- pred1(A) \== pred1(B).


2. A = _,
3. B = _

The above output shows that variables A and B are different variables and both are
unbound.

====================================================================

17
How Prolog answers a query
• Unification.

• Resolution.

• Backtracking.

Unification
Given a goal to evaluate, Prolog works through the clauses in the database trying to match the goal
with each clause in turn, working from top to bottom until a match is found. If no match is found the
goal fails.
likes(ramesh,car).
-likes(X,Y).
X-ramesh
Y-car
Data —>values(properties)---binding
likes(yash,car).
False
Fact ex—-->cat(A).
Fanctor-cat
arity-1

cat(mary).

● Prolog uses the unification technique, and it is a very general form of matching
technique. In unification, one or more variables being given value to make the two call terms
identical.
● This process is called binding the variables to values. For example, Prolog can unify the terms
cat(A), and cat(mary) by binding variable A to atom mary that means we are giving the value
mary to variable A. Prolog can unify person(Kevin, dane) and person(L, S) by binding L and S
to atom kevin and dane, respectively.
● In starting, all variables have no value. In unification, once a variable bound to the value, it
can be made unbound again and then perhaps be bound to a new value using the backtracking.

Unifying Call Terms

In the following, flowchart can summarize the process.en

18
To consider this, we have three cases. In the first case, an atom is unified with another
atom, and it is the easiest way. If two atoms are same, this will only succeed, so

○ the atoms dane unifies and dane succeeds.

○ The atom dane unifies and 'dane' also succeeds.

○ The atom dane unifies and kevin fails.

In the second case, an atom is unified with a compound term like dane with likes(Kevin,
henry). This second case always fails.

In the third case, the two compound terms are unified, and it the most common case. For
example dog(A) with likes(kevin, B) or likes(A, B) with likes(Kevin, henry). In two compound
terms, if functor and arity are same, then the unification fails. Predicate is the same, so unifying
dog(A) and likes(Kevin, B) fail.

19
20
21
• Resolution:
The resolution principle says that if C1 and C2 are Horn clauses and the head of C1 matches one
of the terms in the body of C2,then we can replace the term in C2 with the body of C1. Consider
the following example:

Horn clause→fact[H|T]

takes(jane_doe, his201).

takes(jane_doe, cs254).

takes(ajit_chandra, art302).

takes(ajit_chandra, cs254).

classmates(X, Y) :- takes(X, Z), takes(Y, Z).

If we let X be jane_doe and Z be cs254, we can replace the first term on the right-hand side of the
last clause with the (empty) body of the second clause, yielding the new rule

classmates(jane_doe, Y) :- takes(Y, cs254).

In other words, Y is a classmate of jane_doe if Y takes cs254.

Note that the last rule has a variable (Z) on the right-hand side that does notappear in the head.
Such variables are existentially quantified: for all X and Y, X and Y are classmates if there exists
a class Z that they both take.

The pattern-matching process used to associate X with jane_doe and Z with cs254 is known
as unification. Variables that are given values as a result of unification are said to be instantiated.

The unification rules for Prolog state that

● A constant unifies only with itself.


● Two structures unify if and only if they have the same functor and the same arity, and the
corresponding arguments unify recursively.
● A variable unifies with anything. If the other thing has a value, then the variable is
instantiated. If the other thing is an uninstantiated variable, then the two variables are
associated in such a way that if either is given a value later, that value will be shared by
both.

—---------------------------------------------------------------------------------------------------------------

22
Backtracking
In the process of backtracking, we will go back to the previous goal, and after that, we will try to
find another way to satisfy the goal. In this section, we will give two detailed ways to satisfy a
sequence of goals using the process of backtracking and unification.

—------------------------------------==============================================

Search/Execution Order
two principal search strategies:

● Start with existing clauses and work forward, attempting to derive the goal. This strategy
is known as forward chaining.
● Start with the goal and work backward, attempting to “unresolve” it into a set of
preexisting clauses. This strategy is known as backward chaining.

23
If the number of existing rules is very large, but the number of facts is small, it is possible for
forward chaining to discover a solution more quickly than backwardchaining. In most
circumstances, however, backward chaining turns out to be more efficient. Prolog is defined to
use backward chaining.

Because resolution is associative and commutative, a backward-chaining theorem prover can


limit its search to sequences of resolutions in which terms on the right-hand side of a clause are
unified with the heads of other clauses one by one in some particular order (e.g., left to right).

The resulting search can be described in terms of a tree of subgoals, as shown in Figure below:

24
====================================================================

Prolog Database

Changing the Database: Adding and Deleting Clauses


The normal way of placing clauses in the Prolog database is to consult or reconsult one or more
files. A consult directive causes all the clauses in the file to be loaded into the database to add to
those already there.

A reconsult directive behaves in a similar way to consult, with one crucial difference. If any
clause in the reconsulted file is for the same predicate as a clause already in the database (i.e.
their heads have the same functor and arity), all clauses for that predicate in the database are first
deleted.

Clauses placed into the database normally stay there until added to or deleted by a subsequent
consult or reconsult directive, or until the user exits from the Prolog system when all clauses are
automatically deleted. For most purposes this is entirely sufficient. However Prolog also has
built-in predicates for adding clauses to and deleting clauses from the database which can be
useful for more advanced programming in the language.
25
Like many other 'advanced' features, they need to be used with care. As usual, these built-in
predicates can be used either in the body of a rule or in a directive entered at the system prompt.
As the user's program and the Prolog database are equivalent, using them in the body of a clause
is equivalent to modifying the user's program while it is being used.Specifying a Predicate as
Dynamic

If any predicate is to be modified using assertz, retract etc., it should be specified as dynamic by
a directive in the user's program.
As an example, for predicate mypred with arity 3, the line
?-dynamic(mypred/3).
should be added at or near the start of the program and certainly before the first clause that
mentions the mypred predicate.

Adding Clauses
Two main predicates are available for adding clauses to the database. Both take a
single argument, which must be a clause, i.e. a fact or a rule.
assertz(Clause)
The predicate assertz/1 causes Clause to be added to the database at the end of the
sequence of clauses that define the corresponding predicate.
The clause used for the first argument should be written without a terminating full stop. Rules
must be enclosed in an additional pair of parentheses, e.g.
?-assertz(dog(fido)).
?-assertz((go:-write('hello world'),nl)).
The clause may include one or more variables, e.g.
?-assertz(dog(X)).
?-assertz((go(X):-write('hello '),write(X),nl)).

asserta(Clause)

The predicate asserta/1 causes Clause to be added to the database at the start of the
sequence of clauses that define the corresponding predicate.

The clause used for the first argument should be written without a terminating full stop. Rules
must be enclosed in an additional pair of parentheses,
e.g.
?-asserta(dog(fido)).
?-asserta((go:-write('hello world'),nl)).

Deleting Clauses
Two main predicates are available for deleting clauses from the database.
retract(Clause)
The predicate retract/1 takes a single argument, which must be a clause, i.e. a fact
or a rule. It causes the first clause in the database that matches (i.e. unifies with)
Clause to be deleted.
If the following clauses are in the database
dog(jim).
dog(fido).
dog(X).
the query
?-retract(dog(fido)).
will delete the second clause and the further query
26
?-retract(dog(X)).
will delete the dog(jim) clause, which is the first one of the remaining two clauses
to unify with the query.

retractall(Head)
The predicate retractall/1 takes a single argument which must be the head of a
clause. It causes every clause in the database whose head matches Head to be
deleted. The retractall goal always succeeds even if no clauses are deleted.
Some examples are:
?-retractall(mypred(_,_,_)).
which deletes all the clauses for the mypred/3 predicate, and
?-retractall(parent(john,Y)).
which deletes all clauses for the parent/2 predicate which have the atom john as
their first argument.
—------------------------------------------------------------------------------------------------

The following example, which comprises a series of goals entered at the system prompt,
illustrates the use of the assertz, asserta, retract and retractall predicates for changing the
database.

27
28
—------------------------------------------------------------------------------------------------------------------

Lists in Prolog

Representation 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.

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.

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 −


29
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.

Basic Operations on Lists

Following table contains various operations on prolog lists −

Operations Definition

Membership During this operation, we can verify whether a given element


Checking 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.

30
List- Built-in Predicate:
31
Member built-in predicate

The member built-in predicate takes two arguments. If the first argument is any term
except a variable and the second argument is a list, member succeeds if the first argument
is a member of the list denoted by the second argument (i.e. one

of its list elements).

?- member(a,[a,b,c]).

yes

?- member(mypred(a,b,c),[q,r,s,mypred(a,b,c),w]).

yes

?- member(x,[]).

no

?- member([1,2,3],[a,b,[1,2,3],c]).

Yes

Built-in Predicate: length

The length built-in predicate takes two arguments. The first is a list. If the second is an
unbound variable it is bound to the length of the list, i.e. the number of elements it
contains.

?- length([a,b,c,d],X).

X=4

?- length([[a,b,c],[d,e,f],[g,h,i]],L).

L=3

?- length([],L).

32
L=0

If the second argument is a number, or a variable bound to a number, its valueis compared
with the length of the list.

?- length([a,b,c],3).

yes

?- length([a,b,c],4).

no

?- N is 3,length([a,b,c],N).

N=3

Built-in Predicate: reverse

The reverse built-in predicate takes two arguments. If the first is a list and the second is
an unbound variable (or vice versa), the variable will be bound to the value of the list with
the elements written in reverse order, e.g.

?- reverse([1,2,3,4],L).

L = [4,3,2,1]

?- reverse(L,[1,2,3,4]).

L = [4,3,2,1]

?- reverse([[dog,cat],[1,2],[bird,mouse],[3,4,5,6]],L).

L = [[3,4,5,6],[bird,mouse],[1,2],[dog,cat]]

Note that the order of the elements of the sublists [dog,cat] etc. is not reversed. If both
arguments are lists, reverse succeeds if one is the reverse of the other.

?- reverse([1,2,3,4],[4,3,2,1]).

33
Yes

?- reverse([1,2,3,4],[3,2,1]).

no

Built-in Predicate: append

The term concatenating two lists means creating a new list, the elements of which are
those of the first list followed by those of the second list. Thus concatenating[a,b,c] with
[p,q,r,s] gives the list [a,b,c,p,q,r,s]. Concatenating [] with [x,y] gives[x,y].

The append built-in predicate takes three arguments. If the first two arguments are lists
and the third argument is an unbound variable, the third argument is bound to a list
comprising the first two lists concatenated, e.g.

?- append([1,2,3,4],[5,6,7,8,9],L).

L = [1,2,3,4,5,6,7,8,9]

?- append([],[1,2,3],L).

L = [1,2,3]

?- append([[a,b,c],d,e,f],[g,h,[i,j,k]],L).

L = [[a,b,c],d,e,f,g,h,[i,j,k]]

The append predicate can also be used in other ways. When the first two arguments are
variables and the third is a list it can be used with backtracking to find all possible pairs of
lists which when concatenated give the third argument, as follows.

?- append(L1,L2,[1,2,3,4,5]).

L1 = [] ,
L2 = [1,2,3,4,5] ;
L1 = [1] ,
L2 = [2,3,4,5] ;
L1 = [1,2] ,
L2 = [3,4,5] ;
L1 = [1,2,3] ,

34
L2 = [4,5] ;
L1 = [1,2,3,4] ,
L2 = [5] ;
L1 = [1,2,3,4,5] ,
L2 = [] ;
no

===================================
Imperative Control Flow
• Control Flow The cut :
• Prolog has a number of explicit control flow features
• ! - cut
• zero-argument predicate that always succeeds
• It commits the interpreter to the unification made between the parent goal and the left hand
side of the current rule
Example
member(X, [X|T]).
member(X, [H|T]) :- member(X, T).

member(X, [X|T]) :- !.
member(X, [H|T]) :- member(X, T).

Ex-

35
max_cal(X,Y,Max):- X>= Y, ! , Max =X;

Max = Y.

?- max_cal(5,7,Max).

Max = 7.

?-

Reference:
Family Tree- https://www.tutorialspoint.com/prolog/prolog_relations.htm
https://www.javatpoint.com/prolog-clauses

https://www.tutorialspoint.com/prolog/prolog_towers_of_hanoi_problem.htm

36

You might also like