Prolog 3 Tests and Backtracking 1. Arithmetic Operators Operators for arithmetic and value comparisons are built-in to Prolog = always accessible / don’t.

Slides:



Advertisements
Similar presentations
Chapter 3: Lists, Operators, Arithmetic Part 1. Outline Representation of lists Some operations in lists Operator notation Arithmetic.
Advertisements

SLD-resolution Introduction Most general unifiers SLD-resolution
Computational Models The exam. Models of computation. –The Turing machine. –The Von Neumann machine. –The calculus. –The predicate calculus. Turing.
Prolog.
Declarative Programming Lists in PROLOG Autumn 2014.
Introduction to PROLOG ME 409 Lab - 1. Introduction to PROLOG.
11/10/04 AIPP Lecture 6: Built-in Predicates1 Combining Lists & Built-in Predicates Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
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).
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
INTRODUCTION TO PROLOG. PROLOG BASICS Atoms - most primitive terms that the language manipulates start with lower case letter includes strings (‘inside.
Prolog Programming slides written by Dr W.F. Clocksin.
4. PROLOG Data Objects And PROLOG Arithmetic
Comp 307 Lecture 4:1 Prolog I, II Prolog was taught as a procedural language Control structures: if, while, recursion Data structures: structured terms,
F28PL1 Programming Languages Lecture 17: Prolog 2.
CSE 425: Logic Programming I Logic and Programs Most programs use Boolean expressions over data Logic statements can express program semantics –I.e., axiomatic.
Declarative Programming Autumn 2014 Basic syntax and sample programs.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Constraint Logic Programming Ryan Kinworthy. Overview Introduction Logic Programming LP as a constraint programming language Constraint Logic Programming.
LING 388: Language and Computers Sandiway Fong Lecture 4: 8/31.
© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 9: A closer look at terms Theory –Introduce the == predicate –Take a closer look at term structure.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Lists, Operators, Arithmetic Notes for Ch.3 of Bratko For CSCE 580 Sp03 Marco.
JavaScript, Third Edition
(9.1) COEN Logic Programming  Logic programming and predicate calculus  Prolog statements  Facts and rules  Matching  Subgoals and backtracking.
Prolog Programming Lecture Module 13. Objective ● What is Prolog? ● Prolog program ● Syntax of Prolog ● Prolog Control Strategy ● Execution of Prolog.
Formal Models of Computation Part II The Logic Model
Data Structures Lecture : Stacks (Infix, Postfix and Prefix Expressions) Azhar Maqsood NUST Institute of Information Technology (NIIT)
Introduction to Prolog Terms & Matching Math. Atoms and Terms n mark, alex, di, bob are atoms –Not variables –Not strings –Just things – simple things.
CS 321 Programming Languages and Compilers Prolog part 2.
COP4020 Programming Languages Logical programming with Prolog Prof. Xin Yuan.
CS 403: Programming Languages Lecture 19 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Input, Output, and Processing
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.
30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists1 Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim.
15/11/04 AIPP Lecture 14: Database Manipulation1 Database Manipulation Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 14 15/11/04.
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.
1 Knowledge Based Systems (CM0377) Lecture 3 (Last modified 5th February 2001)
1 COMP 205 Introduction to Prolog Dr. Chunbo Chu Week 14.
1 Prolog and Logic Languages Aaron Bloomfield CS 415 Fall 2005.
PROLOG SYNTAX AND MEANING Ivan Bratko University of Ljubljana Faculty of Computer and Info. Sc. Ljubljana, Slovenia.
Rules Statements about objects and their relationships Expess ◦ If-then conditions  I use an umbrella if there is a rain  use(i, umbrella) :- occur(rain).
Logic Programming and Prolog Goal: use formalism of first-order logic Output described by logical formula (theorem) Input described by set of formulae.
Ch. 13 Ch. 131 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (notes?) Dr. Carter Tiernan.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 21.
© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 9: A closer look at terms Theory –Introduce the == predicate –Take a closer look at term structure.
Operators in Prolog © Patrick Blackburn, Johan Bos & Kristina Striegnitz.
Programming Languages Third Edition Chapter 4 Logic Programming.
LING/C SC/PSYC 438/538 Lecture 15 Sandiway Fong. Did you install SWI Prolog?
Programming Language Concepts Lecture 17 Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Logic Programming.
In The Name Of Allah Lab 03 1Tahani Aldweesh. objectives Searching for the solution’s. Declaration. Query. Comments. Prolog Concepts. Unification. Disjunction.
For Friday No reading Prolog Handout 2. Homework.
Haskell Basics CSCE 314 Spring CSCE 314 – Programming Studio Using GHC and GHCi Log in to unix.cse.tamu.edu (or some other server) From a shell.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
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:... :-....
1 Artificial Intelligence CS370D Prolog programming Declarative meaning of Prolog programs and Lists representation.
Logic Programming Lecture 2: Unification and proof search.
More on Prolog syntax Already seen program statement types: Already seen program statement types: rules: p(X) :- q(X,Y), r(Y,z). rules: p(X) :- q(X,Y),
Section 16.5, 16.6 plus other references
Regular Expressions, Backus-Naur Form and Reverse Polish Notation
A Conjunction is a logical operator that connects two logical terms.
Tests, Backtracking, and Recursion
3.5 Programming paradigms
Prolog fundamentals Module 14.2 COP4020 – Programming Language Concepts Dr. Manuel E. Bermudez.
Chapter 11 :: Logic Languages
Chapter 3: Prolog (Lists, Arithmetic, Operators)
Programming Techniques
PROLOG.
Presentation transcript:

Prolog 3 Tests and Backtracking 1

Arithmetic Operators Operators for arithmetic and value comparisons are built-in to Prolog = always accessible / don’t need to be written Comparisons:, = =, =:= (equals), =\= (not equals) = Infix operators: go between two terms. =</2 is used 5 =< 7. (infix) =<(5,7). (prefix)  all infix operators can also be prefixed Equality is different from unification =/2 checks if two terms unify =:=/2 compares the arithmetic value of two expressions ?- X=Y. ?- X=:=Y. ?- X=Y. ?- X=:=Y. ?-X=4,Y=3, X+2 =:= Y+3. yes ?-X=4,Y=3, X+2 =:= Y+3. yes 2

Examples of operator properties PositionOperator SyntaxNormal Syntax Prefix:-2-(2) Infix:5+17+(17,5) Postfix:N!!(N) Associativity: left, right, none. X+Y+Z is parsed as (X+Y)+Z X+Y+Z is parsed as (X+Y)+Z because addition is left-associative. Precedence: an integer. X+Y*Z is parsed as X+(Y*Z) because multiplication has higher precedence. These are all the same as the normal rules of arithmetic.

Arithmetic Operators (2) Arithmetic Operators : +, -, *, / = Infix operators but can also be used as prefix.  Need to use is/2 to access result of the arithmetic expression otherwise it is treated as a term: |?- X = 5+4.|?- X is 5+4. X = 5+4 ? X = 9 ? yes yes (Can X unify with 5+4?) (What is the result of 5+4?) Mathematical precedence is preserved : /, *, before +,- Can make compound sums using round brackets  Impose new precedence  Inner-most brackets first 4 | ?- X is 5+4*2. X = 13 ? yes | ?- X is (5+4)*2. X = 18 ? yes

Tests within clauses These operators can be used within the body of a clause:  To manipulate values, sum(X,Y,Sum):- Sum is X+Y.  To distinguish between clauses of a predicate definition bigger(N,M):- N < M, write(‘The bigger number is ‘), write(M). bigger(N,M):- N > M, write(‘The bigger number is ‘), write(N). bigger(N,M):- N =:= M, write(‘Numbers are the same‘). 5

Backtracking |?- bigger(5,4). bigger(N,M):- bigger(N,M):- N < M, write(‘The bigger number is ‘),write(M).bigger(N,M):- N > M, write(‘The bigger number is ‘),write(N).bigger(N,M):- N =:= M, write(‘Numbers are the same‘). 6

7 Backtracking |?- bigger(5,4). bigger(5,4):- 5 < 4,  fails write(‘The bigger number is ‘),write(M). bigger(N,M):- N > M, write(‘The bigger number is ‘),write(N). bigger(N,M):- N =:= M, write(‘Numbers are the same‘). Backtrack

8 |?- bigger(5,4). bigger(N,M):- N < M, write(‘The bigger number is ‘), write(M). bigger(5,4):- 5 > 4, write(‘The bigger number is ‘), write(N). bigger(N,M):- N =:= M, write(‘Numbers are the same‘). Backtracking

9 |?- bigger(5,4). bigger(N,M):- N < M, write(‘The bigger number is ‘), write(M). bigger(5,4):- 5 > 4,  succeeds, go on with body. write(‘The bigger number is ‘), write(5). The bigger number is 5 yes |?- Reaches full-stop = clause succeeds Backtracking

10 |?- bigger(5,5).  If our query only matches the final clause bigger(N,M):- N < M, write(‘The bigger number is ‘), write(M). bigger(N,M):- N > M, write(‘The bigger number is ‘), write(N). bigger(5,5):- 5 =:= 5, write(‘Numbers are the same‘). Numbers are the same yes  Is already known as the first two clauses failed. Backtracking

Reporting Answers |?- bigger(5,4).  Question is asked The bigger number is 5  Answer is written to terminal yes  Succeeds but answer is lost This is fine for checking what the code is doing but not for using the proof. |?- bigger(6,4), bigger(Answer,5). Instantiation error! To report back answers we need to  put an uninstantiated variable in the query,  instantiate the answer to that variable when the query succeeds,  pass the variable all the way back to the query. 11

Passing Back Answers To report back answers we need to To report back answers we need to 1. put an uninstantiated variable in the query, | ?- bigger(6,4,Answer),bigger(Answer,5,New_answ er). 2. instantiate the answer to that variable when the query succeeds, 3. pass the variable all the way back to the query bigger(X,Y,Answer):- X>Y. bigger(X,Y,Answer):- X=<Y., Answer = X., Answer = Y.

13 Head Unification To report back answers we need to 1.put an uninstantiated variable in the query, ?- bigger(6,4,Answer),bigger(Answer,5,New_answer). Or, do steps 2 and 3 in one step by naming the variable in the head of the clause the same as the correct answer. = head unification 1 2 bigger(X,Y,X):- X>Y. bigger(X,Y,Y):- X=<Y. 3

Satisfying Subgoals Most rules contain calls to other predicates in their body. These are known as Subgoals. These subgoals can match:  facts,  other rules, or  the same rule = a recursive call 14 1) drinks(alan,orange). 2) likes(alan,coffee). 3) likes(heather,coffee). 4) likes(Person,Drink):- drinks(Person,Drink).  a different subgoal 5) likes(Person,Somebody):- likes(Person,Drink),  recursive subgoals likes(Somebody,Drink). 

