This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
„Advanced Logic Programming“Summer semester 2009 R O O T SSu e se es e 009
This chapter is partly based on slides from the course “Deskriptive Programmierung” held in the summer semester 2008 by Prof. Dr. Rainer Manthey and Dr. Andreas Behrend.
I want to thank the authors for the permission to use and adapt their material for this course.
Terms are the arguments of literals. They may beV i bl h h dVariables X,Y, Father, Method, Type, _type, _Type, . . .Constants Numbers, Strings, ...Function terms person(stan,laurel), +(1,*(3,4)), …p ( , ), ( , ( , )),
Terms are the only data structure in Prolog!Terms are the only data structure in Prolog!
The only thing one can do with terms is unification with other terms!
Prolog can interpret terms as programs!g p p gA Prolog program can easily interpret or modify itself or other programsWe shall discuss this in the chapter about “Metaprogramming”.
Function terms (structures) are terms that are composed of other termski t “ d ” i P l ( bj t ith t b h i i J )akin to “records” in Pascal (or objects without any behavior in Java)
functor subterms
person(peter, mueller, date(27,11,2007))
A bi i ll d
functor subterms
Arbitrary nesting allowedNo static typing: person(1,2,'a') is legal!Function terms are not function calls! They do not yield a result!!!Function terms are not function calls! They do not yield a result!!!
Notation for function symbols: Functor/Arity, e.g. person/3, date/3
Function terms are the only “data constructor” in Prolog I j ti ith i di t t t bit ilIn conjunction with recursive predicates, one can construct arbitrarily deep structures
Strings are enclosed in double quotes (")" l " i t i"Prolog" is a string'Prolog' is an atomProlog (without any quotes) is a variable
A string is just a list of ASCII codes"Prolog" = [80,114,111,108,111,103]
= .(80,.(114,.(111,.(108,.(111,.(103,[])))))
Strings are seldom useful Better use atoms!There are many predefined predicates for manipulating atoms the same y p p p gway as Java uses strings.Prolog strings are useful just for low level manipulationTheir removal from the language has often been suggested
Operators are just syntactic sugar for function terms: 1 3*4 i th i fi t ti f (1 *(3 4))1+3*4 is the infix notation for +(1,*(3,4))head :- body is the infix notation for ':-'(head,body)? goal is the prefix notation for '? '(goal)?- goal is the prefix notation for ?- (goal)
Operator declarations define notation, associativity and precedence:“f” position of functor“x” argument with precedence strictly lower than the functor
non‐associative side
“y” argument with precedence equal or lower than the functor
prefix notation associative side
:- op(1200, fx, '?-').
:- op( 500, yfx, '+'). ‘?‐’ has higher precedence than ‘+’
% Declare predicates using the operator notation:kurt isFatherOf peter. peter isFatherOf paul.peter isFatherOf hans.peter isFatherOf hans.
G isGrandfatherOf C :- G isFatherOf F, F isFatherOf C.G isGrandfatherOf C :- G isFatherOf M, M isMotherOf C.
% Ask goals using the operator notation:?- kurt isGrandfatherOf paul.?- kurt isGrandfatherOf C.? kurt isGrandfatherOf C.?- isGrandfatherOf(G,paul).?- isGrandfatherOf(G,paul), X isFatherOf G.
Structural equality for ground terms: Constants are just Structural equality for ground terms:functors are equal and …… all argument values in the same position are structurally equal.
Unification of terms T1 and T2fi d b tit ti f th i bl f T1 d T2 h th tfinds a substitution σ for the variables of T1 and T2 such that …… if σ is applied to T1 and T2 then the results are equal
Unification satisfies equations ?- p(X,f(Y),a) = p(a,f(a),Y).X = a, Y = a.
?- p(X,f(Y),a) = p(a,f(b),Y).
QuestionHow to unify two variables?
Problem: Infinitely many unifying?- p(X) = p(Z).X a Y a;
fail.
Problem: Infinitely many unifying substitutions possible!!!
Solution
X = a, Y = a;X = b, Y = b;…
Unification finds the most generalunifying substitution
Unification yields Most General Unifier (MGU)(MGU)
Unification of terms T1 and T2fi d th t l b tit ti f th i bl f T1 d T2 hfinds the most general substitution σ for the variables of T1 and T2 such that …… if σ is applied to T1 and T2 then the results are equal
Theorem (Uniqueness of MGU): The most general unifier of two terms T1 and T2 is uniquely determined up to renaming of variablesand T2 is uniquely determined, up to renaming of variables.
If there are two different most general unifiers of T1 and T2, say σ andthen there is also a renaming substitution such that τ, then there is also a renaming substitution γ such that
A renaming substitution only binds variables to variables
Computing the Most General Unifiermgu(T1 T2)mgu(T1,T2)
Input: two terms, T1 and T2
Output: the most general unifier of T and TOutput: σ, the most general unifier of T1 and T2(only if T1 and T2 are unifiable)
Algorithm1. If T1 and T2 are the same constant or variable then σ = { } 2. If T1 is a variable not occurring in T2 then σ = {T1 ← T2} 3 If T is a ariable not occ ring in T then {T T }3. If T2 is a variable not occuring in T1 then σ = {T2 ← T1}4. If T1 = f(T11,...,T1n) and T2 = f(T21,...,T2n) are function terms with the same
functor and arity1. Determine σ1= mgu(T11, T21)2. Determine σ2= mgu(T11σ1, T21σ1)3. . . .4. Determine σn= mgu(T1nσ1…σn-1, T2nσ1…σn-1)5. If all unifiers exist then σ = σ1…σn-1σn
{G dd ht }= {Granddaughter←anna}Same result substitution as on the previous page!
Chapter 2: Syntax and Semantics
Operational Semantics (cont.)
OK, we’ve seen how resolution finds one answer. But what how to find more answers?
Backtracking!
R O O T S
Derivation with Backtracking
f(a). g(a).
f(b). g(b). h(b).
?- f(X), g(X), h(X).
#1, X=a choicepoint: #2
?- g(a), h(a).
#1 choicepoint: #2
?- f(Y), g(Y), h(Y).?- h(a).
#1 choicepoint: #2
The subgoal h(a) fails because there is noThe subgoal h(a) fails because there is no clause whose head unifies with it.The interpreter backtracks to the last “choicepoint” for g(a)
The subgoal g(a) fails because there is no remaining clause (at the choicepoint or after it) whose head unifies with it.The interpreter backtracks to the last
The interpreter reports the successful substitutions
SLD-Resolution with Backtracking: SummarySummary
SLD-Resolution always selects theth l ft t lit l i l did t f b i l dthe leftmost literal in a goal as a candidate for being resolvedthe topmost clause of a predicate definition as a candidate for resolving the current goal
If a clause’s head is not unifiable with the current goal the search proceeds immediately to the next clause
If a clause’s head is unifiable with the current goalthe goal is resolved with that clausethe interpeter remembers the next clause as a choicepoint
If no clause is found for a goal (= the goal fails), the interpreter undoes the current derivation up to the last choicepoint .
Then the search for a candidate clause continues from the choicepoint
A goal is a box with four ports: call, succeed, redo, failNested goals (subgoals) are boxes nested within the own box withNested goals (subgoals) are boxes nested within the own box, with ports of the same kind connected (outer call to inner call, …)
call succeed
g
For chained goals (conjunction)
redofail
For chained goals (conjunction)the “succeed” port is connected to the “call” port of the next goal and the “fail” port is connected to the “redo” port of the previous
call succeed
g1
call succeed
gn…
redofail
g1
redofail
gn…
Viewing Backtracking in the Debugger (1)(1)
?- gtrace, simplify_aexpr(a-a+b-b, Simple).call the graphical tracer … for this goal.g p…
A predicate is recursive if one or more rules in its definition refer to itself.descend(X,Y):- child(X,Y).
descend(X,Y):- child(X,Z), descend(Z,Y).
What does this mean?What does this mean? 1. if Y is a child of X, then Y is a descendant of X2. if Z is a child of X, and Y is a descendant of Z, then Y is a descendant of X
ProvabilityIf l b d d t th t b l th th l i blIf a goal can be reduced to the empty subgoal then the goal is provable.
UndecidabilityyThere is no automated proof system that always answers yes if a goal isprovable from the available clauses and answers no otherwise.Prolog answers yes no or does not terminateProlog answers yes, no or does not terminate.
The evaluation strategy of Prolog is incomplete. B f t i ti d i ti P l ti l d iBecause of non-terminating derivations, Prolog sometimes only derives a subset of the logical consequences of a program.
Exampler, p, and q are logical consequences of this program p :- q. % 1
% 2q :- p. % 2 p :- r. % 3 r. % 4
However, Prolog’s evaluation strategy cannot derivethem. It loops indefinitely:
Each comma separating subgoals becomes ∧ (conjunction).
Each Head :- Body becomes Head ← Body or Body → Heady ← y y →(implication)
Each variable in the head of a clause is bound by a ∀y(universal quantifier)
son(X,Y) :- father(Y,X),male(X).
∀x.∀yEach variable that occurs only in the body of a clause is bound by a ∃Each variable that occurs only in the body of a clause is bound by a ∃(existential quantifier)
grandfather(X):- father(X,Y) , parent(Y,Z).
∀x. ∃y.∃z.
grandfather(X): father(X,Y) , parent(Y,Z).
Translation of Programs (cont.)
A P l i t l t d t t f f l ithA Prolog program is translated to a set of formulas, with each clause in the program corresponding to one formula:
Such a set is to be interpreted as the conjunction of all the formulas inSuch a set is to be interpreted as the conjunction of all the formulas in the set.
Start: Closed First Order Formula (FOF)“Cl d” th t h i bl i i th f ( “b d b ”)“Closed” means that each variable is in the scope of (= “bound by”) a quantifier.
1. Disjunct Variable Form (VDF)Rename variables bound by quantifiers so that they are unique!
2. Elementary Junctor Form (EJF)Reduce ⇒, ⇔, etc. to ∨, ∧ and ¬according to the following rules:
3 Negation form (NF)3. Negation form (NF)EJF and all negations in front of atomic formulas (= literals)
4. Prenex Normal Form (PNF): M ll tifi t th fi ( th l ft h d id ) di t th lMove all quantifiers to the prefix(= the left-hand-side) according to the rules:
if x not free in Φ if x not free in Φ
prefix if x not free in Φ
matrix
if x not free in Φ
if x not free in Φ
if x not free in Φ
if x not free in Φ
The matrix (= remaining right-hand-side part of formula) is quantifier-free
4. Skolem Form (SF)R l i PNF f l ll f h i t ti l i bl bReplace in PNF formula all occurrences of each existential variable by a unique constant Skolemization does not preserve truth but preserves satisfiability. This is sufficient since resolution proves truth of F by proving unsatisfiabilityof ¬F.
5. Conjunctive Normal Form (CNF)Transform quantor-free matrix of formulas in PNF into a conjunction of di j ti f t t d tdisjunctions of atoms or negated atoms A formula can be translated to CNF if and only if it is quantor-free.
6. Clausal Form A formula in PNF, SF and with matrix in CNF is said to be in clausal form.E h j t f f l i l l f i l
Each conjunct of a formula in clausal form is one clause.
Translation of Programs (cont.)
Our previous example already was in Skolem form (no existential quantifiers)quantifiers).
Here is another formula, which is in Prenex but not Skolem form:Here is another formula, which is in Prenex but not Skolem form:
∃x∃v∀y∀w.(R(x,y) ∧ ¬R(w,v))
Its Skolem Form is
∀y∀w (R(c y) R(w c ))∀y∀w.(R(c1,y) ∧ ¬R(w,c2))
Skolem form is often written without quantifiers, abusing the implicitSkolem form is often written without quantifiers, abusing the implicit knowledge that all variables are universally quantified
The formulas we get when translating all have the same structure:
A1 ∧ A2 ∧ · · · ∧ An → B
Such a formula can be rewritten as follows:
A1 ∧ A2 ∧ · · · ∧ An → B by law A → B ≡ ¬A ∨ B we getA1 ∧ A2 ∧ ∧ An → B by law A → B ≡ A ∨ B we get¬(A1 ∧ A2 ∧ · · · ∧ An) ∨ B by law ¬(A∧B) ≡ ¬A ∨ ¬B we get¬A1 ∨ ¬A2 ∨ · · · ∨ ¬An ∨ B
Hence, Prolog clauses can always translated as disjunctions of ti lit l ith t t iti lit lnegative literals with at most one positive literal.
Undecidability of first order logicTh i t t d f t th t l if l iThere is no automated proof system that always answers yes if a goal isprovable from the available clauses and answers no otherwise.
Semi-decidability of first order logicIt is possible to determine unsatisfiability of a formula by showing that itleads to a contradiction (an empty clause)leads to a contradiction (an empty clause)
Implication of Semi-DecidabilityWe cannot prove a goal directly but must show that adding the negation of the goal to the program P makes P unsatisfiable
P s G is proven by showing that (P ∪ ¬G) s {}
Proving a formula by showing that its negation is wrong is called proofby refutation.
ground literals in Dp(c1, f(c2),c2) p(c2, f(c2),c1)
Herbrand Modells
The Interpretation Domain (D) of a program P consists of three sets:The Interpretation Domain (D) of a program P consists of three sets: Const contains all constants occurring in PFunc contains all function symbols occurring in PPred contains a predicate p: HUxHU true for each predicate symbol poccurring in the program P
The Herbrand Universe (HU) of a program P is the set of all ground terms that can be constructed from the function symbols and constants in P
The Herbrand Base of a program P is the set of all positive ground literals that can be constructed by applying the predicate symbols in Pliterals that can be constructed by applying the predicate symbols in P to arguments from the Herbrand Universe of P
A Herbrand Interpretation maps each formula in P to the elements ofA Herbrand Interpretation maps each formula in P to the elements of the Herbrand Base that are its logical consequences
Each ground fact is mapped to true.Each possible ground instantiation of a non-ground fact is mapped to true.Each instantiation of the head literal of a rule that is a logical consequence of the rule body is mapped to true
The Herbrand Model of a program P is the subset of the Herbrand Base of P that is true according to the Herbrand Interpretation. g p
The Herbrand Model can be constructed by fixpoint iteration:Initialize the model with the ground instantiations of facts in PAdd all new facts that follow from the intermediate model and P
until the model does not change anymore (= fixpoint is reached)
Ensure termination of recursive definitions by putting non-recursive goalsbefore recursive ones!before recursive ones!
Succeeds twice and then Succeeds exactly twiceSucceeds twice and then Succeeds exactly twiceloops infinitely for ?-p(X): for ?-p(X): p(0). (X) (Y) (X Y)
Prolog predicates will loop infinitely ifth i t hi i l b f ithere is no matching non-recursive clause before a recursive onethere is no non-recursive “guard” literal before a recursive invocationthere are cycles in the data traversed by a recursive definitionthere are cycles in the data traversed by a recursive definition
either cycles in the data itselfor cycles introduced by rules
there is divergent construction of termsWe’ll see examples of this in the following section about lists!
Usually predefined://*** The predicate length(List, Int) suceeds iff Arg2 is* the number of elements in the list Arg1.*//length([ ],0).length([X|Xs],N) :- length(Xs,N1), N is N1+1.
Head Tail
Tracing an invocation of 'length' with input on first argument:?- length([1,2],N).
Usually predefined://*** The predicate length(List, Int) suceeds iff Arg2 is* the number of elements in the list Arg1.*//length([ ],0).length([X|Xs],N) :- length(Xs,N1), N is N1+1.
Head Tail
Tracing an invocation of 'length' without input on first argument:?- length(X,N).
Predicates are more general than functionsTh i t i lt b t d di th i tThere is not one unique result but many, depending on the input
So resist temptation to document predicates as if they were functions!p p yDon’t write this:
/*** The predicate length(List Int) returns in Arg2* The predicate length(List, Int) returns in Arg2 * the number of elements in the list Arg1.*/
Better write this instead:
/*** The predicate length(List Int) succeeds iff Arg2 is* The predicate length(List, Int) succeeds iff Arg2 is* the number of elements in the list Arg1.*/
Documenting the behaviour of a predicate thoroughly, including behaviour of special “invocation modes”:behaviour of special invocation modes :
“–” means “always a free variable at invocation time”“+” means “not a free variable at invocation time”
Note: This is weaker than “ground at invocation time”“?” means “don’t care whether free or not at invocation time”
//*** length(+List, ?Int) is deterministic* length(-List, -Int) has infinite success set** The predicate length(List, Int) succeeds iff Arg2 is* the number of elements in the list Arg1.*/length([ ],0).length([X|Xs],N) :- length(Xs,N1), N is N1+1.
OK, we’ve seen how to prove or conclude what is true. But what about negation?
Closed world assumptionNegation as failure
“Unsafe negation” versus existential variables
R O O T S
Closed World Assumption
We cannot prove that something is false. W l h th t t it tWe can only show that we cannot prove its contrary.
isFatherOf(kurt,peter).
?- isFatherOf(adam,cain).no. means: we cannot prove that “isFatherOf(adam,cain)” is true
If we assume that everything that is true is entailed by the program, we may then conclude that what is not entailed / provable is not true.This assumption is known as the “Closed World assumption” (CWA)The conclusion is known as “Negation by Failure” (NF)
?- not( isFatherOf(adam,cain) ).yes.
means: we conclude that “not(isFatherOf(adam,cain) )” is true because wecannot prove that “isFatherOf(adam cain)” is true
?- not( isFatherOf(kurt,X) ).no substitution for X returned!
( , )no.
?- ∀X.not(isFatherOf(adam,X)).unsafe infinite result set!
Deductive databases consider all variables to be universally quantified.
yes. no substitution for X returned! unsafe, infinite result set!
However, the set of values for X for which isFatherOf/2 fails is infiniteand unknown because it consists of everything that is not represented in the programin the program. So it is impossible to list all these values!Therefore, the above negated query with universal quantification is