COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D....

71
COSC3306: COSC3306: Programming Programming Paradigms Paradigms Lecture 9: Declarative Lecture 9: Declarative Programming with Programming with Prolog Prolog Haibin Zhu, Ph.D. Haibin Zhu, Ph.D. Computer Science Computer Science Nipissing University Nipissing University (C) 2003 (C) 2003

Transcript of COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D....

Page 1: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

COSC3306:COSC3306:Programming ParadigmsProgramming Paradigms

Lecture 9: DeclarativeLecture 9: DeclarativeProgramming with PrologProgramming with Prolog

Haibin Zhu, Ph.D.Haibin Zhu, Ph.D.Computer ScienceComputer ScienceNipissing University Nipissing University

(C) 2003(C) 2003

Page 2: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ContentsContents

PrologPrologProgram structureProgram structureLogical variableLogical variableSyntax structureSyntax structureProlog facilitiesProlog facilitiesControl structureControl structureResolution and unificationResolution and unificationDFSDFSBacktrackingBacktrackingDeficiencies of PrologDeficiencies of PrologCut OperatorCut OperatorRecursive RulesRecursive Rules

Page 3: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

PrologPrologAt the heart of the Prolog is a stored base of information At the heart of the Prolog is a stored base of information usually called a usually called a knowledge base knowledge base oror database database, which , which consists of facts and rules. The system is consists of facts and rules. The system is interactiveinteractive in in which the user interacts with the system on a question which the user interacts with the system on a question and answer basis. Answering a question involves and answer basis. Answering a question involves processing the data held in the knowledge base. A processing the data held in the knowledge base. A general structure of Prolog is: general structure of Prolog is:

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 4: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

PrologProlog

The basic features of Prolog include a powerful The basic features of Prolog include a powerful pattern-matching facility, a backtracking strategy pattern-matching facility, a backtracking strategy that searches for proofs, uniform data structures that searches for proofs, uniform data structures from which programs are built, and the general from which programs are built, and the general interchangeability of input and output. Owing to interchangeability of input and output. Owing to the lack of a standard definition, several dialects the lack of a standard definition, several dialects of Prolog evolved, differing even in their basic of Prolog evolved, differing even in their basic syntax. Fortunately, the Edinburg version in now syntax. Fortunately, the Edinburg version in now widely accepted as a standard. widely accepted as a standard.

Page 5: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Program StructureProgram Structure

A prolog program consists of three major A prolog program consists of three major components stated as:components stated as:– Series of Series of rulesrules that define the problem that define the problem

domain, which is the relation between objects;domain, which is the relation between objects;– Series of Series of factsfacts that define the that define the

interrelationships among the known objects; interrelationships among the known objects; and and

– Logical statement known as Logical statement known as goalgoal or or queryquery that that is a question from the Prolog system to either is a question from the Prolog system to either prove or disprove.prove or disprove.

Page 6: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Program StructureProgram Structure

In general, the set of facts and rules is called In general, the set of facts and rules is called assertionsassertions or or axiomsaxioms and describes logical relationships among and describes logical relationships among objects and is the basis for the theorem-proving model of objects and is the basis for the theorem-proving model of Prolog system. Prolog programming language restricts Prolog system. Prolog programming language restricts us to the logical statements (Horn clauses) of the form:us to the logical statements (Horn clauses) of the form:

A :- A1, A2, … , An.A :- A1, A2, … , An.The symbol “:-” means The symbol “:-” means ifif and the symbol “,” means and the symbol “,” means andand. . A is the A is the headhead (goal) of the logical statement, A1, A2, …, (goal) of the logical statement, A1, A2, …, An forms the An forms the bodybody (subgoals), and a period terminates (subgoals), and a period terminates every Prolog axiom. Ai is called a literal, which is a every Prolog axiom. Ai is called a literal, which is a relationship between objects or the negation of a relationship between objects or the negation of a relationship between objects. relationship between objects.

Page 7: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ExampleExampleThe following literals can express the The following literals can express the relationship between two objects, relationship between two objects, seyedseyed and and marymary..– likes(seyed, mary).likes(seyed, mary).– father_of(seyed, mary).father_of(seyed, mary).

x pet(x) small(x) apartment(x)

x cat(x) dog(x) pet(x) x poodle(x) dog(x) small(x)poodle(fluffy)

(Logic)apartment(X) :- pet(X), small(X).pet(X):- cat(X).pet(X):- dog(X).dog(X):- poodle(X).small(X) :- poodle(X). poodle(fluffy)

(Prolog)

Page 8: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

QueryQuery

Query is the given input to a program, which is treated as Query is the given input to a program, which is treated as a goal to be proved. In other words, the query is a a goal to be proved. In other words, the query is a question asking about objects and their relationships. In question asking about objects and their relationships. In prolog, a query is just like a fact or rule, except that it is prolog, a query is just like a fact or rule, except that it is started with a special symbol “ ?-”, a question mark and a started with a special symbol “ ?-”, a question mark and a “-”, hyphen.“-”, hyphen.For example, in a query as the form:For example, in a query as the form:

?-?- A1, A2, … , An.A1, A2, … , An.In this case, we proceed by satisfying A1, and A2, and … In this case, we proceed by satisfying A1, and A2, and … , An separately as subgoals., An separately as subgoals. If all subgoals succeed, then we conclude that the goal If all subgoals succeed, then we conclude that the goal succeeds. succeeds. We use the convention that the names of all objects and We use the convention that the names of all objects and relationships start with a lowercase character and relationships start with a lowercase character and variables start with an uppercase letter. variables start with an uppercase letter.

