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.

Slides:



Advertisements
Similar presentations
Artificial Intelligence: Natural Language and Prolog
Advertisements

CS4026 Formal Models of Computation Part II The Logic Model Lecture 6 – Arithmetic, fail and the cut.
© Patrick Blackburn, Johan Bos & Kristina Striegnitz Lecture 10: Cuts and Negation Theory –Explain how to control Prolog`s backtracking behaviour with.
AI/ES (Artificial Intelligence / Expert System) Visual Prolog: Part 2
Computational Models The exam. Models of computation. –The Turing machine. –The Von Neumann machine. –The calculus. –The predicate calculus. Turing.
Prolog The language of logic. History Kowalski: late 60’s Logician who showed logical proof can support computation. Colmerauer: early 70’s Developed.
Logic Programming – Part 2 Lists Backtracking Optimization (via the cut operator) Meta-Circular Interpreters.
Prolog The language of logic. History Kowalski: late 60’s Logician who showed logical proof can support computation. Colmerauer: early 70’s Developed.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
”assert” and ”retract”
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).
1 Knowledge Based Systems (CM0377) Lecture 8 (Last modified 5th March 2001)
Selection (decision) control structure Learning objective
CS 330 Programming Languages 12 / 02 / 2008 Instructor: Michael Eckmann.
MB: 2 March 2001CS360 Lecture 31 Programming in Logic: Prolog Prolog’s Declarative & Procedural Semantics Readings: Sections
CS 330 Programming Languages 12 / 12 / 2006 Instructor: Michael Eckmann.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Expert System Human expert level performance Limited application area Large component of task specific knowledge Knowledge based system Task specific knowledge.
UNIVERSITY OF SOUTH CAROLINA Department of Computer Science and Engineering Controlling Backtracking Notes for Ch.5 of Bratko For CSCE 580 Sp03 Marco Valtorta.
Constraint Logic Programming Ryan Kinworthy. Overview Introduction Logic Programming LP as a constraint programming language Constraint Logic Programming.
Introduction to Analysis of Algorithms
1 CILOG User Manual Bayesian Networks Seminar Sep 7th, 2006.
CSE (c) S. Tanimoto, 2005 Logic Programming 1 Logic Programming Outline: Motivation Examples: The Grandmother relation Formulation in Prolog Logic,
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 15 Logic Programming Q: How many legs does.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
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.
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.
EXPRESSIONS AND ASSIGNMENT CITS1001. Scope of this lecture Assignment statements Expressions 2.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
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.
Flow of Control Chapter 5. Flow of Control n What order computer uses to get answers –sub-goal ordering –clause ordering n Prolog flow-of-control –sequence.
Selection Control Structures. Simple Program Design, Fourth Edition Chapter 4 2 Objectives In this chapter you will be able to: Elaborate on the uses.
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.
Introduction To PROLOG World view of imperative languages. World view of relational languages. A PROLOG program. Running a PROLOG program. A PROLOG.
B. Ross Cosc 4f79 1 Inference mechanisms Backward chaining - goal-driven reasoning which gathers data as needed - Prolog's default mechanism - good for.
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.
BACS 287 Programming Logic 2. BACS 287 Sequence Construct The sequence construct is the default execution mode for the CPU. The instructions are executed.
Logic Programming CSC 358/ Outline Pattern matching Unification Logic programming.
Prolog Program Style (ch. 8) Many style issues are applicable to any program in any language. Many style issues are applicable to any program in any language.
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.
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables IV.
Lab Lecture#4 Lecturer : Sheriff Nafisa TA : Mubarakah Otbi, Duaa al Ofi, Huda al Hakami.
Cs774 (Prasad)L6Backtracking1 Controlling Backtracking : Cuts
Negation Chapter 5. Stating Negative Conditions n Sometimes you want to say that some condition does not hold n Prolog allows this –not/1this is a predicate.
Artificial Intelligence
Predicate Logic One step stronger than propositional logic Copyright © Curt Hill.
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.
For Friday No reading Prolog Handout 2. Homework.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
As the inference engine performs unification and resolution, it sometimes backtracks in unwanted ways. mother(sue, sam). mother(sue, mae). mother(mia,
Answer Extraction To use resolution to answer questions, for example a query of the form  X C(X), we must keep track of the substitutions made during.
The portion of a Prolog interpreter that executes queries (goals) is known as the inference engine. An inference engine is a kind of theorem prover, using.
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),
COSC 2P93 Prolog: Debugging
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now:
Introduction to Logic Programming and Prolog
Programming Paradigms and Languages
Programming Techniques
CSE 3302 Programming Languages
Introduction to Logic Programming and Prolog
Controlling Backtracking : Cuts
Presentation transcript:

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 to using separate clauses... parent(X, Y) :- mother(X, Y). parent(X, Y) :- father(X, Y). SAME AS... parent(X, Y) :- mother(X, Y) ; father(X, Y). Although this saves writing some code, both versions are equivalent in efficiency. Although this saves writing some code, both versions are equivalent in efficiency. 1COSC 2P93 Prolog: Cut

Be careful with “;”! What is going on here? What is going on here? p(X) :- (q(X, Y) ; (r(Y), (s(U, Y); a(U), b(U)) ; r(X)), t(X, Y); w(X) ; z(A),z(B), etc... Too many or’s can make programs very hard to debug (trace)! Too many or’s can make programs very hard to debug (trace)! Rule of thumb: Don’t use or’s in order to reduce number of clauses. Rule of thumb: Don’t use or’s in order to reduce number of clauses. 2COSC 2P93 Prolog: Cut

Controlling Prolog execution Prolog exhaustively searches the computation tree for solutions Prolog exhaustively searches the computation tree for solutions If a goal fails, OR the user inputs ‘;’ at the prompt, then backtracking reverts to the last place in which a clause was chosen, and tries the next. If a goal fails, OR the user inputs ‘;’ at the prompt, then backtracking reverts to the last place in which a clause was chosen, and tries the next. There are lots of advantages of this scheme, most notably, searching for a solution, or multiple solutions, to a query. There are lots of advantages of this scheme, most notably, searching for a solution, or multiple solutions, to a query. However, it can be expensive: However, it can be expensive: Sometimes there is only one solution, and it is a waste of time searching for others -- they don’t exist! Sometimes there is only one solution, and it is a waste of time searching for others -- they don’t exist! Sometimes ‘failure’ after the first solution can take lots of time to infer Sometimes ‘failure’ after the first solution can take lots of time to infer Memory resources are used to contain the computation tree for backtracking. Memory resources are used to contain the computation tree for backtracking. Prolog permits some user control of execution, in order to reduce backtracking. Prolog permits some user control of execution, in order to reduce backtracking. 3COSC 2P93 Prolog: Cut

1. If-then-else (If -> Then ; Else) If goals in If are true, then do Then; else do Else If goals in If are true, then do Then; else do Else Once Then is executed, will go to Then or Else, but cannot backtrack from Then to Else, nor back to If. Once Then is executed, will go to Then or Else, but cannot backtrack from Then to Else, nor back to If. Backtracking will return multiple solutions in Then, and in Else. Backtracking will return multiple solutions in Then, and in Else. (If -> Then) This is equivalent to: (If -> Then ; fail) This is equivalent to: (If -> Then ; fail) 4COSC 2P93 Prolog: Cut

Example If-then-else If N is prime, return ‘prime’, Else ‘notprime’. If N is prime, return ‘prime’, Else ‘notprime’. idNum(N, prime) :- prime(N). idNum(N, notprime) :- idNum(N, notprime) :- \+ prime(N). Note that prime/N is called twice – with identical results! Note that prime/N is called twice – with identical results! Prime testing might be very slow for large integers, so this is very wasteful. Prime testing might be very slow for large integers, so this is very wasteful. 5COSC 2P93 Prolog: Cut

Example if-then-else filterNum(N, Ans) :- (prime(N) -> Ans = prime ; Ans = notprime). Here, prime/1 is called once. No backtracking into it. Here, prime/1 is called once. No backtracking into it. 6COSC 2P93 Prolog: Cut

2. once Often, we want just one solution from a predicate. Often, we want just one solution from a predicate. Multiple answers may slow execution, due to needless backtracking. Multiple answers may slow execution, due to needless backtracking.once(Goal): This calls Goal, and returns first solution. This calls Goal, and returns first solution. Backtracking will immediately fail. Backtracking will immediately fail. Built-in to Sicstus Prolog. Built-in to Sicstus Prolog. 7COSC 2P93 Prolog: Cut

Example of once/1 % delete(A, L, R): Delete A from L, resulting in R. delete(A, [A|T], T). delete(A, [B|T], [B|T2]) :- delete(A, T, T2). delete(A, T, T2). delete(_, [ ], [ ]). ?- delete(a, [a,b,a,c,a],L). L = [b,a,c,a] ? ; L = [a,b,c,a] ? ; L = [a,b,a,c] ? ; L = [a,b,a,c,a] ? ; ?- once( delete(a, [a,b,a,c,a],L) ). L = [b,a,c,a] ? ; no 8COSC 2P93 Prolog: Cut

3. The cut, ! The cut takes the form of a goal in a clause. The cut takes the form of a goal in a clause. Should use only one cut per clause. Should use only one cut per clause. A predicate can have one or more clauses with cuts. A predicate can have one or more clauses with cuts. Scheme : 1. all the clauses before the first clause with a cut are executed with normal backtracking. 2. if the goals before the cut fail, the cut does not activate, and the subsequent clause is used, as normal. 3. if the goals before the cut succeed, the cut activates: a) backtracking back to goals before the cut cannot occur b) backtracking to subsequent clauses after the one with the cut cannot occur --> that clause with the activated cut is “committed” c) the goals after the cut are executed with normal backtracking 9COSC 2P93 Prolog: Cut

The cut - example p(1). %1 p(1). %1 p(2). %2 p(2). %2 p(Y) :- q(3, Z), !, r(Z, Y). %3 p(Y) :- q(3, Z), !, r(Z, Y). %3 p(4). %4 p(4). %4 q(2, 4).r(5, 6). q(2, 4).r(5, 6). q(3, 5).r(5, 7). q(3, 5).r(5, 7). Clauses 1, 2 are executed as normal Clauses 1, 2 are executed as normal In 3, the goal q(3,Z) executes; if it succeeds, then the ! is activated, and the goal r is executed as normal. In 3, the goal q(3,Z) executes; if it succeeds, then the ! is activated, and the goal r is executed as normal. However, in activating this cut... However, in activating this cut... clause 4 will not execute for this particular execution call clause 4 will not execute for this particular execution call clause 3 will not backtrack to q again (in this goal inference) clause 3 will not backtrack to q again (in this goal inference) Note that backtracking in r(Z,Y) occurs as expected, and hence you can still get multiple solutions from clause 3 Note that backtracking in r(Z,Y) occurs as expected, and hence you can still get multiple solutions from clause 3 10COSC 2P93 Prolog: Cut

Green and red cuts There are two usages of cuts: There are two usages of cuts: (i) Green cuts (GOOD): cuts that prune execution branches that do not lead to useful solutions. (ii) Red cuts (BAD): cuts that prune valid solutions 11COSC 2P93 Prolog: Cut

Example: green cut % A list is bad if: (1) it is empty; (2) it has more than 100 items; or (3) it has an integer. test_list(L) :- test_if_bad(L), test_if_bad(L), !, !, write(‘Bad list,’), nl, fail. % print message and fail write(‘Bad list,’), nl, fail. % print message and fail test_list(L) :- write(‘Good list’), nl.% print message and succeed write(‘Good list’), nl.% print message and succeed test_if_bad([ ]). test_if_bad(L) :- length(L, N), N > 100. test_if_bad(L) :- member(X, L), integer(X). a “green cut”, because we know that only one of test_list clauses must succeed to say a list is bad. a “green cut”, because we know that only one of test_list clauses must succeed to say a list is bad. backtracking makes no sense with it. backtracking makes no sense with it. 12COSC 2P93 Prolog: Cut

Green cut Note that we could do the same with if-then-else... Note that we could do the same with if-then-else... test_list(L) :- (test_if_bad(L) -> (test_if_bad(L) -> write(‘Bad list,’), nl, fail; write(‘Good list’), nl ). write(‘Good list’), nl ). 13COSC 2P93 Prolog: Cut

Example: red cut A bad use of cut... A bad use of cut... parent(P, C) :- father(P, C), !. parent(P, C) :- mother(P, C). father(bob, sue). father(bob, kim). mother(mary, sue). mother(mary, kim). A red cut: we get the first solution from father, and never give another valid solution again, from either father or mother! A red cut: we get the first solution from father, and never give another valid solution again, from either father or mother! ?- parent(A, B). A = bob, B = sue ; no. 14COSC 2P93 Prolog: Cut

Red cut Variation: Variation: parent(P, C) :- !, father(P, C). parent(P, C) :- mother(P, C). (rest as before) ?- parent(A, B). A = bob, B = sue ; A = bob, B = kim ; no Same as... Same as... parent(P, C) :- father(P, C). 15COSC 2P93 : Cut

Implementation: If-then-else If-then-else is implemented with a cut: If-then-else is implemented with a cut: P :- (If -> Then;Else). Same as... P :- If, !,Then. P :- Else. 16COSC 2P93 Prolog: Cut

Implementation: once/1 once(P) :- call(P),!or... P,!. This is a “meta-logical” call. This is a “meta-logical” call. Usually built into Prolog. Usually built into Prolog. 17COSC 2P93 Prolog: Cut

More cut examples Example: a deterministic member/2: memberd/2 Example: a deterministic member/2: memberd/2 deterministic clause: one that returns one solution per call deterministic clause: one that returns one solution per call member(A, [A|_). member(A, [_|R]) :- member(A, R). memberd(A, [A|_]) :- !. memberd(A, [_ | R]) :- memberd(A, R). Here, as soon as memberd clause 1 finds a match, it succeeds Here, as soon as memberd clause 1 finds a match, it succeeds Subsequent backtracking to memberd then fails, due to the cut Subsequent backtracking to memberd then fails, due to the cut we prevent memberd clause 2 from finding another match we prevent memberd clause 2 from finding another match Note: memberd same as... ?- once(member(X,Y)). Note: memberd same as... ?- once(member(X,Y)). 18COSC 2P93 Prolog: Cut

Cut examples Example: sum the integers between 1 and n Example: sum the integers between 1 and n sum_to(1, 1) :- !. sum_to(N, Sum) :- M is N - 1, M is N - 1, sum_to(M, Tmp), sum_to(M, Tmp), Sum is Tmp + N. Sum is Tmp + N. Without the cut, backtracking proceeds to sum_to(0,_), sum_to(-1,...) etc Without the cut, backtracking proceeds to sum_to(0,_), sum_to(-1,...) etc with the cut, when the case sum_to(1,1) occurs, backtracking will not commence (via clause 2) with the cut, when the case sum_to(1,1) occurs, backtracking will not commence (via clause 2) again, a green cut: only one solution desired again, a green cut: only one solution desired BUT... simply checking size of N in 2 nd clause will prevent need for a cut... BUT... simply checking size of N in 2 nd clause will prevent need for a cut... 19COSC 2P93 Prolog: Cut

Take out the cut... sum_to(1, 1). sum_to(N, Sum) :- N > 1, N > 1, M is N - 1, sum_to(M, Tmp), sum_to(M, Tmp), Sum is Tmp + N. Sum is Tmp + N. 20COSC 2P93 Prolog: Cut

Cuts Cuts are extralogical: they almost always destroy a program’s logical “declarative” reading. Consider test_list example again... Cuts are extralogical: they almost always destroy a program’s logical “declarative” reading. Consider test_list example again... test_list(L) :- test_if_bad(L), test_if_bad(L), !, !, write(‘Bad list,’), nl, fail. write(‘Bad list,’), nl, fail. test_list(L) :- test_list(L) :- write(‘Good list’), nl. write(‘Good list’), nl. Read literally, the second clause says that all lists are good lists! Read literally, the second clause says that all lists are good lists! Hence we must now ascertain the meaning of this predicate by inspecting what the cut is doing. Hence we must now ascertain the meaning of this predicate by inspecting what the cut is doing. The second clause’s meaning is dependent upon the first clause. The second clause’s meaning is dependent upon the first clause. 21COSC 2P93 Prolog: Cut

Cuts Cuts are unavoidable in many programs. Without them, the program can become too large and inefficient Cuts are unavoidable in many programs. Without them, the program can become too large and inefficient However, cuts usually ruin a logic program’s readability However, cuts usually ruin a logic program’s readability Careless use of cuts can make a Prolog program unintelligible, and hard to debug. Careless use of cuts can make a Prolog program unintelligible, and hard to debug. 22COSC 2P93 Prolog: Cut

When to use cuts 1.Try to make a declarative predicate if feasible: correct, concise, efficient. 2.Else, use “->” (if-then-else) or once/1 if they help. 3.Else, use a cut if it is a green cut. 4.Red cut: use as rarely as possible. Document their function! 23COSC 2P93 Prolog: Cut