19
1 Lecture 15: Introduction to Lecture 15: Introduction to Logic Programming with Logic Programming with Prolog Prolog (Section 11.3) (Section 11.3) A modification of slides A modification of slides developed by Felix Hernandez- developed by Felix Hernandez- Campos at UNC Chapel Hill Campos at UNC Chapel Hill CSCI 431 Programming Languages CSCI 431 Programming Languages Fall 2002 Fall 2002

1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

Embed Size (px)

Citation preview

Page 1: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

11

Lecture 15: Introduction to Logic Lecture 15: Introduction to Logic Programming with PrologProgramming with Prolog

(Section 11.3)(Section 11.3)

A modification of slides developed by Felix A modification of slides developed by Felix Hernandez-Campos at UNC Chapel HillHernandez-Campos at UNC Chapel Hill

CSCI 431 Programming LanguagesCSCI 431 Programming Languages

Fall 2002Fall 2002

Page 2: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

22

Logic ProgrammingLogic Programming

• A logic program is a collection of axiom from which A logic program is a collection of axiom from which theorems can be proventheorems can be proven

• A program is a theoremA program is a theorem– The language tries to find a collection of axioms and The language tries to find a collection of axioms and

inference steps that imply the goalinference steps that imply the goal

• Axiom are written in a standard form known as Axiom are written in a standard form known as Horn Horn clausesclauses

– A Horn clause consists of a A Horn clause consists of a consequentconsequent ( (headhead H) and a H) and a bodybody ( (termsterms B Bii))

H H B B11, B, B22,…, B,…, Bnn

– Semantics: when all BSemantics: when all Bii are true, we can deduce that H is are true, we can deduce that H is truetrue

Page 3: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

33

ResolutionResolution

• Horn clauses can capture most logical statementsHorn clauses can capture most logical statements– But not allBut not all

• The derivation of new statements is known as The derivation of new statements is known as resolutionresolution

– The logic programming system combines existing The logic programming system combines existing statements to find new statementsstatements to find new statements

– For instance,For instance,C C A, B A, BD D C CD D A, B A, B

A and B imply CA and B imply C

If we know that A and B imply C, If we know that A and B imply C, and that C implies D, and that C implies D, then we can deduce that A and B imply Dthen we can deduce that A and B imply D

Page 4: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

44

ExampleExample

flowery(X) flowery(X) rainy(X) rainy(X)

rainy(Rochester)rainy(Rochester)

flowery(Rochester)flowery(Rochester)

VariableVariable

Predicate Applied to a VariablePredicate Applied to a Variable

Predicate Applied to an AtomPredicate Applied to an Atom

Free Variable X acquired value Free Variable X acquired value Rochester during the resolutionRochester during the resolutionThis is known as This is known as UnificationUnification

Page 5: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

55

PrologProlog

• PROgramming in LOGicPROgramming in LOGic

• It is the most widely used logic programming It is the most widely used logic programming languagelanguage

• Its development started in 1970 and it was result of Its development started in 1970 and it was result of the collaboration between researchers from the collaboration between researchers from Marseille, France, and Edinburgh, ScotlandMarseille, France, and Edinburgh, Scotland

• Main applications:Main applications:– Artificial intelligence: expert systems, natural language Artificial intelligence: expert systems, natural language

processing, …processing, …– Databases: query languages, data mining,…Databases: query languages, data mining,…– Mathematics: theorem proving, symbolic packages,…Mathematics: theorem proving, symbolic packages,…

Page 6: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

66

SWI-PrologSWI-Prolog

• We will use SWI-Prolog for the Prolog programming We will use SWI-Prolog for the Prolog programming assignmentassignment

– http://www.swi-prolog.org/http://www.swi-prolog.org/

• After the installation, try the example programAfter the installation, try the example program?- [likes].?- [likes].% likes compiled 0.00 sec, 2,148 bytes% likes compiled 0.00 sec, 2,148 bytesYesYes?- likes(sam, curry).?- likes(sam, curry).NoNo?- likes(sam, X).?- likes(sam, X).X = dahl ;X = dahl ;X = tandoori ;X = tandoori ;X = kurma ;X = kurma ;

Load example likes.pl Load example likes.pl

