syntax and meaning of prolog programs

38
Syntax and Meaning f Prolog Programs This chapter gives a systematic reatment of the syntax and semantics f basic concepts f Piolog, und ntroduces tructured data objects. The topics ncluded are'. o simple data objects atoms, numbers, variables) . structured objects . matching as he fundamental operation on objects o declarative or non-procedural) meaning of a program o procedural meaning of a Program . relation between he declarative and procedural meanings f a program o altering he procedural meaning by reordering clauses nd goals Most of these topics have already been reviewed n Chapter L- Here th e treatment will become nore ormal and detailed. 2.1 Data objects Figure 2.L shows a classification f data objects n Prolog. The Prolog system reiognizes he type of an object in the program by its syntactic orm. This is portibl. because he syntax of Prolog specifies ifferent orms or each ype of const ,/ data objects / \ ,/ \ simple bjects structures , / \ / \ ants variables \

Upload: luis-lopez

Post on 03-Jun-2018

246 views

Category:

Documents


0 download

TRANSCRIPT

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 1/37

SyntaxandMeaning f

Prolog

Programs

This

chapter

givesa

systematic

reatment

of

the

syntax

and

semantics

f

basic

concepts f Piolog, und ntroduces tructured

data

objects.

The

topics

ncluded

are'.

o

simple

data

objects

atoms,

numbers,

variables)

.

structured

objects

.

matching

as

he

fundamental

operation

on

objects

o

declarative

or

non-procedural)

meaning

of

a

program

o

procedural

meaning

of

a

Program

. relationbetween he declarativeandproceduralmeanings f a program

o

altering

he

procedural

meaning

by

reordering

clauses

nd

goals

Most

of

these

topics

have

already

been

reviewed

n

Chapter

L-

Here

the

treatment

will become

nore

ormal

and

detailed.

2.1 Dataobjects

Figure

2.L shows

a classification

f

data objects

n Prolog.

The

Prolog

system

reiognizes

he type

of an

object

in

the

program

by its

syntactic

orm.

This

is

portibl. becausehe

syntax

of Prolog

specifies

ifferent

orms

or each

ype

of

const

,/

atoms

dataobjects

/ \

, / \

simple

bjects

structures

, / \

/ \

ants

variables

\

numbers

Figure

2.1 Data objects

n

Prolog.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 2/37

28

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

data

objects.

We

have

already

seen

a

method

or

distinguishing

etween

atoms

and

variables

n

Chapter

1:

variables

start

with

upper-case

etters

whereas

atoms

start

with

lower-case

etters.

No

additional

niormation

(such

as

data-

type declaration)has o be communicatedo Prolog n order to i".ognize

the

type

of

an

object.

2.1.1

Atoms

and

numbers

In

Chapter

L

we

have

seen

some

simple

examples

f

atoms

and

variables.

n

general,

however,

hey

can

ake

more

complicaied

orms-that

is,

strings

of

the

following

characters:

o

upper-case

etters

A, B,

...,

Z

o

lower-case

etters

8,

b, ...,

z

o

d ig i t s

,

L ,2 ,

. . , 9

.

special

haracters

uch

as +

-

*

I

<)

:

: .

& _-

\.

Atoms

can

be constructed

n

three ways:

(1)

Strings

of

letters,

digits

and

he

underscore

haracter,

-',

starting

with

a

lower-case

etter:

anna

nil

,Os

,L25

x-25A8

x_

x-y

alpha-beta-procedure

miss_Jones

sarahjones

(2)

Strings

of special

characters:

When

using

atoms

of

this form,

some

care is necessary

ecause

ome

strings

of special

characters

already

have a

predefined

meaning;

an

example

s' :- ' .

(3)

Strings

f characters

nclosed

n

singlequotes.

This s

useful f we want,

for

example,

o have

an

atom

hat

startswith

a capital etter.

By enclosing

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 3/37

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 4/37

30 PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

Shoppinglist

r23

23

When

a variable

appears

n

a clause

nce

only,

we

do

not

have

o invent

a

name

or

it.

We

can

use

he

so-called'anonymous'variable,

hich

s

written

as

a

single

underscore

haracter.

For

example,

et

us consider

he following

rule:

hasachild(

X)

:-

parent(

X,

y).

This

rule

says:

oi

all

X, X

has

a child

f

X is a parent

of some

Y.

We

aredefining

the

property

hasachild

which,

as t

is

meant

here,does

not depend

on

the nurni

of thechild.Thus, his saproperplace n which o

usean anonymous

ariable.

The

clause

above

can thus

be

rewritten:

hasachild(

X)

paren(

X, -).

feacntime

a

single

underscore

haracter

occurs

n a

clause t

represents

new

I

anonymous

ariable.

For

example,

we

can say

hat there

s

somebody

who

has

a

child if

there

are

two objects

such hat one

is

a

parent

of

the

other:

somebody-has-child :- parent( _, _).

This

is equivalent

somebodyJras-child

parent(

X, Y).

But

this is,

of

course,quite

different

from:

somebody-has-child parent(X, X).

If

the anonymous

ariable

appears n

a

question

clause

hen

its value

s

not

output

when

Prolog answers

he

question.

f

we

are nterested

n

people

who

have

children,

but not in

the

names

of the

children, then

we can simply

ask:

?-

parent(

X,

The lexical

scope

of

variable

names s

one

clause.This

means hat, for

example, f the nameX15 occurs n two clauses,hen t signifies wo different

variables.

But

eachoccurrence

f X15 within

the

sameclause

means he same

variable,

The

situation s different

for constants: he sameatom alwaysmeans

the

sameobject

in any clause

that is, throughout he whole

program.

2.1.3

Structures

Structuredobjects

or

simpl

structures) re

objects hat haveseveral ompo-

nents.

The

components

hemselves

an,

in

turn,

be structures.

For example,

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 5/37

SYNTAX

AND

MEANTNG

OF

PROLOG

PROGRAMS

31

date(

I

I

I

functor

\/

arguments

(b)

Figure

.2 Date

s

an

example f a

structured

bject:

a)

as

t is represented

s

a tree;

(b)

as t

is

written n

Prolog.

thedatecanbeviewedasa structurewith threecomponents: ay,month,year.

Although

composed

of several

components,

structures

are

treated

in

the

program as single

objects.

n order

to combine

he components

nto a single

object

we have to choose

afunctor.

A suitable

unctor

for our example

s date.

Then

the

date 1st May

1,983 an be

written as:

date(

t, may, 1983)

(see

Figure2.2).

All the componentsn this exampleare constants two integersand one

atom).

Components

an

also

be variablesor other

structures.

Any

day n May

can be

represented y the structure:

date(

Duy, may,

1983)

Note that Day is a

variable

and can

be nstantiated o

any

object

at

some

ater

point

in

the

execution.

This method or datastructuring s simpleandpowerful. It is one of the

reasons

why

Prolog

s

so naturally

applied

o

problems

hat

involve symbolic

manipulation.

Syntactically, ll

data objects n Prolog

are

erms.For example,

may

and

date(1, may, 1983)

are terms.

All structuredobjects

can

be

pictured

as

trees

(see

Figure2,.2

or an

example).

The

root

of

the

tree s the

functor,

and

he offsprings

of

the

root

are

the components.

f a component

s alsoa structure hen t is a subtree

of the

tree

that

corresponds

o the

whole

structured

object.

Our

next

example

will

show

how

structures

an

be

used o represent ome

simple

geometric

bjects

see

Figure2.3).

A

point n two-dimensionalpace

s

l9E3

l,mayr

1983)

I

may

(a)

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 6/37

32

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

P2= (2,3)

t 2

3 4 5 6 7 8

Some

simplegeometric

objects.

igure

2.3

defined

by its

two

coordinates;

a line

segment

s

defined

by two

points;

and a

triangle

can

be

defined

by three

points.

Let

us choose

he

following

functors:

point

for

points,

seg for line

segments,

nd

triangle for triangles.

Then the objects n Figure 2.3 canbe representedby the following Prolog

