0% found this document useful (0 votes)
6 views12 pages

KB-Bab-01

This document provides an overview of Prolog, focusing on its use for defining family relations through an example program. It explains how to declare facts and rules, query the Prolog system, and illustrates the relationships between family members using Prolog syntax. The document also highlights the differences between facts and rules, and discusses the implications of querying the system with various goals.

Uploaded by

ihsan verdian
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)
6 views12 pages

KB-Bab-01

This document provides an overview of Prolog, focusing on its use for defining family relations through an example program. It explains how to declare facts and rules, query the Prolog system, and illustrates the relationships between family members using Prolog syntax. The document also highlights the differences between facts and rules, and discusses the implications of querying the system with various goals.

Uploaded by

ihsan verdian
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/ 12

An Overview

of Prolog

Thischapterreviewsbasicmechanisms of Prologthroughan exampleprogram.


Although the treatment is largely informal many important conceptsare
introduced.

1.1 An exampleprogram:definingfamilyrelations
Prolog is a programming language for symbolic, non-numeric computation. It
is specially well suited for solving problems that involve objects and relations
between objects.Figure 1.1 showsan example: a family relation. The fact that
Tom is a parent of Bob can be written in Prolog as:

parent( tom, bob).

Here we choose parent as the name of a relation; tom and bob are its argu-

Figure l.l A family tree.


4 PROLOG PROGRAMMING FOR ARTIFICIAL INTELLIGENCE

ments.For reasons thatwill becomeclearlaterwe writenamesliketom with an


initial lower-case
letter.The wholefamilytree of Figure1.1is definedby the
followingPrologprogram:

parent( pam, bob).


parent( tom, bob).
parent( tom, liz).
parent( bob, ann).
parent( bob, pat).
parent( pat, jim).

This programconsistsof six clauses.Each of theseclausesdeclaresone fact


about the parentrelation.
When this programhasbeencommunicated to the Prologsystem,Prolog
canbe posedsomequestionsaboutthe parentrelation.For example,Is Bob a
parent of Pat? This questioncan be communicatedto the Prolog systemby
typinginto the terminal:

?- parent( bob, pat).

Havingfound this as an assertedfact in the program,Prologwill answer:

yes

A further querycan be:

?- parent( liz, pat).

Prolog answers

no

becausethe programdoesnot mention anythingabout Liz being a parentof


Pat. It alsoanswers'no'to the question

?- parent( tom, ben).

because the programhasnot evenheardof the nameBen.


More interestingquestionscan alsobe asked.For example:Who is Liz's
parent?

?- parent(X, liz).

Prolog'sanswerwill not be just 'yes'or'no' thistime.Prologwill tell uswhatis


the (yet unknown) value of X such that the abovestatementis true. So the
AN OVERVIEW OF PROLOG

answerls:

X: tom

The questionWho are Bob's children?can be communicatedto Prolog as:

?- parent(bob, X).

This time thereis morethanjust onepossibleanswer.Prologfirst answerswith


one solution:

X:ann

We may now want to seeother solutions.We can saythat to Prolog(in most


Prolog implementationsby typing a semicolon),and Prolog will find other
answers:

;g - pat

'no' becauseall the


If we requestmore solutionsagain,Prolog will answer
solutionshavebeenexhausted.
Our programcanbe askedan evenbroaderquestion:Who is a parentof
whom?Another formulationof this questionis:

Find X and Y suchthat X is a parentof Y.

in Prologby:
This is expressed

?- parent{ X, Y).

Prolognow findsall the parent-childpairsone afteranother.The solutionswill


be displayedone at a time as long as we tell Prologw€ want more solutions,
until all the solutionshavebeenfound. The answersar€ output as:

X-pam
Y : bob;

X:tom
Y : bob;
X:tom
Y : liz;

We canstopthe streamof solutionsby typing,for example,a periodinsteadof


a semicolon(this dependson the implementationof Prolog).
PROLOG PROGRAMMING FOR ARTIFICIAL INTELLIGENCE

Figure 1.2 The grandparent


relation expressedas a
composition of two parent
relations.

Our exampleprogramcanbe askedstill more complicatedquestionslike:


Who is a grandparentof Jim? As our program does not directly know the
grandparentrelation this query has to be broken down into two steps, as
illustratedby Figure 1.2.

(1) Who is a parentof Jim? Assumethat this is someY.