Unification Two terms unify if substitutions can be made for any variables in the terms so that the terms are made identical. If no such substitution exists, the terms do not unify. The Unification Algorithm proceeds by recursive descent of the two terms.  Constants unify if they are identical  Variables unify with any term, including other variables  Compound terms unify if their functors and components unify.

Examples The terms f(X, a(b,c)) and f(d, a(Z, c)) unify. Zc a d f bc a X f The terms are made equal if d is substituted for X, and b is substituted for Z. We also say X is instantiated to d and Z is instantiated to b, or X/d, Z/b.

Examples The terms f(X, a(b,c)) and f(Z, a(Z, c)) unify. Zc a Z f bc a X f Note that Z co-refers within the term. Here, X/b, Z/b.

Examples The terms f(c, a(b,c)) and f(Z, a(Z, c)) do not unify. Zc a Z f bc a c f No matter how hard you try, these two terms cannot be made identical by substituting terms for variables.

Exercise Do terms g(Z, f(A, 17, B), A+B, 17) and g(C, f(D, D, E), C, E) unify? AB +f g Z 17 AB Cf g C E DED

Exercise First write in the co-referring variables. AB +f g Z 17 AB Cf g C E DED

Exercise AB +f g Z AB Cf g C E DED Z/C, C/Z Now proceed by recursive descent We go top-down, left- to-right, but the order does not matter as long as it is systematic and complete.