Page 9: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Logical VariableLogical Variable

The variable in imperative language is not the same The variable in imperative language is not the same concept as a variable in logic programs:concept as a variable in logic programs:– A program variable refers to a memory location that may have A program variable refers to a memory location that may have

changes in its contents; consider an assignment Nchanges in its contents; consider an assignment NNN1.1.– A variable in logic program simply stands for a value that, once A variable in logic program simply stands for a value that, once

determined, will not change. For example, the equation determined, will not change. For example, the equation XX3Y3Y11 and 2X11 and 2X3Y3Y4 specify value for X and Y; namely X4 specify value for X and Y; namely X5 5 and Yand Y2, which will not be changed in this context. A variable in 2, which will not be changed in this context. A variable in Prolog is called a Prolog is called a logical variablelogical variable and acts in a manner and acts in a manner differently. Variables are strings of characters beginning with an differently. Variables are strings of characters beginning with an uppercase letter or an underscore. uppercase letter or an underscore.

– Once a logical variable is bound to a particular value, called an Once a logical variable is bound to a particular value, called an instantiationinstantiation of the variable, that binding cannot be altered of the variable, that binding cannot be altered unless the pattern matching that caused the binding is undone unless the pattern matching that caused the binding is undone because of backtracking. because of backtracking.

Page 10: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Logical VariableLogical VariableThe destructive assignment of imperative languages, The destructive assignment of imperative languages, where a variable with a value binding is changed, cannot where a variable with a value binding is changed, cannot be performed in logic programming. be performed in logic programming. Terms in a query change only by having variables filled in Terms in a query change only by having variables filled in for the first time, never by having a new value replace an for the first time, never by having a new value replace an existing value. existing value. An iterative accumulation of a value is obtained by having An iterative accumulation of a value is obtained by having each instance of a recursive rule take the values passed each instance of a recursive rule take the values passed to it and perform computations of values for new variables to it and perform computations of values for new variables that are then passed to another call.that are then passed to another call.Since a logical variable is bounded once, it is more like a Since a logical variable is bounded once, it is more like a constant identifier with a dynamic defining expression as constant identifier with a dynamic defining expression as in Ada than a variable in an imperative language. in Ada than a variable in an imperative language.

Page 11: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ExampleExample

parent(seyed, parent(seyed, mary).mary).parent(seyed, parent(seyed, mahsa).mahsa).parent(mary, leily).parent(mary, leily).parent(mahsa, parent(mahsa, victoria).victoria).

Some queries:Some queries:? parent(seyed, mary).? parent(seyed, mary).yesyes? parent(X, leily).? parent(X, leily).XXmarymaryyesyes? parent(seyed, X).? parent(seyed, X).XXmary;mary;XXmahsa;mahsa;nono? parent(X, Y).? parent(X, Y).XXseyedseyedYYmarymaryyesyes System will list all of the parent System will list all of the parent

pairs, one at a time if semicolons pairs, one at a time if semicolons are typed.are typed.

The user-typed The user-typed semicolon asks the semicolon asks the system for more solutionssystem for more solutions

Page 12: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Prolog Syntax-Prolog Syntax-ConstantsConstants

– A Constant is one of: A Constant is one of: Atom Atom

Integer Integer

Real Number Real Number

Atoms are made up of: Atoms are made up of:

letters and digits: AB...Zab...z01...9 and _ letters and digits: AB...Zab...z01...9 and _ (underscore) (underscore)

symbol: any number of +, -, *, /, symbol: any number of +, -, *, /,

Page 13: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

VariablesVariables

    Variables usually start with a capital letter. The Variables usually start with a capital letter. The only interesting exception is the special only interesting exception is the special anonymous variableanonymous variable written written __ and pronounced and pronounced ``underscore''. In the rule process(X,Y):- ``underscore''. In the rule process(X,Y):- generate(_,Z), generate(_,Z), test(_,Z), test(_,Z), evaluate(Z,Y). evaluate(Z,Y). the underscores refer to the underscores refer to differentdifferent unnamed unnamed variables. For example, here are two versions of variables. For example, here are two versions of member/2. member/2.

Page 14: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Compound TermsCompound TermsA A Compound TermCompound Term is a is a functorfunctor with a (fixed) with a (fixed) number of number of argumentsarguments each of which may be a each of which may be a PrologProlog termterm. . happy(fred) happy(fred) – principal functor = happy principal functor = happy – 1st argument = a constant (atom) 1st argument = a constant (atom)

sum(5,X) sum(5,X) – principal functor = sum principal functor = sum – 1st argument = constant (integer) 1st argument = constant (integer) – 2nd argument = variable 2nd argument = variable

not(happy(woman)) not(happy(woman)) – principal functor = not principal functor = not – 1st argument = compound term1st argument = compound term

Page 15: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

BNF SpecificationBNF Specification

Page 16: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Prolog Facilities-ArithmeticProlog Facilities-Arithmetic

?:- X is 3+4.?:- X is 3+4.

?:- X is 5-4.?:- X is 5-4.

?:- X is 3*4.?:- X is 3*4.

?:- X is 8/2.?:- X is 8/2.

?:- X is 5 mode 2.?:- X is 5 mode 2.

Page 17: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ComparisonsComparisons

X<Y.X<Y.

X>Y.X>Y.

X=<Y.X=<Y.

X>=Y.X>=Y.

