1 COMP 205 Introduction to Prolog Dr. Chunbo Chu Week 14.

Slides:



Advertisements
Similar presentations
CS4026 Formal Models of Computation Part II The Logic Model Lecture 6 – Arithmetic, fail and the cut.
Advertisements

© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 10: Cuts and Negation Theory –Explain how to control Prolog`s backtracking behaviour with.
CS344: Introduction to Artificial Intelligence Pushpak Bhattacharyya CSE Dept., IIT Bombay Lecture 12–Prolog examples: Himalayan club, member, rem_duplicate,
Chapter 11 :: Logic Languages
4. Using Structures: Example Programs. Contents l Retrieving structured information from a database l Doing data abstraction l Simulating a non-deterministic.
Prolog.
© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 6: More Lists Theory –Define append/3, a predicate for concatenating two lists, and illustrate.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/5.
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.
LING 388: Language and Computers Sandiway Fong Lecture 5: 9/8.
Chapter Three: Lists, Operators, Arithmetic 1. Chapter three: 3.1Representation of lists 3.2Some operations on lists 2.
Prolog The language of logic. History Kowalski: late 60’s Logician who showed logical proof can support computation. Colmerauer: early 70’s Developed.
CS344 : Introduction to Artificial Intelligence Pushpak Bhattacharyya CSE Dept., IIT Bombay Lecture 16- Prolog.
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).
INTRODUCTION TO PROLOG. PROLOG BASICS Atoms - most primitive terms that the language manipulates start with lower case letter includes strings (‘inside.
1 Knowledge Based Systems (CM0377) Lecture 8 (Last modified 5th March 2001)
Prolog OR (disjunction) “;” is same as a logical OR “;” is same as a logical OR It is also equivalent to using separate clauses... It is also equivalent.
CS 330 Programming Languages 12 / 02 / 2008 Instructor: Michael Eckmann.
CS 330 Programming Languages 12 / 12 / 2006 Instructor: Michael Eckmann.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Part 1 The Prolog Language Chapter 5 Controlling Backtracking
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Controlling Backtracking Notes for Ch.5 of Bratko For CSCE 580 Sp03 Marco Valtorta.
1 Non-determinism and Cut  Non-determinism  Backtracking  Controlling Backtracking.
CIA2326 Week3: Prolog: List Processing Lee McCluskey First term:
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Lists, Operators, Arithmetic Notes for Ch.3 of Bratko For CSCE 580 Sp03 Marco.
Prolog Ross (Tate). Filling in the Blanks Rather than reverse((a,b)) returns (b,a) Rather than reverse((a,b)) returns (b,a) What X makes reverse((a,b),
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 15 Logic Programming Q: How many legs does.
(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.
FATIH UNIVERSITY Department of Computer Engineering Controlling Backtracking Notes for Ch.5 of Bratko For CENG 421 Fall03.
CS 321 Programming Languages and Compilers Prolog part 2.
CS 2104 – Prog. Lang. Concepts Logic Programming - II Dr. Abhik Roychoudhury School of Computing.
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.
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.
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.
Introduction To PROLOG World view of imperative languages. World view of relational languages. A PROLOG program. Running a PROLOG program. A PROLOG.
1 Prolog and Logic Languages Aaron Bloomfield CS 415 Fall 2005.
CS Introduction to AI Tutorial 8 Resolution Tutorial 8 Resolution.
Automated Reasoning Early AI explored how to automated several reasoning tasks – these were solved by what we might call weak problem solving methods as.
Ch. 13 Ch. 131 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (notes?) Dr. Carter Tiernan.
Lab Lecture#4 Lecturer : Sheriff Nafisa TA : Mubarakah Otbi, Duaa al Ofi, Huda al Hakami.
Cs774 (Prasad)L6Backtracking1 Controlling Backtracking : Cuts
Artificial Intelligence
Lists in Prolog Sections 3.1, 3.2. Lists n List = sequence of values –[1, 2, 3, 4, 5] –[bob, brian, cathy, mark, david, loretta] –[birds(4, calling),
Simple Data structure and computation. Solving equation? sum(X,Y,Z):- Z is X+Y. ?sum(1,R,7). is/2: Arguments are not sufficiently instantiated ^ Exception:
Programming Language Concepts Lecture 17 Prepared by Manuel E. Bermúdez, Ph.D. Associate Professor University of Florida Logic Programming.
For Monday Exam 1 is Monday Takehome due Prolog Handout 3 due.
In The Name Of Allah Lab 03 1Tahani Aldweesh. objectives Searching for the solution’s. Declaration. Query. Comments. Prolog Concepts. Unification. Disjunction.
1 Artificial Intelligence CS370D Prolog programming List operations.
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.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
C H A P T E R N I N E Logic Programming Part 2 Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
Chapter Three: Operators, Arithmetic 1. Chapter three: 3.3Operator notation 3.4Arithmetic 2.
C. Varela1 Logic Programming (PLP 11, CTM 9.3) Prolog Imperative Control Flow: Backtracking, Cut, Fail, Not Lists, Append Carlos Varela Rennselaer Polytechnic.
6/11/2016 Linear Resolution and Introduction to First Order Logic Michael Leuschel Softwaretechnik und Programmiersprachen Lecture 5.
Logic Programming Lecture 2: Unification and proof search.
Section 16.5, 16.6 plus other references
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now:
Carlos Varela Rensselaer Polytechnic Institute November 17, 2017
Tests, Backtracking, and Recursion
Programming Paradigms and Languages
Carlos Varela Rennselaer Polytechnic Institute November 15, 2016
Presentation transcript:

1 COMP 205 Introduction to Prolog Dr. Chunbo Chu Week 14

Student Evaluations  Course  Faculty  Student Services Course ID: COMP 205 Section Number: V1FF Instructor’s Name: Chunbo Chu 2

3 Review What is Prolog? Prolog Programs  Data Types: constant (atoms, numbers), variables and compound terms  Facts and rules Running Prolog Queries – running program  Unification  Backtracking

4 Prolog Programs Terms  The data objects of the language  Either constant (atom or number), variable or compound term Facts and Rules  Predicates: “Generalized functions”, allowing multiple return values, used in multiple directions  Facts: Predicates assumed to be true  Rules: P(..) :- P 1 (..),P 2 (..),…,P n (..).

List A sequence of any number of items. Structure of lists:.( Head, Tail ).(a,.(b,[ ])) eq. Shorthand:  [tom, jerry] is the same as.(tom,.(jerry, [ ]))  [a | tail] is the same as.(a, tail)  [a,b,c] = [a | [b,c]] = [a,b | [c]] = [a,b,c |[ ]] Elements can be lists and structures:  [a, [1, 2, 3], tom, 1995, date(1,may,1995) ] 5

Operations on Lists Membership  member( X, L) if X is a member of the list L. member(X, [X | Tail]). member(X, [Head | Tail]) :- member(X, Tail). Activity  How to get all members in a list [1, 2, 3]?  member(X,[1,2,3]). 6

How? 7

member([3,Y], [[1,a],[2,m],[3,z],[4,v],[3,p]]). Y = z ; Y = p ; Activity  Find all the numbers in [23,45,67,12,222,19,9,6] whose square is less than 100.  member(X,[23,45,67,12,222,19,9,6]), Y is X*X, Y <

Concatenation  append(L1, L2, L3) if L3 is the concatenation of L1 and L2.  append([ ], L, L).  append([X|L1], L2, [X|L3]) :- append(L1, L2, L3). 9

?- append( [a,b,c], [1,2,3], L). L = [a,b,c,1,2,3] ?- append( L1, L2, [a,b,c] ). L1 = [] L2 = [a,b,c]; L1 = [a] L2 = [b,c]; L1 = [a,b] L2 = [c]; L1 = [a,b,c] L2 = []; false 10

Activity Given [1,2,3,4,5,6,7], find the sublist before 4, and the sublist after 4. ?- append( Before, [4|After], [1,2,3,4,5,6,7]). Before = [1,2,3] After = [5,6,7] Find the immediate predecessor and successor of 4. append(_, [Pred, 4, Succ |_], [1,2,3,4,5,6,7]). Pred = 3 Succ = 5 11

Redefining member using conc: member1(X, L) :- append(_, [X|_], L). Permutations ?-permutation( [a,b,c], P). P = [a,b,c]; P = [a,c,b]; P = [b,a,c]; 12

List Length The length of a list can be calculated in the following way:  if the list is empty then its length is 0.  if the list is not empty then List = [Head | Tail]. In this case the length is equal to 1 plus the length of the tail Tail. length is built in. If you want to try defining it, change the name... 13

length([], 0). length([_|Tail],N) :- length(Tail, N1), N is 1 + N1. ?-length([a,b,[c,d],e], N). N = 4 ?-length(L,4). [_G337, _G340, _343, _346] 14

Database Query Represent a database about families as a set of facts. Each family will be a clause. The structure of a family:  each family has a husband, a wife and children.  children are represented as a list.  each person has a name, surname, date of birth and job. 15

16

Example: family( person(tom, fox, date(7,may,1950), works(bbc,15200)), person(ann, fox, date(9,jan,1949), works(ibm,20000)), [ person(pat, fox, date(1,feb,1973), unemployed), person(jim, fox, date(4,may,1976), unemployed)]). 17

Structure Queries All armstrong families: family( person(_,armstrong,_,_),_,_) Are there families with 3 children? family(_,_,[_,_,_]) Names of families with 3 children. family(person(_,Name,_,_),_,[_,_,_]) 18

All married women that have at least two children: family(_,person(Name,Surname,_,_),[_,_|_]). 19

Structure Queries Defining useful relations:  husband(X) :- family(X,_,_).  wife(X) :- family(_,X,_).  child(X) :- family(_,_,Children), member(X, Children).  exists( Person ) :- husband(Person); wife(Person); child(Person).  dateofbirth( person(_,_,Date,_),Date).  salary(person(_,_,_,works(_,S)), S).  salary(person(_,_,_,unemployed), 0). 20

Names of all people in the database: exists( person(Name,Surname,_,_)). All employed wives: wife(person(Name,Surname,_,works(_,_))). Unemployed people born before 1963: exists(person(Name,Surname,date(_,_,Year), unemployed)), Year <

People born before 1950 whose salary is less than 8000: exists(Person),dateofbirth(Person,da te(_,_,Year)),Year < 1950,salary(Person, Salary), Salary <

Controlling Backtracking if X < 3 then Y = 0 if 3 <= X and X < 6 then Y = 2 if 6 <= X then Y = 4 23

The relation f(X,Y) in prolog: f(X,0) :- X<3. f(X,2) :- 3=<X, X<6. f(X,4) :- 6=<X. 24

Controlling Backtracking This procedure assumes that before f(X,Y) is executed X is already instantiated to a number. The goal: “ f(1,Y), 2<Y.” fails, but before prolog replies ‘false’, it tries all 3 rules. The three rules are mutually exclusive so that one of them at most will succeed. If the goal matches the first rule and then fails, there is no point in trying the others. 25

Controlling Backtracking: Cut Automatic backtracking can cause inefficiency. A cut prevents backtracking from some point on. Written as a ‘!’ sub-goal that always succeeds, but prevents backtracking through it. 26

Correcting the example: f(X,0) :- X<3, !. f(X,2) :- 3=<X, X<6, !. f(X,4) :- 6=<X. Whenever the goal f(X,Y) is encountered, only the first rule that matches will be tried. If we now ask again “ f(2,Y), 2<Y.” we will get the same answer, ‘false’, but only the first rule of ‘f’ will be tried. 27

Another problem: If we ask: ?- f(7,Y). Y=4 What happened: 7 fail 3= fail 6= success. 28

Another improvement: The logical rule  if X<3 then Y=0,  otherwise if X<6 then Y=2,  otherwise Y=4. is translated into: f(X,0) :- X<3, !. f(X,2) :- X<6, !. f(X,4). 29

The last change improved efficiency. BUT, removing the cuts now will change the result !!! ?-f(1,Y). Y = 0; Y = 2; Y = 4; false In this version the cuts do not only effect the procedural meaning of the program, but also change the declarative meaning. 30

Red and Green cuts: When a cut has no effect on the declarative meaning of the program it is called a ‘green cut’. When reading a program, green cuts can simply be ignored. Cuts that do effect the declarative meaning are called ‘red cuts’. This type of cuts make programs hard to understand, and they should be used with special care. 31

32 Queries - Backtracking When asked P 1 (..),P 2 (..),…,P n (..). Most Prolog will attempt the following  Unify P 1 with a fact or rule, instantiate variables if needed  If P 1 unifies with more than one fact or rule, the first one is chosen  If succeed, do the same for P 2, and so on from left to right  If all predicates succeed, the whole goal succeeds  If anyone fails, say P i, Prolog backtracks, and try an alternative of P i-1  The predicates are tried in a Depth-First manner  After a successful query, if user presss ‘ ; ’, backtrack and try alternatives

33 Queries – Backtracking Example before(a,b). before(b,c). before(c,d). before(A,C) :- before(A,B), before(B,C). ?- before(a,c). << Not match

34 Queries – Backtracking Example before(a,b). before(b,c). before(c,d). before(A,C) :- before(A,B), before(B,C). ?- before(a,c). << Unifed, with A  a,C  c Call : before(a,B). before(a,c) :- before(a,B), before(B,c). Exit : before(a,b). << Put B=b << Match Fact 1.yes

35 Queries – Backtracking Example before(a,b). before(b,c). before(c,d). before(A,C) :- before(A,B), before(B,C). ?- before(a,c). before(a,c) :- before(a,B), before(B,c). Call : before(b,c). Exit : before(b,c). << As B=b << Match Fact 2. yes << Unifed, with A  a,C  c

36 Queries – Backtracking Example before(a,b). before(b,c). before(c,d). before(A,C) :- before(A,B), before(B,C). ?- before(a,c). before(a,c) :- before(a,b), before(b,c). yes << succeeds, use the rule with A  a,B  b,C  c

The Meaning of Cut When the cut is encountered as a goal it succeeds immediately, but it commits the system to all choices made between the time the parent goal was invoked and the time the cut was encountered. H :- B1, B2,..., Bm, !,... Bn. when the ! is encountered:  The solution to B1..Bm is frozen, and all other possible solutions are discarded.  The parent goal cannot be matched to any other rule. 37

Consider the program  C :- P, Q, R, !, S, T, U.  C :- V.  A :- B, C, D. And the goal: A Backtracking is possible within P,Q,R. When the cut is reached, the current solution of P,Q,R is chosen, and all other solutions are dumped. 38

The alternative clause “C :- V” is also dumped. Backtracking IS possible in S,T,U. The parent goal is “C” so the goal A is not effected. The automatic backtracking in B,C,D is active. 39

Examples using CUT holiday(friday,may1). weather(friday,fair). weather(saturday,fair). weather(sunday,fair). weekend(saturday). weekend(sunday). % We go for picnics on good weekends and May 1st picnic(Day) :- weather(Day,fair), weekend(Day). picnic(Day) :- holiday(Day,may1). 40

?- picnic(When). … Now change the definition of picnic to the following:  picnic(Day) :- weather(Day,fair), !, weekend(Day). 41

Negation The special goal fail always fails. ( like 1=0. ) The special goal true always succeeds. ( like 1=1. ) “Mary likes all animals but snakes”  likes( mary, X) :- snake(X), !, fail.  likes( mary, X) :- animal(X). 42

Define the relation “different” by the matching meaning - two terms are different iff they do not match. different(X, X) :- !, fail. different(X, Y). 43

Negation Defining “not”:  if Goal succeeds then not(Goal) fails.  Otherwise not(Goal) succeeds.  not(P) :- P, !, fail.  not(P). NOT is a built in prolog procedure, defined as a prefix operator: not(snake(X)) ==> not snake(X) 44

Previous examples that use the combination “!, fail” can now be rewritten: different(X, Y) :- not (X = Y). 45