+ All Categories
Home > Documents > Introduction to Logic Programming with Prolog (Section 11.3)

Introduction to Logic Programming with Prolog (Section 11.3)

Date post: 30-Dec-2015
Category:
Upload: nelle-atkinson
View: 54 times
Download: 1 times
Share this document with a friend
Description:
Introduction to Logic Programming with Prolog (Section 11.3). CSCI 431 Programming Languages Fall 2003. A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill. Prolog. Prolog is a declarative language - PowerPoint PPT Presentation
23
1 Introduction to Logic Introduction to Logic Programming with Prolog Programming with 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 2003 Fall 2003
Transcript

11

Introduction to Logic 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 2003Fall 2003

22

PrologProlog

• Prolog is a Prolog is a declarative languagedeclarative language

• A program is a collection of A program is a collection of axiomsaxioms from which from which theoremstheorems can be proven. can be proven.

– Rather than describing how to compute a solution, a Rather than describing how to compute a solution, a program consists of a data base of facts and logical program consists of a data base of facts and logical relationships (rules).relationships (rules).

– Rather then running a program to obtain a solution, the Rather then running a program to obtain a solution, the user asks a question. When asked a question, the run time user asks a question. When asked a question, the run time system searches through the data base of facts and rules to system searches through the data base of facts and rules to determine (by logical deduction) the answer. determine (by logical deduction) the answer.

33

Logic ProgrammingLogic Programming

• 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

44

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

55

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

66

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,…

77

A Prolog ProgramA Prolog Program

• The program, sometimes called Database is a text file (*.pl) The program, sometimes called Database is a text file (*.pl) that contain the facts and rules. It contains all the relations that contain the facts and rules. It contains all the relations needed to define the problem.needed to define the problem.

• When you launch a program you are in query mode When you launch a program you are in query mode represented by the ? – prompt. In query mode you ask represented by the ? – prompt. In query mode you ask questions about the relations described in the program.questions about the relations described in the program.

• When Prolog is launched the ?- should appear meaning you When Prolog is launched the ?- should appear meaning you are in query mode. In are in query mode. In SWI-PrologSWI-Prolog you can load a program by you can load a program by typing the command typing the command [file].[file]. when the file containing your when the file containing your program is file.pl. When you have done this you can use all program is file.pl. When you have done this you can use all the facts and rules that are contained in the program. the facts and rules that are contained in the program.

88

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

99

ExampleExample

location(desk, office). location(desk, office).

location(apple, kitchen). location(apple, kitchen).

location(flashlight, desk). location(flashlight, desk).

location('washing machine', location('washing machine', cellar). cellar).

location(nani, 'washing location(nani, 'washing machine'). machine').

location(broccoli, kitchen). location(broccoli, kitchen).

location(crackers, kitchen). location(crackers, kitchen).

location(computer, office). location(computer, office).

?- location(apple, kitchen). ?- location(apple, kitchen). yes yes

ProgramProgram

QueryQuery

1010

Prolog Programming ModelProlog Programming Model

• A program is a A program is a database of (Horn) clauses database of (Horn) clauses that are that are assumed to be true.assumed to be true.

• The clauses in a Prolog database are eitherThe clauses in a Prolog database are either facts facts oror rules. rules. Each ends with a period.Each ends with a period.

• A A factfact is a clause without a right-hand side. is a clause without a right-hand side.– rainy(asheville).rainy(asheville).

• A A rulerule has a right-hand side. has a right-hand side.– snowy(X) :- rainy(X), cold(X).snowy(X) :- rainy(X), cold(X).

• The token :- is the implication symbol.The token :- is the implication symbol.

• The comma (,) indicates “and”The comma (,) indicates “and”

1111

Prolog ClausesProlog Clauses

• A A queryquery or or goalgoal is a clause with an empty left-hand is a clause with an empty left-hand side. Queries are given to the prolog interpreter to side. Queries are given to the prolog interpreter to initiate execution of a program.initiate execution of a program.

• 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, numbers, punctuation, and quoted strings)lowercase letter, numbers, punctuation, and quoted strings)» E.g. E.g. curry, 4.5, +, ‘Hi, Mom’curry, 4.5, +, ‘Hi, Mom’

– 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)

1212

StructuresStructures

• Structures consist of an atom called the Structures consist of an atom called the functorfunctor and a and a list of argumentslist 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

1313

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

1414

Another ExampleAnother Example

takes(jane_doe, his201).takes(jane_doe, his201).

takes(jane_doe, cs245).takes(jane_doe, cs245).

takes(ajit_chandra, art302).takes(ajit_chandra, art302).

takes(ajit_chandra, cs254).takes(ajit_chandra, cs254).

classmates(X, Y) :- takes(X, Z), takes(Y, Z).classmates(X, Y) :- takes(X, Z), takes(Y, Z).

classmates(jane_doe, Y) :- takes(Y, cs254).classmates(jane_doe, Y) :- takes(Y, cs254).

via resolution, yields the new rule:via resolution, yields the new rule:

1515

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

1616

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

1717

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

1818

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

1919

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)

2020

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

2121

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

2222

Infinite RegressionInfinite Regression

GoalGoal

2323

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


Recommended