X=\=Y.X=\=Y.

X=:=Y.X=:=Y.

Page 18: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

List OperationsList Operations

List is a sequence of elements that are separated commas, List is a sequence of elements that are separated commas, shown between brackets, and have any length.shown between brackets, and have any length.[H|T] expresses a list [H|T] expresses a list – H matches the head of the listH matches the head of the list– T matches the tailT matches the tail

List Head Tail[a, b, c, d] a [b, c, d][ ] none none[[the, man], human] [the, man] [human][the, [man, human]] the [[man, human]][the, [man, human], arm] the [[man, human], arm]

Page 19: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ExamplesExamples

Last(X, [X]).Last(X, [X]).Last(X, [H|T]):-last(X,T)Last(X, [H|T]):-last(X,T)

?-Last(X, [a,b,c,d).?-Last(X, [a,b,c,d).X = dX = dMember(X,[X|T]).Member(X,[X|T]).Member(X,[H|T]):-member(X,T).Member(X,[H|T]):-member(X,T).?- member(a, [a,b,c,d])?- member(a, [a,b,c,d])Yes.Yes.

Page 20: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ExamplesExamples

Concat([], L, L).Concat([], L, L).

Concat([H|T], L, [H|M)):-concat(T, L, M).Concat([H|T], L, [H|M)):-concat(T, L, M).

?-Concat([a,b,c],[b,e],R).?-Concat([a,b,c],[b,e],R).

R = [a,b,c,d,e].R = [a,b,c,d,e].

?-append(….)?-append(….)

Page 21: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Input and OutputInput and Output

Read(X).Read(X).Average:-read(X), read(Y), Z is (X+Y)/2.Average:-read(X), read(Y), Z is (X+Y)/2.Write (variable).Write (variable).?-X is 2*10, write (x).?-X is 2*10, write (x).Other examples:Other examples:– http://www.cs.dartmouth.edu/~jaa/CS118.99Shttp://www.cs.dartmouth.edu/~jaa/CS118.99S

/Samples/Prolog//Samples/Prolog/– http://www.csci.csusb.edu/dick/cs320/lab/10.hhttp://www.csci.csusb.edu/dick/cs320/lab/10.h

tmltml

Page 22: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

To be ContinuedTo be Continued

Control StructureControl Structure

ResolutionResolution

UnificationUnification

DFSDFS

Page 23: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Control StructureControl Structure

Because Prolog has been implemented with a Because Prolog has been implemented with a concern for efficiency, its control strategy acts concern for efficiency, its control strategy acts with a deterministic approach for discovering with a deterministic approach for discovering proofs. The control system in Prolog can be proofs. The control system in Prolog can be characterized by two criteria:characterized by two criteria:

Goal order, meaning that the control system Goal order, meaning that the control system chooses the first leftmost subgoal.chooses the first leftmost subgoal.

Rule order, meaning that the control system Rule order, meaning that the control system selects the first logical statement.selects the first logical statement.

Page 24: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Control StructureControl Structure

This indicates that, the response to a query is affected This indicates that, the response to a query is affected both by subgoal orders within the goal and by the logical both by subgoal orders within the goal and by the logical statements order within the knowledge base of facts and statements order within the knowledge base of facts and rules. rules. There are two opposite methods in which goal can be There are two opposite methods in which goal can be proved as: proved as: top-downtop-down approach which is similar to approach which is similar to recursionrecursion also called also called backward chainingbackward chaining and and bottom-upbottom-up approach which is similar to approach which is similar to iterationiteration also called also called forward forward chainingchaining. There are various mixtures of top-down and . There are various mixtures of top-down and bottom-up that work from both the goal and the bottom-up that work from both the goal and the hypotheses. It is worth noting that, bottom-up control hypotheses. It is worth noting that, bottom-up control approach is more efficient than top-down approach, approach is more efficient than top-down approach, since the bottom-up execution does not recompute the since the bottom-up execution does not recompute the subgoals. subgoals.

Page 25: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Top-down ApproachTop-down Approach

In this approach, we start with the goal and In this approach, we start with the goal and attempt to prove its correctness by finding a attempt to prove its correctness by finding a sequence of matching logical statements that sequence of matching logical statements that lead to some set of original facts in the lead to some set of original facts in the knowledge base, meaning that all possible knowledge base, meaning that all possible resolution and unification could be performed resolution and unification could be performed until the goal is proved. The top-down approach until the goal is proved. The top-down approach execution of a logic program is similar to execution of a logic program is similar to recursive execution of a procedure. recursive execution of a procedure. The goal G is empty and The goal G is empty and TrueTrue is reached. is reached.No logical statement applies to the leftmost No logical statement applies to the leftmost subgoal of G. subgoal of G.

Page 26: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ExampleExample

Assume a knowledge base contains the following fact Assume a knowledge base contains the following fact and rule.and rule.

mother(mary).mother(mary).female(X)female(X) :=:= mother(X).mother(X).

To trace the query To trace the query female(mary)female(mary), in top-down approach , in top-down approach the Prolog would be required to choose goal as starting the Prolog would be required to choose goal as starting logical statement and use it to infer the truth of the goal. logical statement and use it to infer the truth of the goal. In this example, a new logical statement In this example, a new logical statement mother(mary)mother(mary) can be deduced by matching the goal can be deduced by matching the goal female(mary)female(mary) and and the second logical statement the second logical statement female(X) := mother(X) female(X) := mother(X) in in the knowledge base through instantiation of the knowledge base through instantiation of XX to to marymary. . The goal can be inferred, because the new generated The goal can be inferred, because the new generated logical statement logical statement mother(mary)mother(mary) is similar to the first is similar to the first logical statement of the knowledge base. logical statement of the knowledge base.

Page 27: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Bottom-up ApproachBottom-up Approach

In the bottom-up, we start with the hypotheses In the bottom-up, we start with the hypotheses which is the assumption that the goal is correct which is the assumption that the goal is correct and attempt to reach the goal. This indicates that and attempt to reach the goal. This indicates that we start with the facts and rules of the we start with the facts and rules of the knowledge base and attempt to find a sequence knowledge base and attempt to find a sequence of matches that lead to the goal. In general of matches that lead to the goal. In general bottom-up approach works well when the bottom-up approach works well when the number of possibly correct answers is large. The number of possibly correct answers is large. The bottom-up control can stop in one of two cases:bottom-up control can stop in one of two cases:The goal G is achieved and True is reached.The goal G is achieved and True is reached.No logical statements can satisfy each other in No logical statements can satisfy each other in order to make a new logical statement. order to make a new logical statement.

Page 28: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ExampleExample

Assume a knowledge base contains the following fact Assume a knowledge base contains the following fact and rule.and rule.

mother(mary).mother(mary).female(X)female(X) :=:= mother(X).mother(X).

To trace the query To trace the query female(mary)female(mary), in bottom-up approach , in bottom-up approach the Prolog would be required to search through the the Prolog would be required to search through the knowledge base in order to make a logical statement knowledge base in order to make a logical statement correspond to the goal. In this example, the goal can be correspond to the goal. In this example, the goal can be deduced by matching the first fact deduced by matching the first fact mother(mary)mother(mary) with the with the right side of the second rule right side of the second rule female(X) := mother(X) female(X) := mother(X) through instantiation of through instantiation of XX to to marymary. A new generated . A new generated logical statement as logical statement as female(mary)female(mary) indicates that the goal indicates that the goal can be inferred, because it is similar to the goal.can be inferred, because it is similar to the goal.

Page 29: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Resolution and UnificationResolution and Unification

As an important practical application, resolution As an important practical application, resolution theorem proving also known as the theorem proving also known as the resolution resolution refutation systemrefutation system has made the current has made the current generation of Prolog interpreter possible. generation of Prolog interpreter possible. Unification is the search process of finding the Unification is the search process of finding the general substitution of variables that makes two general substitution of variables that makes two literally identical.literally identical.In general, when the interpreter tries to verify a In general, when the interpreter tries to verify a goal it searches the database of facts and rules goal it searches the database of facts and rules to find a matching fact or rule’s head. This is to find a matching fact or rule’s head. This is corresponding to pattern matching and variable corresponding to pattern matching and variable binding. binding.

Page 30: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

UnificationUnification

Selects a fact if:Selects a fact if:– The name is the same as that of the goal to be proven.The name is the same as that of the goal to be proven.– The number of arguments is the same.The number of arguments is the same.– For all corresponding arguments one of the following conditions holds:For all corresponding arguments one of the following conditions holds:

They are exactly the same constant.They are exactly the same constant.They are an unbound variable and a constant. In this case the variable They are an unbound variable and a constant. In this case the variable becomes bound to the constant. becomes bound to the constant. They are both variables. In this case, if one is bound then the other becomes They are both variables. In this case, if one is bound then the other becomes bound to the same object. If both are bound, then both become bound to the bound to the same object. If both are bound, then both become bound to the same object. same object.

– If no matching fact or rule’s head can be found by unification, then the If no matching fact or rule’s head can be found by unification, then the goal fails. goal fails.

This indicates that, the resolution and unification works by canceling This indicates that, the resolution and unification works by canceling out matching literals that appear on different sides of the “:-” sign. If out matching literals that appear on different sides of the “:-” sign. If we have two logical statements, any two matching (or unifiable) we have two logical statements, any two matching (or unifiable) literals, which appear both on the right of one of them and on the left literals, which appear both on the right of one of them and on the left of the other, cancel each other out.of the other, cancel each other out.

Page 31: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ExampleExample

Consider the following facts and rules translated Consider the following facts and rules translated into Prolog clause form on the right.into Prolog clause form on the right.– (1)(1) :- a.:- a. a a– (2)(2) a :- b, c, d.a :- b, c, d. b b c c d d a a– (3)(3) b :- e, f.b :- e, f. e e f f b b– (4)(4) c :-c :- cc– (5)(5) d :-d :- dd– (6)(6) e :-e :- ee– (7)(7) f :-f :- ff

Page 32: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

The procedure of resolution for the The procedure of resolution for the above exampleabove example

The literal e in line 6 can be unified with the literal e in The literal e in line 6 can be unified with the literal e in line 3. line 3.

The literal f in line 7 cancels out the literal f in line 3. The literal f in line 7 cancels out the literal f in line 3.

The literal b in line 3 cancels out the literal b in line 2. The literal b in line 3 cancels out the literal b in line 2.

The literal c in line 4 can be resolved with the literal c in The literal c in line 4 can be resolved with the literal c in line 2. line 2.

The literal d in line 5 cancels out the literal d in line 2. The literal d in line 5 cancels out the literal d in line 2.

After all the above, we are left with the literal a in line 2, After all the above, we are left with the literal a in line 2, that can be canceled out with the original query, the that can be canceled out with the original query, the literal a in line 1. literal a in line 1.

Page 33: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Resolution by unificationResolution by unification

However, two literals do not have to be identical to be resolved. For However, two literals do not have to be identical to be resolved. For example, in the followingexample, in the following

parent_of(X, Y) :- father_of(X, Y), male(X).parent_of(X, Y) :- father_of(X, Y), male(X).father_of(john, mary).father_of(john, mary).male(john).male(john).

father_of(X, Y) literal appearing to the right of the first rule can be father_of(X, Y) literal appearing to the right of the first rule can be unified with father_of(john, mary) in the second fact. These two unified with father_of(john, mary) in the second fact. These two literals are unifiable when the variable X is instantiated to the literals are unifiable when the variable X is instantiated to the constant john, and the variable Y to the constant mary. Thus, constant john, and the variable Y to the constant mary. Thus,

parent_of(X, Y) :- father_of(X, Y), male(X).parent_of(X, Y) :- father_of(X, Y), male(X).father_of(john, mary).father_of(john, mary).

can be resolved tocan be resolved toparent_of(john, mary) :- male(john).parent_of(john, mary) :- male(john).

Page 34: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Resolution by refutation proofs Resolution by refutation proofs

Resolution by refutation proofs requires that the axioms and Resolution by refutation proofs requires that the axioms and the negation of the goal be placed in the negation of the goal be placed in clause formclause form notation. notation. Clause form represents the logical statements as a set of Clause form represents the logical statements as a set of disjunction of literals. disjunction of literals. The most common form of resolution is called binary The most common form of resolution is called binary resolution, the basis for Prolog interpreter that is applied to resolution, the basis for Prolog interpreter that is applied to two clauses when one contains a literal and the other its two clauses when one contains a literal and the other its negation. negation. If these literals contain variables, the literals must be unified If these literals contain variables, the literals must be unified to make them equivalent. In this case, a new clause is to make them equivalent. In this case, a new clause is produced consisting of the disjuncts of all the literals in the produced consisting of the disjuncts of all the literals in the two clauses excluded the literal and its negative instance, two clauses excluded the literal and its negative instance, which are said to have been resolved or cancelled out. which are said to have been resolved or cancelled out.

Page 35: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

A Procedure of Refutation ProofsA Procedure of Refutation ProofsThe resulting clause receives the unification substitution under which The resulting clause receives the unification substitution under which the literal and its negation are found as equivalent. In general, the the literal and its negation are found as equivalent. In general, the resolution refutation proofs can be stated as the following steps:resolution refutation proofs can be stated as the following steps:

1.1. Put the set of facts and rules into clause form notation.Put the set of facts and rules into clause form notation.2.2. Add the negation of what is to be proved (goal or query), in clause form to Add the negation of what is to be proved (goal or query), in clause form to

the set of axioms.the set of axioms.3.3. Perform the following steps until there is no resolvable clause; if there is Perform the following steps until there is no resolvable clause; if there is

no resolvable clause go to Step 4.no resolvable clause go to Step 4.1)1) Unify (resolve) these clauses together, making new clauses that logically Unify (resolve) these clauses together, making new clauses that logically

