View
215
Download
2
Embed Size (px)
Citation preview
26 October 2006 Foundations of Logic and Constraint Programming 1
Negation: Procedural Interpretation
Anoverview
• Whynegation
• Extendedprogramsandqueries
• Thecomputationmechanism:SLDNF-derivations
• Allowedprogramsandqueries
[ApBo94]KrzysztofAptandRolandBol,LogicProgrammingandNegation:ASurvey,JournalofLogicProgramming,19/20:9-71,1994.
26 October 2006 Foundations of Logic and Constraint Programming 2
Example (1)
In many cases, it is important to find solutions that do not satisfy someproperty.TheintroductionofnegationinLogicProgrammingaimsatenablingadeclarativestyleforspecifyingsuchsituations.
Example:GivenprogramPbelow
forwhichairportsdoIhaveadirectflightfromLisbon,butnotfromPorto?
Inthiscase,adeclarativespecificationoftheintendedqueryis
direct(lisbon,X), direct(porto,X).
wherestandsfornegation.
direct(lisbon, london).direct(lisbon,paris).direct(lisbon, madrid).kfurt)direct(lisbon,frankfurt).direct(porto,madrid).direct(porto,paris).direct(porto,london).
26 October 2006 Foundations of Logic and Constraint Programming 3
Example (2)
When sets are represented by lists, some operations on sets are alsoconvenientlyexpressedbymeansofnegation.
Example1:SetDifference
% diff(S,T,R) : R = S \ T
diff([],_,[]) ←
diff([H|T], L, R) ← member(H,L), diff(T,L,R].
diff([H|T], L, [H|R])← member(H,L), diff(T,L,R].
Example2:SetDisjointness(ST=)
% disjoint(S,T) : S T = disjoint([], _) ←
disjoint([H|T], L) ← member(H,L), disjoint(T,L).
26 October 2006 Foundations of Logic and Constraint Programming 4
Extended Logic Programs and Queries
• First,somedefinitionsregardingnegation
• “”denotesthenegationsign
• A,Aareliterals:Aisanatom
• A, Aaregroundliterals:Aisagroundatom
• Qisanextendedquery:Qisafinitesequenceofliterals
• H ← Bisanextendedclause:Hisanatom,Bisanextendedquery.
• Pisanextendedprograms:Pisafinitesetofextendedclauses.
• Now, to “compute” negation, a particular semantics for negation has beenwidelyadoptedinlogicprogramming,namelynegation as failure.
• Intuitively,“ifyoucannotprovethatPistrue,thenPmustbefalse(?)”.
26 October 2006 Foundations of Logic and Constraint Programming 5
Negation as Failure
• Tocomputenegation,ithasbeenadoptedaparticularsemanticsfornegation,namelynegationasfailure.
• Intuitively,ifyoucannotprovethatPistrue,thenPmustbefalse(?).
Negation as Failure (NF):
1. AssumeAisselectedinthequeryQ = L, A , N.
2. IfP {A} succeeds
thenthederivationof P {Q} failsatthispoint.
3. IfallderivationsofP {A} fail
thenQresolvestoQ’ = L, N.
• Hence A succeeds iff A finitely fails
A finitely fails iff A succeeds
26 October 2006 Foundations of Logic and Constraint Programming 6
SLDNF resolvents
1. LetQ = L, A , Nbeaquery,Atheselected,positive,literal.
• LetH ← Mbeavariantofaclausec,whichisvariabledisjointwithQ,isamguofAandH;
• thenQ’ = ( L, M , N ) istheSLDNF-resolventofQ(wrtAwith);
• theSLDNF-derivation stepisdenotedbyQ c Q’
2. LetQ = L, A , Nbeaquery,Atheselected,negativeandground,literal.
• ThenQ’ = ( L, N ) istheSLDNF-resolventofQ(wrtAwith);
• theSLDNF-derivation stepisdenotedbyQ Q’
• Note:Nosubstitutionisperformedduetothenegativeliteral.Thisliteral,thatshouldbeground,isonlycheckedfornottrue.
26 October 2006 Foundations of Logic and Constraint Programming 7
Pseudo Derivations
1. AmaximalsequenceofSLDNF-derivationsteps
Q0 1c1 Q1 ...
Qn-1 ncn Qn ...
isapseudo-derivationofP {Q}
:
• Q0, ... , Qn, ...arequeries,eachemptyorwithoneliteralselectedinit;
• 1naresubstitutions;
• c1, ... , cn, ... are clauses of program P (in case a positive literal isselectedinthepreceedingquery);
• ForeverySLDNF-derivationstepwithinputclause,thestandardisation apart(“freshvariables”)conditionholds.
26 October 2006 Foundations of Logic and Constraint Programming 8
Forests
• Since for each negated ground literal a “distinct” derivation is started, thewholeprocedureisbettermodeledasasetoftrees(forest).
• F = (T, T, subs)isaforest:
• Tisasetoftreeswhere- Nodesarequeries- Aliteralisselectedineachnonemptyquery- Leavesaremarkedas“success”,“failure”or“floundered”
• T T isthemaintree • subsassignstosomenodesoftreesinTwithselectednegativeground
literalAasubsidiarytreeofT,withrootA.
• TreeT T issuccessful :itcontainsaleafmarkedas“success”
• TreeT T isfinitely failed :itisfiniteandallleavesaremarkedas“failure”
26 October 2006 Foundations of Logic and Constraint Programming 9
Pre-SLDNF Trees
• The class ofpre-SLDNF trees for a programP is the smallest classC offorestssuchthat
• foreveryqueryQ:
- The initial pre-SLDNF tree ({TQ}, TQ, subs) is in C, where TQcontainsthesinglenodeQandsubs(Q)areundefined.
• foreveryF C :
- Theextensionof F isin C.
26 October 2006 Foundations of Logic and Constraint Programming 10
Extension of Pre-SLDNF Trees (1)
Extension of forest F = (T, T, subs) :
a. Everyoccurrenceoftheemptyqueryismarkedas“success”
b. Foreverynon-emptyqueryQ,whichisanunmarkedleafinsometreeinT,performthefollowingaction:
LetLbetheselectedliteralofQ
1. Lispositive
IfQhasnoSLDNF-resolvents
thenQismarkedas“failure”
else
for every program clause c which is applicable toL, exactly onedirect descendant of Q is added. This resolvent is the SLDNF-resolventofQwithcwrt.L.
26 October 2006 Foundations of Logic and Constraint Programming 11
Extension of Pre-SLDNF Trees (2)
Extension of forest F = (T, T, subs) : (cont.)
2. L=Aisnegative
IfAnon-ground
thenQismarkedas“floundered”
else(Aisground)
• subs(Q)undefined
newtreeT’withsinglerootAisaddedtoTandsubs(Q)issettoT’
• subs(Q)definedandsuccessful
Qismarkedasfailure
• subs(Q)definedandfinitelyfailed
SLDNF-resolventofQisaddedastheonlydirectdescendentofQ
• subs(Q)definedandneithersuccessfulnorfinitelyfailed
noaction
26 October 2006 Foundations of Logic and Constraint Programming 12
SLDNF-Trees
An SLDNF-tree
:
limitofasequence F0, F1, F2, ...,where
• F0istheinitialpre-SLDNFtree
• Fi+1 isanextensionofFi,foreveryi N
An SLDNF-tree for P {Q}
:
SLDNF-tree inwhichQistherootofthemaintree
26 October 2006 Foundations of Logic and Constraint Programming 13
Successful, Failed and Finite SLDNF-Trees
• A(pre-)SLDNF-treeis successful
: itsmaintreeissuccessful
• A(pre-)SLDNF-treeis finitely failed
: itsmaintreeisfinitelyfailed
• ASLDNF-treeis finite
: noinfinitepathexistsinit,where
apathisasequenceofnodesN0, N1, N2, ... suchthatforevery i( N), Ni+1
is
• eitheradirectdescendantofNi ;
• ortherootofsubs(Ni)
26 October 2006 Foundations of Logic and Constraint Programming 14
Example (1)
Program P:
q ← q
q
q
q
q
q
• TheSLDNF-treefor P { q} isinfinite
26 October 2006 Foundations of Logic and Constraint Programming 15
Example (2)
• TheSLDNF-treefor P { q} issuccessful
Program P:
q ← r
r ←
r ← r
q
q
rfailure
r
□ success
□ success
r
□ success
r
□ success
1
2
3
4
4a
4b
26 October 2006 Foundations of Logic and Constraint Programming 16
SLDNF- derivation
• ASLDNF-derivation ofP {Q}:
branchinthemaintreeofaSLDNF-treeFforP {Q}togetherwiththesetofalltreesofFwhoserootscanbereachedfromthenodesinthisbranch.
• ASLDNF-derivation issuccessful :
itendswithsuccess(□).
• Acomputed answer substitution (CAS) ofQ0 (wrt ):
(12n) | var(Q0)
wherethemaintreeofanSLDNF-treeforP {Q0}containsthebranch
=Q0 1 Q1 ... Qn-1 nQn = □
26 October 2006 Foundations of Logic and Constraint Programming 17
A Theorem on Limits
• The following theorem justifies that the determination ofwhether aSLDNF-tree is successful or finitely failed is a search problem in a finite searchspace.
Theorem
1. EverySLDNF-treeisthelimitofauniquesequenceofpre-SLDNF-trees.
2. IftheSLDNF-treeFisthethelimitofthesequenceF0, F1, F2, ...,then:
i. FissuccessfulandyieldsCAS
iffsomeFi issuccessfuland yieldsCAS
ii. Fisfinitelyfailed
iffsomeFi isfinitelyfailed.
26 October 2006 Foundations of Logic and Constraint Programming 18
Why Select Ground Literals Only
• Ideally,whenaAisselectedinaquery,wewouldlikeSLDNF-resolutiontoanswerthequestion:
“IsthereasubstitutionthatmakesatomAfalse?”
• Unfortunately,SLDNF-resolutionanswersadiffrentquestion:
“Arethere nosubstitutionsthatmakeatomAtrue?”
• IndeedSLDNFdoesnotchecktheexistencialclosureofA, i.e. P |= A, butratherthenegation(failure)oftheexistencialclosureofA,i.e.P |= A,whichisinfactequivalenttoP |= A.
• Itiseasytoseethattheonlysituationwhere(A)(A),i.e.
x1, xkAx1, xkA
occurs when there are no variables in atomA, thus justifying the need forgroundliterals.
26 October 2006 Foundations of Logic and Constraint Programming 19
Why Select Ground Literals Only (Example 1)
• Thedifferencebetween(A)(A)canbeobservedinprogram
zero(0) ←positive(x) ← zero(x)
forqueryQ = positive(y).
• Indeed,ratherthanfindingwhethertherearepositivenumbers,i.e.“aretherenon-zeronumbers” ,SLDNFanswers thequitedifferent questionof “areallnumbersnon-zero”,whichisofcoursefalse(0iszero!).
positive(y)
zero(y)failure zero(y)
□ success
{x/y}
{y/0}
26 October 2006 Foundations of Logic and Constraint Programming 20
Why Select Ground Literals Only (Example 2)
• The “unintended” behaviour od SLDNF does not occur when the query isground;neitherwithQ0 = positive(0),nor Q1 = positive(s(0)).
zero(0) ←positive(x) ← zero(x)
• Inbothcases,the“correct”answersaregiven:• 0isnotpositive• s(0)ispositive
positive(0)
zero(0)failure zero(0)
□ success
{x/0}
{}
positive(s(0))
zero(s(0))sucess zero(s(0))
failure
{x/s(0)}
26 October 2006 Foundations of Logic and Constraint Programming 21
Extended Selection Rule
• (Extended) selection rule:
Functionwhich,givenapre-SLDNF-treeF = (T, T, subs) selectsa literal ineverynon-emptyunmarkedleafineverytreeinT.
• SLDNF-tree F isviaaselectionrule R :
Fisthelimitofasequenceofpre-SLDNF-trees,inwhichliteralsareselectedaccordingtoR.
• SelectionruleRissafe:
Rneverselectsanon-groundnegativeliteral.
26 October 2006 Foundations of Logic and Constraint Programming 22
Blocked Queries
• Query Q is blocked
:
Qisnon-emptyand
containsexclusivelynon-groundnegativeliterals
• P {Q}flounders
:
someSLDNF-treefor P {Q}containsablockednode.
Notice that floundering causes a the program to behave in the “unintendedway”,discussedbefore.
26 October 2006 Foundations of Logic and Constraint Programming 23
Allowed Programs and Queries do not Flounder
• Query Q is allowed :
everyx var(Q)occursinapositiveliteralofQ
• Clause H ← B is allowed :
H, Bisallowed
• (Unit)clause H ← is allowed :
H isagroundatom
• ProgramPis allowed :
allclausesofPareallowed
Theorem 3.13 (Apt and Bol, 1994)
AssumethatPandQareallowed.Then
• P {Q}doesnotflounder;
• IfisaCASofQ,thenQisground.
26 October 2006 Foundations of Logic and Constraint Programming 24
SLDNF implementation in Prolog
• Operationally, Prolog systems use the cut (“!”) mechanism to implementnegation as failure literally, by means of the built-in meta-predicate “\+”,definedasfollows
% \+ is the negation operator
% (1) A finitely fails iff A succeeds \+A :- call(A), !, fail.
% (2) A succeeds iff A finitely fails\+A.
• Thenegationofanatom(orgoal)istreatedseparately,startinganewtree.
a) If the goal succeedswith some substitution themeta-predicate isforceedtofail,withnoalternative(duetothe!).
b) Ifthegoalfailsthecutisnotinvokedandthecatchallclausemakesthemeta-predicate\+tosucceed,withnosubstitution.
26 October 2006 Foundations of Logic and Constraint Programming 25
Specifics of Prolog
• InProlog,SLDNF-resolution(SelectionruledrivenLinearResolutionforDefiniteclausesaugmentedbyNegationasFailure)isinstantiatedbyadopting
• Leftmost selection rule % leftmost literals fromresolvents
• Aprogramisasequenceofclauses %topclausesfirst
• Non-groundnegativeliteralsselected! %floundering!
• Unificationwithoutoccurs check %incorrectunification
• Depth-first search, backtracking % trapped in infinite branches
• The notions of SLDNF-resolution, -resolvents, -trees, etc. are “replaced” byLNDF-correspondents.
26 October 2006 Foundations of Logic and Constraint Programming 26
Extended Prolog Trees
LetP beanextendedprogramandQ0anextendedquery.Then
The Extended Prolog Tree for P {Q0} is the forest of finitely branching,ordered treesofqueriespossiblymarkedwith “success”or “failure”,producedasfollows:
• Startwithforest({TQ0 }, TQ0
, subs),
whereTQ0containsthesinglenodeQ0andsubs(Q0)isundefined
• Repeatedlyapplyoperationexpand (F,Q).tothecurrentforest
F = (T, T, subs)
where
• T1 Tisleftmost,bottommost(i.e.mostnestedsubsidiary)treewithanunmarkedleaf.
• QistheleftmostunmarkedleafinT1,
26 October 2006 Foundations of Logic and Constraint Programming 27
Operation Expand (1)
LetF = (T,T,subs)bethecurrentforest,whereT1 Tisleftmost,bottommosttreewithanunmarkedleaf,andQistheleftmostunmarkedleafinT1.
Operationexpand (F,Q).isdefinedasfollows:
• IfQ = □then
1. MarkQwith“sucess”
2. IfT1 T,thenremovefromT1alledgestotherightofthebranchthatendswithQ (i.e.donotrepeatsuccessinasubsidiarytree).
• IfQhasnoLDNF-resolvents,then
markQwith“failure”
elseletLbetheleftmostliteralinQ
26 October 2006 Foundations of Logic and Constraint Programming 28
Operation Expand (2)
– Lispositive
Add for each clause that is applicable to L, an LDNF-resolvent as adescendantofQ(suchthattheorderoftheclausesispreserved)
– L = Aisnegative(notnecessarilyground!)
• Ifsubs(Q)isundefined
thenaddanewtreeT’ = Aandsetsubs(Q)toT’
• Ifsubs(Q)isdefinedandsuccessful
thenmarkQwith“failure”
• Ifsubs(Q)isdefinedandfinitelyfailed
then add in T1 the LNDF-resolvent of Q as the onlydescendantofQ
26 October 2006 Foundations of Logic and Constraint Programming 29
Prolog Negation does not Check Floundering
• From the specification, Prolog does not check whether a negated goal isgroundornot.Hence, computation isneverblocked,but theprice topay isfloundering.Thiscanbeshowninthefollowinginteraction.
| ?- positive(0).no
| ?- positive(s(s(0))).yes
| ?- positive(X).no % ????
• The reason for floundering is, of course, thecall of thenongroundnegativegoal\+zero(X).
zero(0).positive(X):- \+ zero(X)
26 October 2006 Foundations of Logic and Constraint Programming 30
Prolog Users Must Avoid Floundering
• To avoid floundering, anuser must take care to write programs which areallowed.
• This can in general be achieved by specifying what the variables “might be”, before specifying what they “are not”.
• Example: Insteadofprogram useprogram
| ?- positive(X). | ?- positive(X).
no % ???? X = s(0) ? ;
X = s(s(0)) ? ;
X = s(s(s(0))) ? ;...
zero(0). positive(X):-
\+ zero(X)
zero(0). positive(X):- num(X), \+ zero(X)
num(0). num(s(X)):- num(X).