terms:

p1

:

point(l,l)

p2:

point(2,3)

S

:

seg(Pl,

P2):

seg(

point(l,1), point(2,3))

T

:

triangle(

point(4,Z),

point(6,4),point(7,l)

)

p1

=

proint

/ \

(4.2)

(7,1)

S = s e g

/ \

, / \

I

point

point

/ \

/ \

/ \

/

\

l 1 2 3

T

=

triangle

-/ l\

. / l \

point

point point

/ \

/ \

/ \

4 2 6 4 7 1

Figure

2.4 Tree

representation

f

the objects n

Figure 2.3.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 7/37

SYNTAX

AND

MEANING

OF

PROLOG

PROGRAMS

33

The

corresponding

ree

representation

f

these

objects

s shown

n

Figure

2.4.

In

general,

he

functor

at

the root

of

the tree

is called

the

principal

unctor

of.

the term.

If

in

the

same

program

we also

had

points in three-dimensional

pace

then

we could

use another

unctor,

point3,

say,

or

their

representation:

point3( X, Y, Z)

We can, however,

use he

same

name,

point,

for

points

n

both

two and

three

dimensions,

nd write for

example:

point(X1, Y1) and point(X,Y, Z)

If

the samenameappears

n the

program

n two different

oles,

as s the case

or

point

above, he Prolog

system

will

recognize

he

differenceby

the number

of

arguments,

nd

will

interpret

this nameas wo functors:one

of

them

with

two

argumentsand

the other one with

three

arguments.

This is so

because ach

functor is defined by two things:

(1)

the name, whose

syntax

s that of atoms;

(2)

the arity

-

that

is, the

number

of arguments.

As already

explained,

all

structuredobjects

n

Prolog

are trees, repre-

sented

n the

program

by

terms.

We will study wo more exampleso illustrate

how naturally

complicateddata objectscan

be represented y

Prolog terms.

Figure 2.5 shows the tree

structure that corresponds o

the

arithmetic

expression

( a + b ) * ( c - 5 )

According

o

the

syntax

of

terrns ntroduced

so

ar this canbe written, using

he

symbols

*', '*'

and

-'

as unctors,as

ollows:

*(

+(

a, b),

-(

c, 5)

)

Figure 2.5

A tree

structure that

corresponds

( a + b ) * ( c - 5 ) .

\

/

./

+

\

b

/

\

5

to

the

arithmetic expression

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 8/37

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

This

is of

course

a legal

Prolog

term;

but

this is

not

the form

that

we

would

normally

ike

to

have.

We

would

normally prefer

the

usual,

nfix

notation

as

used n

mathematics.

n fact,

Prolog

alsoallows

us to

use

he

infix

notation

so

thatthe symbols*' ,'*' and -' arewrittenas nfix operators.Detailsof how

the programmer

can

define

his or

her own

operators

will

be

discussed

n

Chapter

3.

As the

last

example

we

consider

some

simple

electric

circuits

shown n

Figure

2.6.

The

right-hand

side

of

the

figure

shows he

tree

representation

f

these

circuits.

The

atoms tl,

12, 13

and 14

are he namesof

the resistors.

The

r1 12

+

(a)

Figure

2.6

Somesimpleelectric

circuitsand heir tree

representations:

a)

sequential

composition f resistors

1

and 12;

b)

parallel

composition

f two resistors;

c)

parallel

compositionof three resistors;

d)

parallel

compositionof

r1 and

anothercircuit.

\

12

seq

/

I

par

/ \

/ \

rl 12

par

/ \

/ \

rl

par

/ \

/ \

12 r3

per

/ \

/ \

rl

seq

/ \

/ \

per r4

/ \

/ \

12

r3

r1

l-1.---,-l

H

(b)

r1

r:l

l r2 l

- , -7

t-.,'LJ

(c)

H

r l

Fr

I ' r l

#

(d)

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 9/37

SYNTAX

AND

MEANING

OF

PROLOG

PROGRAMS

35

functors

par and

seq

denote

the

parallel

and

the

sequential

compositions

of

resistors

espectively.

The

corresponding

Prolog

terms

are:

seq(

11,

12)

par(

r1,

12)

par( 11,

Par(

r2,

13)

)

par( r1, seq(

Par(

12,

r3)'

14)

)

Exercises

2.1 Which

of the

following

are syntactically

orrect

Prolog

objects?

What

kinds

of object

are

they

(atom,

number,

variable,

structure)?

(a) Diana

(b)

diana

(c)

'Diana'

(d)

-diana

(e)

'Diana

goes

souttrl

(f)

goes(

diana, south)

(e)

as

(h)

s(

x, Y)

(i)

*( north, west)

(j)

three(

Black(

Cats)

)

2.2

Suggest

representation

or rectangles, quares

nd circles

asstructured

Prolog

objects. Use

an approach similar

to that

in Figure

2.4.

For

example,a rectangle anbe represented y four points(or maybe hree

points only). Write

some example

erms

that

represent

some

concrete

objects

of

these

ypes

using he

suggestedepresentation.

2.2 Matching

In the previoussectionwe have seenhow terms can be usedto represent

complex data objects.

The most

important

operation

on terms

s matching.

Matching alone can

produce

some nterestingcomputation.

Given

two

terms,

we

say hat

they

match f.:

(1)

they are

dentical,or

(2)

the

variables

n

both

terms can be instantiated

o objects

n such a

way

that

after the

substitution

of variables y these

objects he

termsbecome

identical.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 10/37

36

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

For

example,

he

terms

date(

D,

M, 19g3)

nd

date(

Dl,

may,

yl)

match.

one

instantiation

hat

makes

both

terms

dentical

s:

. D is instantiatedo Dl

o

M is

instantiated

o

may

.

Y1

is

instantiated

o

1983

This

instantiation

s

more

compactly

written

in

the familiar

form

in

which

Prolog

outputs

results:

D : D 1

M : m a y

Yl

:

1983

on the

other

hand,

the terms

date(

D, M,

l9s3) and

date(

Dl, Ml,

1444)

o

not

match,

nor

do the

terms

date(

X,

y,

Z)

and

point(

X,

y,

Z).

Matching

s a

process

hat

takes

as nput

two

terms

and

checks

whether

they

match.

f

the terms

do

not match

we

say hat

this

process/ails.

f

they do

match

hen

the process

ucceeds

nd it also

nstantiates

he variables

n both

terms o

such

values hat the termsbecome dentical.

Let

us consider

again

he

matching

of

the two dates.

The request

or this

operation

can

be communicated

o the Prolog

systemby

the following

ques-

tion,

using

he

operator

:':

?-

date(

D,

M, 1983)

=

date( Dl,

may, Y1).

We

havealready

mentioned

he instantiation

D

=

D1, $t

:

hay, Yl

=

1983,

which

achieves

he match.

There

are, however,

other instantiations

hat

also

makeboth terms dentical.Two of them are as ollows:

D = 1

D l

: 1

M: may

Yl

:

1983

D

:

third

D1

:

third

. M : m iy

Yl

:

1983

These wo instantiations

re

said

o

be

less eneral

han

the first one

because

they constrain

he

values

of

the variables

D

and

D1 stronger

han necessary.

For making

both

terms n our

example dentical, t is only

mportant hat

D and

D1 have the

same

value,

although

this value

can be anything.

Matching n

Prolog always

esults

n the

most

general

nstantiation. This

is

the

instantiation

that commits

he

variables

o

the

east

possible

xtent,

hus

eaving he

greatest

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 11/37

SYNTAX

AND

MEANING

OF

PROLOG

PROGRAMS

37

possible

reedom

or

further

instantiations

f further

matching

s

required.

As

an

example

consider

he following

question:

?- date(

D,

M, 1983) : date{Dl, maY,Y1),

date(

D,

M, 1983)

:

date(

15' M'

Y).

To

satisfy

he first

goal,

Prolog

nstantiates

he

variables

as

ollows:

D : D l

M: may

Yl

:

1983

After

having

satisfied

he second

oal,