produced from them.produced from them.2)2) Produce a contradiction by generating an empty clause. If there is an empty Produce a contradiction by generating an empty clause. If there is an empty

clause, stop and report the query is true.clause, stop and report the query is true.3)3) The substitution used to produce the empty clause are those under which the The substitution used to produce the empty clause are those under which the

opposite of the negated goal is true. opposite of the negated goal is true. 4.4. Stop and report that the query is false; meaning that there is no solution Stop and report that the query is false; meaning that there is no solution

associated with this query.associated with this query.5.5. It is worth noting that, the Step 3 is intended to produce an empty clause, It is worth noting that, the Step 3 is intended to produce an empty clause,

indicating that there is a solution associated with the goal.indicating that there is a solution associated with the goal.

Page 36: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Producing the Clause Form Producing the Clause Form

In the following, we outline the process of conjunctive In the following, we outline the process of conjunctive normal form reduction through examples and give a brief normal form reduction through examples and give a brief description for each step. description for each step. – We eliminate :We eliminate : “ if ” by using the equivalent form as: “ if ” by using the equivalent form as:

b :b : a a a a b b– We eliminate We eliminate “ implies ” by using the equivalent form as: “ implies ” by using the equivalent form as:

a a b b a a b b– We reduce the scope of negation. This can be accomplished We reduce the scope of negation. This can be accomplished

