Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP4730/2004/lec9/H.Melikyan Logic Programming in Prolog  A Brief Introduction to Predicate Calculus  Predicate Calculus and Proving Theorems  An Overview.

Similar presentations


Presentation on theme: "COMP4730/2004/lec9/H.Melikyan Logic Programming in Prolog  A Brief Introduction to Predicate Calculus  Predicate Calculus and Proving Theorems  An Overview."— Presentation transcript:

1 COMP4730/2004/lec9/H.Melikyan Logic Programming in Prolog  A Brief Introduction to Predicate Calculus  Predicate Calculus and Proving Theorems  An Overview of Logic Programming  The Origins of Prolog  The Basic Elements of Prolog  Applications of Logic Programming.  Examples (allots).

2 COMP4730/2004/lec9/H.Melikyan Logic Programming & Prolog  Prolog (Programming in Logic) is the prime example of a logic programming language - only one with real wide spread use.  These languages are declarative They let the programmer indicate what is to be computed, but leave (some/many/most of) the details of how it is to be computed to the system  Not based on state modification (e.g., not imperative) Also not procedural in nature. Procedure or function is not the primary programming construct  Does not have control flow (as we are used to thinking of it)  Quite different

3 COMP4730/2004/lec9/H.Melikyan What We Wont To Do With This?  Declarative semantics are simpler Will make simple statements in logic. Can understand their meaning without knowing the "state" of the program at the point of execution (e.g., the value of all the variables) which implies understanding a lot about the execution history of the program up to that point. If system can pull it off, its just plain a lot easier to say what, but not how.  downside of logic programming, may be quite inefficient.  Often have to compromise declarative semantics some for efficiency.  But if it is well suited to the problem get a big win

4 COMP4730/2004/lec9/H.Melikyan What do we have? Programming in a logic programming language (we will stick to Prolog) is based on statements in predicate calculus (logic) As we will see, you can also look at this several different ways (e.g., searching in a relational database).

5 COMP4730/2004/lec9/H.Melikyan Review of Logic and The Predicate Calculus  Proposition - logical statement that may or may not be true - made up of "objects" and their relationships to each other - combined with logical operators (and, or, etc.) Will program in clauses that represent propositions.  Objects in logic programming made up of simple terms (constants or variables) in Prolog these will end up being: variables (ids starting in upper case), numeric and string literals, and symbolic literals (ids starting in lower case)

6 COMP4730/2004/lec9/H.Melikyan Parts of Prolog Atomic Propositions represents a relation two parts: functor - names the relation parameters - objects which take part in the relation Examples (Simpsons Family) parent( marge, lisa ). parent( marge, bart ). parent( marge, maggie ). parent( homer, lisa ). parent( homer, bart ). parent( homer, maggie ). Or facultyMember(melikyan). teaches(melikyan, comp4730).

7 COMP4730/2004/lec9/H.Melikyan Functors  Note: functors do not supply meaning just ids, -we interpret them -logic would work the same with "foo" and "bar  Functors simply name a relation Atomic propositions either indicates members of that relation (facts) faculty(melikyan). faculty(tokuta). faculty(soaf). teaches(melikyan, comp4730). teaches(tokuta, comp4850). teaches(soaf, comp1520). Or a question about membership in a relation (query) teaches(X, comp1520). faculty(Y).

8 COMP4730/2004/lec9/H.Melikyan Compound Propositions Compound Propositions two or more atomic propositions combined with logical operators  Precedence: ¬ then  then 

