Course Content • Introduction to Prolog and Logic Programming.

Slides:



Advertisements
Similar presentations
Artificial Intelligence: Natural Language and Prolog
Advertisements

CS4026 Formal Models of Computation Part II The Logic Model Lecture 1 – Programming in Logic.
Chapter 11 :: Logic Languages
1. An Overview of Prolog.
Prolog.
Introduction to PROLOG ME 409 Lab - 1. Introduction to PROLOG.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
Inference and Reasoning. Basic Idea Given a set of statements, does a new statement logically follow from this. For example If an animal has wings and.
1 Logic Programming. 2 A little bit of Prolog Objects and relations between objects Facts and rules. Upper case are variables. parent(pam, bob).parent(tom,bob).
About prolog  History  Symbolic Programming Language  Logic Programming Language  Declarative Programming Language.
4. PROLOG Data Objects And PROLOG Arithmetic
CS 330 Programming Languages 12 / 02 / 2008 Instructor: Michael Eckmann.
Declarative Programming Autumn 2014 Basic syntax and sample programs.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Constraint Logic Programming Ryan Kinworthy. Overview Introduction Logic Programming LP as a constraint programming language Constraint Logic Programming.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming
(9.1) COEN Logic Programming  Logic programming and predicate calculus  Prolog statements  Facts and rules  Matching  Subgoals and backtracking.
1 COMP 205 Introduction to Prolog Dr. Chunbo Chu Week 13 Slides Courtesy to: Peter LO.
Formal Models of Computation Part II The Logic Model
Notes for Chapter 12 Logic Programming The AI War Basic Concepts of Logic Programming Prolog Review questions.
Introduction to Python
ProLog PROgramming in LOGic. Description of Prolog Prolog stands for PROgramming in LOGic. It is a nonprocedural and declarative language.
Declarative vs Procedural Programming  Procedural programming requires that – the programmer tell the computer what to do. That is, how to get the output.
Chapter 8 High-Level Programming Languages. 8-2 Chapter Goals Describe the translation process and distinguish between assembly, compilation, interpretation,
14/10/04 AIPP Lecture 7: The Cut1 Controlling Backtracking: The Cut Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 7 14/10/04.
1 Sections 1.5 & 3.1 Methods of Proof / Proof Strategy.
30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists1 Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim.
F28PL1 Programming Languages Lecture 16: Prolog 1.
Artificial Intelligence Programming in Prolog Lecture 1: An Introduction 23/09/04.
CMPF144 FUNDAMENTALS OF COMPUTING THEORY Module 5: Classical Logic.
For Wednesday No new reading Prolog handout 2 Chapter 9, exercise 4.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now Chapter 9, exs 4 and 6. –6 must be in Horn clause form Prolog Handout 2.
Slide 1 Propositional Definite Clause Logic: Syntax, Semantics and Bottom-up Proofs Jim Little UBC CS 322 – CSP October 20, 2014.
Introduction To PROLOG World view of imperative languages. World view of relational languages. A PROLOG program. Running a PROLOG program. A PROLOG.
PROLOG SYNTAX AND MEANING Ivan Bratko University of Ljubljana Faculty of Computer and Info. Sc. Ljubljana, Slovenia.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Logic Programming Languages Session 13 Course : T Programming Language Concept Year : February 2011.
Ch. 13 Ch. 131 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (notes?) Dr. Carter Tiernan.
Logical and Functional Programming
For Monday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 21.
Introduction to Prolog. Outline What is Prolog? Prolog basics Prolog Demo Syntax: –Atoms and Variables –Complex Terms –Facts & Queries –Rules Examples.
CS 337 Programming Languages Logic Programming I (Logic, Intro to Prolog)
Programming Languages Third Edition Chapter 4 Logic Programming.
Programming Language Concepts Lecture 17 Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Logic Programming.
Logic Programming Dr. Yasser Nada Fall 2010/2011 Lecture 1 1 Logic Programming.
MB: 26 Feb 2001CS Lecture 11 Introduction Reading: Read Chapter 1 of Bratko Programming in Logic: Prolog.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Knowledge Based Information System
Artificial Intelligence CIS 342 The College of Saint Rose David Goldschmidt, Ph.D.
For Friday No reading Prolog Handout 2. Homework.
Prolog 3 Tests and Backtracking 1. Arithmetic Operators Operators for arithmetic and value comparisons are built-in to Prolog = always accessible / don’t.
For Wednesday No reading Prolog handout 2 Chapter 9, exercise 4.
Introduction to Prolog Asst. Prof. Dr. Senem Kumova Metin Revised lecture notes of “Concepts of Programmig Languages, Robert W. Sebesta, Ch. 16”
Chapter 2 Syntax and meaning of prolog programs Part 1.
Chapter Three: Operators, Arithmetic 1. Chapter three: 3.3Operator notation 3.4Arithmetic 2.
Prolog Fundamentals. 2 Review Last Lecture A Prolog program consists of a database of facts and rules, and queries (questions). –Fact:.... –Rule:... :-....
Logic Programming Logic programming Candidates should be familiar with the concept of logic programming for declaring logical relationships.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Section 16.5, 16.6 plus other references
Expressions and Assignment
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now:
Declarative Computation Model Single assignment store (VRH 2
Chapter 2 Syntax and meaning of prolog programs
Chapter 2: Prolog (Introduction and Basic Concepts)
Representations & Reasoning Systems (RRS) (2.2)
PROLOG.
Presentation transcript:

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 Intelligence – Games, natural language processing, metainterpreters

Course 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

Books 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.

How 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

Logic 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.

Prolog 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).