(2) Who is a parentof Y? Assumethat this is someX.

Sucha composedqueryis written in Prologasa sequenceof two simpleones:

?- parent( Y, jim), parent( X, Y).

The answerwill be:

X:bob
Y-pat

Our composedquerycanbe read:Find suchX and Y that satisfythe following


two requirements:

parent( Y, jim) and parent( X, Y)

If we changethe orderof the two requirementsthe logicalmeaningremainsthe


same:

parent( X, Y) and parent( Y, jim)

We can indeeddo this in our Prologprogramand the query

?- parent( X, Y), parent( Y, jim).

will producethe sameresult.


In a similarway we can ask: Who are Tom's grandchildren?

?- parent( tomnX), parent( X, Y).


AN OVERVIEW OF PROLOG

Prolog'sanswersare:

X:bob
Y : ann;
X:bob
Y-pat

Yet anotherquestioncouldbe: Do Ann and Pat havea commonparent?This


can be expressedagainin two stePs:

(1) Who is a parent,X, of Ann?


(?) Is (this same)X a parentof Pat?

The correspondingquestionto Prologis then:

?- parent( X, ann), parent( X, pat).

The answeris:

X:bob

Our exampleprogramhashelpedto illustratesomeimportantpoints:

o It is easyin Prologto define a relation,such as the parentrelation,by


statingthe n-tuplesof objectsthat satisfythe relation.
o The usercaneasilyquerythe Prologsystemaboutrelationsdefinedin the
program.
o A Prolog programconsistsof clauses.Each clauseterminateswith a full
stop.
o The arguments of relations can (among other things) be: concrete
objects,or constants(suchastom and ann), or generalobjectssuchasX
and Y. Objectsof the first kind in our programarecalledatoms.Objects
of the secondkind are calledvariables.
. Questionsto the systemconsistof one or more goals. A sequenceof
goals,suchas
parent( X, ann), parent( X, pat)
meansthe conjunctionof the goals:
X is a parent of Ann, and
X is a parentof Pat.
The word 'goals' is usedbecauseProlog acceptsquestionsas goalsthat
are to be satisfied.
o An answerto a questioncanbe eitherpositiveor negative,dependingon
PROLOG PROGRAMMING FOR ARTIFICIAL INTELLIGENCE

whetherthe correspondinggoal can be satisfiedor not. In the


caseof a
positive answerwe say that the correspondinggoal was
satisfiableand
that the goalsucceeded.
Otherwisethe gbalwasunsatisfiable anditfailed.
o If severalanswerssatisfythe questionthen Prologwill find as many
of
them as desiredby the user.