using a number of the transformation rules. These includeusing a number of the transformation rules. These include a ( a ( a ) a ) a a ( a ( a b ) b ) a a b b ( a ( a b ) b ) a a b b

Page 37: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Producing the Clause Form (Cont’d)Producing the Clause Form (Cont’d)

We convert the expression to the conjunction of We convert the expression to the conjunction of disjunction of literals. This requires using the associative disjunction of literals. This requires using the associative and distributive properties of and distributive properties of and and . These include. These include– a a ( b ( b c ) c ) ( a ( a b ) b ) c c– a a ( b ( b c ) c ) ( a ( a b ) b ) c c– a a ( b ( b c ) c ) ( a ( a b ) b ) ( a ( a c ) c )

It is important to mention that, the following logical It is important to mention that, the following logical statementstatement– a a ( b ( b c ) c )

is already in clause form notation, because is already in clause form notation, because is not is not distributed. Hence, it consists of the following two clauses:distributed. Hence, it consists of the following two clauses:– aa– ( b ( b c ) c )

Page 38: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

ExampleExample

Example:Example: We consider the following statements We consider the following statements translated into logical statements on the right translated into logical statements on the right and we wish to prove that “Poddy will die”.and we wish to prove that “Poddy will die”.

StatementStatement Logical StatementLogical StatementAll dogs are animals.All dogs are animals. (X) dog(X) (X) dog(X) animal(X). animal(X).

