+ All Categories
Home > Documents > COMP4730/2004/lec9/H.Melikyan Logic Programming in Prolog A Brief Introduction to Predicate...

COMP4730/2004/lec9/H.Melikyan Logic Programming in Prolog A Brief Introduction to Predicate...

Date post: 28-Dec-2015
Category:
Upload: spencer-webster
View: 221 times
Download: 0 times
Share this document with a friend
42
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).
Transcript

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

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

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

COMP4730/2004/lec9/H.Melikyan

What do we have?Programming in a logic programming language (we will stick toProlog) is based on statements in predicate calculus (logic)As we will see, you can also look at this several differentways (e.g., searching in a relational database).

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.

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

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

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

COMP4730/2004/lec9/H.Melikyan

Compound PropositionsCompound Propositions two or more atomic propositionscombined with logical operators

Precedence: ¬ then then

COMP4730/2004/lec9/H.Melikyan

Examplesa b c ( a ^ b c )a (b c) d ( a (b ^ c ) d )

Variables can appear in propositions but only whenintroduced 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)

COMP4730/2004/lec9/H.Melikyan

Predicate Calculus/ Clausal FormSymbolic 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: B1 B2 . . . Bn A1 A2 . . . Am 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).

COMP4730/2004/lec9/H.Melikyan

Predicate Calculus and Proving TheoremsWould like to infer new propositions (e.g., facts) from someexisting set of propositions. Automatic theorem proving( hada greater deal of interest in early days of computer science50’s-60’s). The most significant breakthroughs wasRobinson's discovery of the resolution principle.(1965)

An inference rule that can be applied automatically is "Resolution"

If we have: P1 P2 and

Q1 Q2

and it turns out that P1 is identical to Q2, then we can

rename P1 and Q2 to T to get: T P2 and Q1 Tfrom which we can deduce: Q1 P2 (this is resolution)

COMP4730/2004/lec9/H.Melikyan

Unification and InstantiationResolution gets more complex if variables are involvedTo use resolution in the presence of variables, weneed to find values for variables that allow matchingto proceedExample 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" ofvalues to variables is called Unification

Temporarily "assigning" a value to a variable forunification is called instantiation of the variable

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:

Q1 Q2 ... Qn (fact) or P Q1 Q2 ... Qn (implication)

headless Horn clauses headed Horn Clauses( P is called a head)

COMP4730/2004/lec9/H.Melikyan

Note: you can't express all propositions this way lack ofnegation is particularly troubling as we will see later

Prolog notation for

Q1 Q2 ... Qn is Q1, Q2, ... ,Qn . (fact or query)

and

P Q1 Q2 ... Qn is P :- Q1, Q2,... , Qn (rule)

Two ways to read a rule:

P :- Q1, Q2 .

If Q1 and Q2 then conclude P.

To show P, first show Q1, then Q2

COMP4730/2004/lec9/H.Melikyan

Prolog fundamentals ( Second look)

Atom , Terms

Clauses, Facts,

Queries, Rules,

Lists in Prolog

COMP4730/2004/lec9/H.Melikyan

/* file facts.plraining. 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  

COMP4730/2004/lec9/H.Melikyan

A Subset of Prolog (BNF form)

<idstr> {<letter> | <digit> | _ }* <atom> <lowercase letter> <idstr> <term> <atom> <fact> <term> . <clause> <fact> <query> <fact>

More coming...

COMP4730/2004/lec9/H.Melikyan

Reltions

parent(kim,holly). parent(margaret,kim). parent(margaret,kent). parent(esther,margaret). parent(herbert,margaret)parent(herbert,jean).

<idstr> {<letter> | <digit> | _ }* <atom> <lowercase letter> <idstr> <term> <atom> | <compound term> <termlist> <term> { , <term> } <compound term>-> <atom>'(' <termlist>')' <fact> <term> . <clause> <fact> <query> <termlist> .

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, thoseoccurrences are independent. When the same variable occurs morethan once in the same clause, all those occurrences must beinstantiated the same way.

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

COMP4730/2004/lec9/H.Melikyan

A Subset of Prolog

<idstr> {<letter> | <digit> | _ }* <atom> <lowercase letter> <idstr> <variable> <uppercase letter> <idstr> <term> <atom> | <variable> <compound

term> <termlist> <term> { , <term> } <compound term> <atom> '('<termlist> ')' <fact> <term> . <rule> <term> : <termlist> . <clause> <fact> <rule> <query> <termlist> .

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.

 

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

? ancestor(X,holly). X = kim ; X = margaret ; X = esther ;

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.

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

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­

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

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­

COMP4730/2004/lec9/H.Melikyan

Program lengthRecursive calculation of the length (number of elements) of a list. If the list is empty, the length is 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­

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­

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 ?

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­;­

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?

COMP4730/2004/lec9/H.Melikyan

Search ( The Knapsack Problem )

One of the most important strengths of Prolog is in solvingproblems 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?

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.  

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

 

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.  

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

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

COMP4730/2004/lec9/H.Melikyan

Maximization and The findall Predicate

We are searching for any solution that achieves some targetNumber of calories. Suppose instead we want a best solution:one that maximizes the number of calories for the givenknapsack capacity? Prolog isn't quite as helpful with that...  The findall Predicate There is a predefined predicate you can use to collect allProlog's solutions in a list: findall(Var,Goal,L)  Var should be one of the variables that occurs in the Goalterm. It finds all the ways Goal can succeed. It collects allThe successful bindings of Var in the list L.

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

 

COMP4730/2004/lec9/H.Melikyan

HW #91.(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 04Please send the solutions via email to [email protected] hand in hard copy by the beginning of the class


Recommended