You are on page 1of 33

ARTIFICIAL INTELLIGENCE

UNIT-4
PROLOG
Artificial Intelligence

Unit-4 prolog programming

Prolog stands for programming logic it is a computer programming language. Since its
beginning in 1970’s its been used by the programmers for applications of symbolic
computation like
• Relational databases
• Mathematical logic
• Abstract problem solving
• Understanding natural language
• Design automation
• Symbolic equation solving
• Many areas of artificial intelligence

• In prolog programming programmers ask about objects and their relationships


occurs in the problem and which relationships are true about the desired solution.
• Prolog programming can be viewed as both descriptive and prescriptive.
• When a computer is programmed using prolog. The computer carries out the
computation is specified partly by declarative statements, partly what new facts
can infer from old ones, and partly explicit control information given by the
programmer.
Objects and relationships:-
Prolog is a computer programming language that involves objects and their
relationships.
Example:-
When we say john owns the book
Here john and book are objects, ownership is the relationship that exists between two
objects and further the relationship has specific order
John owns the book, the book does not own john
In some problems some relationships does not mention all the objects that are
involved
Example:- the jewel is valuable
Here in this example we are specifying a relationship being valuable the jewel.
But here we dint specify who finds the jewel valuable and why?

• Objects in prolog differs from objects and relationships of OOP. object is a data
structure that can inherit fields and executable methods from class hierarchy. Prolog
does not compared with OOP
• In prolog objects represents things that we can represent using terms from which all
data and prolog programs are constructed.
• Prolog programs consists of a set of clauses where each clause is either a fact about
the given information or a rule about how the solution may relate to the given facts.
Programming:-
Computer programing in prolog consists of:-
• Specifying some facts about objects and their relationships
• Defining some rules about objects and their relationships
• Asking questions about objects and their relationships

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 2|Page


Artificial Intelligence

• We can consider prolog program as a storehouse of facts and rules uses it to


answer questions and it provides ways to make inferences from one fact to
another finding the value of the variables that can lead to logical deductions.
 Facts:-
In prolog suppose if we write john likes mary. This fact consists of two objects john
and mary and a relationship likes in prolog we can write facts as
likes ( john, mary ).
Important points to be noted about facts and objects:-
1. The names of all relationships and objects must begin with lower case letters ex:- john,
likes, mary.
2. The relationships are written first and objects are enclosed in round brackets
separated by commas.
3. For every fact it must be terminated with a dot “.” or period
It is also important to pay attention of what order the objects are written between the
brackets.
likes(john , mary ) .
likes (mary, john). Both are not same
Examples of facts:-
1. Valuable(gold). ---→ gold is valuable
2. Female(jane). ----→jane is female
3. Owns(jane , gold). -→jane owns gold
4. Father(john, mary). -→john is father of mary
5. Gives(john, book, mary). -→ john gives the book to mary
In the examples john, jane are names refers to individuals.
Gold, valuable refers to non count words. While choosing names we must decide how
to interpret names.
The interpretation of names sometimes will have many meanings it is you as a
programmer has to decide.

The names of the objects written inside round brackets are called arguments.
And the relationship is called the predicate.
likes(john, mary) ----→ likes is a predicate having two arguments.
Facts in prolog allows to represent arbitrary facts about arbitrary objects.
Collection of facts is called database.
Questions:-
Once we have facts we can ask some questions about them.
In prolog a question looks just like facts except that we put a special symbol before it.
The special symbol followed by a ? And a - hyphen
?-owns(mary,book)
Prolog tries to match the predicate with in the database. It looks for the facts that
unify the facts in the question.
If prolog finds a fact that unifies with the question then it returns “yes” if no facts
unifies with the question then prolog replies “no”.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 3|Page


Artificial Intelligence

 First three questions answers is no, it does not mean the statement is false. It means
that no facts unifies with the question.
 What happens suppose if we ask a question about relationships not there In the
database?
 The question can simply say no or a warning can be given before saying no, or an error
message can be printed.
Example:-

Variables:-
• In prolog we can not only name particular objects but we can also use
terms like X to stand for objects that are unwilling to name. Terms of this
kind are called variables.
• When prolog uses variables the variables can be instantiated or non
instantiated. A variable is instantiated when there is a object that stands
for. A variable is not instantiated when the object is not known.
• In prolog programming variables begins with capital letter.
• When prolog is asked question containing variable it searches through all
the facts to find the objects that stand for the variable

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 4|Page


Artificial Intelligence

After returning one value prolog program will wait for further
instructions:-
1. If you press the enter key it means you are satisfied with just one
answer then prolog will stop searching for more.
2. If you press semicolon ( ; ) with enter key prolog will resume and
starts searching for other possibilities where it left the place
marker. When prolog tries to find other possible answers from the
place marker we say that prolog is re-satisfying the question.
3. The variable X is now instantiated with mary. Prolog puts a place
marker at the fact likes(john, mary) and returns X=mary.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 5|Page


