prolog programming introduction to prolog (part4) cs 370 – cs461

8
Prolog programming Introduction to Prolog (part4) CS 370 – CS461

Upload: derick-halcomb

Post on 16-Dec-2015

225 views

Category:

Documents


9 download

TRANSCRIPT

Page 1: Prolog programming Introduction to Prolog (part4) CS 370 – CS461

Prolog programmingIntroduction to Prolog (part4) CS 370 – CS461

Page 2: Prolog programming Introduction to Prolog (part4) CS 370 – CS461

How to solve this problem?Consider the following facts:

parent(pam,bob).

parent(tom,bob).

parent(tom,liz).

parent(bob,ann).

parent(bob,pat).

parent(pat,jim).

If we want to describe a new relation

called “ predecessor”, which checks if a

specific node is a predecessor of another

node or not. For example: ?- predecessor(tom , pat).

How can this relation be described?

pam tom

bob liz

ann pat

jim

Page 3: Prolog programming Introduction to Prolog (part4) CS 370 – CS461

Defining relations by Recursive Rule.

•To solve the previous predecessor(tom, pat) relation problem we have to defined a recursive rule.

•This relation will be defined in terms of the parent relation.

•The whole definition can be expressed with two rules:

1. First rule will define the direct predecessor.

2. Second rule will be the indirect predecessors.

Page 4: Prolog programming Introduction to Prolog (part4) CS 370 – CS461

Defining relations by Recursive Rule.

1. Direct Rule

For all X and Z X is a predecessor of Z if X is a parent of Z.

The rule will be:

predecessor( X , Z ) :- parent( X , Z ).

x

z

Predecessorparent

Page 5: Prolog programming Introduction to Prolog (part4) CS 370 – CS461

Defining relations by Recursive Rule.

2. Indirect Rule

Y1

Y2

z

Predecessor

parent

x

Y1

z

Y2

Predecessor

parent

Predecessor

Predecessor

Page 6: Prolog programming Introduction to Prolog (part4) CS 370 – CS461

Defining relations by Recursive Rule.

2. Indirect Rule

For all X and Z there is a Y such that:

X is a predecessor of Z if

X is a parent of Y and Y is a predecessor of Z.

The rule will be:

predecessor( X , Z ) :-

parent( X , Y) , predecessor(Y,Z).

Page 7: Prolog programming Introduction to Prolog (part4) CS 370 – CS461

Defining relations by Recursive Rule.

•Thus ,we have constructed a complete program for the

predecessor relation, which consists of two rules: one

for direct predecessors and one for indirect predecessors.

•Both rules must be rewritten together as :

predecessor( X , Z ) :- parent( X , Z ).

predecessor( X , Z ) :-

parent( X , Y ) , predecessor( Y , Z ).

Page 8: Prolog programming Introduction to Prolog (part4) CS 370 – CS461

Class exercise(1)

•Write a rule to describe the successor relation?