This goal cannot be proved, so it assumed This goal cannot be proved, so it assumed to be false (This is the so called to be false (This is the so called Close Close World AssumptionWorld Assumption))

Asks the interpreter to Asks the interpreter to find more solutionsfind more solutions

Page 7: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

77

SWI-PrologSWI-Prolog

• The editor shipped as part of SWI-Prolog supports The editor shipped as part of SWI-Prolog supports coloring and context-sensitive indentationcoloring and context-sensitive indentation

– Try “Edit” under “File”Try “Edit” under “File”

Page 8: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

88

Prolog Programming ModelProlog Programming Model

• A program is a A program is a database of (Horn) clausesdatabase of (Horn) clauses

• Each clauses is composed of Each clauses is composed of termsterms::– ConstantsConstants (atoms, that are identifier starting with a (atoms, that are identifier starting with a

lowercase letter, or numbers)lowercase letter, or numbers)» E.g. E.g. curry, 4.5curry, 4.5

– Variables Variables (identifiers starting with an uppercase letter)(identifiers starting with an uppercase letter)» E.g. E.g. FoodFood

– Structures Structures (predicates or data structures)(predicates or data structures)» E.g. E.g. indian(Food)indian(Food), , date(Year,Month,Day)date(Year,Month,Day)

Page 9: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

99

Data StructuresData Structures

• Data structures consist of an atom called the Data structures consist of an atom called the functorfunctor and a list of argumentsand a list of arguments

– E.g. E.g. date(Year,Month,Day)date(Year,Month,Day)

– E.g.E.g.

T = tree(3, tree(2,nil,nil), tree(5,nil,nil))T = tree(3, tree(2,nil,nil), tree(5,nil,nil))

33

5522

FunctorsFunctors

Page 10: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1010

Principle of ResolutionPrinciple of Resolution

• Prolog execution is based on the Prolog execution is based on the principle of principle of resolutionresolution

– If CIf C11 and C and C22 are Horn clauses and the head of C are Horn clauses and the head of C11 matches matches one of the terms in the body of Cone of the terms in the body of C22, then we can replace the , then we can replace the term in Cterm in C22 with the body of C with the body of C11

• For example,For example,CC11: : likes(sam,Food) :- indian(Food), mild(Food).likes(sam,Food) :- indian(Food), mild(Food).

CC22: : indian(dahl).indian(dahl).

CC33: : mild(dahl).mild(dahl).

– We can replace the first and the second terms in CWe can replace the first and the second terms in C11 by C by C22 and Cand C3 3 using the principle of resolution (after using the principle of resolution (after instantiatinginstantiating variable variable FoodFood to to dahldahl))

– Therefore, Therefore, likes(sam, dahl)likes(sam, dahl) can be proved can be proved

Page 11: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1111

UnificationUnification

• Prolog associates variables and values using a Prolog associates variables and values using a process known as process known as unificationunification

– Variable that receive a value are said to be Variable that receive a value are said to be instantiatedinstantiated

• Unification rulesUnification rules– A constant unifies only with itselfA constant unifies only with itself– Two structures unify if and only if they have the same Two structures unify if and only if they have the same

functor and the same number of arguments, and the functor and the same number of arguments, and the corresponding arguments unify recursivelycorresponding arguments unify recursively

– A variable unifies to with anythingA variable unifies to with anything

Page 12: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1212

EqualityEquality

• Equality is defined as Equality is defined as unifiabilityunifiability– An equality goal is using an infix predicate An equality goal is using an infix predicate ==

• For instance,For instance,?- dahl = dahl.?- dahl = dahl.YesYes?- dahl = curry.?- dahl = curry.NoNo?- likes(Person, dahl) = likes(sam, Food).?- likes(Person, dahl) = likes(sam, Food).Person = samPerson = samFood = dahl ;Food = dahl ;NoNo?- likes(Person, curry) = likes(sam, Food).?- likes(Person, curry) = likes(sam, Food).Person = samPerson = samFood = curry ;Food = curry ;NoNo

Page 13: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1313

EqualityEquality

• What is the results ofWhat is the results of

?- likes(Person, Food) = likes(sam, Food).?- likes(Person, Food) = likes(sam, Food).