Artificial Intelligence

Conjunctions:-

• Suppose we wish to answer questions more complicated relationships


such as Do john and Mary like each other? Prolog first finds John likes
mary it returns “yes” then finds if mary likes john.
• This problem consists of two separate goals that prolog system need
to satisfy. This type of combinations can be more likely to be asked in
prolog programming.

( , ) represents and
Conjunctions and the use of variables:-

Conjunction of goals to be arranged from left to right separated by


commas. Each goal has a left hand neighbour and a right hand neighbour

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 6|Page


Artificial Intelligence

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 7|Page


Artificial Intelligence

Rules:-

 This can be listed instead of writing all the objects what john likes. This
fact can be written as a rule.
 Rules are used when a fact depends on a group of other facts.

 A rule is a general statement about object and relationship.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 8|Page


Artificial Intelligence

Let us ask the question:-

Sometimes the facts and rules can be combined in the predicates if it is


done so then they are called clauses for a predicate.
Consider a rule:-
A person may steal something if the person is a thief and and the person
likes the thing.

Here the predicate may_steal has two arguements P, T to represent P any


steal T. this rule depends on clauses thief and likes.

comments:-
Comments are enclosed in /*……*/ they are ignored by the prolog. But for
programmer convenience they can be added to the prolog program.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 9|Page


Artificial Intelligence

CHAPTER-2
Syntax:-
Syntax:- it describes how we can allow words to fit together.
Ex:- I see a zebra is a correct sentence.
Zebra I see a is not a correct sentence.
PROLOG programs are built from terms. A term is either a constant, a variable or a
structure. Each term is written as a sequence of characters.
A to Z--→Upper case letters
A to z--→lower case letters
0 to 9-→ digits
+,- / \ ( ) → special signs.

Constants:-

Constants name specific objects or specific relationships. Two kinds of


constants atoms & numbers.
Ex:- likes mary john book etc…. Are atoms
“ ?- “ and “ :-” are also called atoms.
Atoms can be written as letters, digits, signs.
Atoms made of signs are made up of signs only.
Atoms normally begins with lower case letters.
Atoms beginning with uppercase letter or digit.
If an atom is enclosed in single quotes ‘ ‘ then the atom may have any
character in its name.
Numbers are the other kind of constants.
17, 2.67 e2, e represents exponential power of 10.

Prolog has added libraries to define features such as arithmetic


operations on rational numbers & numbers of arbitrary precision.
Variables:- variables look like atoms except they begin with a capital letter
or an underscore.
Variable should be thought of name of an object that we are unwilling to
name at the time we write the program.
X, Y, Z
If it is anonymous variable we can write it as:-
?- likes ( _ , john ).

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 10 |


Page
Artificial Intelligence

Structures:-

Structures are called component terms a structure is a single object


consisting of a collection of other objects called components.
Ex:- index card of a library book
Structure helps to organize the data in a program because they permit a
group of related information to be treated as a single object instead of a
separate entities.
Structure in prolog is represented by its functor & components.
Ex:-
Owns(john, book(wuthering_heights, bronte)).
Inside owns fact we have a structure by name of book, which has two
components title & an author.

Structures may participate in question answering using variables.


Ex:- if john owns any book by any of the Bronte sisters.
?- owns ( john, book ( X, author ( Y, bronte))).
?- owns( john, book( _, author( _ , bronte))).
Owns ( john, book( Ulysses, author(james, joyce), 3129)).
John owns the 3129th copy of Ulysses by james joyce.
A predicate is a functor of a structure.

Characters:-

Character name of constants & variables are built up from strings of


characters.
Prolog recognizes two kinds of characters printing & non-printing
characters(blank space, tab key etc ).
Character set:-
A to Z
a to z
0 to 9
+-()/\[]
Characters may be printed, read from the keyboard, compared, & take in
arithmetic operations.
Operators:- Arithmetic operators are commonly written as
x + y * z ------→ + , * are operators.
we write in prolog as
+ ( X, * (Y, Z)).

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 11 |


Page
Artificial Intelligence

ex:-
(3 + 4) --→ +(3,4)
To evaluate an operator we need to know 3 things about each operator
* its position
* its precedence
* its associativity.
The syntax of the term with operator depends on the position of the
operator.
+ * - / operators are written between their arguments so we call them
infix operators.
It is also possible to write operator before the argument –x+y negates the
value of X.
Operators that comes before arguments are called prefix operators.
Some operators comes after their arguments called postfix operators.
Example:- “ X!” factorial of X. factorial is denoted by exclamation mark
comes after the argument.
The precedence of operator tells us about which operation is to be carried
out first.
+(x, * ( y,z)). * is performed first before addition.
Multiplication and division has higher precedence over addition and
subtraction.
A-b/c --→-(a, /(b,c)).