Exercise AB +f g Z 17 AB Cf g C E DED Z/C, C/Z, A/D, D/A

Exercise AB +f g Z 17 AB Cf g C E DED Z/C, C/Z, A/17, D/17

Exercise AB +f g Z 17 AB Cf g C E DED Z/C, C/Z, A/17, D/17, B/E, E/B

Exercise AB +f g Z 17 AB Cf g C E DED Z/17+B, C/17+B, A/17, D/17, B/E, E/B

Exercise AB +f g Z 17 AB Cf g C E DED Z/17+17, C/17+17, A/17, D/17, B/17, E/17

Exercise – Alternative Method Z/C AB +f g Z 17 AB Cf g C E DED

Exercise – Alternative Method Z/C AB +f g C 17 AB Cf g C E DED

Exercise – Alternative Method A/D, Z/C AB +f g C 17 AB Cf g C E DED

Exercise – Alternative Method D/17, A/D, Z/C DB +f g C 17 DB Cf g C E DED

Exercise – Alternative Method D/17, A/17, Z/C 17B +f g C B Cf g C E E

Exercise – Alternative Method B/E, D/17, A/17, Z/C 17B +f g C B Cf g C E E

Exercise – Alternative Method B/E, D/17, A/17, Z/C 17E +f g C E Cf g C E E

Exercise – Alternative Method C/17+E, B/E, D/17, A/17, Z/C 17E +f g C E Cf g C E E

Exercise – Alternative Method C/17+E, B/E, D/17, A/17, Z/17+E 17E +f g + E +f g + E E E E E

Exercise – Alternative Method E/17, C/17+E, B/E, D/17, A/17, Z/C 17E +f g + E +f g + E E E E E

Exercise – Alternative Method E/17, C/17+17, B/17, D/17, A/17, Z/C 17 +f g + +f g +

Structures and Lists 38