Poddy is a dog.Poddy is a dog. dog(poddy).dog(poddy).

All animals will die.All animals will die. (Y) animal(Y) (Y) animal(Y) die(Y). die(Y).

Poddy will die.Poddy will die. die(poddy).die(poddy).

Page 39: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Example 1Example 1

First, we convert the logical statements to the following First, we convert the logical statements to the following clause form notation.clause form notation.

Logical StatementLogical Statement Clause FormClause Form1. 1. (X) dog(X) (X) dog(X) animal(X) animal(X) dog(X) dog(X) animal(X) animal(X)2. dog(poddy)2. dog(poddy) dog(poddy)dog(poddy)3. 3. (Y) animal(Y) (Y) animal(Y) die(Y) die(Y) animal(Y) animal(Y) die(Y) die(Y)

We negate the query that “Poddy will die”.We negate the query that “Poddy will die”.4. die(poddy)4. die(poddy) die(poddy) die(poddy)

Next, we resolve the clauses having opposite literals, Next, we resolve the clauses having opposite literals, producing a new clause by resolution procedure and producing a new clause by resolution procedure and continue until the empty clause is found. continue until the empty clause is found.

On.pl

Page 40: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.10 Resolution proof for Poddy will die

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 41: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Example 2Example 2

Consider the following logical statements translated into Prolog clause form Consider the following logical statements translated into Prolog clause form on the right. We would like to know that “who does John like?” by issuing a on the right. We would like to know that “who does John like?” by issuing a query asquery as?- likes(john, Somebody).?- likes(john, Somebody).

Logical StatementLogical Statement Clause FormClause Form1. likes(david, bert).1. likes(david, bert). likes(david, bert)likes(david, bert)2. likes(bert, john).2. likes(bert, john). likes(bert, john)likes(bert, john)3. likes(john, X) :- likes(X, bert).3. likes(john, X) :- likes(X, bert). likes(X, bert) likes(X, bert) likes(john, X) likes(john, X)4. ?- likes(john, Somebody).4. ?- likes(john, Somebody). likes(john, Somebody) likes(john, Somebody)It is worth noting that, we convert the rule It is worth noting that, we convert the rule likes(john, X) :- likes(X, bert)likes(john, X) :- likes(X, bert) to to form form likes(X, bert) likes(X, bert) likes(john, X) likes(john, X) in order to be converted into clause in order to be converted into clause form, meaning that form, meaning that ifif is changed to is changed to impliesimplies..The empty clause indicates that, the query is true when the variable The empty clause indicates that, the query is true when the variable SomebodySomebody is instantiated to the constant is instantiated to the constant DavidDavid. .

Likes.pl

Page 42: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.11 Resolution proof for ? – likes (john, Somebody)

© 2003 Brooks/Cole Publishing / Thomson Learning™

Error!!, P374 Fig. 11.11

Page 43: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Example 3Example 3

Logical StatementLogical Statement1.1. on(b, a).on(b, a).2.2. on(a, table).on(a, table).3.3. above(X, Y):- on(X,Y).above(X, Y):- on(X,Y).4.4. above(X, Z):- above(X, Y), above(Y, Z).above(X, Z):- above(X, Y), above(Y, Z).5.5. ?-above(b,table).?-above(b,table).

Clause FormClause Form1.1. on(b, a).on(b, a).2.2. on(a, table).on(a, table).3.3. on(X,Y) V above(X, Y). on(X,Y) V above(X, Y). 4.4. above(X, Y) above(X, Y) above(Y, Z) above(Y, Z) above(X, Z). above(X, Z).5.5. above(b,table).above(b,table).

On.pl

Page 44: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.12 Resolution proof for ? - above (b, table)

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 45: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Depth-First SearchDepth-First Search

Matching the fact and rule with the first Matching the fact and rule with the first subgoalsubgoal

Try the facts and rules in orderTry the facts and rules in order

Adding the precondition of the rule at the Adding the precondition of the rule at the beginning of the goal after a matchbeginning of the goal after a match

Page 46: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.13 Portion of the Prolog depth-first search tree leading to success

© 2003 Brooks/Cole Publishing / Thomson Learning™

Family.pl

Page 47: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

To be continuedTo be continued

BacktrackingBacktracking

Deficiencies of PrologDeficiencies of Prolog

Cut OperatorCut Operator

Recursive RulesRecursive Rules

Page 48: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

BacktrackingBacktracking

Prolog uses unification to match a goal to Prolog uses unification to match a goal to the head of a clause, but if there are the head of a clause, but if there are several candidate clauses, which does several candidate clauses, which does Prolog choose to try first? In most cases Prolog choose to try first? In most cases Prolog looks through the clauses in the Prolog looks through the clauses in the order in which they are entered in the logic order in which they are entered in the logic base. This is not the case for a 'sorted' base. This is not the case for a 'sorted' predicate, which is, as the name implies, predicate, which is, as the name implies, stored in sorted order.stored in sorted order.

Page 49: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

BacktrackingBacktrackingProlog's backtracking top-to-bottom, left-to-right search is Prolog's backtracking top-to-bottom, left-to-right search is simple and effective. Backtracking works as follows: simple and effective. Backtracking works as follows:

