4.1 Course Content Introduction to Prolog and Logic Programming. Prolog basic constructs: Facts,...

91
4.1 Course Content • Introduction to Prolog and Logic Programming. • Prolog basic constructs: Facts, rules, knowledge base, goals, unification, instantiation. • Prolog syntax, characters, equality and arithmetic. • Data Structures: Structures and trees, lists, strings. • Control Structures: – Backtracking, recursion, cut and failure. • Input and output, assertions, consulting. • Applications: Databases, Artificial

Transcript of 4.1 Course Content Introduction to Prolog and Logic Programming. Prolog basic constructs: Facts,...

4.14.1

Course ContentCourse Content

• Introduction to Prolog and Logic Programming.

• Prolog basic constructs: Facts, rules, knowledge base,

goals, unification, instantiation.

• Prolog syntax, characters, equality and arithmetic.

• Data Structures: Structures and trees, lists, strings.

• Control Structures:

– Backtracking, recursion, cut and failure.

• Input and output, assertions, consulting.

• Applications: Databases, Artificial Intelligence

– Games, natural language processing, metainterpreters

4.24.2

Course AimsCourse Aims

• This course aims to help you to:

• Understand a radically different programming paradigm: Declarative programming

• See how logic programming contributes to the quest for Artificial Intelligence

• Learn a new programming language called Prolog

• Appreciate the strengths and weaknesses of Prolog

4.34.3

BooksBooks

• Useful Books

• Textbook:Ivan Bratko, Prolog-Programming for Artificial Intelligence, 3rd Edition, Addison Wesley, 2001.

• Optional books for further reading:

– Leon Sterling and Ehud Shapiro, The Art of Prolog,2nd Edition, MIT Press, 1994.

– W. F. Clocksin, C. S. Mellish, Programming in Prolog:Using the Iso Standard, 5th edition, Springer-Verlag,2003.

4.44.4

How to Succeed in this CourseHow to Succeed in this Course

• Attend all classes and make sure you understand everything covered in each class before coming to the next.

• If you need help come to see me during my office hours.

• In case you miss a class, make sure you cover the material of that class at home from the notes and the textbook.

• Do all homework and assignments – these are designed to help you understand and use the material taught.

• Read the relevant sections of the textbook

• Practice with Prolog at home

4.54.5

Logic ProgrammingLogic Programming

• Problem Solving =

– Problem Description + Logical Deductions

• How do we build in the ability to do the deductions?

• Ideally we would like to be able to tell the computer ‘what’ we want it to do and not ‘how’ we want it to do it.

4.64.6

PrologProlog

• Prolog = Programming in Logic.

• Prolog is based on first order logic.

• Prolog is declarative (as opposed to imperative):

– You specify what the problem is rather than how to solve it.

• Prolog is very useful in some areas (AI, natural language processing), but less useful in others (graphics, numerical algorithms).

4.74.7

Introducing PrologIntroducing Prolog

• Prolog is the first attempt to design a purely declarative programming language.

• It is short for ‘Programmation en Logique’.

• It was developed in the 1970’s by

– Robert Kowalski and Maarten Van Emden (Edinburgh)

– Alain Colmerauer (Marseille)

• It was efficiently implemented by DavidWarren.

4.84.8

Imperative vs DeclarativeImperative vs Declarative

• Programming In imperative programming (e.g. Java, Pascal, C++), you tell the computer HOW to solve the problem, i.e. do this, then do that.

• In declarative programming (e.g. Prolog),you declare WHAT the problem is, and leave it to the computer to use built-in reasoning to solve the problem.

4.94.9

ComparisonComparison

4.104.10

Introducing PrologIntroducing Prolog

• When you write a Prolog program, you are writing down your knowledge of the problem – you are modelling the problem.

• Prolog is widely used for specifying and modelling systems (e.g. Software prototyping, design of circuits), and for many artificial intelligence applications such as expert systems and natural language processing.

4.114.11

Logic ProgrammingLogic Programming

• A program in logic is a definition (declaration) of the world - the entities and the relations between them.

• Logic programs establishing a theorem (goal) and asks the system to prove it.

• Satisfying the goal:

– yes, prove the goal using the information from the knowledge base

– no: cannot prove the truth of the goal using the information

from the knowledge base the goal is false according to available information

4.124.12

4.134.13

Predicate LogicPredicate Logic

• Involves entities and relations between entities.

– Entities are expressed using: Variables : X, Y, Somebody, Anybody Constants : fido, fiffy, bigger, dog, has, bone Logical operators - connectors between relations

and , or, not, logically implies, logically equivalent, for all, exists

– Relations are expressed using: Predicates - express a simple relation among entities, or a

property of some entity fido is a dog - dog(fido) fiffy is a dog - dog(fiffy) fido is bigger than fiffy - bigger(fido, fiffy)

4.144.14

Predicate Logic (cont.)Predicate Logic (cont.)

• Formulas - express a more complex relation among entities

– if fido is bigger than fiffy, and fiffy has a bone, then fido can take the bone

• Sentences - are formulas with no free variables

– dog(X) contains a variable which is said to be free while

the X in for all X.dog(X) is ∀ bound.

4.154.15

Prolog ConceptsProlog Concepts

• For a powerful, all-purpose programming language prolog has remarkably few concepts.

• A Prolog program consists of a set of clauses

• Each clause is either a fact or a rule

4.164.16

ClausesClauses

• In Prolog, rules (and facts) are called clauses.

• A clause always ends with ‘.’

– Clause: <head> :- <body>. you can conclude that <head> is true, if you canprove that

<body> is true

– Facts - clauses with an empty body: <head>. you can conclude that <head> is true

– Rules - normal clauses (or more clauses)

– Queries - clauses with an empty head: ?- <body>. Try to prove that <body> is true

4.174.17

Examples of ClausesExamples of Clauses

• Facts:

male(philip).

female(anne).

parent(philip,anne).

• Rules:

father(X,Y) :- parent(X,Y), male(X).

ancestor(X,Y) :- parent(X,Y).

ancestor(X,Y) :- ancestor(X,Z), parent(Z,Y).

4.184.18

PROLOG Data ObjectsPROLOG Data Objects

• Programs process data.

• PROLOG data objects :

Terms

structures simple objects

literal constantsvariables

atomsnumbers

4.194.19

PROLOG Data Objects IIPROLOG Data Objects II

• PROLOG data objects are called terms.

• PROLOG distinguishes between terms according to their syntactic structure.

– Structures look different from simple objects.

• PROLOG is a typeless language.

– All it checks is that arithmetic operations are done with numbers and I/O is done with ASCII characters.

– Checks are done at run time.

• PROLOG fans claim that typelessness gives great flexibility.

4.204.20

AtomsAtoms

• Atoms : non-numeric literal constants. Strings containing combinations of

– lower case letters

– upper case letters

– digits

– special characters like +, -, _, *, >, < etc.

• Three types of atom : alphanumerics, special character strings and (single) quoted character strings.

• Alphanumerics :

– Similar to C++ or Java identifiers.

– Strings of letters, digits and _. Must start with a lower case letter. Relation names must always be alphanumeric atoms.

– e.g. octavius, constantine1, fred_bloggs.

4.214.21

Atoms IIAtoms II

• Special character strings :

– Strings of the allowed special characters. May not contain letters, digits or _.

– e.g. >==>, ----, <<<>>>.

• Quoted character strings :

– Strings of any character enclosed between ‘.

– e.g. ‘Fred Bloggs’, ‘3 pounds of spuds.’.

– Very useful for atoms beginning with upper case letters.

emperor(‘Octavius’).

4.224.22

NumbersNumbers

• PROLOG allows both integer and floating point types.

• Integer :

– e.g. 23, 10243, -23.

• Floats :

– e.g. 0.23, 1.0234, -12.23.

• Floats using exponential notation :

– e.g. 12.3e34, -11.2e-45, 1.0e45.

• PROLOG suffers from the usual problems with floating point rounding errors.

• PROLOG is terrible at numeric computation.

– See below.

4.234.23

VariablesVariables

• Strings of letters, digits and _. Must start with an upper case letter or with _.

• Similar to alphanumerics.

– e.g. X, Variable, Fred_bloggs, _23.