Exercises
1.1 Assumingthe parentrelationasdefinedin thissection(seeFigure1.1),
what will be Prolog'sanswersto the folrowingquestions?
(a) parent(jim, X).
(b) parent( X, jim).
(') parent( paffi, X), parent( X, pat).
(d) parent(paffi, X), parent( X, Y), parent( Y, jim).

1.2 Formulatein Prologthe following questionsaboutthe parentrelation:


(a) Who is Pat'sparent?
(b) Does Liz havea child?
(c) Who is Pat'sgrandparent?

1.2 Extendingthe exampleprogramby rules


Our example program can be easily extended in many interesting ways. Let us
first add the information on the sex of the people that occur in the parent
relation. This can be done by simply adding the following facts to our program:

female( pam).
male( tom).
male( bob).
female( liz).
female( pat).
female( ann).
male( jim).

The relations introduced here are male and female. These relations are unary
(or one-place) relations. A binary relation like parent defines a relation
between pairs of objects; on the other hand, unary relations can be used to
declare simple yes/no properties of objects. The first unary clauseabove can be
read: Pam is a female. We could convey the same information declared in the
two unary relations with one binary relation, sex, instead. An alternative piece
AN OVERVIEW OF PROLOG

of programwould then be:

sex( pam, feminine).


sex(tom, masculine).
sex(bob, masculine).

As our next extensionto the program let us introduce the offspring


relation as the inverseof the parent relation. We could define offspring in a
similarway as the parentrelation;that is, by simplyprovidinga list of simple
factsaboutthe offspringrelation,eachfact mentioningonepair of peoplesuch
that one is an offspringof the other. For example:

offspring(liz, tom).

However, the offspring relation can be defined much more elegantly by making
use of the fact that it is the inverse of parent, and that parent has already been
defined. This alternative way can be based on the following logical statement:

For all X and Y,


Y is an offspring of X if
X is a parent of Y.

This formulation is already close to the formalism of Prolog. The correspond-


ing Prolog clause which has the same meaning is:

offspring( Y, X) :- parent( X, Y).

This clause can also be read as:

For all X and Y,


if X is a parent of Y then
Y is an offspring of X.

Prolog clausessuch as

offspring( Y, X) :- parent( X, Y).

are called rules. There is an important difference between facts and rules. A
fact like

parent( tom, liz).

is something that is always, unconditionally, true. On the other hand, rules


specify things that may be true if some condition is satisfied. Therefore we say
that rules have:

o a condition part (the right-hand side of the rule) and


10 PROLOG PROGRAMMING FOR ARTIFICIAL
INTELLIGENCE

o a conclusionpart (the left-handsideof the rule).

The conclusionpart is alsocalledthe headofa clauseand


the conditionpart the
body of a clause.For example:

offspring(y, X) :- parent(X, y).

head body
If the condition parent(X, Y) is true then a logical consequence of this is
offspring( Y, X).
How rules are actually used by Prolog is illustratedby the following
example.Let us ask our programwhetherLiz is an offspringbt rom:

?- offspring(liz, tom).

There is no fact about offspringsin the program,thereforethe only way to


considerthis questionis to applythe rule aboutoffsprings.The rule ii genlral
in the sensethat it is applicableto anyobjectsX andY; thereforeit canalsobe
appliedto suchparticularobjects asliz and tom. To apply the rule to liz and
tom, Y hasto be substitutedwith liz, andX with tom. We savthat the variables
X and Y becomeinstantiated to:

X=tom and Y:liz

After the instantiationwe haveobtaineda specialcaseof our generalrule. The


specialcaseis:

offspring(liz, tom) :- parent( tom, liz).

The conditionpart hasbecome

parent( tom, Iiz)

Now Prologtries to find out whetherthe conditionpart is true. So the initial


goal

offspring(liz, tom)

hasbeen replacedwith the subgoal

parent( tom, liz)

This (new)goalhappensto be trivial asit canbe found asa factin our program.
This meansthat the conclusionpart of the rule is also true, and Prolog will
answerthe questionwith yes.
Let us now add more family relationsto our exampleprogram. The
AN OVERVIEW OF PROLOG 11

9.:'"' o.*"8'
parent I mother
I
€r -.-rB grandparent

Figure 1.3 Definition graphsfor the relationsoffspring,mother and grandparentin


termsof other relations.

specification of the mother relation can be based on the following logical


statement:

For all X and Y.


X is the mother of Y if
X is a parent of Y and
X is a female.

This is translatedinto Prologas the followingrule:

mother( X, Y) :- parent( X, Y), female(X).

A commabetweentwo conditionsindicatesthe conjunctionof the conditions,


meaningthat both conditionshave to be true.
Relations such as parent, offspring and mother can be illustrated by
diagramssuchasthosein Figure1.3.Thesediagramsconformto the following
conventions.Nodesin the graphscorrespondto objects- that is, argumentsof
relations.Arcs betweennodescorrespondto binary (or two-place)relations.
The arcsareorientedso asto point from the first argumentof the relationto the
secondargument.Unary relationsare indicatedin the diagramsby simply
markingthe correspondingobjectswith the nameof the relation.The relations
that are beingdefinedarerepresented by dashedarcs.So eachdiagramshould
beunderstoodasfollows:if relationsshownby solidarcshold, thenthe relation
shownby a dashedarc alsoholds. The grandparentrelation canbe, according
to Figure 1.3, immediatelywritten in Prologas:

grandparent(X, Z) :- parent(X, Y), parent( Y, Z).

At this point it will be usefulto make a commenton the layout of our


programs.Prolog givesus almostfull freedomin choosingthe layout of the
program.So we can insert spacesand new lines as it best suitsour taste.In
generalwe want to makeour programslook niceandtidy, and, aboveall, easy
to read.To this endwe will often chooseto write the headof a clauseand each
12 PROLOG PROGRAMMING FOR ARTIFICIAL INTELLIGENCE

goal of the body on a separateline. When doing this,


we will indent goalsin
order to makethe differencebetweenthe headundth. goalsmore
visible.For
example,the grandparentrule would be, accordingto this convention,
written
as follows:

grandparent(X, Z) :-
parent( X, Y),
parent(Y, Z).

Figure 1.4 illustratesthe sisterrelation:

For any X and Y,


X is a sisterof Y if
(1) both X and Y havethe sameparent,ancl
(2)Xisafemale.

female

Figure 1.4 Defining the sisterrelation.

The graph in Figure L.4 can be translatedinto Prologas:

sister( X, Y)
parent( Z,
parent( Z,
female( X).

Noticethe way in whichthe requirement'bothX and Y havethe sameparent'


hasbeenexpressed. The followinglogicalformulationwasused:someZ must
be a parentof X, andthissameZ mustbe a parentof Y. An alternative,but less
elegantwaywouldbeto say:Z1.isa parentof X, andz2is a parentof y, andZt
is equalto 22.
We can now

sister(ann, pat).

The answerwill be as expected(seeFigure 1.1). Thereforewe might


AN OVERVIEW OF PROLOG 13

concludethat the sisterrelation, as defined,works correctly'There is, how-


ever, a rather subtle flaw in our program which is revealedif we ask the
questionWho is Pat'ssister?:

?- sister(X, pat).

Prologwill find two answers,one of which may come as a surprise:

X : ann;
X-pat U:/BR
So, Pat is a sisterto herself?!This is probablynot what we had in mind when
defining the sister relation. However, accordingto our rule about sisters
Prolog's answeris perfectly logical. Our rule about sistersdoesnot mention
that X and Y must not be the sameif X is to be a sisterof Y. As this is not
requiredProlog(rightfully)assumes that X andY canbe the same,andwill asa
consequence find that any femalewho hasa parentis a sisterof herself.
To correctour rule about sisterswe haveto add that X and Y must be
different.We will seein laterchaptershow thiscanbe donein severalways,but
for the moment we will assumethat a relation different is alreadyknown to
Prolog, and that

different( X, Y)

is satisfiedif and only if X and Y are not equal. An improvedrule for the sister
relationcan then be:

sister(X, Y) :-
parent( Z, X),
parent( Z, Y),
female( X),
different( X, Y).

Someimportantpointsof this sectionare:

o Prologprogramscan be extendedby simplyaddingnew clauses.


o Prolog clausesare of three types:facts, rules and questions.
O Factsdeclarethingsthat are always,unconditionallytrue.
o Rulesdeclarethingsthat are true dependingon a givencondition.
o By meansof questionsthe usercanaskthe programwhat thingsaretrue.
a Prologclausesconsistof the headandthe body.Thebodyis a list of"goals
separatedby commas.Commasare understoodasconjunctions.
Factsare clausesthat have the empty body. Questionsonly have the
body. Ruleshavethe headand the (non-empty)body.
t4 PROLOG PROGRAMMING FOR ARTIFICIAL INTELLIGENCE

In the courseof computation,a variablecan be substitutedby another


object. we saythat a variablebecomesinstantiated.
Variablesare assumedto be universallyquantifiedand are read as .for
all'. Alternativereadingsare,however,possiblefor variablesthat appear
only in the body. For example
hasachild(X) :- parent(X, y).
can be read in two ways:
(u) For all X and Y,
if X is a parentof Y then
X hasa child.
(b) For all X,
X hasa child if
there is someY suchthat X is a parentof y.

Exercises
1.3 Translatethe followingstatementsinto prolog rules:
(a) Everybody who has a child is happy (introduce a one-argument
relationhappy).
(b) For all X, if X has a child who hasa sisterthen X hastwo children
(introduce new relation hastwochildren).

1.4 Define the relation grandchildusingthe parentrelation. Hint: It wilt be


similarto the grandparentrelation (seeFigure 1.3).

1.5 Definethe relationaunt( X, Y) in termsof the relationsparentandsister.


As an aid you can first draw a diagramin the styleof Figure 1.3 for the
aunt relation.

1.3 A recursiverule definition


Let us add one more relation to our family program, the predecessorrelation.
This relation will be defined in terms of the parent relation. The whole
definition can be expressedwith two rules. The first rule will define the direct
(immediate) predecessorsand the second rule the indirect predecessors.We
say that some X is an indirect predecessorof some Z if. there is a parentship
chain of people between X and Z, as illustrated in Figure 1.5 . In our example of
Figure 1.1, Tom is a direct predecessorof Liz and an indirect predecessorof
Pat.

You might also like