1.1. If Prolog cannot prove a sub-goal in the body of a clause, If Prolog cannot prove a sub-goal in the body of a clause, then it looks at the sub-goal then it looks at the sub-goal immediately to its leftimmediately to its left. If there . If there are any other clauses which can be used to re-prove this are any other clauses which can be used to re-prove this goal, then any variable bindings which resulted from the goal, then any variable bindings which resulted from the previous clause selection are discarded, and Prolog previous clause selection are discarded, and Prolog continues with the new proof. continues with the new proof.

2.2. If the sub-goal which initially failed was the If the sub-goal which initially failed was the firstfirst goal in the goal in the body of the clause, then the whole goal fails, and the body of the clause, then the whole goal fails, and the backtracking continues in the backtracking continues in the parentparent clause (the clause clause (the clause containing the reference to the goal whose proof just containing the reference to the goal whose proof just failed). failed).

Page 50: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

BacktrackingBacktracking

Backtracking is a very powerful tool since Backtracking is a very powerful tool since it will try and generate a solution by it will try and generate a solution by automated search. automated search.

Unfortunately it can sometimes be too Unfortunately it can sometimes be too powerful, generating solutions that were powerful, generating solutions that were not wanted, and so we have to have some not wanted, and so we have to have some way of controlling it. way of controlling it.

Page 51: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Deficiencies of PrologDeficiencies of Prolog

Resolution order controlResolution order control

Semantics of PrologSemantics of Prolog

The closed world assumptionThe closed world assumption

Page 52: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Resolution order controlResolution order control

In Prolog, statement order is meaningful. In Prolog, statement order is meaningful.

The user can affect both efficiency and semantics by ordering the The user can affect both efficiency and semantics by ordering the statements in a Prolog program.statements in a Prolog program.– parent(bob, pat).parent(bob, pat).– parent(tom, bob).parent(tom, bob).– pred(X, Z) :- parent(X, Z).pred(X, Z) :- parent(X, Z).– pred(X, Z) :- parent(X, Y), pred(Y, Z).pred(X, Z) :- parent(X, Y), pred(Y, Z).– ?- pred(tom, pat).?- pred(tom, pat).– YesYes

If the rules are:If the rules are:– pred(X, Z) :- pred(Y, Z), parent(X, Y).pred(X, Z) :- pred(Y, Z), parent(X, Y).– pred(X, Z) :- parent(X, Z).pred(X, Z) :- parent(X, Z).– ?- pred(tom, pat)?- pred(tom, pat)

Page 53: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Semantics of PrologSemantics of Prolog

Procedural semantics: Procedural semantics: – how Prolog answers questions.how Prolog answers questions.

Declarative semantics: Declarative semantics: – the logical meaning of Prolog programthe logical meaning of Prolog program

Programs with the same declarative semantics may Programs with the same declarative semantics may have different Procedural xsemantics.have different Procedural xsemantics.– Example:Example:

P :- R, S.P :- R, S.P :- S, R.P :- S, R.

Danger of indefinite loopingDanger of indefinite looping– Consider Consider – p :- p.p :- p.– ?- p.?- p.

Page 54: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

The closed world assumptionThe closed world assumption

Anything that cannot be proved to be Anything that cannot be proved to be true is assumed to be false.true is assumed to be false.For Prolog, the only truths are those For Prolog, the only truths are those that can be proved using the given that can be proved using the given facts. Prolog cannot prove that a given facts. Prolog cannot prove that a given goal is false. Prolog adopts the closed goal is false. Prolog adopts the closed world assumption to assume that world assumption to assume that anything that cannot be proved to be anything that cannot be proved to be true be false.true be false.

Page 55: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.15 Tree structure of facts

© 2003 Brooks/Cole Publishing / Thomson Learning™

Resorder.pl;Resorder1.pl;Resorder2.pl

Page 56: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Cut OperatorCut Operator

Denoted with a "Denoted with a "!".!". !/0!/0 is always true, so if a is always true, so if a clause containing a cut is read as a statement of clause containing a cut is read as a statement of truth, it behaves as if there were no cut there. truth, it behaves as if there were no cut there. But cut affects the way backtracking is But cut affects the way backtracking is performed as follows: performed as follows: – Once a cut is executed, the choice of the clause Once a cut is executed, the choice of the clause

which contains it is which contains it is frozenfrozen as a proof step. Also any as a proof step. Also any choices made during the proof of the goals between choices made during the proof of the goals between the head of the clause and the cut are frozen. Thus the head of the clause and the cut are frozen. Thus cut acts like a fence. When backtracking passes over cut acts like a fence. When backtracking passes over the cut (heading left in a clause), then proof the cut (heading left in a clause), then proof reconsideration continues not with the goal to the left reconsideration continues not with the goal to the left of the of the !!, but , but the goal to the left of the goal which the goal to the left of the goal which chose the clause containing the cut.chose the clause containing the cut.

Page 57: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.16 The effect of Cut in the first rule

© 2003 Brooks/Cole Publishing / Thomson Learning™

Orcut.pl

Page 58: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

© 2003 Brooks/Cole Publishing / Thomson Learning™

Figure 11.17 The effect of a Cut in the second rule

Page 59: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.18 The effect of Cut in conjunction with fail

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 60: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

"cut" problem"cut" problem