• PROLOG variables are logical variables, not store variables.

– Given values by instantiation during matching not by assignment .

• Sometimes we don’t want to give a variable a name because we don’t care about it’s value.

– Anonymous variables.

4.244.24

VariablesVariables

• Scope rule:

• – Two uses of an identical name for a logical variable only refer to the same object if the uses are within a single clause.

happy(Person) :- healthy(Person). % same person

wise(Person) :- old(Person). /* may refer to other

person than in above clause. */

• Two commenting styles!

4.254.25

Variables IIVariables II• Very common in queries :

|? - parent(_,gaius).true ?|? -

• Can also use them in facts or rules :

killer(X) :- murdered(X,_).

|? - killer(tiberius).yes|? -

• GNU PROLOG doesn’t bother printing the name of tiberius’ killer.

• Each use of _ in a clause can take a different value.

4.264.26

VariablesVariables

• Names that stand for objects that may already or may not yet be determined by a Prolog program

– if the object a variable stands for is already determined, the variable is instantiated

– if the object a variable stands for is not yet determined, the variable is uninstantiated

• a Prolog variable does not represent a location that contains a modifiable value; it behaves more like a mathematical variable (and has the same scope)

• An instantiated variable in Prolog cannot change its value

• Constants in Prolog : numbers, strings that start with lowercase, anything between single quotes

• Variables in Prolog: names that start with an uppercase letter or with ‘_’

• Examples:

Variables Constants

X,Y, Var, Const, x, y, var,const

_const, _x, _y some_Thing, 1, 4, ‘String’,“List of ASCII codes”

39

4.274.27

Anonymous variablesAnonymous variables

• a variable that stands in for some unknown object

• stands for some objects about which we don’t care

• several anonymous variables in the same clause

• need not be given consistent interpretation

• written as _ in Prolog

?- composer(X, _, _).

X = beethoven;

X = mozart;

• We are interested in the names of composers but not their birth and death years.

4.284.28

• Structured objects are objects that have several components

• The components can, in turn be structures|? - date(1,may,1983).

• date is functor and 1, may, 1983 are the parameters