Person = samPerson = samFood = _G158 ;Food = _G158 ;

NoNo

Internal Representation for an Internal Representation for an uninstantiated variableuninstantiated variableAnyAny instantiation proves the equality instantiation proves the equality

Page 14: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1414

Execution OrderExecution Order

• Prolog searches for a resolution sequence that Prolog searches for a resolution sequence that satisfies the goalsatisfies the goal

• In order to satisfy the logical predicate, we can In order to satisfy the logical predicate, we can imagine two search strategies:imagine two search strategies:

– Forward chainingForward chaining, derived the goal from the axioms, derived the goal from the axioms– Backward chainingBackward chaining, start with the goal and attempt to , start with the goal and attempt to

resolve them working backwardsresolve them working backwards

• Backward chaining is usually more efficient, so it is Backward chaining is usually more efficient, so it is the mechanism underlying the execution of Prolog the mechanism underlying the execution of Prolog programsprograms

– Forward chaining is more efficient when the number of Forward chaining is more efficient when the number of facts is small and the number of rules is very largefacts is small and the number of rules is very large

Page 15: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1515

Backward Chaining in PrologBackward Chaining in Prolog

• Backward Backward chaining chaining follows a follows a classic classic depth-first depth-first backtracking backtracking algorithmalgorithm

• ExampleExample– Goal:Goal:

Snowy(C)Snowy(C)

Page 16: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1616

Depth-first backtrackingDepth-first backtracking

• The search for a resolution is ordered and depth-firstThe search for a resolution is ordered and depth-first– The behavior of the interpreter is predictableThe behavior of the interpreter is predictable

• Ordering is fundamental in recursionOrdering is fundamental in recursion– Recursion is again the basic computational technique, as it Recursion is again the basic computational technique, as it

was in functional languageswas in functional languages– Inappropriate ordering of the terms may result in non-Inappropriate ordering of the terms may result in non-

terminating resolutions (infinite regression)terminating resolutions (infinite regression)– For example: GraphFor example: Graph

edge(a,b). edge(b, c). edge(c, d).edge(a,b). edge(b, c). edge(c, d).

edge(d,e). edge(b, e). edge(d, f).edge(d,e). edge(b, e). edge(d, f).

path(X, X).path(X, X).

path(X, Y) :- edge(Z, Y), path(X, Z).path(X, Y) :- edge(Z, Y), path(X, Z).

CorrectCorrect

Page 17: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1717

Depth-first backtrackingDepth-first backtracking

• The search for a resolution is ordered and depth-firstThe search for a resolution is ordered and depth-first– The behavior of the interpreter is predictableThe behavior of the interpreter is predictable

• Ordering is fundamental in recursionOrdering is fundamental in recursion– Recursion is again the basic computational technique, as it Recursion is again the basic computational technique, as it

was in functional languageswas in functional languages– Inappropriate ordering of the terms may result in non-Inappropriate ordering of the terms may result in non-

terminating resolutions (infinite regression)terminating resolutions (infinite regression)– For example: GraphFor example: Graph

edge(a,b). edge(b, c). edge(c, d).edge(a,b). edge(b, c). edge(c, d).

edge(d,e). edge(b, e). edge(d, f).edge(d,e). edge(b, e). edge(d, f).

path(X, Y) :- path(X, Z), edge(Z, Y).path(X, Y) :- path(X, Z), edge(Z, Y).

path(X, X).path(X, X).

IncorrectIncorrect

Page 18: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1818

Infinite RegressionInfinite Regression

GoalGoal

Page 19: 1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill

1919

ExamplesExamples

• GenealogyGenealogy– http://ktiml.mff.cuni.cz/~bartak/prolog/genealogy.htmlhttp://ktiml.mff.cuni.cz/~bartak/prolog/genealogy.html

• Data structures and arithmeticData structures and arithmetic– Prolog has an arithmetic functor Prolog has an arithmetic functor isis that unifies arithmetic that unifies arithmetic

valuesvalues» E.g.E.g. is (X, 1+2), X is 1+2is (X, 1+2), X is 1+2

– Dates exampleDates example» http://http://ktimlktiml..mffmff..cunicuni..czcz/~/~bartakbartak/prolog/basic_/prolog/basic_structstruct.html.html