"cut" (!) is a goal that always succeeds immediately. "cut" (!) is a goal that always succeeds immediately. cut is used to avoid unnecessary backtracking.cut is used to avoid unnecessary backtracking.Example:Example:member(X, [X|L]).member(X, [X|L]).member(X, [Y|L]) :- member(X, L).member(X, [Y|L]) :- member(X, L).This is 'non-deterministic': if X occurs serveral times This is 'non-deterministic': if X occurs serveral times then any occurrence can be found. then any occurrence can be found. A deterministic member: use a cut to prevent A deterministic member: use a cut to prevent backtracking as soon as X is found.backtracking as soon as X is found.member(X, [X|L]):-!.member(X, [X|L]):-!.member(X, [Y|L]) :- member(X, L).member(X, [Y|L]) :- member(X, L).

Page 61: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

"cut" problem"cut" problem

This will generate just one solution.This will generate just one solution.

?- member(X, [a, b, c]).?- member(X, [a, b, c]).

X=a;X=a;

nono

The use of cut is not recommended because it The use of cut is not recommended because it destroys one of the important advantages of logic destroys one of the important advantages of logic programming, i.e., programs do not specify how programming, i.e., programs do not specify how solutions are to be found.solutions are to be found.

  

Page 62: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Negation as failureNegation as failure

ExampleExample– sibling(X, Y) :- parent(M, X), parent(M, Y), sibling(X, Y) :- parent(M, X), parent(M, Y), not(X = Y).not(X = Y).

Definition of negation in Prolog:Definition of negation in Prolog:– not(P) :- P, !, fail; true.not(P) :- P, !, fail; true.

Which can be read:Which can be read:– If P succeeds, then not(P) fails, otherwise not(P) succeeds.If P succeeds, then not(P) fails, otherwise not(P) succeeds.

Page 63: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

The negation problemThe negation problem

The Prolog not operator is not equivalent to a logical The Prolog not operator is not equivalent to a logical NOT operator. NOT operator.

not(not(some_goal)).not(not(some_goal)).

is not always equivalent to some_goal.is not always equivalent to some_goal.

?. not human(mary).?. not human(mary).

YesYes

This means only that there is not enough This means only that there is not enough information in the program to prove that Mary is information in the program to prove that Mary is human. Prolog's reasoning is based on the closed human. Prolog's reasoning is based on the closed world assumption.world assumption.

Page 64: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Recursive RulesRecursive Rules

Let's look at a more interesting extension to the directed Let's look at a more interesting extension to the directed graph program. graph program. Suppose we aren't satisfied with a predicate which Suppose we aren't satisfied with a predicate which distinguishes pairs of nodes linked by paths of length two. distinguishes pairs of nodes linked by paths of length two. Suppose we want a general predicate which is satisfied by Suppose we want a general predicate which is satisfied by a pair of nodes just in case they are linked by a path in the a pair of nodes just in case they are linked by a path in the graph - a path of any (positive) length. graph - a path of any (positive) length. Thinking recursively, we can see that there is a path from Thinking recursively, we can see that there is a path from one node to another if there is an edge between them (a one node to another if there is an edge between them (a base case), or if there is an edge to an intermediate node base case), or if there is an edge to an intermediate node from which there is a path to the final node. from which there is a path to the final node. The following two rules define the path relation for our The following two rules define the path relation for our program. program.

Page 65: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Recursive RulesRecursive Rules

path(Node1,Node2) :- edge(Node1,Node2). path(Node1,Node2) :- edge(Node1,Node2).

path(Node1,Node2) :- path(Node1,Node2) :- edge(Node1,SomeNode), edge(Node1,SomeNode), path(SomeNode,Node2). path(SomeNode,Node2).

There are two important characteristics in this There are two important characteristics in this example. First, the use of two rules (with the example. First, the use of two rules (with the same head) to define a predicate reflects the same head) to define a predicate reflects the use of the logical ``OR'' in a use of the logical ``OR'' in a PrologProlog program. program.

Page 66: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Recursive RulesRecursive Rules

We would read these two rules as: We would read these two rules as:

path(Node1,Node2) is true if path(Node1,Node2) is true if edge(Node1,Node2) is true edge(Node1,Node2) is true oror if there is a node if there is a node SomeNode for which both SomeNode for which both edge(Node1,SomeNode) and edge(Node1,SomeNode) and path(SomeNode,Node2) are true. Second, the path(SomeNode,Node2) are true. Second, the predicate used in the head of the second rule predicate used in the head of the second rule also appears in the body of that rule. The two also appears in the body of that rule. The two rules together show how a recursive definition rules together show how a recursive definition can be implemented in can be implemented in PrologProlog . .

Page 67: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.19 A train route between five cities

© 2003 Brooks/Cole Publishing / Thomson Learning™

Travel.pl

Page 68: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.20 The first stage of the journey

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 69: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.21 The program that corresponds to ? – travel (boiling-springs, columbia)

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 70: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

Figure 11.22 The program that corresponds to ? - travel (boiling-springs, columbia) query

© 2003 Brooks/Cole Publishing / Thomson Learning™

Page 71: COSC3306: Programming Paradigms Lecture 9: Declarative Programming with Prolog Haibin Zhu, Ph.D. Computer Science Nipissing University (C) 2003.

SummarySummary

PrologPrologProgram structureProgram structureLogical variableLogical variableSyntax structureSyntax structureControl structureControl structureResolution and unificationResolution and unificationDFSDFSBacktrackingBacktrackingDeficiencies of PrologDeficiencies of PrologCut OperatorCut OperatorRecursive RulesRecursive RulesProlog facilitiesProlog facilities