• All data objects are term. (e.g. may, date(1,may,1983).

• All structured objects can be pictured as trees. The root of the tree is the functor.

• Examples of the book (p:34-37)

StructuresStructures

4.294.29

4.304.30

Structures - ExerciseStructures - Exercise

• Description:

– point in the 2D space

– triangle

– a country has a name is located in a continent at a certain position has population has capital city which has a certain population has area

4.314.31

Structures - ExerciseStructures - Exercise

• Knowledge base:

country(canada, location(america, north), population(30), capital(‘Ottawa’,1),area(_)).

country(usa, location(america, north), population(200), capital(‘Washington DC’, 17), area(_)).

4.324.32

A Particular StructureA Particular Structure

• How can we represent the courses a student takes?

courses(csi2111, csi2114, csi2165)

courses(csi2114, csi2115, csi2165, mat2343)

courses(adm2302, csi2111, csi2114, csi2115, csi2165)

• Three different structures.

• In general, how do we represent a variable number of arguments with a single structure?

• LISTS

4.334.33

Verify Type of a TermVerify Type of a Term

• var(+Term): Succeeds if Term is currently a free variable.

• nonvar(+Term): Succeeds if Term is currently not a free variable.

• integer(+Term): Succeeds if Term is bound to an integer.

• float(+Term): Succeeds if Term is bound to a floating point number.

• number(+Term): Succeeds if Term is bound to an integer or a floating point number.

• atom(+Term): Succeeds if Term is bound to an atom.

• string(+Term): Succeeds if Term is bound to a string.

• atomic(+Term): Succeeds if Term is bound to an atom, string, integer or float.

• compound(+Term): Succeeds if Term is bound to a compound term.

4.344.34

4.354.35

DefinitionsDefinitions

• Three basic constructs in Prolog

– Facts, rules, and queries.

• Knowledge base (database)

– A collection of facts and rules.

– Prolog programs are knowledge bases.

• We use Prolog programs by posing queries.

4.364.36

FactsFacts

• A fact represents a unit of information that is assumed to be true.

its_raining.

• Often, a fact asserts some property of a term, or a list of terms.

male(philip).

parent(philip,anne).

4.374.37

FactsFacts• Facts are used to state things that are unconditionally true.

– We pay taxes. we_pay_taxes.

– The earth is round. The sky is blue. round(earth). blue(sky).

– Beethoven was a composer that lived between 1770 and 1827. composer(beethoven,1770,1827).

– Tom is the parent of Liz. parent(liz, tom).

– fido is bigger than fiffy. bigger(fido,fiffy).

• Exercise: John owns the book. John gives the book to Mary.

4.384.38

RulesRules

• A rule represents a conditional assertion

• (‘this is true if this is true’).

• need_umbrella :- its_raining.

• father(X,Y) :- parent(X,Y), male(X).

IF AND

4.394.39

RulesRules

• In general a rule is an expression of the form

A :- B1, B2,…, Bn.

where A and B1, B2,…, Bn are atomic formulas.

– A is called the head of the rule.

– B1, B2,…, Bn is called the body of the rule.

4.404.40

RulesRules

• Rules state information that is conditionally true of the domain of interest.

• The general form of these properties

– p is true if (p1 is true, and p2 is true, … and pn is true)

• Horn clause

– p :- p1, p2, …, pn.

• Interpretation (Prolog) :

– in order to prove that p is true, the interpreter will provethat each of p1, p2, …, pn is true

– p - the head of the rule

– p1, p2, …, pn - the body of the rule (subgoals)

4.414.41

ExamplesExamples

• A man is happy if he is rich and famous.

• In Prolog:

– The ‘,’ reads ‘and’ and is equivalent to /\ of predicate calculus.

happy(Person) :- man(Person), rich(Person),famous(Person).

4.424.42

Rules and DisjunctionsRules and Disjunctions

• Someone is happy if he/she is healthy, wealthy or wise.

• In Prolog:

• More exactly:

– Someone is happy if they are healthy OR

– Someone is happy if they are wealthy OR

– Someone is happy if they are wise.

happy(Person) :- healthy(Person).

happy(Person) :- wealthy(Person).

happy(Person) :- wise(Person).

4.434.43

Both Disjunctions and ConjunctionsBoth Disjunctions and Conjunctions

• A woman is happy if she is healthy, wealthy or wise.

• In Prolog:

happy(Person) :- healthy(Person), woman(Person).

happy(Person) :- wealthy(Person), woman(Person).

happy(Person) :- wise(Person), woman(Person).

4.444.44

RulesRules

• If there is smoke there is fire. fire :- smoke.

• Liz is an offspring of Tom if Tom is a parent of Liz.

offspring(liz, tom) :- parent(tom, liz).

• Y is an offspring of X if X is a parent of Y.

offspring(Y, X) :- parent(X, Y).

• Two persons are sisters if they are females and have the same parents.

siblings(P1, P2) :- parent(P, P1), parent(P, P2).

• What is the problem with this rule?

• Exercise: Family relations

grandparent(X,Y) :-

4.454.45

ExampleExample

cat(349, ‘Dickens’, ‘Oliver Twist’).

cat(487, ‘Bronte’, ‘Jane Eyre’).

cat(187, ‘Boole’, ‘Laws of Thought’).

...

fiction(Author, Title) :-

cat(Num, Author, Title),

Num > 200, Num < 600.

4.464.46

QueriesQueries

• Once we have a Prolog program we can use it to answer a query.

– ?- parent(philip, anne).

– ?- border(wales, scotland).

• The Prolog interpreter responds ‘yes’ or ‘no’.

• Note that all queries must end with a dot.

4.474.47

QueriesQueries

• The goal represented as a question.

?- round(earth). /* is it true that the earth is round? */

?- round(X). /* is it true that there are entities which are round?

(what entities are round?) */

?- composer(beethoven, 1770, 1827). /* is it true that

Beethoven was a composer who lived between 1770 and

1827)? */

?- owns(john, book). /* is it true that john owns a book? */

?- owns(john, X). /* is it true that john owns something? */

4.484.48

QueriesQueries

• A query may contain variables:

• ?- parent(philip, Who).

• The Prolog interpreter will respond with the values for the variables which make the query true (if any).

• Otherwise it will respond with a ‘no’.

4.494.49

ExampleExample

?- parent(philip, Who).

Who = anne;

Who = charles;

Who = andrew;

no

If we have the Prolog program:

male(charles).

male(edward).

male(philip).

parent(philip, anne).

parent(philip, edward).

parent(philip, charles).

4.504.50

Example (cont.)Example (cont.)

And we enter the query:

?- parent(X, charles), parent(X,Y), male(Y).

Then we get the response

X = philip,

Y = edward;

What happens next?

If we have the Prolog program:

male(charles).

male(edward).

male(philip).

parent(philip, anne).

parent(philip, edward).

parent(philip, charles).

4.514.51

ExampleExample

• We have a Prolog program:

likes(mary, food).

likes(mary, apple).

likes(john, apple).

likes(john, mary).

• Now we pose the query:

?- likes(mary, X), likes(john, X).

• What answers do we get?

4.524.52

PredicatePredicate

• composer(beethoven,1770,1827) → predicate

– composer → functor

– beethoven, 1770, 1827 → arguments

– number of arguments: 3 → arity.

– write as composer/3

4.534.53

Side-effectsSide-effects

• Some queries may cause the system to carry out certain actions.

• ?- halt.

– this causes the Prolog system to exit.

• ?- consult(‘myfile’).

– this causes the Prolog system to read the contents of myfile and add the clauses to the current program.

– this causes the Prolog system to read the user input as a Prolog program until terminated by a CTRL-D.

• ?- listing(predname).

– this causes the Prolog system to output a listing of the clauses defining the predicate predname in the current program.

4.544.54

ExerciseExercise

• Suppose we have the following Prolog program:

male(charles).

male(philip).

:

parent(philip, anne).

parent(elizabeth, edward).

:

wife(elizabeth, philip).

wife(mary, george).

• Write queries to find:

1. The parents of charles.

2. The father of charles.

3. The grandparents of charles.

4. All the grandchildren of the grandparents of charles.

4.554.55

Matching, Unification, and InstantiationMatching, Unification, and Instantiation

• Prolog will try to find in the knowledge base a fact or a rule which can be used in order to prove a goal

• Proving :

– match the goal on a fact or head of some rule. If matching succeeds, then:

– unify the goal with the fact or the head of the rule. As a result of unification:

– instantiate the variables (if there are any), such that the matching succeeds

• NB: variables in Prolog cannot change their value once they are instantiated !

4.564.56

MatchingMatching

• Two terms match when

– They are identical

– Or the variables in both terms can be instantiated to objects in such a way that after the substitution of variables of these objects the terms become identical

e.g. Date(D,M, 1983) vs date(D1, may, Y1) matches

4.574.57

MatchingMatching

• General Rules for matching two terms S and T

– If S and T are constants then S and T match only if they are the same object

– If S is a variable and T is anything then they match and S is instantiated to T. Vice versa

– If S and T are structures then they match only if S and T have the same principal functor and All their corresponding components match

The resulting instantiation is determined by the matching of the components.

4.584.58

MatchingMatching

• Matching: Prolog tries to find a fact or a head of some rule with which to match the current goal

• Match: the functor and the arguments of the current goal, with the functor and the arguments of the fact or head of rule

• Rules for matching :

– constants only match an identical constant

– variables can match anything, including other variables

Goal Predicate Matching

constant constant yes

constant other_constant no

Var some_constant yes

Var Other_Var yes

some_constant Some_Var yes

4.594.59

Instantiation and UnificationInstantiation and Unification

• Instantiation

– the substitution of some object for a variable– a variable is instantiated to some object

composer(X, 1770, 1827) succeeds with X instantiated to beethoven

• Unification

– the instantiations done such that the two terms that match become identical

– two terms match if: they are identical objects their constant parts are identical and their variables can

be instantiated to the same object

composer(X,1770,1827) unifies with composer(beethoven,1770,1827)

with the instantiation X = beethoven

4.604.60

UnificationUnification

• Done after a match between the current goal and a fact or the head of a rule is found

• It attaches values to variables (instantiates the variables), such that the goal and the predicate are a perfect match:

– match:

goal - composer(beethoven, B, D) with fact composer(beethoven,1770,1827)

– unification: B will be instantiated to 1770 D will be instantiated to 1827 such that the goal will match

the fact.

4.614.61

Unification (cont.)Unification (cont.)

• If the match is done on the head of some rule, then the instantiations done for the variables are also valid in the body of the rule:

– match: goal - contemporaries(beethoven, mozart) with head of

contemporaries(X, Y) :-

composer(X, B1, D1),composer(Y, B2, D2), X \== Y, …

– unification: X will be instantiated to beethoven Y will be instantiated to mozart and now the rule will look:

contemporaries(beethoven, mozart) :-

composer(beethoven,B1,D1), composer(mozart, B2, D2),

beethoven \== mozart, ...

4.624.62

4.634.63

4.644.64

4.654.65

Unification OperatorsUnification Operators

• = \= = = \= = is

• Three Kinds of Equality

• When are two terms said to be equal?

• We introduce 3 types of equality now (more later)

– X = Y: this is true if X and Y match.– X is E: this is true if X matches the value of the arithmetic

expression E.– T1 == T2: this is true if terms T1 and T2 are identical

Have exactly the same structure and all the corresponding

components are the same. The name of the variables also

have to be the same. It is called: literal equality.

• If X == Y, then X = Y. the former is a stricter form ofequality.

4.664.66

Unification Operator: =Unification Operator: =

• = → unifies with: X = Y

– succeeds as long as X and Y can be unified

– X may or may not be instantiated

– Y may or may not be instantiated

– X and Y become bound together (they now refer to the same object)

? - p1(a, [A, [B, C] ],25) = p1(C, [B, [D, E] ], 25).

A = B = D, C = E = a, yes

? - a(b, X, c) = a(b, Y, c).

X = Y, yes

4.674.67

Unification Operators: \=Unification Operators: \=

• \= → does not unify with: X \= Y

– succeeds as long as X and Y cannot be unified

– both X and Y must be instantiated (why?)

– X and Y may have uninstantiated elements inside them

? - [A, [B, C]] \= [A, B, C].

yes

? - a(b, X, c) \= a(b, Y, c).

no

4.684.68

Unification Operator: ==Unification Operator: ==

• == → is already instantiated to: X == Y

– succeeds as long as X and Y are already instantiated to the same object

– in particular, any variable inside X and Y must be the same

? - a(b,X,c) == a(b,Y,c).

no

? - a(b,X,c) == a(b,X,c).

yes

4.694.69

Unification Operators: \==Unification Operators: \==

• \== → not already instantiated to: X \== Y

– succeeds as long as X and Y are not already instantiated to the same object

? - A \== hello.

yes

? - a(b,X,c) \== a(b,Y,c).

yes

4.704.70

Arithmetic Operator: isArithmetic Operator: is

• is → arithmetic evaluation : X is Expr

– succeeds a long as X and the arithmetic evaluation of Expr can be unified

– X may or may not be instantiated

– Expr must not contain any uninstantiated variables

– X is instantiated to the arithmetic evaluation of Expr

? - 5 is ( ( 3 * 7 ) + 1 ) / 4.

yes

? - X is ( ( 3 * 4 ) +10) mod 6.

X = 4

4.714.71

ArithmeticArithmetic

• Predefined operators for doing arithmetic:

+ addition

- subtraction

* multiplication

/ division

** power

mod modulo, the remainder of integer division

However, the computation is not “ automatically”:

?- X = 1 + 2.

X = 1 + 2

So, 1 + 2 is a term and X matches that term. To force computation:

?- X is 1 + 2.

X = 3

The infix operator is/2 evaluates the right-side term by calling built-in procedures. All variables must be instantiated to numbers at the time of evaluation!

4.724.72

ArithmeticArithmetic

• Also comparisons invoke evaluation, in this case of both the left-hand side and the right-hand side of the expression:

?- 277 * 37 > 10000.

yes

• The comparison operators:

X > Y X is greater than Y

X < Y X is less than Y

X >= Y X is greater than or equal to Y

X =< Y X is less than or equal to Y

X =:= Y the values of X and Y are equal

X =\= Y the values of X and Y are not equal

4.734.73

ArithmeticArithmetic

• Note the difference between ‘=’ and ‘=:=’; the first operator matches terms, possibly instantiating variables; the second causes arithmetic evaluation and cannot cause instantiation of variables. For example:

?- 1 + 2 =:= 2 + 1.

yes

?- 1 + 2 = 2 + 1.

no

?- 1 + A = B + 2.

A = 2

B = 1

?- 1 + A =:= B + 2.

ERROR

• Other standard functions for arithmetic: sin(X), cos(X), log(X), exp(X), etc.

4.744.74

ArithmeticArithmetic

Two examples for arithmetic operations.

• gcd/3: greatest common divisor D of two positive integers X and Y, using the following cases:

1. If X and Y are equal, then D is equal to X;

2. If X < Y then D is equal to the greatest common divisor of X and the difference Y – X;

3. If Y < X then do the same as in case 2, with X and Y interchanged.

gcd( X, X, X).

gcd( X, Y, D) :-

X < Y,

Y1 is Y - X,

gcd( X, Y1, D).

gcd( X, Y, D) :-

Y < X,

gcd( Y, X, D).

4.754.75

4.764.76

Declarative Semantics (what)Declarative Semantics (what)

• Declarative semantics - telling Prolog what we know.

• If we don’t know if something is true, we assume it is false -closed world assumption.

• Sometimes we tell it relations that we know are false. (sometimes it is easier to show that the opposite of a relation is false, than to show that the relation is true)

• I know (it is true) that the max between two numbers X and Y is X, if X is bigger than Y. max(X, Y, X) :- X > Y.

• I know that the max between two numbers X and Y is Y if Y is bigger or equal to X. max(X, Y, Y) :- Y >= X.

• ?- max(1, 2, X).

4.774.77

Declarative Semantics (cont.)Declarative Semantics (cont.)

• I know that 0 is a positive integer.

positive_integer(0).

• I know that X is a positive integer if there is another positive integer Y such that X is Y+1.

positive_integer(X) :- positive_integer(Y), X is Y+1.

?- positive_integer(3).

?- positive_integer(X).

4.784.78

Declarative meaningDeclarative meaning

• Declarative vs. Procedural meaning in Prolog

• Consider the clause

P:-Q, R.

Declarative:

1. P is true if Q and R are true

2. From Q and R follows P

Procedural

1. To solve problem P first solve the subproblem Q then the subproblem R

2. To satisfy P first satisfy Q then R

4.794.79

• Difference: Procedural does not only define the logical relations bw head of the clause and the goals in the body, but also the order in which the goals are processed

• Formal definition:The declarative meaning of a programs determines whether a given goal is true and if so, for what values of variables it is true.

• Instance: An instance of a clause C is the clause C with each of its variables substituted by some term.

• Variant: A variant of a clause C is such an instance of the clause C where each variable is substituted by another variable

Declarative meaningDeclarative meaning

4.804.80

ExamplesExamples

clause

haschild(X):-parent(X,Y)

variants

haschild(A):-parent(A,B)

haschild(X):-parent(X,Y)

instances

haschild(peter):-parent(peter,ann)

4.814.81

Procedural Semantics (how)Procedural Semantics (how)

• Procedural semantics - how do I prove a goal?

max(X, Y, X) :- X > Y.

max(X, Y, Y) :- Y >= X.

?- max(1, 2, X).

If I can prove that X is bigger then Y, then I can prove that the max between X and Y is X.

or, if that doesn’t work,

If I can prove that Y is bigger or equal to X, then I can prove that the max between X and Y is Y.

4.824.82

Procedural Semantics (cont.)Procedural Semantics (cont.)

positive_integer(0).

positive_integer(X) :- positive_integer(Y), X is Y+1.

?- positive_integer(3).

If I can prove that X is 0, then I can prove that X is a positive integer or,

If I can prove that Y is a positive integer, and if X is Y+1, then I can prove that X is a positive integer.

I can prove that Y is a positive integer if I can prove that Y is 0 or

If I can prove that Z is a positive integer, and if Y is Z+1, then I can prove ...

4.834.83

• Specifies how prolog answers questions

• To answer a question means to try to satisfy a list of goals.

• A procedure for executing a list of goals wrt a given program.

• Read the procedure for executing a list of goals on page 49

• Analyze predecessor program

– According to the declarative semantics of Prolog we can, w/o affecting the declarative meaning, change The order of the clauses in the program And the order of goals in the bodies of clauses (page 59-

60)

Procedural meaningProcedural meaning

4.844.84

Procedural meaningProcedural meaning

• The declarative meaning of programs in pure Prolog does not depend on the order of the clauses and the order of the goals in clauses

• The procedural meaning does depend on the order of goals and clauses. Thus the order can affect the efficiency of the program; an unsuitable order may even lead to innfiniti recursive calls.

• Give declaratively correct0 program, changing the order of the clauses and goal can improve the program’s efficiency while retaining its declarative correctness. Reorderprevent looping

4.854.85

Arithmetic Computation In PROLOGArithmetic Computation In PROLOG

• PROLOG was designed for symbolic computation.

– Not good at numeric computation.

• PROLOG arithmetic operations :

+, -, *, *, div, mod.

• Arithmetic doesn’t work as you might expect.

|? - X = 3 + 4.X = 3 + 4yes|? -

• = means do these terms match?

• X is a logical variable so it matches with the structure 3 + 4.

– Very useful.

4.864.86

Arithmetic Computation In PROLOG IIArithmetic Computation In PROLOG II

• To get PROLOG to actually perform the arithmetic we must use the is operator.

|? - X is 3 + 4.X = 7yes|? - X is 1 + 2 * 3 / 4 - 5.X = -2.5 ;yes|? -

• Not quite the same as assignment in C++ or Java.

• Means compute arithmetic expression on right hand side and test whether it matches with expression on left hand side.

|? - X = 8, X is 4 + 4.X = 8yes|? -

4.874.87

Arithmetic Computation In PROLOG IIIArithmetic Computation In PROLOG III

• Can use expressions containing other logical variables but must be careful about the sub-goal ordering.

|? - X is 3 + 4, Y is X + X.X = 7Y = 14yes|? - Y is X + X, X is 3 + 4.uncaught exception:error(...)|? -

• Remember, PROLOG works left to right.

• Can’t use is backwards. It’s functional not relational.

4.884.88

Arithmetic Computation In PROLOG IVArithmetic Computation In PROLOG IV

• The usual arithmetic comparison operators are available.

=:= Equal.

=\= Not equal.

< Less than.

> Greater than.

>= Greater than or equal to.

=< Less than or equal to.

• Like is they won’t work with uninstantiated logical variables.

• For non numeric values programmers normally use the general matching and non-matching operators, = and \=.

4.894.89

A Numeric RuleA Numeric Rule

fact(1,1). % fact 1fact(N,R) :- % fact 2 NewN is N - 1, fact(NewN,NewR), R is NewR * N.

• NB : Must use logical variables NewN and NewR so we can use is to force evaluation of the arithmetic expressions.

|? - fact(1,V).V = 1 ?yes|? - fact(2,V).V = 2 ?yes|? - fact(4,V).V = 24 ?yes|? -

4.904.90

SummarySummary

• PROLOG data objects are called Terms.

– Terms are either structures or simple objects. Simple objects are variables or literal

constants.Literal constants are numbers or atoms.

• PROLOG is typeless.

– Run time checks that only numbers are used in arithmetic and characters in I/O.

• PROLOG allows both integer and floating numeric types.

• Variables are logical variables not store variables.

– Given values by instantiation not assignment.

– Given values required to make query succeed.

4.914.91

Summary IISummary II

• Sometimes we don’t want to give a variable a name because we don’t care about its value.

– Anonymous variables.

– Denoted by _.

– Can be used in queries, facts or rules.

• PROLOG is for symbolic computation.

– Not very good for numeric computation.

• Provides usual arithmetical and logical operators (some with strange names).

• Must use is operator to force numeric computation to occur.

– Only one uninstantiated variable allowed. Must be on LHS of is. is will not work backwards.