39 The central ideas of Prolog SUCCESS/FAILURE –any computation can “succeed'' or “fail'', and this is used as a ‘test‘ mechanism. MATCHING –any two data items can be compared for similarity, and values can be bound to variables in order to allow a match to succeed. SEARCHING –the whole activity of the Prolog system is to search through various options to find a combination that succeeds. Main search tools are backtracking and recursion BACKTRACKING –when the system fails during its search, it returns to previous choices to see if making a different choice would allow success.

Prolog Data Objects (Terms) 40 Simple objects Structured Objects Constants IntegersAtoms Symbols Strings Signs VariablesStructuresLists a bob l8r_2day ‘a’ ‘Bob’ ‘L8r 2day’ ==> … X A_var _Var date(4,10,04) person(bob,48) [] [a,b,g] [[a],[b]] [bit(a,d),a,’Bob’]

Structures To create a single data element from a collection of related terms we use a structure. A structure is constructed from a functor (a constant symbol) and one of more components. somerelationship (a,b,c,[1,2,3]) The components can be of any type: atoms, integers, variables, or structures. As functors are treated as data objects just like constants they can be unified with variables 41 functor

Structure unification 2 structures will unify if  the functors are the same,  they have the same number of components,  and all the components unify. | ?- person(Nm,london,Age) = person(bob,london,48). Nm = bob, Age = 48? yes | ?- person(Someone,_,45) = person(harry,dundee,45). Someone = harry ? yes (A plain underscore ‘_’ is not bound to any value. By using it you are telling Prolog to ignore this argument and not report it.) 42

Structure unification (2) A structure may also have another structure as a component. |?-addr(flat(4),street(‘Home Str.’),postcode(eh8_9lw)) = addr(flat(Z),Yy,postcode(Xxx)). Z = 4, Yy = street(‘Home Str.’), Xxx = eh8_9lw ? yes Unification of nested structures works recursively:  first it unifies the entire structure,  then it tries to unify the nested structures. 43 Remember to close brackets! Reported variables are ordered according to number of characters in the variable name.

Structures = facts? The syntax of structures and facts is identical but:  Structures are not facts as they are not stored in the database as being true (followed by a period ‘.’);  Structures are generally just used to group data;  Functors do not have to match predicate names. However predicates can be stored as structures command(X):- X. | ?- X = write(‘Passing a command’), command(X). Passing a command X = write('Passing a command') ? yes 44 By instantiating a variable with a structure which is also a predicate you can pass commands.

Lists A collection of ordered data. Has zero or more elements enclosed by square brackets (‘[ ]’) and separated by commas (‘,’). [a]  a list with one element []  an empty list [34,tom,[2,3]]  a list with 3 elements where the 3 rd element is a list of 2 elements. Like any object, a list can be unified with a variable |?- [Any, list, ‘of elements’] = X. X = [Any, list, ‘of elements’]? yes 45

List Unification Two lists unify if they are the same length and all their elements unify. |?-[a,B,c,D]=[A,b,C,d]. |?-[(a+X),(Y+b)]=[(W+c),(d+b)]. A = a, W = a, B = b, X = c, C = c, Y = d? D = d ? yes yes |?- [[X,a]]=[b,Y]. |?-[[a],[B,c],[]]=[X,[b,c],Y]. no B = b, X = [a], X = [a], Y = [] ? Y = [] ? yes yes 46 Length 1 Length 2

Definition of a List Lists are recursively defined structures. “An empty list, [], is a list. A structure of the form [X, …] is a list if X is a term and […] is a list, possibly empty.” This recursiveness is made explicit by the bar notation  [Head|Tail] (‘|’ = bottom left PC keyboard character) Head must unify with a single term. Tail unifies with a list of any length, including an empty list, [].  the bar notation turns everything after the Head into a list and unifies it with Tail. 47

Head and Tail |?-[a,b,c,d]=[Head|Tail]. |?-[a,b,c,d]=[X|[Y|Z]]. Head = a, X = a, Tail = [b,c,d]? Y = b, yes Z = [c,d]; yes yes |?-[a] = [H|T]. |?-[a,b,c]=[W|[X|[Y|Z]]]. H = a, W = a, T = []; X = b, yes Y = c, Z = []? yes Z = []? yes |?-[] = [H|T]. |?-[a|[b|[c|[]]]]= List. no List = [a,b,c]? yes yes 48

Summary Prolog’s proof strategy can be represented using AND/OR trees. Tree representations allow us trace Prolog’s search for multiple matches to a query. They also highlight the strengths and weaknesses of recursion (e.g. economical code vs. infinite looping). Recursive data structures can be represented as structures or lists. Structures can be unified with variables then used as commands. Lists can store ordered data and allow its sequential processing through recursion. 49

50 Thank You!