Introducing 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.

Imperative 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.

Comparison

Introducing 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.

Logic 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

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

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.

Prolog 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

Clauses 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

Examples 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).

PROLOG Data Objects Programs process data. PROLOG data objects : Terms structures simple objects literal constants variables atoms numbers

PROLOG 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.

Atoms 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.

Atoms 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’).

Numbers PROLOG allows both integer and floating point types. Integer : 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.

Variables 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.

Variables 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!

Variables 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.

Variables 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

Anonymous 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.

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

Structures - 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

Structures - 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(_)).

A 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

Verify 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.

Definitions 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.

Facts 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).

Facts 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.

Rules 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

Rules 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.

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

Examples 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).

Rules 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).

Both 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).

Rules 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) :-

Example 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.

Queries 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.

Queries 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? */

Queries 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’.

Example ?- parent(philip, Who). If we have the Prolog program: 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).

Example (cont.) If we have the Prolog program: male(charles). male(edward). male(philip). parent(philip, anne). parent(philip, edward). parent(philip, charles). 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?

Example 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?

Predicate composer(beethoven,1770,1827) → predicate composer → functor beethoven, 1770, 1827 → arguments number of arguments: 3 → arity. write as composer/3

Side-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.

Exercise 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.

Matching, 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 !

e.g. Date(D,M, 1983) vs date(D1, may, Y1)  matches Matching 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

Matching 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.

Matching 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

Instantiation and Unification 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

Unification 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.

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

Unification 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.

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

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

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

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

Arithmetic 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

Arithmetic 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!

Arithmetic 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

Arithmetic 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.

Arithmetic Two examples for arithmetic operations. gcd/3: greatest common divisor D of two positive integers X and Y, using the following cases: If X and Y are equal, then D is equal to X; If X < Y then D is equal to the greatest common divisor of X and the difference Y – X; 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). Y < X, gcd( Y, X, D).

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

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

Declarative meaning Declarative vs. Procedural meaning in Prolog Consider the clause P:-Q, R. Declarative: P is true if Q and R are true From Q and R follows P Procedural To solve problem P first solve the subproblem Q then the subproblem R To satisfy P first satisfy Q then R

Declarative meaning 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

Examples clause haschild(X):-parent(X,Y) variants haschild(A):-parent(A,B) instances haschild(peter):-parent(peter,ann)

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.

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 ...

Procedural meaning 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 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. Reorderprevent looping

Arithmetic 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 + 4 yes |? - = means do these terms match? X is a logical variable so it matches with the structure 3 + 4. Very useful.

Arithmetic Computation In PROLOG II To get PROLOG to actually perform the arithmetic we must use the is operator. |? - X is 3 + 4. X = 7 yes |? - X is 1 + 2 * 3 / 4 - 5. X = -2.5 ; |? - 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 = 8

Arithmetic 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 = 7 Y = 14 yes |? - 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.

Arithmetic 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 \=.

A Numeric Rule fact(1,1). % fact 1 fact(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 ? |? - fact(4,V). V = 24 ? |? -

Summary 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.

Summary 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.