9 COMP4730/2004/lec9/H.Melikyan Examples a  b  c ( a ^ b  c ) a  (b  c)  d ( a  (b ^ c )  d ) Variables can appear in propositions but only when introduced by special symbols called Quantifiers: Universal  X.P For all X, P is true Existential  X.P There exists a value of X such that P is true (often leave out the ".") Examples:  X.(teachingFaculty(X)  facultyMember(X))  X.(teachingFaculty(X)  Y.teaches(X,Y)) (Won't see much in the way of quantifiers, but they are implicit in a number of places)

10 COMP4730/2004/lec9/H.Melikyan Predicate Calculus/ Clausal Form Symbolic Logic can be used for the three basic needs of formal logic - to express propositions, - to express relationships between propositions, - to describe how propositions can be inferred prom other propositions that are assumed to be true. Clausal form: B 1  B 2 ...  B n  A 1  A 2 ...  A m where As and Bs are terms.  The meaning of this clausal form proposition is as follows: If all of As are true, then at least one of B is true. The primary characteristics of clausal form propositions are followings  Existential quantifiers are not required;  Universal quantifiers are implicit in the use of variables in atomic propositions.  No operations other than conjunction or disjunction are required and also they can appear only on specified side.  All prediacte calculus propositions can be converted to clausal form Nilsson (1971).

11 COMP4730/2004/lec9/H.Melikyan Predicate Calculus and Proving Theorems Would like to infer new propositions (e.g., facts) from some existing set of propositions. Automatic theorem proving( had a greater deal of interest in early days of computer science 50’s-60’s). The most significant breakthroughs was Robinson's discovery of the resolution principle.(1965) An inference rule that can be applied automatically is "Resolution" If we have: P 1  P 2 and Q 1  Q 2 and it turns out that P 1 is identical to Q 2, then we can rename P1 and Q2 to T to get: T  P2 and Q1  T from which we can deduce: Q1  P2 (this is resolution)

12 COMP4730/2004/lec9/H.Melikyan Unification and Instantiation Resolution gets more complex if variables are involved To use resolution in the presence of variables, we need to find values for variables that allow matching to proceed Example f(X,Y)  P2(Y,X) Q1(foo)  f(foo, bar) if we rename X = foo and Y = bar we can conclude Q1(foo)  P2(bar, foo) Process of finding these suitable "assignments" of values to variables is called Unification Temporarily "assigning" a value to a variable for unification is called instantiation of the variable

13 COMP4730/2004/lec9/H.Melikyan Horn Clauses  Resolution process often requires backtracking instantiate a variable with a value matching fails backtrack by instantiating with another value and trying match again.  Prolog operates on the basis of unification. Consider propositions with variables (queries).  Unification becomes a search process, find a set of assignments of values to variables that make this proposition true.  Prolog uses limited form of logical expression: Horn Clauses: Q 1  Q 2 ...  Q n (fact) or P  Q 1  Q 2 ...  Q n (implication) headless Horn clauses headed Horn Clauses( P is called a head)

14 COMP4730/2004/lec9/H.Melikyan Note: you can't express all propositions this way lack of negation is particularly troubling as we will see later Prolog notation for Q 1  Q 2 ...  Q n is Q 1, Q 2,...,Q n. (fact or query) and P  Q 1  Q 2 ...  Q n is P :- Q 1, Q 2,..., Q n (rule) Two ways to read a rule: P :- Q 1, Q 2. If Q 1 and Q 2 then conclude P. To show P, first show Q 1, then Q 2

15 COMP4730/2004/lec9/H.Melikyan Prolog fundamentals ( Second look) Atom, Terms Clauses, Facts, Queries, Rules, Lists in Prolog

16 COMP4730/2004/lec9/H.Melikyan /* file facts.pl raining. cold. bleak. depressing. Prolog program in a file called facts ?­ consult(facts). facts compiled, 0.00 sec, 2,184 bytes. Yes ?­raining. Yes ?­ cold. Yes ?­ warm. [WARNING: Undefined predicate: 'warm/0'] No

17 COMP4730/2004/lec9/H.Melikyan A Subset of Prolog (BNF form)  { | | _ }*  .  More coming...

18 COMP4730/2004/lec9/H.Melikyan Reltions parent(kim,holly). parent(margaret,kim). parent(margaret,kent). parent(esther,margaret). parent(herbert,margaret) parent(herbert,jean).  { | | _ }*   |  {, } -> '(' ')' .  .

19 COMP4730/2004/lec9/H.Melikyan parent(kim,holly). parent(margaret,kim). parent(margaret,kent). parent(esther,margaret). parent(herbert,margaret). parent(herbert,jean). parent(god, X). ?­ parent(herbert,Y). Y = margaret Yes ?­ parent(herbert,Y). Y = margaret ; Y = jean ; No ?­ The scope of a variable is the clause. When the same variable occurs in different clauses, those occurrences are independent. When the same variable occurs more than once in the same clause, all those occurrences must be instantiated the same way.

20 COMP4730/2004/lec9/H.Melikyan parent(kim,holly). parent(margaret,kim). parent(margaret,kent). parent(esther,margaret). parent(herbert,margaret). parent(herbert,jean). grandparent(X,Y) :­ parent(X,Z), parent(Z,Y). greatgrandparent(X,Y) :­ grandparent(X,Z), parent(Z,Y).

21 COMP4730/2004/lec9/H.Melikyan A Subset of Prolog  { | | _ }*   |  {, }  '(' ')' .  :­.  .

22 COMP4730/2004/lec9/H.Melikyan Recursive Rules A parent is an ancestor: ancestor(X,Y) :­ parent(X,Y). The ancestor of a parent is an ancestor: ancestor(X,Y) :­ parent(Z,Y), ancestor(X, Z). Using these rules we have defined the ancestor relation recursively.

23 COMP4730/2004/lec9/H.Melikyan Ancestor ( parent3.pl) parent(kim,holly). parent(margaret,kim). parent(margaret,kent). parent(esther,margaret). parent(herbert,margaret). parent(herbert,jean). grandparent(X,Y) :­ parent(X,Z), parent(Z,Y). greatgrandparent(X,Y) :­ grandparent(X,Z), parent(Z,Y). ancestor(X,Y) :­ parent(X,Y). ancestor(X,Y) :­ parent(Z,Y), ancestor(X,Z). v ?­ ancestor(X,holly). v X = kim ; v X = margaret ; v X = esther ;

24 COMP4730/2004/lec9/H.Melikyan Integers in Prolog An integer may be used as a term. For now we'll be using them like atoms: children(fred,2) Another day, we'll see how to evaluate integer expressions and so on.

25 COMP4730/2004/lec9/H.Melikyan Lists in Prolog We started with the very basics of lists. Prolog lists are comma-separated and put in square brackets. They are just like any other term in most respects. You can split lists apart or put them together via unification with the "split“ ('|') syntax: Prolog term [],.(1,[]).(1,.(2,.(3,[]))), [1,2,3] [1,2,fred] Prolog allows [Head|Tail] as shorthand for.(Head,Tail). Besides being a little easier to read, there is more flexibility: 1. [Head | Tail] - matches a list, binding Head to the first element and Tail to the rest 2. [1, 2 | Tail] - matches a list whose first two elements are 1 and 2, binding Tail to the rest 3. [Head | [3,4]] - matches a list of length 3 whose last two elements are 3 and 4, binding Head to the first

26 COMP4730/2004/lec9/H.Melikyan The = Operator A goal X = Y succeeds if X and Y can beunified. You could do something similar by writing your own predicate, equals(X,X). There's also X \= Y, which is not(X = Y). ?­ X = abc. Yes ?­ X = f(a,b). X = f(a, b) Yes ?­ X = 1+2*3. X = 1+2*3

27 COMP4730/2004/lec9/H.Melikyan The is Operator A goal X is Y succeeds if Y is a numeric expression, and X can be unified with the value of that expression. So (finally!) it evaluates expressions. All variables must be instantiated. ?­ X is 1+2*3. X = 7 ; No ?­ X is 1 / 2. X = 0.5 ; No ?­ X is 1+Y.

28 COMP4730/2004/lec9/H.Melikyan Comparison Operators  There are numeric comparisons, >=, =:=, and =\=  They evaluate numeric expressions: ?­ 1<2+3. Yes ?­ 1 > 2+3. No ?­ 1 =< 2+3. Yes ?­ 1 >= 2+3. No ?­ 1+2 =:= 2+1. Yes

29 COMP4730/2004/lec9/H.Melikyan Program length Recursive calculation of the length (number of elements) of a list. v If the list is empty, the length is v Otherwise, the length is one larger than the length of the list obtained by removing the first element of the original list. xlength([],0). xlength([_|Tail],Len) :­ xlength(Tail, TailLen), Len is 1 + TailLen. ?­ xlength([1,2,3,4,5],X). X = 5 ; No ?­ xlength([a,b,c], X). X = 3 ; No ?­ xlength(X, 3). X = [_G276, _G279, _G282] Yes

30 COMP4730/2004/lec9/H.Melikyan An Experiment xlength([],0). xlength([_|Tail],Len) :­ xlength(Tail, TailLen), Len = 1 + TailLen. ?­ xlength([],X). X = 0 ; No ?­ xlength([1,2,3,4,5],X). X = 1+ (1+ (1+ (1+ (1+0)))) ; No ?­ xlength([1,2,3,4,5],X), Len is X. X = 1+ (1+ (1+ (1+ (1+0)))) Len = 5 ; No

31 COMP4730/2004/lec9/H.Melikyan A gcd Predicate gcd(X,X,X). gcd(X,Y,Denom) : - X < Y, NewY is Y ­ X, gcd(X,NewY,Denom). gcd(X,Y,Denom):­ X > Y, NewX is X ­ Y, gcd(NewX,Y,Denom). ?­ gcd(5,5,X). X = 5 ; No ?­ gcd(12,21,X). X = 3 ; No ?­ gcd(91,105,X). X = 7 ; No ?­ gcd(13,23,X). X = 1 ; No ?­ gcd(13,X,1). // What about this ?

32 COMP4730/2004/lec9/H.Melikyan A sum Predicate sum([],0). sum([Head|Tail],X) :­ sum(Tail,TailSum), X is Head + TailSum. ?­ sum([1,2,3,4,5],X). X = 15 ; No ?­ sum([1,3,5,7,9],X). X = 25 ;

33 COMP4730/2004/lec9/H.Melikyan A factorial Predicate factorial(1,1). factorial(X,Fact):­ NewX is X ­ 1, factorial(NewX,NF), Fact is X *NF. ?­ factorial(3,X). X = 6 Yes ?­ factorial(5,X). X = 120 Yes ?­ factorial(1,X). X = 1 Yes Don't ask for more solutions here; it will never complete. Is there a way to fix this problem?

34 COMP4730/2004/lec9/H.Melikyan Search ( The Knapsack Problem ) One of the most important strengths of Prolog is in solving problems that require search. Today: The knapsack problem Martians invade and you must hide out in the forest. Your refrigerator contains:  milk, 800 calories, 4 kg.  break, 400 calories, 2 kg.  chocolate, 700 calories, 1 kg.  jar of peanut butter, 600 calories, 3 kg. Your knapsack holds 4 kg. What do you take?

35 COMP4730/2004/lec9/H.Melikyan Representation  We'll represent the contents of a refrigerator with a list of triples: [(Item,Calories,Weight),...] So in the previous example, the refrigerator contents would be represented as: · We can use the same representation for the contents of the knapsack. [(milk,800,4),(bread,400,2), (chocolate,700,1),(pb,600,3)], We need predicates to compute the total weight and total Calories in a knapsack. weight([],0). weight([(_,_,W) | Rest], X) :­ weight(Rest,RestW), X is W + RestW. calories([],0). calories([(_,C,_) | Rest], X):­ calories(Rest,RestC), X is C +RestC.

36 COMP4730/2004/lec9/H.Melikyan Subsequence A knapsack is a subsequence of the refrigerator contents.  X is a subsequence of Y if they are both empty  X is a subsequence of the tail of Y  they have the same head, and the tail of X is a subsequence of the tail of Y The subseq Predicate subseq([],[]). subseq([Item | RestX], [Item | RestY]) : ­ subseq(RestX,RestY). subseq(X, [_ | RestY]) : ­ subseq(X,RestY).

37 COMP4730/2004/lec9/H.Melikyan Searching for a Solution  We want a list of knapsack contents whose total weight is within the capacity, and whose total calories achieves some target.  Searching all subsequences to find the one you want is simple in Prolog: knapsack(Fridge, Capacity, Goal, Knapsack) :­ subseq(Knapsack,Fridge),weight(Knapsack,Weight), Weight =< Capacity, calories(Knapsack,Calories), Calories >= Goal.

38 COMP4730/2004/lec9/H.Melikyan The Program ( ver 1) weight([],0). weight([(_,_,W) | Rest], X) :­ weight(Rest,RestW), X is W + RestW. calories([],0). calories([(_,C,_) | Rest], X) :­ calories(Rest,RestC), X is C + RestC. subseq([],[]). subseq([Item | RestX], [Item | RestY]) :­ subseq(RestX,RestY). subseq(X, [_ | RestY]) :­ subseq(X,RestY). knapsack(Fridge, Capacity, Goal, Knapsack) :­ subseq(Knapsack,Fridge), weight(Knapsack,Weight), Weight =< Capacity, calories(Knapsack,Calories),

39 COMP4730/2004/lec9/H.Melikyan ?­knapsack([(milk,800,4),(bread,400,2),(chocolate,700,1), (pb,600,3)],4,800,X). X = [(milk, 800, 4)] Yes ?­knapsack([(milk,800,4),(bread,400,2),(chocolate,700,1), (pb,600,3)],4,1300,X). X = [ (chocolate, 700, 1), (pb, 600, 3)] Yes ?­knapsack([(milk,800,4),(bread,400,2),(chocolate,700,1), (pb,600,3)],4,1400,X). No

40 COMP4730/2004/lec9/H.Melikyan Maximization and The findall Predicate We are searching for any solution that achieves some target Number of calories. Suppose instead we want a best solution: one that maximizes the number of calories for the given knapsack capacity? Prolog isn't quite as helpful with that... The findall Predicate There is a predefined predicate you can use to collect all Prolog's solutions in a list: findall(Var,Goal,L) Var should be one of the variables that occurs in the Goal term. It finds all the ways Goal can succeed. It collects all The successful bindings of Var in the list L.

41 COMP4730/2004/lec9/H.Melikyan Extra Point Assignment: Your strategy: collect all legal knapsacks, then choose the one with the most calories. To receive full credit for this assignment your program must be received by April 27, 2002

42 COMP4730/2004/lec9/H.Melikyan HW #9 1.(Review Questions) Answer all the questions ( ## 1 - 23) on the page 662 from your textbook 2. Do all listed problems listed in HW9.( class hendout) Assigned 04 / Due 04 Please send the solutions via email to gmelikian@wpo.nccu.edu and hand in hard copy by the beginning of the class


Download ppt "COMP4730/2004/lec9/H.Melikyan Logic Programming in Prolog  A Brief Introduction to Predicate Calculus  Predicate Calculus and Proving Theorems  An Overview."

Similar presentations


Ads by Google