Operator associativity:-
Consider how operators are associated. When we have several operators
with same precedence then we use associativity.
Addition, subtraction, multiplication, division all are left associative.
8/2/2 = (8/2)/2 = 2, 8/(2/2)= 8
A left associate operator must have the same or lower precedence
operations on the left and lower precedence operations on the right .
8/4/4= (8/4)/4 5+8/2/2= 5+ ((8/2)/2).

Equality and unification:-


One predicate is equality which is an infix opearotr “ = “ . When an
attempt is made to satisfy the goal ?- X = Y. prolog tries to unify X and Y
and the goal succeeds if they unify.
The equality predicate is built in. The rules for deciding whether X and Y
are equal are as follows:-

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 12 |


Page
Artificial Intelligence

Variable co-refer, if two un instantiated variables are equal, they refer


to same thing.

Arithmetic:-
People use computers to perform operations on numbers.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 13 |


Page
Artificial Intelligence

Consider the following database about the population and area of various
countries in 1976.
pop(x,y) means the population of country X is about Y million people.

Now to find the density of a country, we must use the rule that the density
is the population divided by the area.
A prolog rule for this is:

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 14 |


Page
Artificial Intelligence

CHAPTER-3
DATA STRUCTURES AND TREES:

A complicated structure we can write it as a tree, in which each functor is


a node and components are branches.
Each component may point to another structure, so we can have
structures within structures.
Example:- parents(Charles, Elizabeth, Philip)

Lists:-
• It is a common data structure in non-numeric programming.
• List Is a ordered sequence of elements that can have any length.
• “ ordered” means the order of elements in the sequence matters.
• Elements in the list may be any terms, constants, variables or
structures.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 15 |


Page
Artificial Intelligence

• Lists are used to represent parse trees, grammars, city map, computer
programs and mathematical entities such as graphs, formulas and
functions.
List can be represented as a special kind of tree.
• A list is either empty list having no elements, or it is a structure that
has two components head & tail.
• The end of a list is represented as a tail that is set to the empty list.
• Empty list is writes as [ ].
• The head and tail of a list are components of the functor named “ . “

• The list consisting of one element “ a “ is .( a, [ ] )

.a(,.(b,.(c, [])))

 The list in “ vine diagram “ looks like as below.

Some people uses vine diagram to represent the lists. The list growing
from left to right, the branches are hanging down.
The dot notation is not suitable for writing complicated lists.
Another syntax for writing list in prolog program ie., list notation.
It consists of the elements of the list separated by commas, & the whole
list is enclosed in square brackets list notation as [ a ] and [ a, b, c ].
[ ] empty list
[the, men[like, to , fish]]
[ a, v1, b [x,y]]

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 16 |


Page
Artificial Intelligence

The head of a list is the first component of the “ . “ functor that is used
to construct lists.
Head of a rule & head of a list both are not same. The tail of Variables in
a list can be instantiated at any time, we can provide a way to put “
holes “ in the lists that can be filled with data at a later time
a list is a second component of the “.” functor.
When a list appears in the square bracket notation the head of the list is
the first element of the list. The tail is a list that contains every element
except the first

Note:- empty list has neither head nor tail


The common operation with lists is to split a list into its head & tail.
There is a special notation in prolog to represent lists with head X & tail
Y written as [X|Y]
X instantiated to head
Y instantiated to tail
Example:-
p([l,2,3]).
p([the, cat, sat, [on, the, mat]]).
?- p([X|Y]).

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 17 |


Page
Artificial Intelligence

X=1 Y = [2, 3]
X = the [Y= cat, sat, [on, the, mat]]
?- P([-, -, -, [-IX]]).
X = [the, mat]

Mapping:-
Given a prolog structure, we frequently wish to construct a new
structure that is similar to the old one but changed in some way. We
traverse the old structure component- by – component and construct
the components of the new structure we call this as mapping.
For example:-
Let us consider a prolog program in which we type an English sentence
and prolog replies with another sentence that is an altered version of
the one we typed.

Steps to convert the dialogues into program:-


1. Accept a sentence that is typed in by the user.
2. Change each “ you “ in the sentence to word “ I “.
Compiled by Mrs. S Farzana Begum@SMDC,Ballari 18 |
Page
Artificial Intelligence

3. Likewise change any “are“ to “am not”.


4. Change “French” to “German”
5. Change “do” to “no”
6. When applied to carefully choosen sentences such as the above
this scheme will produce sensible sentences. It does not work on
every sentence.

2. A prolog program to change one sentence to another can be written as:-