he instantiation

becomes

more

specific

as

follows:

D = 1 5

D l : 1 5

M: may

Yl

:

1983

Y: 1983

This examplealso llustrates

hat variables, uring he

execution f

consecutive

goals,

ypicatly

become

nstantiated o increasingly

more

specific

values.

The

general

ules to decidewhether

two terms,

S

and T, match

are as

follows:

(]*)

ffi

(3)i

The last

of these

ules

can

be

visualized

y

considering

he tree

represen-

tationof terms,

as

n the

example

f

Figure2.7.The matching

rocess

tartsat

the

root

(the

principal

unctors).

As

both

functorsmatch,

he

process

roceeds

to

the argumentswhere

matching of the

pairs

of

corresponding

arguments

occurs.So the whole matching

process

an be thought

of as consisting

f the

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 12/37

38

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

triangle

triangle

Figure

2.7 Matching riangl{

poin(l,l),

A,

point(2,3)

:

triangl{ X,

point(4,Y),

point(Z,Z)

.

following

sequence

f

(simpler)

matching

operations:

triangle

:

triangle,

poin(l,l)

:

X,

A

-

point(4,Y),

point(2,3;

:

point(z,Z).

The whole matching

process

succeeds

because

all

the

matchings

n

the

sequence ucceed.

he

resulting nstantiation

s:

;5

:

point(l,l)

4

=

point(4,Y)

Z : 3

The

following example

will

illustrate

how matching

alone

canbe

used

or

interesting computation.

Let

us return

to

the simple

geometric

objects

of

Figure 2.4,

and

define

a

piece

of

program

for

recognizing

horizontal

and

vertical line segments. Vertical' is a property of segments,so it can be

formalized n

Prolog as a unary

relation.

Figure

2.8

helps

to

formulate

this

relation. A segment

s

vertical

f

the x-coordinates

f

its end-points

are

equal,

otherwise here

s no other

restriction

on

the segment.

The

property'horizon-

tal' is similarly

formulated,

with

only

x

and

y

interchanged.

The following

program,

consisting

of

two facts,

does

he

job:

vertical(

seg(

point(X,Y),

point(X'Yl)

).

horizontal(seg(point(X,Y), pornt(Xl,Y) ).

./point

/ \

l l

./

x

\

point

/ \

2 3

\

point

/ \

2 Z

point

/ \

4 Y

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 13/37

SYNTAX

AND

MEANING

OF

PROLOG

PROGRAMS

39

The

following

conversation

s

possible

with

this

program:

?-

vertical(

seg(

point(l,l),

point(l,2)

) ).

yes

?-

vertical(

seg(

point(l,l),

point(2'Y)

) ).

no

?-

horizontal(

seg(

point(l,1),

point(2'Y)

)

).

Y : l

The first

question

was

answered'yes'because

he

goal

n the

question

matched

oneof the

facts

n the

program.

For

the second

uestion

no

match

was

possible.

In

the

third

question,Y

was forced

to become

1

by matching

he

fact about

horizontal

segments.

point(X,Yl)

Figure

.8 Illustration

f

vertical ndhorizontaline

segments.

A more

general question

to

the

program

is: Are there

any

vertical

segmentshat start

at

the

point (2,3)?

?-

vertical(

seg(

point(2,3),

P)

).

p

=

point(Z,y)

This answermeans:

Yes, any segment hat

ends

at any

point

(2,Y),

which

means

anywhereon the

vertical

line x

:

2. lt

should

be noted

that Prolog's

actualanswerwould

probably

not look asneat

asabove,

but

(depending

n the

Prolog

mplementation sed)

somethingike this:

p

:

point(2,_136)

This

s,

however,only a cosmetic ifference.

Here

-136 s

a

variable hat has

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 14/37

40

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

not

been

nstantiated.

136

s,

of course,

legalvariable

name

hat

the

system

has

constructed

uring

he

execution.

The

system

as

o

generate

ew

names

n

order

to rename

he

user'svariables

n

the program.

This

is necessary

or two

reasons: irst, becausehe samename n different clauses ignifiesdifferent

variables,

and

second,

n

successive

pplications

f

the

same

Clause,

ts

,copy'

with

a new

set

of variables

s

used

each ime.

Another

interesting

question

o our

program

s:

Is

there a

segment

hat s

both

vertical

and

horizontal?

?-

vertical(

S), horizontal(

S).

S

:

seg(

point(X,Y),

point(X,Y)

)

This

answer

y

Prolog

says:Yes,

anysegment

hat

s

degenerated

o a

point

has

the property

of

beingvertical

and horizontal

at

the

same

ime.

The answerwas,

again,

derived

simply

by

matching. As

before, some

internally

generated

names

may

appear

n the answer,

nstead

of the

variable

namesX and

Y.

Exercises

2.3

Will

the

following

matching

operations

succeed

r

fail? If they

succeed,

what are the resulting nstantiations f variables?

(a) point(

A, B)

:

point(

l,

2)

(b)

point(

A, B)

:

point(

X, Y,

Z)

(c) plus(

2,2)

--

4

(d)

+( 2'

D) +(

8,2)

(e)

triangle(

point(-l,O),

P2,

P3):

triangle(

Pl,

point(l,0),

point(O,Y)

The resulting

nstantiationdefinesa family

of

triangles.

How would

you describe his family?

2.4

Using

he

representation

or line segments s

describedn this

section,

write

a term

that

represents

ny vertical ine segmentat

x

--

5.

2.5

Assume

that

a

rectangle is

represented by the

term

rectangle(

Pl, P2, P3,

P4) where he

P's are he vertices

of the

rectangle

positively

ordered.

Define

the relation

regular(R)

which is

true if R is a rectanglewhose

sides

are vertical and horizontal.

2.3

Declarativemeaning

of

Prolog

programs

We

havealready

seen

n Chapter 1 that Prolog

programs

an

be understood

n

two ways: declaratively

and

procedurally.

n this

and the next sectionwe

will

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 15/37

SYNTAX

AND

MEANING

OF PROLOG

PROGRAMS

41

consider

a more

formal

definition

of the

declarative

and

procedural

meanings

of

programs n basic

Prolog.

But first

et us ook

at

the

difference

etween

hese

two meanings

gain.

Considera clause

P : -

Q , R .

where

P,

Q

and R

have the syntax

of terms. Some

alternative

declarative

readings

of this clause

are:

P

is true

if

Q

and R are

true.

From

Q

and R follows

P.

Two

alternativeprocedural

eadingsof this

clause

are:

To

solve

problem

P,

first

solve the subproblem

O

and

then the

subproblem

R.

To

satisfyP

first

satisfy

Q

and

then

R.

Thus the difference

between

he declarative

eadingsand

the

procedural

ones

is that the atter

do not only define

he

ogical

elationsbetween

he headof

the

clauseand

the

goals

n

the

body, but also

the

order

in which

the

goals

are

processed.

Let

us now

formahze

he declarative

meaning.

The

declarative

meaning

of

programs

determineswhether

a

givengoal

s

true, and if

so, for what values

of

variables

t is true.

To

precisely

define

the

declarativemeaning

we need

o introduce

he conceptof instanceof.a clause.

An instance f a clauseC is theclauseC with eachof its variables ubstituted y

some erm.

A varianr

of a clause

C

is such

an instance

of

the clauseC where

each

variable

s

substituted

y anothervariable.For

example,consider he

clause:

hasachild(

X)

:-

parent(

X, Y).

Two

variants

of this clause

are:

hasachild(

A)

:-

parent(

A, B).

hasachild(

Xl) :-

parent(

Xl,

X2).

Instances f

this

clauseare:

hasachild(

peter)

hasachild(

barry)

parent( peter,

Z).

parent(

barry,

small(caroline)

.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 16/37

42

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

Given

a

program

and

a

goal

G, the

declarative

P : -

Q ; R '

is

read:

P is

true

f

Q

is true

or

R is true. The

meaning

f

this clauses

thus he

same

as he meaning

of the

following

two

clausesogether:

P: -4 .

P : - R .

The

commabinds

stronger

han

the semicolon.

So the

clause

P : -

Q , R ; S , T , U .

is

understood

s

P : -

( Q , R ) ; ( S , T , U ) .

and means he

sameas he

clauses:

P : - Q , R .

P : - S , T , U .

Exercises

2.6

Considerhe

ollowing

rogram:

f( 1,

one).

f( s(1),

two).

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 17/37

SYT.ITAXAND MEANING

OF PROLOG

PROGRAMS

43

f( s((1)),

three).

f(

s(s(s(X))),

N) :-

f(

x, N).

How

will

Prolog

answer

the following

questions?

Whenever

several

answers

re

possible,

give at least

wo.

(a)

?-

f(

s(1),

A).

(b)

?-

f(

s(s(l),

two).

(c)

?-

f(

s(s(s(s(s(s(1)))))),

).

(d)

?-

(

D, three).

2.7

The following

program says

hat

two

people are

relatives f

(a)

one

is a

predecessor

f the other,

or

(b)

they

have a

common

predecessor, r

(c)

they

have

a

common

successor:

relatives(

X,

Y) :-

predecesso(X, Y).

relatives(

X,

Y) :-

predecessor( , X).

relatives(

X,

Y)

:-

predecessor( , X),

predecessor(2,Y).

relatives(X,

Y)

:-

predecessor(

,

Z),

predecessor(Y,

).

Can you shorten his program by using he semicolonnotation?

2.8

Rewrite the following

program

without using

he

semicolon

notation.

translate(

Number,

Word)

:-

Number

:

1,

Word

:

one;

Number

:

2,

Word

:

two;

Number

:

3, Word

:

three.

2.4

Proceduralmeaning

The

procedural

meaningspecifies

howProlog

answers

uestions.

o answer

a

question means o try

to

satisfy

a list

of

goals.

They

can be satisfied

f

the

variables

hat

occur

n

the

goalscan

be

nstantiated

n

such

a way

hat the

goals

logically

ollow from the

program.

Thus

he

proceduralmeaning

of Prolog

s a

procedure

or executing

a list

of

goalswith respect

o

a

given

program.

To

'execute

goals'

means:

ry to

satisfy

hem.

Vo

X and

Y have

a common

Predecessor

%o

X and

Y

have a

common

successor

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 18/37

program

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

I}.ITELLIGENCE

success/failure

ndicator

instantiation

f variables

Figure

2.9

InpuVoutput

iew

of the

procedure

hat

executes list

of

goals.

Let

us call

this

procedure

execute.

As shown n Figure2.9,

the inputs o

and

the

outputs

rom

this

procedure

are:

input: a program

and a

goal

list

output:

a successifailure

ndicator

and an instantiation

of variables

The

meaning

of the two

output

results

s as ollows:

(1)

The

success/failure

ndicator

s

'yes'

if the

goals

are

satisfiableand

'no'

otherwise.

We say

that

'yes'

signals

a successfulermination

and

'no'

a

failure.

(2)

An

instantiation

of

variables

s only

produced

n the

caseof

a successful

termination;

n the

case

of failure

there

s

no instantiation.

In

Chapter

L, we

have n

effect alreadydiscussed

nformally

what

pro-

cedure

execute

does,

under the

heading

How

Prolog

answers

questions?'.

What

follows

in the rest

of this

section

s

just

a more formal

and

systematic

description

of

this

process,

and

can

be skippedwithout

seriously

affecting he

understanding

f

the

rest

of

the

book.

Particularoperations n the goalexecutionprocess re illustratedby the

example n Figure

2.L0.It

may

be helpful o studyFigure

2.l0before

reading

the

following

general

description.

PROGRAM

big( bear).

big( elephant).

smal( cat).

brown(

bear).

black(

cat).

gray(

elephant).

dark( Z) :-

black( Z).

dark(

Z) :-

brown( Z).

Vo Clause

I

Vo Clause

2

Vo Clause 3

Vo Clause

4

Vo Clause

5

Vo Clause

6

Vo Clause

7:

Anything black

is dark

Vo Clause8: Anything

brown is dark

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 19/37

(1)

(2)

SYNTAX AND MEANING OF PROLOG PROGRAMS

45

QUESTION

?- dark( X),

big( X).

EXECUTION TRACE

%

Who is dark

and big?

Initial

goal

list: dark(

X),

big(

X).

Scan

he

program

rom top

to bottom

looking for

a clausewhosehead

matches

he

first

goal

dark(

X).

Clause

7

found:

dark( Z)

:-

black(

Z).

Replace he first

goal

by the instantiatedbody

of

clause

7,

givinga new

goal

ist.

black(

X), big( X)

(3)

Scan the

program

to

find

a match with

black(

X). Clause

5 found:

black( cat). This

clause

has no body,

so the

goal

list,

properly

instanti-

ated,

shrinks o:

big( cat)

(4)

Scan he

program

for the

goal

big( cat).

No clause ound. Therefore

backtrack

o step

3)

and undo he nstantiationX:

cat.

Now the

goal

ist

is again:

black(

X), big( X)

Continue

scanning the

program

below clause 5.

No

clause

found.

Therefore backtrack o step

(2)

and continue

scanning

below

clause7.

Clause8 is found:

dark(

Z) :-

brown( Z).

Replace

he

first goal n

the

goal

ist by

brown(

X),

giving:

brown( X),

big( X)

(5)

Scan he program

o

match

brown( X), finding

brown( bear).This clause

hasno body,

so

the

goal

ist shrinks o:

big( bear)

(6)

Scan he program

and ind

clause

ig(

bear).

t

has

no body

so

he

goal

ist

shrinks

o

empty.

This

indicates

successfulermination,

and the corre-

sponding

ariable

nstantiation

s:

X

=

bear

Figure

2.10

An

example

o illustrate

the

procedural

meaning

of

Prolog:

a sample

race

of the procedureexecute.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 20/37

46 PROLOG

PROGRAMMING

FOR

ARTIFICIAL INTELLIGENCE

To execute

a

list

of

goals

G l ,

G 2 , . . . ,

G m

the

procedure

execute

oes

he following:

t*#ffi 'ff,ffii'{ ffi' '; e * *in't

*l,, lffiffi,.(r.wffiffi ffi ,ffi#,iffimej,,ffi #,#*,'i

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 21/37

SYNTAX

AND

MEANING OF PROLOG PROGRAMS 47

This

procedure

s

more

compactly

written

in a Pascallike

notation

in

Figure

2.7r.

Several

additiondl

remarks

are in

order here regarding the

procedure

execute spresented. irst, t wasnot explicitlydescribed ow the final result-

ing nstantiation

f variables

s

produced.

t

is

the

nstantiation

S

which

ed to a

successfulermination,

and

waspossibly

urther refinedby additional nstan-

tiations

that were

done in

the

nested ecursive

calls o execute.

Whenever

a recursive

call to

execute ails.

the execution returns to

SCANNING,

continuing

at

the

program

clause

C

that

had been last used

before.

As the application

f

the

clause

C did not lead o

a successfulermina-

tion Prolog

has

to try

an alternative

clause

to

proceed.

What

effectively

happenss that Prologabandonshis whole part of the unsuccessfulxecution

and

backtracks

o the

point

(clause

C)

where

his failed branch

of the execution

was

started.

When he

procedure

acktracks

o a certain

point,

all

the variable

instantiations

hat were

done after

that

point

are undone.This ensures hat

Prolog

systematically

xamines

all the

possible

alternative

paths

of execution

until one is

found that

eventually

succeeds, r until all of them have been

shown o fail.

We

have already

seen hat

even after a

successfulermination the

user

can orce

he system o

backtrack o

search or more

solutions.

n our descrip-

tion of executehis detail was eft out.

Of course, n

actual mplementations

f Prolog,

severalother refine-

mentshave

o be added

o execute.One

of them is to reduce he

amount

of

procedure

execute

(Program.,

GoalList,

Success)

;

Input

arguments:

Progranr:

list

of

clauses

GoalLisl: list of goals

Output argument:

Success:

ruth value

Success

ill

become

true

if

GoalLisf is

true

with

respect

to Progrom

Local variables:

Goal:

goal

OtherGoals:

list of goals

Satisfied:

truth value

MatchOK:

truth value

Instant:

instantiation

of

variables

H, ,H ' , 81 , BI ' , . . . , Bn, Bn ' : goa ls

Auxil iary

functions:

empty(L):

returns

true if

L is

the

empty

list

head(L):

returns

the

first

element

of

list

L

tail(L):

returns

the

rest

of L

oppend(Ll

,L2):

appends

ist

L2 at

the

end

of

list

L1

match(Tl

,T2,MatchoK,Instant):

tr ies

to

match

terms

T1 and T2:

if

succeeds

hen

MatchOK

is

true

and

Instant

is

the corresponding

instantiation

of

variables

substitute(lnstant,Goals)

substitutes

variables

in

Goals

according

to instantiation

Instant

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 22/37

48

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

begin

if

empty(GoalList)

then Succes,s

_ true

else

begin

Goal ::

head(GoalList);

OtherGoals

:

-

tail(GoalLisr)

;

Satisfied

:

-

false;

while

not

Satisfied

and

"

more clauses

n

program"

do

begin

Let

next

clause

n

Program

be

H : - B I

, B n .

Construct

a variant

of

this clause

H '

: - 87 '

. . . , ,

n '

match

G

oal,H',

M

atchO

K,Ins ant)

if

MatchOK

then

begin

NewGoals

-

append(fB] ' , . . . ,8n' f ,OtherGoals);

NewGoals

:

-

substitute(Instant,NewGoalr)

execute(Progrem

N

ewG

oals

Satisfied)

end

end;

Success

-

Satisfied

end

end;

Figure

.ll

Executing

rolog

oals.

scanninghroughthe programclauseso improveefficiency.So a practical

Prolog

mplementation

ill

not

scan

hrough

all the

clauses

f

the

program,

but

will

only consider

he

clauses

bout

he relation n

the

current

goal.

Exercise

2.9

Consider

he

program

n

Figure2.10

and simulate,

n the style

of Figure

2.10,Prolog's xecution f thequestion:

?-

big( X),

dark( X).

Compare

our

execution

race

with that of Figure

2.10when

he

question

wasessentially

he

same,but

with the

goals

n the

order:

?- dark(

X), big( X).

In which

of

the two cases

oesProloshave

o do more

work before he

answer s

found?

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 23/37

SYNTAX

AND

MEANING

OF

PROLOGPROGRAMS

2.5

Example:

monkey

and

banana

The

monkey

and

banana

roblem

s oftenusedasa simpleexample f problem

solving.

our Prologprogram

or thisproblem

will

showhow he mechanisms

f

matching

and backtracking

anbe

used n

suchexercises.We

will develop he

program

n the

non-procedural

ay,

and henstudy

ts

procedural

ehaviour n

detail. The program

will

be compact

and

llustrative.

We

will use he

followingvariation

of the

problem.

There s

a monkeyat

the

door into

a room. tn

the middle

of the room

a banana s hanging

rom the

ceiling.

The monkey

s hungry

and wants

o

get

the

banana,but he cannot

stretch

high

enough rom the

floor. At

the windowof

the

room

there

s

a box

themonkeymayuse.The monkeycanperform he followingactions:walk on

the floor,

climb

the box,

push

he box around

if

it is alreadyat the box) and

grasp

he banana f

standingon the

box directly

under the banana.Can the

monkey

get

the banana?

One mportant ask

n

programming

s that of finding

a

representation

f

the

problem

n terms

of concepts

f the

programming

anguage

sed. n our

casewe can

hink of the

monkey

world' asalways

eing

n

some tate

hat

can

changen

time. The current

state s determined

y the

positions

f

the

objects.

For

example, he initial

stateof the world is determined

by:

(1)

Monkey

s at door.

(2)

Monkey s on floor.

(3)

Box is at

window.

(4)

Monkey doesnot

havebanana.

It is convenient

o combineall of

these our

pieces

of

information nto one

structured

bject.

Let

uschoose he word'state'

as he functor o

hold

the four

components ogether.

Figure 2.12 shows

he initial

state

repreSented

s a

structuredobject.

Our

problem

canbe

viewed

asa one-person

ame.

Let

us

now ormalize

the rules

of the

game.

First,

the

goal

of

the

game

s a situation

n

which the

monkeyhas

he banana; hat s,

any state n which

he astcomponents

has':

state( ) -, -,

has)

state

atdoor

onfloor

atwindow

hasnot

Figure

2.12 The

initial state

ofthe monkey

world represented

sa structured bject.

The

four components

re: horizontalposition

of monkey,

vertical

position

of monkey,

positionof box, monkeyhasor hasnot the banana.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 24/37

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

Second,what

are the allowed moves hat change he

world from one

state

o

another?

There are four

types of moves:

(1) graspbanana,

(2)

climb

box,

(3) push

box,

(4)

walk

around.

Not all

moves

are

possible

n

every

possible

state

of

the

world.

For example,

the move

grasp'

is

only

possible

f the monkey s

standing n the box directly

under

he banana

which

s

in the

middle of the room) and doesnot

have he

bananayet. Such rules can be formalized in Prolog as

a three-place elation

narned

move:

mov{

Statel,

M, State2)

The

three

arguments

of

the

relation

specify a move thus:

State2

tatgl

--------)

M

Statel is

the state

before

the move.

M is the move executed

and

State2

s the

state

after the move.

The move

grasp',

with its necessary recondition

on the statebefore

he

move,

can be defined

by

the clause:

This

fact

says

that

after the

move

the

monkey has

rernained

on the

box in the

middle

of the

room.

In

a similar way

we

can

express he

fact

that the

walk from

any

horizontal position

Pl to any

position

this

regardless

f the

position

of the

box and whether

All this

can

be

defined

by the

following Prolog fact:

move(

state( Pl,

onfloor, B, H),

walk( Pl,

P2),

state( P2,

onfloor, B, H)

).

move(

state(

middle,

onbox,

grasp,

state(middle, onbox,

middle,

hasnot),

middle, has)).

Vo

Before

move

Vo

Move

VoAfter move

the banana,

and he has

monkey

on the floor can

P2. The

monkey

can do

it

has he bananaor not.

Vo

Walk

from

PL to PZ

Note

that this

clausesays

many

things,

including,

for example:

the

move

executed

was

walk

from

some

position

Pl

to some

position

P2'

the monkey

is

on the

floor

before and

after the move;

o

o

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 25/37

o

o

SYNTAX AND MEANING

OF PROLOG PROGRAMS 5 1

MOYC

M

canget

canget

has

Figure

2.13

Recursive

ormulation

of

canget.

the

box

is at

some point

B

which

remained

the

same after the move;

the

'has

banana'

status remains

the

same

after the

rnove.

The

clause

actually

specifies

a

applicableo anysituation hat

Sucha specification

s

therefore

the

concept

of Prolog

variables

whole

set of

possible

moves because it

is

matches the specified state before the move.

sometimes

alsocalled

a

move

schema.Due

to

such

schemas

can

be

easily

programmed

in

Prolog.

The

other two

types of moves,

push'

and

'climb',

can be similarly

specified.

The

main kind of question

hat our

program

will have

o

answer s:

Can

the monkey

n some nitial

state S

get

the banana?This can be formulated asa

predicate

canget(S)

where

the argumentS s a state

of

the

monkey world. The

program

or canget

can be basedon two observations:

(1)

For

any stateS in which the monkey

alreadyhas he banana, he

predi-

cate

canget

must certainly

be true; no move is needed n this case.This

corresponds o the Prolog fact:

cange(

state(-, -, -, has)

).

(2)

In

other cases

ne or more moves

are necessary. he monkeycan

get

the

banana n

any state

51

f there s

somemoveM from state

51

o

some

state

52, such hat

the monkeycan hen

get

he banana n state

52

(in

zero

or

more

moves).This principle

s llustrated

n Figure2.I3. A Prologclause

that corresponds

o this rule is:

canget(

Sl)

:-

move( 51, M,

S2),

canget( S2).

This

completes

ur

program

which

s

shown n Figure2.14.

The

formulation

of canget is

recursive

and is similar to that of the

predecessor

elation

of

Chapter 1

(compare

Figures

2.I3 and 1.7). This

prin-

ciple s used

n Prolog

againand

again.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 26/37

52

PR.OLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

%

Legal

moves

move( state( middle, onbox, middle,

grasp,

state(

middle,

onbox,

middle,

move(

state(

P,

onfloor, P, H),

climb,

state(

P,

onbox, P, H)

).

move(

state(

Pl,

onfloor, Pl,

H),

push(

Pl,

P2),

state( P2, onfloor, P2, H)

).

move(

state(

Pl,

onfloor, B,

H),

walk( Pl, P2),

state( P2,

onfloor,

B,

H)

).

hasnot),

Vo

Grasp

banana

has)

).

Vo

Climb

box

Vo

Push

box from

Pl

to

P2

Vo

Walk

from

Pt

to P2

Vocanget(

State):

monkey

can

get

banana

n State

canget(

state(

-, -,

-,

has)

).

canget( Statel) :-

move(

Statel,

Move,

State2),

canget(

State2).

can

1:

Monkey

already

has t

can 2: Do some work to get it

Do

something

Get

it

now

Vo

Vo

Vo

Vo

Figure

2.14

A

program

or the

monkey

ndbanana

roblem.

-

We have

developed

ur monkeyand bananaprogram n the non-pro-

cedural

way.

Let

us now

study

its

procedural

behaviour

by

considering

tre

following

question

o

the

program:

?- canget(

state(

atdoor,

onfloor,

atwindow, hasnot)

.

Prolog's

nswer

s'yes'.

The process

arriedout

by

Prolog

o reach

hisanswer

proceeds,

ccording

o

the

procedural

emantics

f Prolog, hrough

a

sequence

of

goal

lists.

It

involves

some

search

or right moves

among

the

possible

alternativemoves.At somepoint hissearchwill takea wrongmove eading o

a

dead

branch.At

this

stage,

backtracking

will help t

to

recover.

Figure

2.15

illustrates

his

search

rocess.

To answer

he question

Prolog had to

backtrackonce

only. A right

sequence f

moves

was

found

almost straight

away. The reason

or this

efficiency of

the

program

was

the order in which

the clauses

about the move

relationoccurred

n

the program.

The

order n our case

luckily)

urned

out

to

be

quite

suitable.

However,

ess

uckyorderings

re

possible.

ccording

o

the

rulesof the game,

he

monkey

could

ust

as

easily ry to walk here or

there

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 27/37

SYNTAX

AND

MEANING

OF PROLOG

PROGRAMS

grasp climb

push

walk(atdoor,P2)

climb push(

2,P2')

grasp

climb

walk

grasp

P2'

=middle

Figure

2.15 The

monkey's

search

or

the banana.

The search tarts

at the top

node and

proceeds

downwards,

as indicated.

Alternative

moves are tried

in the left-to-risht

order. Backtracking

occurred

once

only.

without ever touching

he

box,

or aimlessly

ush

the box around. A more

thorough nvestigation

will

reveal,asshown n the following

section, hat the

ordering of

clauses s, in the case

of our

program,

in

fact critical.

2.6 Orderof clausesandgoals

2.6.1

Danger

of

indefinite

ooping

Consider

he ollowing

lause:

p : - p .

This

sayshat

p

is rue f

p

is true'.

This s declaratively

erfectly

orrect, ut

.53

I

I

I

backtrack

I

I

I

I

push

state(

atdoor,onfloor,atwindow,

hasnot)

state(P2,

onfloor,atwindow,hasnot)

state(atwindow,

onbox,atwindow,

hasnot)

state(

2',

nfloor,

2', asnot)

state( 2',

onb

oxlPz

hasnot)

state(middle,

onbox,

middle,

has)

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 28/37

54

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

procedurally

s

quite

useless.

n

fact, such

a clausecan

cause

problems

o

Prolog.

Consider

he

question:

' - p.

Using

he

clause

bove, he

goal

p

is

replaced

y the same oalp;

this

will be

n

turn

replaced

by

p,

etc.

In sucha caseProlog

will enter

an

infinite

loop

not

noticing hat

no progress

s being

made.

This

example

s

a simple

way

of

getting

Prolog

to loop indefinitely.

However,

similar

ooping

could

have

occurred

n someof

our

previous

xample

programs

f we

changed

he order

of

clauses, r

the order of goals

n

the

clauses.

t

will be

instructive

o

consider

omeexamples.

In the

monkey

and banana rogram,

he

clauses bout

he

move

elation

were

ordered

thus:

grasp,

climb, push,

walk

(perhaps

unclimb'

should be

added

or completeness).

hese

clauses

ay hat

grasping

s

possible,

limbing

is

possible,

tc.

According

o

the

procedural

emantics

f

prolog,

the order

oi

clauses

ndicates

hat

the

monkey prefers

grasping

o climbing,

climbing

o

pushing,

etc. This

order

of preferences

n fact

helps

he

monkey o

solve

he

problem.

But

what

couldhappen

f the order

was

different?

Let usassume

hat

the

'walk'

clause

appears

irst.

The

execution

of our

original

goal

of

the

previoussection

?-

canget(

stat{

atdoor,

onfloor,

atwindow,

hasnot)

.

would

this

time

produce

he

following

trace.

The

first

four goal

lists

(with

variables

ppropriately

enamed)

are

the

sameas

before:

(1)

canget(

state(

atdoor,

onfloor,

atwindow,

hasnot)

)

The

second

clause

of

canget

('c

anz')

is

applied, producing:

(2)

move(

state(

atdoor,

onfloor,

atwindow,

hasnot),

M,,

S2,),

canget(

s2')

By the

move

walk(

atdoor, PZ')

we get:

(3)

canget(

state(Pz',

onfloor,

atwindow,

hasnot)

)

using

the

clause

can?'again

the

goal

list

becomes:

(4)

move(

state(

P2',

onfloor,

atwindow,

hasnot),

M',

s2"),

canget(

s2")

Now

the

difference

occurs.

The

first

clause

whose

head

above

is

now

'walk'

(and

not

'climb'

as

before).

matches

he

first goal

The instantiation

is

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 29/37

SYNTAX

AND MEANING

OF

PROLOGPROGRAMS

55

52"

=

state(P2",

onfloor,

atwindow, hasnot).

Therefore he

goal

ist becomes:

(5)

canget(

state(P2",

onfloor,

atwindow, hasnot)

Applying

he clause

can?'we

obtain:

(6)

move(

state(

P2",

onfloor,atwindow,hasnot),

M"'

,

52"'),

canget(

2"')

Again,

walk'

is

now tried first,

producing:

(7) canget(state(P2"' , onfloor,atwindow,hasnot)

Let us now

compare he

goals

3), (5)

and

(7).

They are he same

apart rom

one

variable;

his

variable

s, n turn, P', P"andP"'. As

we

know,

hesuccessf

a

goal

doesnot depend n

particular

names f variablesn the

goal.

This means

that from

goal

ist

(3)

the execution race shows

no

progress.

We

can see, n

fact, that

the same

wo

clauses,

can2'

and

walk',

are used

epetitively.The

monkey walks around without ever trying to use

the

box.

As there

is no

progress

made this

will

(theoretically)

go

on for

ever: Prolog will

not realize

that there s no point in continuingalong his ine.

This exampleshows

Prolog trying to solvea

problem

n such

a way that a

solutiort

s

never reached,althougha solution

exists.Suchsituations

re

not

unusual

n Prolog

programming. nfinite loopsare, also,

not unusual

n other

progtamming anguages.What l'sunusual n comparison

with

other

languages

is

that the declarativemeaning

of a Prolog

program may

be

correct, but the

program

is at the same time

procedurally

incorrect

in that

it

is

not able to

producean answer o a

question. n such ases rolog

maynot be able o

satisfy

a goalbecauset tries o reachan answerby choosing wrongpath.

A natural

question

o ask at this

point

is:

Can

we not

makesomemore

substantial

hange

o

our

program

so as o drastically

revent

any danger

of

looping?Or

shallwe alwayshave o

rely

ust

on a suitable

orderingof clauses

and

goals?

As it turnsout

programs,

specially

argeones,

wouldbe too

fragile

if they

just

had to rely on some suitable

ordering. There are several

other

methods hat

preclude nfinite loops,

and

theseare much

more

general

and

robust han he orderingmethod tself.These echniques

ill be used egularly

later in the book, especially

n

those chapters

hat deal with

path

finding,

problemsolvirrg nd search.

2.6.2 Program variations

through reorderlng

of clauses

and

goals

Already

in the example

programs

of Chapter 1 there

was a latent dangerof

producing

a cyclingbehaviour.

Our

program

o specify

he

predecessor

elation

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 30/37

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

in ChapterL was:

predecessor(

, Z)

'.

parent( X, Z).

predecessor(

, Z)

:-

parent(

X, Y),

predecessor(

, Z\.

Let

us analyze

somevariations

of this

program.

All the

variationswill

clearly

have

the same

declarative

meaning,

but not the sameprocedural

meaning.

Vo

Four versions

of the

predecessor

program

Vo

The

original version

predl(

X, Z)

:-

parent(

x,

z).

predl(

x,

z)

.-

parent(

x,

Y),

predl(

Y,

Z) .

vo

variation

: swap

lauses

f

the

original

ersion

pred2(

x, z)

,-

parent(

x,

Y),

pred2(

Y,

Z).

pred2(

x, z)

'-

parent(

x,

z).

Vo Variation b: swap goals in second

clause

of the

original version

pred3(

, Z)

:-

parent(

,

z).

pred3(

, z)

:-

pred3(

,

Y),

parent(

Y,

Z).

Vo

Variation

c:

swap goals

and clauses

of the

original version

pred4(

, z)

.-

pred4(

X,

Y),

parent(

Y,

Z).

pred4(

, z)

.-

parent(

,

z).

Figure

2.16

Four versions

of the

predecessor

program.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 31/37

SYNTAX

AND

MEANING

OF

PROLOG

PROGRAMS

57

According o

the declarative

emantics

f Prolog

we can,

without

affecting

he

declarativemeaning,

change

(1) the order of clausesn the program,and

(2)

the

order of

goals

n the

bodiesof

clauses.

The

predecessor

rocedure

consists

of

two clauses,

and

one

of them

has two

goals

n the

body.

Thereare,

herefore,

our

variations

f

this

program'

all

with

the

same

declarative

meaning.

The four

variations

are

obtained

by

(1)

swapping

oth

clauses,

nd

(2) swappinghe goals or eachorderof clauses.

The corresponding

our

procedures,

called

predl,

pted2,

pred3

and

pred4,

are

shown

n Figure

2.1"6.

There

are

important

differences

in

the

behaviour

of

these

four

declaratively

equiva-lent

rocedures.

To

demonstrate

hese,

consider

the

parent elation

asshown

n

Figure

1.1

of Chapter

L. Now,

what

happens

f

we

ask

whether

Tom

is a

predelessor

of Pat

using

the

four

variations

of

the

predecessor

elation:

?-

predl( tom,

Pat).

yes

?-

pred2(

tom,

Pat).

yes

?-

pred3( tom,

Pat).

yes

?-

pred4(

om,

Pat).

In

the

last case

Prolog

cannot

find

the

answer.

This

is

manifested

on

the

terminal

by a

Prolog

message

uch

as'More

core

needed''

Figuie

1.11

n-Chapter

L showed

he trace

of

predl

(in

chapter

L called

predeceJsor)

roduced

or

the

above

question.

Figure

2.17

shows

he corre-

sponding

races

or

pred2,pred3

nd

pred4.

Figure

2.17(c)

clearly

shows

hat

pred4 slopeless,andFigure2.17(a) ndicateshat pred2 s rather nefficient

compared

o

predl:

pred2

does

much

more searching

nd

backtracking

n the

family

tree.

This

comparison

should

remind

us

of a

general

practical

heuristic

n

problemsolving:

t is often

useful

o

try the

simplest

dea

irst.

In

our

case,

all

ihe

versions

f the

predecessorelation

are

based

on two

ideas:

o

the

simpler

dea

s to

check

whether

he

two arguments

f the

predecessor

relation

satisfy

he

parent

elation;

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 32/37

58

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

the

more

complicated

dea

s

to find

somebody

between'

both people

(somebody

who

is

related

to

them

by

the

parent

and

predicessor

relations).

of the

four

variations

of

the

predecessor

elation,

predl

does

simplest

hings

first-

on the

contrary,

pred4

always

ries

complicated

hings

first.

pred2

and

pred3

are

n between

he

two

extremes.

Even

without

a detailed

study

of the

execution

races,predl

should

be clearly

preferred

merely

on

the

grounds

of

the rule

'try

simple

hings

irst'.

This

rule will

be

in

geneial

a usefulguide

n

programming.

our

four

variations

of

the

predecessor

rocedure

can

be further

com-

pargd by considering he question: what types of questionscan particular

variations

answer,

and what

types

can

hey not

answer?

t turns

out that

predl

pred2(

,z)

:-

parent(

, Y),

prd2(Y,Zl.

pred2(

,7,)

:-

parent(

,z),

Y'= bob

Y"

=

pg;t

(a)

pred2(

om,

pat)

parent(

om,

Y

)

pred2(

'rpat)

pred2(

bob,

pat)

parent(

ob,

Y")

2(Y"

rpat)

perent(

b,

pat)

pred2(ann,

pat)

parent(ann,

"')

2{Y"'.rpat)

perent(

ann,

Pat)

paren( Pet,Y"')

pr€d2(

Y"'

,pat)

paruqpaLpar)

paren(jh,

Y'-")

Prcdz(Y"",pd)

Y"'

=

jim

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 33/37

SYNTAX

AND

MEANING

OF PROLOG

PROGRAMS

59

pred3(x,z\

-

parent(x,z),

pred3(

,z)

:-

pred3(x,),

parent(Y,Z).

(b)

(c)

pped4(X,Zl

'

pred4(x,

)n

parent(Y,Zl.

pred4{X,Zl

:-

pflrent{xrz),

pred4(to+,Y')

parent(Y,pet)

pred4(tory,

,')

pnrent(Y,

Y

)

psrent{Y

Pat)

predr(togl,,

;)

parent(Y,,

{

)

perent(Y-,

)

perent(Y,pat)

FiSurp

2.f?

The

behaviour

of three

forrnulations

of

the

prpdegg$sof

elation

oq

the

qu-estion:s Tom

a

predegessor

f Pat?

pred3(torrtr

aO

parent(tom,pa9

pred3(top,

')

parent(

,

pat)

1f

rl,

parent(tot,il

parent(

.,

Pat)

1t

| |

y '=

bob

t l

parent(

bob,

pflO

yes

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 34/37

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

and

pred2

are

both

able

to reach

an

answer or

any

type

of question

about

predecessors;

red4

cannever

each

an

answer;

nd

pred3

sometimes

anand

sometimes

annot.

One

example

n

which

pred3

ails

s:

?-

pred3(

iz,

jim).

This

question

again

brings

he

system

nto

an infinite

sequence

f

recursive

calls.

Thus

pred3

also

cannot

be

considered

rocedurally

orrect.

2.6.3

Combining

declarative

and

procedural

views

The

foregoing

section

has

shown

that

the

order

of

goals

and

clauses

oes

matter.Furthermore,hereareprogramshatare

declaratively

orrect.

but do

not

work

in practice.

such discrepancies

etween

he

declarative

and pro-

cedural

meaning

may

appear

nnoying.

One

may

argue:

Why

not

simply

orget

about

he

declarative

meaning.

This

argument

an

be

brought

o

an

extreme

with

a clause

uch

as

predecessor(

X, Z)

i

predecessor(

X,

Z).

which

s declaratively

orrect,but scompletely selesssa workingprogram.

.

The

reason

why

we

should

not

forget

about

he

declarative

m-eaning

s

that progress

n.programming

technology

s

achieved

by

moving

away

from

procedural

details

toward_

eclarative

aipects,

which

are

noro,uily

easier

o

formulate

and

understand.

The

system

tself,

not

the programmer,

should

carry

he

burden

of

filling

in

the

procedural

details.

proiog

"cloes

help

toward

this

end,

although,

as we

have

seen

n

this

section,

t

onr

herps

partiaily:

t

sometimes

oes

work

out

the procedural

etails

tseltproperly,

and

sometimes

it

does

not.

The philosophy

dopted

by

many

s

that

i

is uettei

to

have

at reast

somedeclarativemeaning ather thannoni (,none' s the case n mostother

programming

anguages).

he practical

aspect

of

this

view

is

that

it

is often

rather

easy

to get

a

working

program

on."

*" have

a program

that

is

declaratively

orrect.

consequentry,

a

usefur

practicar

uppiouJh

hat

often

works

s

to

concentrate

n

the

declarative

specti

tttre

proutem,

hen

est

he

resulting

rogram

on the

computer,

and

f itiails

proceduraily

ry

to

rearrange

the

clauses

nd

goals

nto

a right

order.

2.7

Remarks

on

the

relation

between

prolog

and

logic

Prolog

is

related

to

mathematical

ogic,

so its

syntax

and

meaning

can

be

specified

most

concisely

ith

referencei

o

logic.

piolog

is ndeed

often

defined

that

way.

However,

such

an

ntroduction

olrolog

u.iu-",

that

the

reader

s

familiar

with

certain

concepts

f

mathematical

olic.

These

on."p,,

are, on

the

other

hand,

certainly

not

necessary

or

understinding

na

using

rrolog

asa

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 35/37

SYNTAX AND

MEANING

OF

PROLOG

PROGRAMS

61

programming ool,

which is the aim

of

this

book.

For the

reader

who is

especially

nterested

n the relationbetween

Prolog

and ogic,

he ollowing

are

some

basic links

to mathematical

ogic, together

with some

appropriate

references.

Prolog'ssyntax

s

that of

the

irst-order

predicate

ogic

formulas

written in

the

so-called lause

orm

(a

form in

which

quantifiersare not

explicitly

writ-

ten),

and

urther restricted o Horn clauses

nly

(clauses

hat haveat

most

one

positive literal). Clocksin

and Mellish

(1981)

give

a Prolog

program

that

transforms

first-order

predicate

calculus

ormula

nto

the clause

orm'

The

proceduralmeaning

of

Prolog

s based

on the

resolution

principle

fot

mechani-

cal

theorem

proving

introduced

by Robinson

n his classical

aper

(1965).

Prologusesa

special trategy

or resolution

heorem

provingcalledSLD.

An

introduction

o the irst-order

predicate alculus

nd esolution-based

heorem

proving can be found

in Nilsson

1981.Mathematical

uestions

egarding

he

properties f

Prolog's

rocedural

meaningwith

respect

o logic

areanalyzed

y

Lloyd

(1984).

Matching

n Prolog

corresponds

o

what

is called

unification

n logic.

However,

we

avoid the

word

unification

because

matching,

or

efficiency

reasons

n mostProlog

systems,

s mplemented

n a

way hat

doesnot

exactly

correspond

o

unification

see

Exercise

.10).

But from

the

prqtical

point of,

view tirisapproximationo unification s quite adequate. U €fgf t&e Lt

Exercise

2.10

What

happens

f we ask

Prolog:

?-

x - f (x ) .

Should

this

request

for

matching

succeed

or

fail?

According

to the

definition of unification in logic this should ail, but what happensaccord-

ing to

our definition

of matching

n

Section

2.2?

Try

to explain

why

many

Prolog

implementations

answer

the

question above

with:

x

-

f(f(f(f(f(f(f(f(f(f(f(f(f(f(

Summary

So

ar we havecovered

a

kind of basic

Prolog,

also

called

pure

Prolog'.

It

is

'pure'

becauset corresponds

losely

o formal

ogic. Extensions

hose

aim s

to tailor

the

language oward

some

practical

needs

will

be covered

ater in the

book

(Chapters

,

5,6,7).Important

points

of

thischapter

re:

Simple

objects

in Prolog

are atoms,

variables

and

numbers.

Structured

objects,

or structures,

are used

to

represent

objects

that

have

several

components.

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 36/37

I

o

PROLOG

PROGRAMMING

FOR

ARTIFICIAL

INTELLIGENCE

Structures

re

constructed

y

means

f

functors.

Each

unctor

s

defined

by

its

name

and

arity.

The

type

of

object

s

recognized

ntirely

by

its

syntactic

orm.

The

exical

cope

f

variables

s

one

clause.

hus

he

same

ariable

name

in

two

clauses

means

wo

different

variables.

Structures

an

be

naturally

pictured

as

rees.

Prolog

can

be

viewed

as

a

language

or

processing

rees.

The

matching

peration

akes

wo

terms

and

ries

o

make

hem

identical

by

instantiating

he

variables

n

both

terms.

Matching,

if

it

succeeds,

esults

n

the

mostgeneral

nstantiation

of

variables.

The

declarative

semantics

of

prolog

respect

to

a

given

program,

and

if

variables

it

is

true.

defines

whether

a

goal

s true

with

it

is

true,

for

what

instantiation

of

A

comma

between

oals

means

he

conjunction

f goals.

A

semicolon

between

oals

means

he

disjunction

f

goals.

The

procedural

semantics

f

Prolog

s

a

procedure

or

satisfying

a

list

of

goals

n

the

context

of

a

given

progiam.

h.

procedure

utputs

he

truth

or falsityof thegoal istand hecorrespondingnstantiationsf variables.

The

procedure

utomatically

acktrurtr

to

examine

lternatives.

The

declarative

meaning

f

programs

n

'pure

Prolog'

does

not

depend

n

the

order

of

clauses

nd

the

order

of

goals

n

clauses.

The

procedural

meaning

oes

depend

n

the

order

of goals

and

clauses.

Thus

the

order

can

affect

the

efiiciency

of the

p.ogru*;

an

unsuitable

order

may

even

ead

o

infinite

recursive

alls.

Given

a

declaratively

orrect

program,

changing

he

order

of

clauses

nd

goalscan mprove heprogram'smiriency*triG retaining

ts

declarative

correctness.

eordering

s

one

rnethod

f preventing

nOefinite

ooping.

There

are

other

more

general

echniques,

apart

from

reordering,

o

prevent

indefinite

looping

and

thereby

makl

programs

procedurally

robust.

concepts

discussed

n

this

chapter

are:

data

objects:

atom,

number,

variable,

tructure

term

functor,

arity

of

a

functor

principal

unctor

of

a terrn

matching

of

terms

most

general

nstantiation

declarative

emantics

instance

f

a

clause,

ariant

of

a

clause

procedural

semaRtics

executing

oals

8/11/2019 Syntax and meaning of prolog programs

http://slidepdf.com/reader/full/syntax-and-meaning-of-prolog-programs 37/37

SYNTAX AND MEANING OF

PROLOG

PROGRAMS 63

References

Clocksin, W. F. and Mellish,

C. S.

(1981)

Programming

n Prolog.

Springer-

Verlag.

Lloyd, J.

W.

(1984)

Foundations

of Logic

Programming.

Springer-Verlag.

Nilsson, N. J.

(1931)

Principlesof

Artificial Intelligence.

Tioga;

also Springer-

Verlag.

Robinson,

A. J.

(1965)

A machine-oriented

ogic

based

on the

resolution

principle.

JACM

12: 2341.