Prolog programming Introduction to Prolog (part4) CS 370
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). parent(jim,jon). 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 jon
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: First rule will define the direct predecessor. Second rule will be the indirect predecessors.
Defining relations by Recursive Rule. 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 parent Predecessor z
Defining relations by Recursive Rule. x 2. Indirect Rule parent Y1 Y1 parent Y2 Predecessor Predecessor Y2 Predecessor Predecessor z z
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).
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 ). parent( X , Y ) , predecessor( Y , Z ).
Class exercise(1) Write a rule to describe the successor relation?