• No results found

Well-Terminating, Input-Driven Logic Programs

N/A
N/A
Protected

Academic year: 2021

Share "Well-Terminating, Input-Driven Logic Programs"

Copied!
14
0
0

Loading.... (view fulltext now)

Full text

(1)

Well-Terminating, Input-Driven Logi Programs

Jan{GeorgSmaus

UniversityofKentatCanterbury,Canterbury,CT27NF,UnitedKingdom,

telephonexx44/1227/827553, fax762811,j.g.smausuk .a .uk

Abstra t. Weidentifya lassofpredi atesforwhi hterminationdoes

notdependonleft-to-rightexe ution.Allthatisrequiredisthat

deriva-tionsare input-driven, that is, inea h derivationstep, the input

argu-ments of the sele ted atom do not be ome instantiated. The method

ofshowingthat apredi ateis inthat lassisbasedonlevelmappings,

loselyfollowingthetraditionalapproa hforLDderivations.Many

pred-i atesterminateundersu hweakassumptions.Knowingthesepredi ates

anbe averyusefulpart of amore omprehensive methodofshowing

termination,whi hwouldhavetomakemorespe i assumptionsabout

thesele tionrule.

Keywords:Logi programming,termination,modes,sele tion rules.

1 Introdu tion

Terminationoflogi programshasbeenwidelystudiedforLDderivations, that

is derivationswhere theleftmost atomin aqueryis alwayssele ted[1,3,8{11,

13℄.Alloftheseworksarebasedonthefollowingidea:atthetimewhenanatom

ainaqueryissele ted,itispossibletopindown thesize 1

ofa.Thissize annot

hangeviafurtherinstantiation.Itisthenshownthatfortheatomsintrodu ed

inthisderivationstep,itisagainpossibletopindowntheirsizewheneventually

theyaresele ted,andthattheseatomsaresmallerthana.

Thisideahasalsobeenappliedtoarbitraryderivations[6℄.Sin eno

restri -tionisimposedonwhenanatom anbesele ted,itisrequiredthatinea hquery

inaderivation,thesizeofea hatomisalwaysbounded.Programsthatful llthis

requirementare alled strongly terminating. The lass of stronglyterminating

programsisverylimited.

Formostprograms,itisne essaryforterminationtorequirea ertaindegree

ofinstantiationofanatombeforeit anbesele ted.This anbea hievedusing

delay de larations [2,16{21℄.The problem is that, depending on what kind of

delayde larationsandsele tionruleareused, itisnotpossibletopindownthe

size ofthesele tedatom, sin ethissize maydepend ontheresolutionof other

atoms in the query that are not yet resolved. Nevertheless, [17,18℄ and to a

limitedextent[16℄arebasedontheideades ribedabove,whereas[19{21℄avoid

anyexpli itmentionof\size"andinsteadtrytoredu etheproblemtoshowing

termination forLDderivations.

1

Thete hni almeaningof\pinningdownthesize" di ersamongdi erentmethods.

CORE

Metadata, citation and similar papers at core.ac.uk

(2)

thesele tionruleontheonehand andmakingveryspe i assumptionsonthe

other.Webelievethatareasonableminimalrequirementfortermination anbe

formulatedintermsofmodes:

Inea hderivationstep,theinputargumentsofthesele tedatom annot

be omeinstantiated.

Inotherwords,anatominaquery anonlybesele tedwhenitissuÆ iently

in-stantiatedsothatthemostgeneraluni erwiththe lauseheaddoesnotbindthe

inputargumentsoftheatom. We allderivations whi hmeetthis requirement

input-driven.

Thispaperisaboutidentifyingpredi atesforwhi hallinput-driven

deriva-tionsare nite.Otherworksinthisareahaveusuallymadespe i assumptions

about thesele tion ruleand thedelayde larations,for examplelo al sele tion

rules[17℄,delayde larationsthattestargumentsforgroundnessorrigidness[16,

18℄,orthedefaultleft-to-rightsele tionruleofmostPrologimplementations[19{

21℄.In ontrast,weshowhowpreviousresultsaboutLDderivations anbe

gen-eralised,theonlyassumptionaboutthesele tionrulebeingthatderivationsare

input-driven.We loselyfollow[13℄.

Weexploit that under ertain onditions, itis enough to relyon arelative

de reaseinthesizeofthesele tedatom,eventhoughthissize annotbepinned

down.

Example 1.1. Considertheusualappendprogramandthefollowinginput-driven

derivation,where thesele tedatomisunderlined:

append([1℄;[℄;As);append(As;[℄;Bs)!

append([℄;[℄;As 0 );append([1jAs 0 ℄;[℄;Bs)! append([℄;[℄;As 0 ) ;append(As 0 ;[℄;Bs 0 )! append([℄;[℄;Bs 0 )!2: When append([1jAs 0

℄;[℄;Bs) is sele ted, it is not possible to pin down its size

in any meaningful way. In fa t, nothing an be said about the length of the

derivation asso iated with append([1jAs 0

℄;[℄;Bs) without knowing about other

atoms whi h might instantiate As 0

. However, the derivation ould be in nite

onlyifthederivationasso iatedwithappend([℄;[℄;As 0

)wasin nite.Ourmethod

isbasedonsu hadependen ybetweentheatomsofaquery.

Notsurprisingly,the lassofprogramsforwhi hallinput-drivenderivationsare

nite isquite limited,although itis obviouslylargerthan the lass ofstrongly

terminatingprograms.Realisti ally,a omprehensivemethodforproving

termi-nationwouldhavetomakestrongerassumptions.However,withintheframework

ofsu hamethod,it anbeusefultoknowforwhi hpredi atestermination an

alreadybeensuredonlyassuminginput-drivenderivations.Thisisdemonstrated

in[21℄,butapartfromthat,webelievethatithasnotbeenre ognisedpreviously.

Example 1.2. Consider the following program whi h permutes a list. Assume

(3)

permute(Y, [U | X℄) :-delete(Y, U, Z), permute(Z, X). delete([X|Z℄, X, Z). delete([U|Y℄, X, [U|Z℄) :-delete(Y, X, Z).

Thenwehavethefollowingin niteinput-drivenderivation:

permute([1℄;W)! delete([1℄;U 0 ;Z 0 );permute(Z 0 ;X 0 )! delete([℄;U 0 ;Z 00 );permute([1jZ 00 ℄;X 0 )! delete([℄;U 0 ;Z 00 );delete([1jZ 00 ℄;U 00 ;Z 000 );permute(Z 000 ;X 00 )! delete([℄;U 0 ;Z 00 );delete(Z 00 ;U 00 ;Z 0000 );permute([1jZ 0000 ℄;X 00 )!:::

Therestofthispaperisorganisedasfollows.Thenextse tion xesthenotation.

Se tion 3introdu eswellandni elymodedprogramsand Se tion4showsthat

for these, it is suÆ ient to prove termination for one-atom queries. Se tion 5

then deals with how one-atom queries an be proven to terminate. Se tion 6

dis ussestheresultsandtherelatedwork.

2 Preliminaries

Ournotation follows [1,13℄. Forthe examplesweuse Prologsyntax. Were all

someimportantnotions.Thesetof variablesin asynta ti obje toisdenoted

asvars (o).Thedomainofasubstitutionisdenotedasdom().Therestri tion

ofasubstitutiontothevariableso urringinasynta ti alobje toisdenoted

asjo.A synta ti obje tislinearifeveryvariableo ursinitat moston e.

Forapredi atep=n,amodeisanatomp(m

1 ;:::;m n ),where m i 2fI;Og

for i 2f1;:::;ng. Positions with I are alled input positions,and positions

with O are alled output positions of p. We assume that a xed mode is

asso iatedwithea hpredi atein aprogram.Tosimplifythenotation,anatom

writtenasp(s;t)means:sistheve torofterms llingtheinputpositions,andt

istheve torofterms llingtheoutputpositions.Anatomp(s;t)isinput-linear

ifsislinear.

Aqueryisa nitesequen eofatoms.AderivationstepforaprogramP is

apairhQ;i;hR ;i, whereQ=Q

1 ;p(s;t);Q 2 andR=Q 1 ;B;Q 2 arequeries;

 is asubstitution; p(v ;u) B a renamedvariantof a lausein P and the

mostgeneraluni erofp(s;t) andp(v ;u). We allp(s;t) thesele ted atom

andR  theresolventofQandh B.Aderivationstepisinput-drivenif

dom()\vars(s)=;.

Aderivation  foraprogram P is asequen e hQ

0 ; 0 i;hQ 1 ; 1 i;:::, where

ea hsu essivepairhQ

i ; i i;hQ i+1 ; i+1

iin isaderivationstep.Alternatively,

wealsosaythat isaderivationofR[fQ

0 

0

(4)

0 0 1 1

alwaystheleftmostatominaquery.Aninput-drivenderivationisaderivation

onsistingofinput-drivenderivationsteps.

If Q;a;R ;(Q;B;R ) is a step in a derivation, then ea h atom in B is a

dire t des endantofa,and bisadire tdes endantof bforallb2Q;R .

Wesaybis ades endant ofa if(b;a)isin there exive,transitive losure of

therelationisadire tdes endant.Thedes endantsofasetofatomsarede ned

intheobviousway.If,foraderivation:::Q;:::;Q 0

;Q 00

:::,thesele tedatomin

Q 0

;Q 00

isades endantofanatomain Q,thenQ 0

;Q 00

isana-step.

3 Modes

In this se tion weintrodu e thenotions ofwell moded and ni ely moded

pro-grams.Well-modednesshasbeenusedbeforetoshowterminationofLD

deriva-tions[13℄.Inthe ontextofarbitraryinput-drivenderivations,itisalso ru ial

torequirethatprogramsareni elymoded.

Well-modednesshasbeenintrodu edin [12℄andwidelyusedforveri ation

sin e.InMer uryit isevenmandatorythatprogramsarewellmoded,whi h is

oneof thereasonsforitsremarkableperforman e[22℄.

De nition3.1 (well moded).A queryQ=p

1 (s 1 ;t 1 );:::;p n (s n ;t n )is well

modedifforalli2f1;:::;ng

vars(s i ) [ j<i vars (t j ) (1) The lausep(t 0 ;s n+1

) Qiswellmodedif(1)holdsforalli2f1;:::;n+1g.

Aprogramiswellmodedifallofits lausesarewellmoded.

Another ommon on eptforveri ationisthefollowing.

De nition3.2 (ni ely moded). A query Q = p

1 (s 1 ;t 1 );:::;p n (s n ;t n ) is ni ely modedift 1 ;:::;t n

isalinearve toroftermsandforalli2f1;:::;ng

vars (s i )\ [ ji vars (t j )=;: (2) The lauseC=p(t 0 ;s n+1

) Qisni elymodedifQisni elymodedand

vars (t 0 )\ n [ j=1 vars (t j )=;: (3)

AprogramP isni elymodedifallofits lausesareni elymoded.

Note that other authors have denoted the lause head of C as p(s

0 ;t n+1 ) or p(s 0 ;t 0

),whi hallowsforamore ompa tde nition[13℄ 2

,furthermore

suggest-ingthat thereisananalogybetween(2)and(3)above[2℄.Wehave hosennot

2

We refer to the de nitionof simply moded here, but this is very similar to ni ely

(5)

ondly,theanalogyismisleading.Itwouldbemoreappropriatetoseeananalogy

between(3)andtherequirementthatt

1 ;:::;t

n

isalinearve toroftermsthan

between(3)and(2).

Example 3.1. TheprograminEx.1.2iswellandni elymoded.Itisneitherwell

moded nor ni elymoded in reverse mode, howeverit an easily be made well

andni elymoded byinter hangingthetwobodyatomsinthese ond lause.

Theexampleshowsthatmultiplemodesofapredi ate anbeobtainedbyhaving

multiple(renamed)versionsofapredi ate.Thisiswhyitisoftenassumedthat

ea h predi ate has a xed mode [2,13,19,22℄. However, this usually implies

a tual odedupli ationand isthereforeareallossofgenerality.

In this paper, assuming a xed mode for ea h predi ate is not a loss of

generality, but merely anotational onvenien e. We onsider arbitrary

input-drivenderivations.Thetextualpositionofanatomwithin aqueryisirrelevant

foritssele tion.Anyresultthatholdsforawellmodedprogramalsoholdsfora

programwheretheatomsinea h lausebodyarepermutedinanarbitraryway.

Inthissense,we anassumethattheprogramofEx.3.1iswellmodedandni ely

modedin bothmodes.Wheneverone onsidersspe i sele tionruleswherethe

textualpositionisrelevant,onehastotreatmultiplemodesexpli itly[21℄.

The following lemma states a persisten e property of well-modedness [2,

Lemma16℄. IthasbeenshownpreviouslyforLDderivations[5℄.

Lemma3.1. EveryresolventofawellmodedqueryQandawellmoded lause

C,wherevars (C)\vars (Q)=;,iswellmoded.

Forni ely-modedness,thereisasimilarpersisten eproperty.Ithasbeenshown

previouslyforLDresolvents[5℄andarbitraryresolvents[2℄.Howeverinthe

lat-ter ase, it was requiredthat the lause head is input-linear. Forinput-driven

derivations, this is notne essary. Itis assumed that thesele ted atom is

suÆ- ientlyinstantiated, so that a multiple o urren e of the samevariable in the

inputargumentsofthe lause head annot auseanybindingsto thequery.

Lemma3.2. Everyresolventof a ni elymoded queryQ and a ni elymoded

lauseC,wherethederivationstepisinput-drivenandvars (C)\vars(Q)=;,

isni elymoded.

Proof. Let C = h B. We want to use [2, Lemma 11℄. Therefore we must

showthat we an assumewithout lossof generality that his input-linear.Let

C 0

= h 0

Eq;B be the lause obtained from C by repeatedly applying the

followingtransformation:Iftheinputargumentsofthe lausehead ontaintwo

o urren esof avariablex,repla e oneo urren e withafresh variabley and

addtheequationx=yatthebeginningofthe lause body.

Thenh 0

isinput-linear,andC 0

isni elymoded,wherethepredi ate=inEq

isusedin mode(I;I).Furthermore,ifQ=Q

1 ;a;Q 2 and hQ;;i;hQ 1 ;B;Q 2 ; i

(6)

tion hQ;;i;hQ 1 ;Eq;B;Q 2 ;  0 i;:::;hQ 1 ;B;Q 2 ; i usingC 0

andthe lause\z=z:"(whi his on eptuallythede nition of=).

By [2, Lemma 11℄, (Q 1 ;Eq;B;Q 2 ) 0

is ni ely moded. Furthermore, sin e

hQ 1 ;Eq;B;Q 2 ;  0 i;:::;hQ 1 ;B;Q 2

; i is input-driven, it follows that Eq 0

is a

sequen eofatomsoftheforms=s.Therefore 0 =and(Q 1 ;B;Q 2 )isni ely moded. ut

Forani elymodedprogramandquery,itisguaranteedthateveryinput-driven

derivationsteponlyinstantiatesotheratomsinthequerythato urtotheright

ofthesele tedatom.

Lemma3.3. Let P be a ni ely moded program, Q = Q

1

;p(s;t);Q

2

a ni ely

moded query, and hQ;;i;hQ

1 ;B;Q

2

; i an input-driven derivation step. Then

dom()\vars(Q

1 )=;.

Proof. Sin e the derivation step is input-driven, it follows that dom()jQ 

vars (t).Thussin eQisni elymoded,dom ()\vars (Q

1

)=;. ut

4 Controlled Coroutining

Inthisse tionwede newell-terminatingpredi ates,thatispredi atesforwhi h

all one-atomquerieshave nite derivations. Asin [13℄,wethen show that

ter-minationforone-atomqueriesimpliesterminationforarbitraryqueries.

ForLDderivations, this isalmost obvious andonlyrequires that programs

and queriesare well moded [13,Lemma 4.2℄.Given aderivation  for aquery

a

1 ;:::;a

n

,thesub-derivationsforea ha

i

donotinterleave,andtherefore an

beregardedasaderivationfora

1

followedbyaderivationfora

2

andsoforth.The

followingexampleillustrates thatin the ontext ofinterleavingsub-derivations

( oroutining),thisismu hlessobvious.

Example 4.1. Considertheusualappend program

append([℄,Y,Y).

append([X|Xs℄,Ys,[X|Zs℄)

:-append(Xs,Ys,Zs).

in modeappend(I;I;O)andthequery

append([℄;[℄;As);append([1jAs℄;[℄;Bs);append(Bs;[℄;As):

This query is well moded but not ni ely moded. Then we have the following

in niteinput-drivenderivation:

append([℄;[℄;As);append([1jAs℄;[℄;Bs);append(Bs;[℄;As)!

append([℄;[℄;As);append(As;[℄;Bs 0 );append([1jBs 0 ℄;[℄;As)! append([℄;[℄;[1jAs 0 ℄);append([1jAs 0 ℄;[℄;Bs 0 );append(Bs 0 ;[℄;As 0 )!:::

This well-known termination problem of programs with oroutining has been

(7)

De nition4.1 (well-terminating predi ate/atom). Let P be a well and

ni elymodedprogram.Apredi atepinP iswell-terminatingifforea hwell

andni elymodedqueryp(s;t),allinput-drivenderivationsofP[fp(s;t)gare

nite.An atomiswell-terminatingifitspredi ateiswell-terminating.

Thefollowinglemma saysthat awell-terminating atom annotpro eed

inde -nitelyunlessitisrepeatedlyfed bysomeotheratom.

Lemma4.1. Let P be a well and ni ely moded program and F;b;H a well

and ni ely moded query where b is a well-terminating atom. An input-driven

derivationofP[fF;b;Hg anhavein nitelymanyb-stepsonlyifithasin nitely

manya-steps,forsomea2F.

Proof. Inthis proof,we allana-stepforsomea2F anF-step, andlikewise

forH.ByLemma3.3,anyH-stepdoesnotinstantiateanydes endantofb.Thus

theH-steps an bedisregarded,andwithoutlossofgenerality,weassumeH is

empty.Let  =hF;b; ;i;:::;hQ 0 ; 0 i;hQ 1 ; 1 i:::

beaninput-drivenderivationsu hthathQ

0 ; 0 i;hQ 1 ; 1 i::: ontainsnoF-steps

(thatis,  ontainsonly nitely manyF-steps).Sin ebyLemma3.3, nob-step

aninstantiateanydes endantofF,thereexistsaninput-drivenderivation

 2 =hF;b; ;i;:::;hR ;i;:::;hQ 0 ; 0 i;hQ 1 ; 1 i:::

su hthathF;b; ;i;:::;hR ;i ontainsonlyF-stepsandhR ;i;:::;hQ

0 ;

0 i

on-tainsonly b-steps (thatis, the F-stepsare moved forwardusing theSwit hing

Lemma[15℄).Sin eR=R 0

;b forsomeR 0

,thereexistsaninput-drivenderivation

 3 =hb;i;:::;hI 0 ; 0 i;hI 1 ; 1 i:::

obtainedfromhR ;i;:::;hQ

0 ; 0 i;hQ 1 ; 1

i:::byremovingthepre xR 0 inea h query. Lett 1 ;:::;t m

betheve torofoutputargumentsofR 0 andasubstitution su hthat(t 1 ;:::;t m

) isground.ThenbyDef.3.1,bisawellmodedquery.

ByLemma 3.3, nob-step instantiates t

1 ;:::;t m .Therefore from  3 we an

onstru taninput-drivenderivation

 4 =hb;i;:::;hI 0 ; 0 i;hI 1 ; 1 i:::

Sin ebisawellandni elymodedqueryandbiswell-terminating,

4 is nite. Therefore 3 , 2

, and nally are nite. ut

The following lemma is a onsequen eand states that well-terminating atoms

ontheirown annotprodu eanin nitederivation.

Lemma4.2. LetPbeawellandni elymodedprogramandQawellandni ely

modedquery.Aninput-drivenderivationofP[fQg anbein niteonlyifthere

(8)

derivation forQ.Weshowthat anhavein nitelymanyb-stepsonlyif has

in nitelymanystepswhereanatomisresolvedthatisnotwell-terminating.

Theproofisbyindu tiononthelengthofF.IfF isempty,theresultfollows

from Lemma4.1.Nowsuppose F ontainsatleast oneatom.ByLemma4.1, 

anhave in nitelymany b-stepsonly if forsome a2F,  has in nitelymany

a-steps.Ifaisnotwell-terminating,theresultfollowsimmediately.Ifa is

well-terminating,letF =F 1 ;a;F 2 .Sin eF 1

ontainsfeweratomsthanF,theresult

followsfrom theindu tivehypothesis. ut

Lemma4.2providesuswiththeformaljusti ationforrestri tingourattention

to one-atomqueries.However,itrequires thatprogramsand queriesareni ely

moded. Thisisnotne essaryforLDderivations[13℄.

We now de ne well-terminating programs. The de nition di ers from the

orrespondingonein[13℄in thatthey onsideronlyLDderivations.

De nition4.2 (well-terminating program). Let P be a well and ni ely

moded programandQawellandni elymodedquery. P is well-terminating

ifallinput-drivenderivationsofP[fQgare nite.

Thefollowingisanobvious orollaryofLemma4.2.

Corollary 4.3. AprogramP iswell{terminatingifandonlyifallitspredi ates

arewell-terminating.

5 Showing Weak Termination

All of thementionedapproa hesto termination [1,3,8{11,13℄moreorless

ex-pli itlyrelyonmeasuringthesizeoftheinputin aquery.Weagree withEtalle

etal.[13℄that itisreasonabletomakethisdependen yexpli it.Thisgivesrise

tothe on eptofmodedlevelmapping[13℄,whi hisaninstan eoflevelmapping

rst introdu ed in [6,7℄. B

P

denotes the set of groundatoms using predi ates

o urringin P.

De nition5.1 (modedlevelmapping).LetPbeaprogram.j:jisamoded

level mappingif

1. itis alevelmapping,thatisafun tion j:j:B

P !IN,

2. foranytandu,jp(s;t)j=jp(s;u)j.

Fora2B

P

,jaj isthelevelofa.

Thusthelevelofanatomonlydependsonthetermsin theinputpositions.

Thefollowing on ept,adoptedfrom[1℄,isusefulforprovingterminationfor

awholeprogramin rementally,byprovingitforonepredi ateatatime.

De nition5.2 (dependson).Letp;qbepredi atesin aprogramP.Wesay

that prefersto qifthereisa lauseinP withpinitsheadandqinitsbody,

andpdependsonq(writtenpwq)if(p;q)isinthere exive,transitive losure

(9)

q(u;v )standsforpwq,andlikewisefor=and.Furthermore,wedenotethe

equivalen e lassofapredi atepwithrespe ttoas[p℄

 .

Thefollowingde nitionprovidesuswitha riteriontoprovethatapredi ate

iswell-terminating.

De nition5.3 (well-a eptable). LetP beaprogramandj:jamodedlevel

mapping. A lause C = h B is well-a eptable (with respe t to j:j) if

foreverysubstitutionsu hthatC isground,andforeveryain B su h that

ah,wehavejhj>jaj.

A set of lauses is well-a eptable with respe t to j:j if ea h lause is

well-a eptablewithrespe ttoj:j.

Let us ompare this on ept to some similar on epts in the literature:

re ur-rent[6℄,well-a eptable [13℄anda eptable [4,11℄programs.

Like[11,13℄ andunlike[4,6℄,werequirejhj>jajonly foratomsa where

ah.Thisis onsistentwiththeideathatterminationshouldbeproven

in re-mentally:toshowterminationforapredi atep,itisassumedthatallpredi ates

q with p=qhavealreadybeenshown to terminate. Therefore we anrestri t

ourattentiontothepredi atesqwhereqp.

Like[6℄andunlike[4,11,13℄,ourde nitiondoesnotinvolvemodelsor

om-putedanswersubstitutions.Traditionally,thede nition ofa eptableprograms

is based on a model M of the program, and for a lause h a

1 ;:::;a n , jhj > ja i j is only required if M j= (a 1 ;:::;a i 1

). The reason is that for

LD derivations, a

1 ;:::;a

i 1

must be ompletely resolved before a

i

is sele ted.

Bythe orre tnessofLDresolution[15℄andwell-modedness[5℄,thea umulated

answer substitution , just before a

i

is sele ted, is su h that (a

1 ;:::;a i 1 ) is groundandMj=(a 1 ;:::;a i 1 ).

Su h onsiderations ountforlittlewhenderivations aremerelyrequiredto

beinput-driven.ThisisillustratedinEx.1.2.Inthethirdlineofthederivation,

permute([1jZ 00

℄;X 0

)issele ted,although thereisnoinstan eofdelete([℄;U 0

;Z 00

)

in the model of theprogram. This problem has been des ribedby saying that

delete makes a spe ulative output binding [19℄. Programs that do not make

spe ulativeoutputbindingsare onsideredin[20℄.

Theorem 5.1. Let P be a well and ni elymoded program and pbe a

pred-i ate in P. Suppose all predi ates q with p = q are well-terminating,and all

lausesde ningpredi atesq2[p℄



arewell-a eptable.Thenp,andhen eevery

predi atein[p℄



,iswell-terminating.

Proof. Supposethesetof lausesde ningthepredi atesq2[p℄



is

well-a ept-ablewithrespe ttothemodedlevelmappingj:j.Foranatomausingapredi ate

in[p℄



,wede nejjajj=sup(fjajjaisgroundg),ifthesetfjajjaisgroundg

isbounded.Otherwisejjajjis unde ned.Observethat

(10)

ea h atom whose predi ateis in [p℄



. The multisetis formalised asafun tion

Size,whi htakesasargumentsaqueryandanaturalnumber.

Size(Q)(n)=#fq(u;v )jq(u;v )is anatomin Q;qpandjjq(u;v )jj=ng

Note that ifaquery ontainsseveral identi alatoms, ea h o urren emust be

ounted.Wede neSize(Q)<Size(R )ifandonlyifthereisanumberlsu hthat

Size(Q)(l)<Size(R )(l)andSize(Q)(l 0 )=Size(R )(l 0 )foralll 0 >l.Intuitively,

ade rease with respe t to < is obtainedwhen anatom in a queryis repla ed

with a nite numberof smaller atoms. It is easy to see (Konig's Lemma [14℄)

that alldes ending hainswithrespe t to<are nite.

Let Q

0

= p(s;t) bea welland ni ely moded query. Then s is ground and

thus jjQ 0 jj is de ned. Let  = Q 0 ;Q 1 ;Q 2 ::: be an input-driven derivation of P[fQ 0 g.

Sin eallpredi atesqwithp=qarewell-terminating,itfollowsbyLemma4.2

that there annot be an in nite suÆx of  without any steps where an atom

q(u;v )su hthatqpisresolved.Weshowthatforalli0,ifthesele tedatom

in Q

i ;Q

i+1

is q(u;v ) and q p, then Size(Q

i+1 ) < Size(Q i ), and otherwise Size(Q i+1 )Size(Q i

). This impliesthat  is nite, and, as the hoi e of the

initialqueryQ

0

=p(s;t) wasarbitrary,piswell-terminating.

Consideri0andletC=q(v

0 ;u m+1 ) q 1 (u 1 ;v 1 );:::;q m (u m ;v m )bethe

lause,q(u;v )thesele tedatomandthemostgeneraluni erusedinQ

i ;Q i+1 . Ifp=q,then p=q j

forallj 2f1;:::;mgandhen eby() itfollowsthat

Size(Q

i+1

)Size(Q

i ).

Now onsider qp.Sin e C is awell-a eptable lause, jjq(v

0 ;u m+1 )jj> jjq j (u j ;v j

)jjforallj withq

j

p.Thistogetherwith()impliesSize(Q

i+1 )<

Size(Q

i

). ut

Example 5.1. Wenow give afew examples of well-terminating predi ates. We

denote the term size of aterm t,that is the numberof fun tion and onstant

symbolsthat o urint,asTSize(t).

The lauses de ning append(I;I;O) (Ex. 4.1) are well-a eptable, where

jappend(s 1 ;s 2 ;t)j = TSize(s 1

). Thus append(I;I;O) is well-terminating.The

sameholdsforappend(O;O;I),de ningjappend(t

1 ;t

2

;s)j=TSize(s).

The lauses de ning delete(I;O;O) (Ex. 1.2) are well-a eptable, where

jdelete(s;t

1 ;t

2

)j = TSize(s). Thus delete(I;O;O) is well-terminating. The

sameholdsfordelete(O;I;I),de ningjdelete(t;s

1 ;s 2 )j=TSize(s 2 ).

Inasimilarway,we anshowthat permute(O;I)iswell-terminating.

How-ever,permute(I;O)isnotwell-terminating.

Figure 1shows afragmentfrom aprogram for then-queens problem. The

mode is fnqueens(I;O); sequen e(I;O); safe(I); permute(O;I); <(I;I) ;

is(O;I); safeaux(I;I;I); nodiag(I;I;I); =\=(I;I)g. Again using as level

mappingthetermsizeofoneofthearguments,one anseethatthe lauses

de n-ingfnodiag;safeaux;safegarewell-a eptableandthusthesepredi atesare

well-terminating.Thisinformationisusefulsin ethisprogramreliesonnon-LD

(11)

sequen e(N,Seq), safe(Sol), permute(Sol,Seq). safe([℄). safe([N|Ns℄) :-safe_aux(Ns,1,N), safe(Ns). safe_aux([M|Ms℄,Dist,N) :-no_diag(N,M,Dist), Dist2 is Dist+1, safe_aux(Ms,Dist2,N). no_diag(N,M,Dist) :-Dist =\= N-M, Dist =\= M-N.

Fig.1.Aprogramforn-queens

Asamore omplexexample, onsiderthefollowingprogram,whosemodeis

fplusone(I);minustwo(I);minusone(I);g. This example uses the su essor

notationfornaturalnumbers.

plus_one(X) :- minus_two(s(X)). minus_two(s(X)) :- minus_one(X). minus_two(0). minus_one(s(X)) :- plus_one(X). minus_one(0). Wede ne

jplusone(s)j=3TSize(s)+4

jminustwo(s)j=3TSize(s)

jminusone(s)j=3TSize(s)+2

Thentheprogramiswell-a eptableandthuswell-terminating.

We see that wheneverin some argument position of a lause head, there is a

ompoundtermofsomere ursivedatastru ture,su has[XjXs℄,andallre ursive

allsinthebodyofthe lausehaveastri tsubtermofthatterm,su hasXs,in

the sameposition | then the lause is well-a eptable using aslevelmapping

thetermsize of thatargumentposition.Sin e thissituation o urs veryoften,

it an be expe ted that an average program ontains many well-terminating

predi ates. However,it is unlikely that in anyreal program,allpredi ates are

well-terminating.

Thelastexampleshowsthatmore omplexs enariosthantheonedes ribed

abovearepossible,butwedoubtthattheywouldofteno urinpra ti e.

There-forelevelmappingssu hastheoneusedin theexamplewillrarelybeneeded.

ConsideragainDef.5.3.Givena lause h a

1 ;:::;a n andanatoma i h, werequirejhj>ja i

j forallgroundingsubstitutions , ratherthanonlyfor 

su hthat(a

1 ;:::;a

i 1

)isin a ertainmodeloftheprogram.Thisisof ourse

aseriousrestri tion.InEx.1.2,assumingmodepermute(I;O),there anbeno

moded level mapping su h that jpermute(Y;[UjX℄)j > jpermute(Z;X)j for all

. It mightbe possible to relax Def. 5.3 to allowmore programs,but thefa t

(12)

Wehave identi edthe lassof programsfor whi h all input-driven derivations

are nite.Aninput-drivenderivationisaderivationwhereinea hstep,theinput

arguments of thesele ted atom are not instantiated. Predi ates anbe shown

tobeinthat lassusing thenotionsoflevel mappinganda eptable lauseina

verysimilarwayto methodsforLDderivations[8,11,13℄.

Thispaper loselyfollows[13℄.Thereastatementisshownwhi hisessentially

the onverse of Thm. 5.1. It says that if apredi ate is well-terminating, then

there is a level mappingsu h that the lausesde ning the predi ate are

well-a eptable. Itwouldbe interestingto showasimilarresultforarbitrary

input-drivenderivations, but webelievethat it mustbediÆ ult,sin eour de nition

ofa eptabilityismu hmorerestri tive.

We have laimed that most other approa hes to termination rely on the

idea that the size of an atom an be pinned down when the atom is sele ted.

Te hni ally,this usually meansthat theatom is boundedwith respe t to some

levelmapping[4,6,13,18℄.This isdi erentin[9,11℄,wheretermination anbe

shownforthequery,say,append([X℄;[℄;Zs)usingaslevelmappingthetermsize

ofthe rstargument,eventhoughthetermsizeof[X℄isnotbounded. However,

themethodonlyworksforLDderivationsandreliesonthefa t thatanyfuture

instantiationofX annota e tthederivationforappend([X℄;[℄;Zs).Thereforeit

ise e tivelypossibletopindownthesize ofappend([X℄;[℄;Zs).

In ontrast,weshowthatunder ertain onditions,itisenoughtorelyona

relativede reaseinthesizeofthesele tedatom,eventhoughthissize annotbe

pinneddown.More on retely,weusethat anatom in aquery annot pro eed

inde nitely unless itis repeatedly fed by someother atom o urring earlierin

thequery.This impliesthat everyderivationforthequeryterminates.

Bezem[6℄hasidenti edthe lassofstronglyterminatingprograms,whi hare

programsthatterminate underany sele tionrule. Whileitisshownthatevery

totalre ursivefun tion anbe omputedbyastronglyterminatingprogram,this

does not hange thefa t that few existing programs are stronglyterminating.

Transformationsareproposedforthreeexampleprogramstomakethemstrongly

terminating,butthetransformationsare ompli atedandad-ho .

Thispaperismoreabstra tthantheliteratureonprogramswithdelay

de -larations [2,16{21℄. We are not on erned with the details of parti ular delay

onstru ts.Instead, weonlyassumewhat we seeasthe basi purposeof delay

de larations:ensuringthatderivationsareinput-driven.Notethatdependingon

what kindof onstru tsare used, ensuringthat derivations are input-driven is

a tuallyquitesubtle[21℄.Nevertheless,delayde larationsare learlyapowerful

instrumentforthispurpose.

Onthewhole,thereseemstobeastrongrelu tan etogiveuptheideathat

thesizeofanatommustbepinneddownwhentheatomissele ted.Thisistrue

even for[6℄, where noassumptions at allare made aboutthesele tion rule. It

isalsotruefor[17℄,wherealo al sele tion ruleisassumed,that isaruleunder

whi honlymostre entlyintrodu edatoms anberesolvedinea hstep.In[18℄,a

(13)

there is mainly to generate delay de larations automati ally rather thanprove

termination. 3

Howeverinsome ases,thedelayde larationsthat aregenerated

requireanargumentofanatomtobearigidlistbeforethatatom anbesele ted,

whi hissimilarto[17,18℄.Su husesofdelayde larationsgofarbeyondensuring

that derivationsareinput-driven.

Wedo not laimto present a omprehensivemethod for showing

termina-tion.Inanaverageprogram,somepredi atesarewell-terminatingbutsomeare

not.Ingeneral,onehastomakestrongerassumptionsaboutthesele tionrule.

Nevertheless,it isuseful toknowwhi hpredi ates arewell-terminating,

essen-tially be ause it means that one has to make the stronger assumptions only

forthepredi atesthatarenotwell-terminating.Forexample,requiringground

orrigid arguments[16,18℄ ouldbelimited to atomswhose predi ates arenot

well-terminating.

In[21℄,well-terminatingpredi atesare onsideredinamore on retesetting

than here and are alled robust predi ates. The default left-to-right sele tion

ruleofmostPrologimplementationsisassumed.Itisexploitedthatthetextual

position of atomsusing robustpredi ates in lause bodies is irrelevantfor

ter-mination.Theotheratomsmustbepla edsu hthattheatomsprodu ingtheir

inputo urearlier.

A knowledgements

TheauthorwouldliketothankFloren eBenoyforproofreadingthispaper.This

workwasfunded byEPSRCGrantNo.GR/K79635.

Referen es

1. K.R.Apt. From Logi ProgrammingtoProlog. Prenti eHall,1997.

2. K.R.AptandI.Luitjes. Veri ationoflogi programswithdelayde larations.In

Pro eedingsofAMAST'95,LNCS,Berlin,1995.Springer-Verlag.InvitedLe ture.

3. K. R. Apt and D. Pedres hi. Studies in Pure Prolog: Termination. In J. W.

Lloyd,editor,Pro eedingsoftheSymposiuminComputationalLogi ,LNCS,pages

150{176.Springer-Verlag,1990.

4. K.R.AptandD.Pedres hi. Modularterminationproofsforlogi andpureProlog

programs. InG.Levi,editor,Advan esinLogi ProgrammingTheory,pages183{

229.OxfordUnversityPress,1994.

5. K. R. Apt and A. Pellegrini. On the o ur- he k free Prolog programs. ACM

Toplas,16(3):687{726,1994.

6. M. Bezem.Strongterminationoflogi programs. JournalofLogi Programming,

15(1&2):79{97,1993.

7. L. Cavedon. Continuity, onsisten y and ompleteness properties for logi

pro-grams. InG.Leviand M. Martelli, editors, Pro eedings of the 6thInternational

Conferen e onLogi Programming,pages571{584.MITPress, 1989.

3

For thereaderfamiliar with[16℄, it is notsaidhowit isshownthat programsare

(14)

story. Journalof Logi Programming,19/20:199{260, 1994.

9. D.DeS hreye,K.Vers haetse,andM.Bruynooghe.Aframeworkforanalysingthe

terminationofde nitelogi programswithrespe tto allpatterns.InPro eedings

of FGCS,pages481{488.ICOTTokyo,1992.

10. S. De orte and D. De S hreye. Automati inferen e of norms: a missing link

in automati termination analysis. In D. Miller, editor, Pro eedings of the 10th

InternationalLogi Programming Symposium,pages420{436.MITPress,1993.

11. S.De orteandD.DeS hreye. Terminationanalysis:Somepra ti alpropertiesof

thenormandlevelmappingspa e.InJ.Ja ar,editor,Pro eedingsofthe15thJoint

International Conferen e andSymposiumonLogi Programming,pages 235{249.

MITPress,1998.

12. P. Dembinski and J. Ma luszynski. AND-parallelism with intelligent

ba ktra k-ing for annotatedlogi programs. InPro eedings of the 2nd International Logi

ProgrammingSymposium,pages29{38.MITPress,1985.

13. S.Etalle, A. Bossi,and N.Co o. Well-terminating programs. Journal of Logi

Programming,1998. A eptedforpubli ation.

14. M. Fitting. First-order Logi and Automated TheoremProving. Springer-Verlag,

1996.

15. J.W.Lloyd. Foundations ofLogi Programming. Springer-Verlag,1987.

16. S.Luttringhaus-Kappel. Controlgenerationforlogi programs. InD.S.Warren,

editor, Pro eedings of the 10th International Conferen e onLogi Programming,

pages478{495.MITPress,1993.

17. E. Mar hioriand F.Teusink. Provingterminationof logi programs withdelay

de larations. InJ. W.Lloyd,editor, Pro eedings of the12th International Logi

ProgrammingSymposium,pages447{461.MITPress,1995.

18. J. C.Martin and A. M. King. GeneratingeÆ ient, terminating logi programs.

InM.BidoitandM.Dau het,editors,Pro eedingsofTAPSOFT'97,LNCS,pages

273{284.Springer-Verlag,1997.

19. L. Naish. Coroutiningand the onstru tionofterminatinglogi programs.

Te h-ni alReport92/5,UniversityofMelbourne,1992.

20. J.-G. Smaus, P. M. Hill, and A. M. King. Preventing instantiation errors and

loops for logi programs withseveral modesusing blo kde larations. In Pierre

Flener,editor,Pre-pro eedingsofthe8thInternationalWorkshoponLogi Program

Synthesis andTransformation, numberUMCS-98-6-1, pages72{29. University of

Man hester,1998. Extendedabstra t.

21. J.-G. Smaus, P. M. Hill, and A. M. King. Termination of logi programs with

blo kde larations runninginseveralmodes. InC.Palamadessi,editor,

Pro eed-ingsofthe10thSymposiumonProgrammingLanguageImplementationsandLogi

Programming,LNCS.Springer-Verlag,1998.

22. Z.Somogyi,F.Henderson,andT.Conway. Theexe utionalgorithmofMer ury,

aneÆ ientpurelyde larativelogi programminglanguage. JournalofLogi

References

Related documents

A subsequent single-center trial was performed using a 1-day Tc-99m tetrofosmin adenosine-stress/ rest MPI protocol and a 3 min scan for stress and 2 min for rest using the

Corinth, but the principal issue over which Paul is urging the Corinthians to separate from.. them is the pagan σοφία σαρκική that has distorted their assessments of

In brief, the effect of foreign ownership on stock return volatility in Vietnamese listed companies will give more significant insights into the role of foreign investors in

In further experiments the neural network ensemble was trained by means of a training set composed of 60 training patterns (20 patterns for each class). The next phase of

Since the premium rate only affects risky profits, expression (3) allows us to derive the effect on total industry profits of domestic firms exporting to market j

The current paper investigated the managerial Decision Making Styles (DMS) of 54 deans from four randomly selected Malaysian public universities which corresponded to the

Noticing that on these lines, the volume and the surface area must be zero, we can ignore these as physically unreasonable solutions. • Thus our critical point is the only

Summarizing, in the next section we will propose a new solution concept for three-player games in which the payo¤s are the NBS of the three-player negotiation with disagreement