1. We need to recognise that there is a releationshp between the
original altered sentence. So we need to define a prolog predicate,
called alter such that
alter(x,y) means that sentence X can be altered to give sentence Y

An empty list altered to an empty list.


Alter([],[])
 The main job of alter is to:-
1. Change the head of the input list into another word, and let the
head of the output list stand for that word.
2. Use alter on the tail of the input list, and let the tail of the output
list stand for the altered tail.
3. If we have reached the end of the input list, then there is nothing
more to go onto the output list, so we can terminate the output
list with and empty list empty[]

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 19 |


Page
Artificial Intelligence

Altering a list with head H and tail T gives a list with head X and
tail Y if changing word H gives word X and altering the list T gives
the list Y. what is meant by “changing “ one word into another.
change(X,Y) means word X changes to Y at the end of the
database we need a “ catchall” fact because if a word is not
changed into another word it needs to be changed into itself.
Change(X,X) means word x is changed to itself.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 20 |


Page
Artificial Intelligence

Joining structures together

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 21 |


Page
Artificial Intelligence

Backtracking and cut:-

a) A unifying fact can be found. In this case we say the goal has been
matched. We mark the place in the database, and instantiate any
previously uninstantiated variables that have unified. If we matched
against a rule, we shall first have to attempt to satisfy the subgoals
introduced by the rule. If the goal succeeds, we attempt to satisfy the
next goal.
b) No unifying fact can be found. In this case, we say the goal has failed.
We attempt to re-satisfy the goal.
2. We can attempt to re-satisfy a goal. We try to attempt to re-satisfy each of
the subgoals in turn. If no subgoal can be re-satisfied in a suitable way, we
attempt to find an alternative clause for the goal itself. We must make
uninstantiated any variables that became instantiated when the previous
clause was chosen. We resume searching the database from where the goal’s
place-marker was previously put. The new “backtracked” goal may either
succeed or fail and either step (a) or (b) would occur.
 A special mechanism that can be used in Prolog programs: the “cut”. The
cut allows you to tell Prolog which previous choices it need not consider
again.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 22 |


Page
Artificial Intelligence

 The simplest way a set of facts can allow multiple solutions to a question
is when there are several facts that will match against the question.
 If we have the following facts in which father(X,Y) means that the father
of X is Y:

It finds these answers by searching through the database to find the


facts and rules about father in the order in which they were given.
If we ask ?- father(_, X).

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 23 |


Page
Artificial Intelligence

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 24 |


Page
Artificial Intelligence

 A special mechanism that can be used in Prolog programs: the “cut”. The
cut allows you to tell Prolog which previous choices it need not consider
again when it backtracks through the chain of satisfied goals. There are
two reasons it may be important to do this.
 The cut, in Prolog, is a goal, written as !, which always succeeds, but
cannot be backtracked. It is best used to prevent
unwanted backtracking, including the finding of extra solutions by Prolog
and to avoid unnecessary computations.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 25 |


Page
Artificial Intelligence

Find maximum of 2 numbers:-


max(X,Y,M):- write( ‘ condition 1’ ), X>=Y, M=X.
Max(_,Y,M) :- write( ‘condition 2’), M=Y.
?-max(5,3,M)
Condition 1
M=5; //true
Condition 2
M=3 is also executed when goal is reached to prevent backtracking we use cut
max(X,Y,M):- write( ‘ condition 1’ ), X>=Y, M=X !.
Max(_,Y,M) :- write( ‘condition 2’), M=Y.
?-max(5,3,M)
Condition 1
M= 5 is executed
Common uses of cuts:

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 26 |


Page
Artificial Intelligence

Combination of cut and fail:


In the above example we can backtrack any number of times between a
and b when once cut succeeds between c and d after processing c and d
we cannot backtrack to b.
After executing fail we will never perform e and f, will never execute the
program terminates.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 27 |


Page
Artificial Intelligence

 We shall define a predicate pp such that the goal pp(X,Y) displays the list
in a helpful way. The name pp means “pretty print”.
 For example the list [1,2,3] is pretty printed as

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 28 |


Page
Artificial Intelligence

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 29 |


Page
Artificial Intelligence

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 30 |


Page
Artificial Intelligence

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 31 |


Page
Artificial Intelligence

Write a program to add two numbers in PROLOG programming

Prolog problem to add two numbers.

?- start.
X= |: 1.
Y= |: 2.
Sum is 3
yes

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 32 |


Page
Artificial Intelligence

code for prolog program to add two numbers:-


predicates
start.
sum.
clauses
start:- sum,nl.
sum:- write(\"X= \"),readreal(X),
write(\"Y= \"),readreal(Y),
S = X+Y,
write(\"Sum is \"),write(S).
goal
start.

Compiled by Mrs. S Farzana Begum@SMDC,Ballari 33 |


Page

You might also like