Proving Termination of Input-Consuming Logi Programs Jan{Georg Smaus y Computing Laboratory
University of Kentat Canterbury
Canterbury, Kent, CT2 7NF, United Kingdom
September 1999
Abstra t
A lass of predi ates is identied for whi h termination does not dependon
left-to-right exe ution. The onlyassumption about the sele tion ruleis that
derivations are input- onsuming, that is, in ea h derivation step, the input
argumentsofthesele ted atom donotbe omeinstantiated. Thisassumption
isanaturalabstra tionofpreviousworkonprogramswithdelayde larations.
Themethodforshowingthatapredi ateisinthat lassisbasedonlevel
map-pings, loselyfollowingthetraditionalapproa hforLD-derivations. Programs
areassumedtobewellandni elymoded,whi haretwowidelyused on epts
for veri ation. Many predi ates terminate under su h weak assumptions.
Knowingthese predi atesisusefuleven forprogramswherenotall predi ates
havethisproperty.
1 Introdu tion
Termination of logi programs has been widely studied for LD-derivations,
thatisderivationswheretheleftmostatominaqueryisalwayssele ted[1 , 3 ,
7,8,9,10 ,12 ℄. Allofthese worksarebasedonthefollowingidea: atthetime
when an atom a ina query is sele ted, it is possible to pin down the size 1
of
a. Thissize annot hangeviafurtherinstantiation. It isthenshownthatfor
theatoms introdu edinthisderivation step,it isagain possibleto pin down
ThisTe hni alReport10-99isthelongversionofapaperwiththesametitlepresented
atICLP'99[22 ℄.
y
TheauthorisnowworkingatINRIA-Ro quen ourt,BP105,78153LeChesnayCedex,
Fran e.
1
Thete hni almeaningof\pinningdownthesize"diersamongdierentmethods. This
willbedis ussedinSe t.7.
CORE
Metadata, citation and similar papers at core.ac.uk
a.
This idea has also been applied to arbitrary derivations [6℄. Sin e no
re-stri tion is imposed on when an atom an be sele ted, it is required that in
ea h query in a derivation, the size of ea h atom is always bounded.
Pro-grams that fulll thisrequirement are alled strongly terminating. The lass
ofstrongly terminatingprogramsisvery limited.
Formostlogi programs,itisne essaryforterminationtorequirea ertain
degree of instantiation of an atom before it an be sele ted. This an be
a hieved using delay de larations [2, 17 , 18 , 19 , 20, 23 , 24 ℄. The problem
is that, dependingon what kindof delay de larations and sele tion rule are
used,it is often notpossibleto pindown thesize of the sele ted atom, sin e
this sizemay dependon the resolution of other atoms in the query that are
notyetresolved. Nevertheless,theapproa hes by Mar hioriand Teusink [18℄
and Martin and King [19 ℄, and to a limited extent Luttringhaus-Kappel[17℄
are based on the idea des ribed above. Other approa hes avoid any expli it
mentionof\size"andinsteadtrytoredu etheproblemtoshowingtermination
forLD-derivations[20,23 , 24 ℄.
Our approa h falls between the two extremes of making no assumptions
about the sele tion rule on the one hand and making very spe i
assump-tions on the other. We believe that a reasonable minimal requirement for
termination an beformulatedinterms ofmodes:
Inea h derivation step, theinputarguments of thesele ted atom
annotbe ome instantiated.
Inotherwords,an atominaquery an onlybesele ted whenitissuÆ iently
instantiatedsothatthemostgeneralunier(MGU)withthe lauseheaddoes
not bind the input arguments of the atom. We all derivations whi h meet
thisrequirement input- onsuming.
This paper is aboutidentifying predi ates for whi h all input- onsuming
derivations are nite. Other works in this area have usually made spe i
assumptionsaboutthe sele tion ruleand thedelay de larations,for example
lo alsele tionrules[18 ℄,delayde larationsthattestargumentsforgroundness
orrigidness [17 , 19 ℄, orthe default left-to-right sele tionrule of most Prolog
implementations[20,23 ,24 ℄. In ontrast,weshowhowpreviousresultsabout
LD-derivations an be generalised, the only assumption about the sele tion
rulebeing thatderivationsare input- onsuming.
We exploitthatunder ertain onditions,itisenoughto relyon arelative
de rease in the size of the sele ted atom, even though this size annot be
pinneddown.
Example 1.1 Consider the usual append program, where the rst two
we indi atesome ofthevariable bindingsmade inthisderivation.
append([1℄;[℄;As);append(As;[℄;Bs); (As=[1jAs 0 ℄ ) append([℄;[℄;As 0 );append([1jAs 0 ℄;[℄;Bs); (Bs=[1jBs 0 ℄ ) append([℄;[℄;As 0 );append(As 0 ;[℄;Bs 0 ); (As 0 =[℄ ) append([℄;[℄;Bs 0 );2 (Bs 0 =[℄ ) When append([1jAs 0
℄;[℄;Bs) is sele ted, itis not possibleto pin down its size
in any meaningful way. In fa t, nothing an be said about the lengthof the
(input- onsuming) derivation asso iated with append([1jAs 0
℄;[℄;Bs) without
knowingaboutotheratomswhi hmightinstantiateAs 0
. However,the
deriva-tion ouldbeinniteonlyifsomederivationasso iatedwithappend([℄;[℄;As 0
)
was innite. Our methodis based on su h a dependen ybetween the atoms
ofa query.
As we will dis uss in Se t. 7, previous approa hes [6 , 17 , 18 , 19 ℄ annot
formally show termination of derivations with oroutining su h as the one
above.
Even though the lass ofprograms forwhi h all input- onsumingderivations
areniteis obviouslylarger thanthe lass of stronglyterminatingprograms,
itis stillquite limited. Thefollowingexampleillustratesthis.
Example 1.2 Considerthefollowingprogram,whereforbothpredi ates,the
rst positionisthe onlyinputposition.
permute([℄, [℄). 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).
Thenwe have thefollowing inniteinput- onsumingderivation:
permute([1℄;W); (W=[U 0 jX 0 ℄ ) delete([1℄;U 0 ;Z 0 ) ;permute(Z 0 ;X 0 ); (Z 0 =[1jZ 00 ℄ ) delete([℄;U 0 ;Z 00 );permute([1jZ 00 ℄;X 0 ); (X 0 =[U 00 jX 00 ℄ ) 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 );:::
Toensureterminationevenforprogramsliketheoneabove,mostauthorshave
made stronger assumptions about the sele tion rule, thereby negle ting the
important lass forwhi hassuminginput- onsumingderivationsis suÆ ient.
We have attempted to formulate our resultsasgenerally aspossibleto make
them widelyappli able.
The rest of thispaper is organised as follows. The next se tion xes the
Se tion5thendealswithhowone-atomqueries anbeproventoterminate. In
Se t. 6wesket h howthemethod presentedhere ouldbeapplied. Se tion7
dis ussestheresultsand the relatedwork.
2 Preliminaries
Our notation follows Apt[1 ℄ and Etalle et al. [12 ℄. For the examples we use
Prolog syntax. We re all some important notions. The set of variables in
a synta ti obje t o is denoted as vars(o). A synta ti obje t is linear if
every variable o urs init at moston e. The domain of a substitution is
dom()=fxjx6=xg.
Forapredi atep=n,amodeisanatomp(m
1 ;:::;m n ),wherem i 2fI;Og
fori2f1;:::;ng. PositionswithI are alledinputpositions, andpositions
with O are alled output positions of p. We assume that a xed mode is
asso iatedwithea hpredi ateinaprogram. Tosimplifythenotation,anatom
written as p(s;t) means: s is the ve tor of terms lling the inputpositions,
and t is the ve tor of terms lling the output positions. An atom p(s;t) is
input-linearifs islinear,output-linear iftis linear.
A query is a nite sequen e of atoms. Atoms are denoted by a, b, h,
queriesbyB,F,H,Q,R . Wewritea2B ifaisanatominB. Aderivation
step fora program P is a pair hQ;i;hR ;i, whereQ =Q
1 ;p(s;t);Q 2 and R=Q 1 ;B;Q 2
arequeries;isasubstitution;p(v ;u) B arenamedvariant
of a lause in P and an MGU of p(s;t) and p(v ;u). We allp(s;t) the
sele tedatomand R theresolvent of Qand h B. A derivationstep
isinput- onsuming ifdom ()\vars(s)=;. 2
Aderivation foraprogramP isasequen e hQ
0 ; 0 i;hQ 1 ; 1 i;:::where ea h pairhQ i ; i i;hQ i+1 ; i+1
i in is aderivation step. Alternatively,we also
saythat isa derivation ofP [fQ
0
0
g. We sometimesdenote aderivation
asQ 0 0 ;Q 1 1
;:::. An LD-derivation is a derivation where thesele ted atom
isalwaystheleftmostatominaquery. Aninput- onsuming derivationisa
derivation onsistingof input- onsumingderivationsteps.
If(F;a;H); (F;B;H) isa stepina derivation,thenea h atominBisa
dire tdes endantofa,andbisadire t des endantofbforallb2F;H.
We say b is a des endant of aif (b;a) is in the re exive, transitive losure
of the relationis a dire t des endant. The des endants of a set of atoms are
denedintheobviousway. ConsideraderivationQ
0 ;:::;Q i ;:::;Q j ;Q j+1 ;:::. We all Q j ;Q j+1 an a-step if a is an atom in Q i
and the sele ted atom in
Q j ;Q j+1 isa des endant of a. 2
Sin etheMGUisuniqueuptovariablerenaming,wemayassumethatwhenever
In this se tion we introdu e well moded and ni ely moded programs, whi h
arestandard on eptsusedforveri ationoflogi programs[2 ,5,11 ,12 ,13 ℄.
Well-modednesshas beenintrodu edby Dembinski and Ma luszynski [11℄
and widely used sin e. In Mer ury it is even mandatory that programs are
wellmoded(possiblyafterreorderingof atomsbythe ompiler),whi hisone
ofthe reasonsforits remarkableperforman e[25 ℄.
Denition 3.1 [well moded℄ A query Q = p
1 (s 1 ;t 1 );:::;p n (s n ;t n ) is well
modedifforall i2f1;:::;ng and L=1
vars(s i ) i 1 [ j=L vars(t j ) (1) The lausep(t 0 ;s n+1
) Qiswellmodedif(1)holdsforalli2f1;:::;n+1g
and L=0. Aprogram iswell modedifall of its lauses are wellmoded.
Notethat aone-atom query p(s;t)is wellmodedifand onlyifs isground.
Anotherwidely used on ept isthe following.
Denition 3.2 [ni elymoded℄A queryQ=p
1 (s 1 ;t 1 );:::;p n (s n ;t n )is ni e-ly modedift 1 ;:::;t n
isa linearve tor ofterms and foralli2f1;:::;ng
vars(s i )\ n [ j=i vars(t j )=;: (2) The lause C=p(t 0 ;s n+1
) Q isni ely modedifQ isni elymodedand
vars(t 0 )\ n [ j=1 vars(t j )=;: (3)
Aprogram isni ely modedifall ofits lauses areni elymoded.
Note that a one-atom query p(s;t) is ni ely moded if and only if vars(s)\
vars(t)=;andt islinear. We anthusstate thefollowingpropositionwhi h
followsfrom thedenitions.
Proposition 3.1 A one-atom query p(s;t) is well and ni ely moded if and
onlyifsis groundand t is linear.
Example 3.1 The program in Ex. 1.2 is well and ni ely moded in mode
fpermute(I;O);delete(I;O;O)g. It isneitherwellmodednorni elymoded
inmodefpermute(O;I);delete(O;I;I)g,howeverit aneasilybemadewell
maintaining multiple (renamed) versions of a predi ate, whi h dier in the
orderof atomsinthe lausebodies. Thisiswhysomeauthorsnditjustied
toassumethatea hpredi atehasaxedmode[12 ,20 ,25 ℄. However, inthose
works,assumingaxedmodeis,fromaformalpointofview,arealrestri tion,
even ifone mayndthat this ode dupli ation isnota problem inpra ti e.
In this paper, assuming a xed mode for ea h predi ate is not at all a
restri tion. We onsider derivations where the textual position of an atom
withinaquery isirrelevantforits sele tion. Thereforeit immediatelyfollows
that if we show termination for a program, we have also shown termination
forthesameprogramwheretheatomsinea h lausebodyarepermutedinan
arbitraryway. Inthissense,we anassumethattheprogramofEx.1.2iswell
modedand ni elymodedinboth modes(Ex. 3.1). It is merelyfor notational
onvenien e that we assume, in all formal statements, a \left-to-right" data
ow intheabovedenitions.
Of ourse,usingaprogramindierentmodesatea hrunrequiresthatthe
sele tion rule somehow \knows" what mode is assumed in a parti ular run,
sin e otherwise it would not be dened what an input- onsumingderivation
is. This an be realisedfor examplebyusing delay de larations[23 , 24 ℄, but
inthispaper,wedo notworryabouthowthisis a hieved.
If one onsidersderivationswherethe textual positionof an atom is
rele-vant for its sele tion,one needs more general denitionsthan theones above
that involve permutations of the atoms [23 ℄. The relationship of the textual
order andthe dire tionofdata ow isdis ussedin detailin[21 , Se t. 5.3℄.
The following lemmas state persisten e properties of well-modednessand
ni ely-modedness.
Lemma 3.2 EveryresolventofawellmodedqueryQandawellmoded lause
C,wherevars(C)\vars(Q)=;,iswellmoded[2 ,Lemma 16℄.
Lemma 3.3 Every resolvent of ani elymodedqueryQ and a ni elymoded
lauseC, where vars(C)\vars(Q)=; and the head of C is input-linear, is
ni elymoded[2 , Lemma11℄.
For input- onsuming derivations, the requirement that the lause head is
input-linear an be dropped. It is assumed that the sele ted atom is
suÆ- ientlyinstantiated,so thatamultipleo urren e ofthe samevariable inthe
inputarguments of the lause head annot ause any bindingsto the query.
Note that requiring input-linear lause heads is quite a severe restri tion in
thatitrulesoutinputargumentsofthesele tedatombeingtestedforequality.
Lemma 3.4 Every resolvent of ani elymodedqueryQ and a ni elymoded
lause C, where the derivation step is input- onsuming and vars(C) \
1 n 1 m
some k 2f1;:::;ng, a
k
=p(s;t) and p(v ;u) are uniable withMGU ,and
dom()\vars(s)=;. Nowlet C 0 =p(v 0 ;u) b 1 ;:::;b m
bean input-linear lausesu hthat
1. vars(v )vars(v 0
) and vars(v 0
)\vars(Q)=;,
2. thereexistsasubstitution su hthatC 0
=Canddom()=vars(v 0
)n
vars(v ).
Intuitively, v 0
is obtained from v by renaming, for ea h variable o urring
several times,all butoneo urren esapart usingfresh variables.
Sin e dom()\vars(s)=;,it follows that =
1 2 ,where 1 isan MGU of vand s, andv 1 =s, and 2 isan MGUof u 1 and t 1 . By (2)and sin ev 1 =s,we have v 0 1
=s. Moreover by(1), (2) and sin e
dom(
1
)vars(v ),wehave dom (
1 )vars(v 0 ), andhen e 1 isanMGU ofv 0 and s. By(2), u=uand t=t. Therefore 2 isan MGU ofu 1 and t 1 . Sowehavethat 1 isanMGUofv 0 ands,and 2 isanMGUofu 1 andt 1 . Therefore 1 2 =isanMGUofp(v 0
;u)andp(s;t)[1 ,Lemma2.24℄. Hen e
byLemma 3.3, (a 1 ;:::;a k 1 ;b 1 ;:::;b m ;a k+1 ;:::;a n
) is ani elymoded
re-solvent ofC 0
and Q. However, by(1)and (2),
(a 1 ;:::;a k 1 ;b 1 ;:::;b m ;a k+1 ;:::;a n )= (a 1 ;:::;a k 1 ;b 1 ;:::;b m ;a k+1 ;:::;a n ); and so(a 1 ;:::;a k 1 ;b 1 ;:::;b m ;a k+1 ;:::;a n ) isni elymoded. 2
For a ni ely moded program and query, it is guaranteed that every
input- onsuming derivation step only instantiates other atoms in the query that
o ur to theright ofthesele ted atom.
Lemma 3.5 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- onsuming derivation step.
Thendom()\vars(Q
1 )=;.
Proof. Sin e the derivation step is input- onsuming, dom()\vars(Q)
vars(t). Thussin eQis ni elymoded,dom()\vars(Q
1
)=;. 2
This se tion mainly served the purpose of re alling some well-known mode
Inthisse tion we deneatom-terminating predi ates. A predi atepis
atom-terminatingif(under ertain onditions)all input- onsumingderivationsofa
queryp(s;t) arenite. Like Etalleetal. [12 ℄, we then showthat termination
forone-atom queriesimpliesterminationforarbitrary queries.
ForLD-derivations, itisalmostobviousthatitis suÆ ientto show
termi-nationforone-atomqueries,anditonlyrequiresthatprogramsandqueriesare
wellmoded[12 ,Lemma4.2℄. GivenanLD-derivation foraquerya
1 ;:::;a
n ,
the sub-derivations for ea h a
i
do not interleave, and therefore an be
re-gardedasa derivationfora
1
followedbyaderivationfora
2
andsoforth. The
followingexampleillustratesthatinthe ontextofinterleavingsub-derivations
( oroutining),thisis bynomeansobvious.
Example 4.1 Considertheusualappendprogram
append([℄,Y,Y).
append([X|Xs℄,Ys,[X|Zs℄)
:-append(Xs,Ys,Zs).
inmode append(I;I;O) and thequery
append([℄;[℄;As);append([1jAs℄;[℄;Bs);append(Bs;[℄;As):
Thisquery is wellmodedbut notni elymoded. Then we have the following
inniteinput- onsumingderivation:
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 );:::
Thiswell-knowntermination problemof programswith oroutining hasbeen
identiedas ir ularmodes[20℄.
To avoid theproblem, we requireprograms and queries to be ni elymoded.
Re allthatbyProp. 3.1, aone-atom queryp(s;t)iswelland ni elymodedif
and onlyifs is groundand t islinear.
Denition 4.1 [atom-terminatingpredi ate/atom℄LetP beawellandni ely
modedprogram. Apredi atepinP isatom-terminatingifforea hwelland
ni elymodedqueryp(s;t), allinput- onsumingderivationsofP[fp(s;t)gare
nite. An atom isatom-terminatingifits predi ateisatom-terminating.
Thefollowinglemma saysthat anatom-terminating atom annotpro eed
in-denitelyunlessitisrepeatedlyfedbysomeotheratom. Thelemmaissimilar
to [23 , Lemma 4.2℄. Note however that here, we do not require that lause
heads are input-linear. There is a lemma [21, Lemma 6.2℄ whi h subsumes
both[23 ,Lemma4.2℄andLemma4.1, butusingthislemmawould ompli ate
and ni ely moded query where b is an atom-terminating atom. An
input- onsumingderivationofP [fF;b;Hg an haveinnitelymanyb-stepsonlyif
ithasinnitelymany a-steps,forsome a2F.
Proof. In this proof, by an F-step we mean an a-step, for some a 2 F;
likewise we dene an H-step. By Lemma3.5, no H-step an instantiateany
des endant of b. Thus the H-steps an be disregarded, and without loss of
generality,weassumeHisempty. Suppose isaninput- onsumingderivation
forP [fF;bg ontainingnitelymanyF-steps. Let
=hF;b; ;i;:::;hQ 0 ; 0 i; ~ su h thathQ 0 ; 0 i; ~
ontains no F-steps. Sin e by Lemma 3.5, no b-step an
instantiateanydes endant of F,there existsan input- onsumingderivation
2 =hF;b; ;i;:::;hR ;i;:::;hQ 0 ; 0 i; ~
su h that hF;b; ;i;:::;hR ;i ontains onlyF-steps and hR ;i;:::;hQ
0 ; 0 i; ~
ontainsonlyb-steps(thatis,theF-stepsaremovedforwardusingthe
Swit h-ingLemma[16 ℄). Sin eR=R 0
;b forsomeR 0
,thereexistsaninput- onsuming
derivation 3 =hb;i;:::;hI 0 ; 0 i; ~ 3
obtainedfrom hR ;i;:::;hQ
0 ;
0 i;
~
byremovingtheprexR 0
inea hquery.
By Lemmas 3.2 and 3.4, R is well and ni ely moded. Let V be the set
of variables in the output positions of R 0
and a substitution su h that
dom()= V and V is ground. Then by Def. 3.1, b is ground inits input
positions. Moreover, sin e doesnotinstantiatetheoutputargumentsofb,
itfollows thatb is output-linear. ThusbyProp. 3.1, b iswelland ni ely
moded.
ByLemma3.5,nob-stepin
2
,andhen enoderivationstepin
3
, an
instan-tiatea variable inV. Sin e dom() =V,it thus follows that from
3
we an
onstru t aninput- onsumingderivation
4 =hb;i;:::;hI 0 ; 0 i; ~ 3 :::
Sin e b is a well and ni ely moded query and b is atom-terminating,
4 is nite. Therefore 3 , 2
,andnally are nite. 2
The followingtheorem is a onsequen e of Lemma 4.1 and states that
atom-terminatingatomson theirown annot produ ean innitederivation.
Theorem 4.2 LetP bea welland ni elymodedprogram and Q a welland
atom-terminating.
Proof. We rstshowthatforanywellandni elymodedqueryQ 0
,an
input- onsuming derivation of P [fQ 0
g an be innite only if it ontains at least
onestepwhereanatomisresolvedthat isnotatom-terminating (). Solet 0
be an inniteinput- onsumingderivation ofP [fQ 0
g.
If for ea h atom-terminating b 2 Q 0
, the derivation 0
ontains only nitely
many b-steps,then 0
ontains innitelymany a-stepsforsome a2Q 0
whi h
isnot atom-terminating. Hen ethe rst a-step in 0
is a step wherean atom
isresolved that isnotatom-terminating. So inthis ase, () follows.
Otherwise,let Q 0
=F;b;H,where b isthe rst atom-terminating atom inQ 0
su hthat 0
ontainsinnitelymanyb-steps. ThenbyLemma4.1, 0
ontains
innitelymany a-steps, forsome a2F that is notatom-terminating. Hen e
the rst a-step in 0
is a step where an atom is resolved that is not
atom-terminating. So inthis ase, ()followsaswell.
Nowlet be aninnite input- onsumingderivation ofP [fQg. Assume,for
the purpose of deriving a ontradi tion, that ontains only nitely many
steps where an atom is resolved that is not atom-terminating. Let ~
be a
suÆx of ontaining no steps where an atom is resolved that is not
atom-terminating. By Lemmas 3.2 and 3.4, the rst query of ~
is welland ni ely
moded. Moreover, ~
isinnite,andsowe havea ontradi tionto (). Thusit
followsthat ontainsinnitelymanystepswherean atomisresolvedthat is
notatom-terminating,whi h ompletes theproof. 2
Theorem 4.2 provides us with the formal justi ation for restri ting our
at-tentionto one-atom queries. Thusthequestionishowit an be shownthata
predi ateisatom-terminating.
5 Showing that a Predi ate is Atom-Terminating
Terminationproofsusuallyrely,more orlessexpli itly,on measuringthesize
of theinput ina query [1 , 3 , 7 ,8 , 9, 10 ,12 ℄. We agree with Etalle etal. [12℄
that itis reasonable to make this dependen yexpli it. This gives riseto the
on eptofmoded levelmapping [12 ℄,whi hisaninstan eoflevel mapping[6℄.
B
P
denotesthe setof groundatoms usingpredi ates o urringinP.
Denition 5.1 [modedlevel mapping℄Let P be a program. j:jis a moded
level mappingif
1. itisa levelmapping,that isa fun tionj:j:B
P ;IN,
P
Thusthelevel ofan atom onlydependson thetermsin theinputpositions.
Thefollowing on eptisusefulforprovingterminationforawholeprogram
in rementally,by provingitforone predi ateat a time[1 ℄.
Denition 5.2 [depends on℄ Let p;q be predi atesin a program P. We say
p referstoq ifthereisa lauseinP withpinitsheadand qinitsbody,and
p depends on q (written pwq) if(p;q) isinthe re exive,transitive losure
ofrefers to. We writep=q ifpwq and q 6wp,and pq ifpwq and qwp.
Abusing notation, we shall also use the above symbols for atoms, where
p(s;t)wq(u;v ) standsforpwq,and likewise for=and . Furthermore,we
denotethe equivalen e lassof a predi atepwith respe t to as[p℄
.
The followingdenitionprovidesuswitha riterionto provethat a
pred-i ate isatom-terminating.
Denition 5.3 [ICD-a eptable℄ Let P be a program and j:j a moded level
mapping. A lauseC=h Bisa eptableforinput- onsuming
deriva-tions(withrespe t toj:j)ifforeverysubstitutionsu hthatCisground,
and forevery a2B su h thatah, we have jhj>jaj. We abbreviate
a - eptable for input- onsuming derivations byICD-a eptable.
A setof lauses isICD-a eptable with respe t toj:jifea h lause is
ICD-a eptablewith respe tto j:j.
Let us ompare this on ept with some similar on epts in the literature:
re urrent[6 ℄, well-a eptable[12 ℄ and a eptable[4, 10 ℄programs.
LikeDe orte andDeS hreye [10 ℄and Etalleetal. [12 ℄butunlikeAptand
Pedres hi [4℄ and Bezem [6 ℄, we require jhj > jaj only for atoms a where
a h. This is onsistent with the idea that termination should be proven
in rementally: to show termination for a predi ate p, it is assumed that all
predi atesq withp =q have already beenshown to terminate. Therefore we
an restri tourattention to thepredi ates q whereq p.
Like Bezem but unlike Apt and Pedres hi, De orte and De S hreye and
Etalleet al.,ourdenitiondoesnotinvolve modelsor omputedanswer
sub-stitutions. Traditionally,the denitionof a eptable programs is based on a
model M of the program, and for a lause h a
1 ;:::;a n , jhj > ja i j is onlyrequired if M j=(a 1 ;:::;a i 1
). The reason is that for LD-derivations,
a
1 ;:::;a
i 1
mustbe ompletelyresolved beforea
i
issele ted. Bythe
orre t-ness of LD-resolution [16℄ and well-modedness [5℄, the a umulated answer
substitution,just beforea
i
is sele ted,issu hthat(a
1 ;:::;a i 1 ) isground and M j=(a 1 ;:::;a i 1 ).
Su h onsiderations ount for little when derivations are merely required
to be input- onsuming. This is illustrated in Ex. 1.2. In the third line of
the derivation, permute([1jZ 00
℄;X 0
of delete([℄;U;Z ) in the model of the program. This problem has been
des ribedbysayingthatdeletemakes aspe ulative output binding [20 , 24℄.
Theorem 5.1 LetP beawellandni elymodedprogramandpbeapredi ate
inP. Supposeallpredi atesqwithp=qareatom-terminating,andall lauses
dening predi ates q 2 [p℄
are ICD-a eptable. Then p, and hen e every
predi atein[p℄
,isatom-terminating.
Proof. Suppose the set of lauses dening the predi ates q 2 [p℄
is
ICD-a eptable withrespe t to themoded levelmappingj:j. Foran atom ausing
a predi ate in [p℄
, we dene jjajj = sup(fjaj j a is groundg), if the set
fjajja isgroundg isbounded. Otherwisejjajjis undened. Observethat
ifjjajjisdened foran atoma, thenjjajjjjajjforall . ()
Tomeasurethesizeofaquery,weusethemultiset ontainingthelevelofea h
atomwhosepredi ateisin[p℄
. Themultisetisformalisedasafun tionSize,
whi h takes asargumentsa queryand a naturalnumber.
Size(Q)(n)=#fq(u;v )jq(u;v ) is an atomin Q;qp and jjq(u;v )jj=ng
Note that if a query ontains several identi al atoms, ea h o urren e must
be ounted. We deneSize(Q) <Size(R ) ifand onlyif there is a numberl
su hthatSize(Q)(l)<Size(R )(l)andSize(Q)(l 0 )=Size(R )(l 0 )foralll 0 >l.
Intuitively,a de reasewithrespe tto <is obtainedwhenan atominaquery
isrepla edwitha nitenumberofsmalleratoms. ByKonig'sLemma[14 ℄,all
des ending hainswithrespe tto < arenite.
LetQ
0
=p(s;t)beawelland ni elymodedquery. Thensisgroundandthus
jjQ 0 jj is dened. Let = Q 0 ;Q 1 ;Q 2 ::: be an input- onsumingderivation of P [fQ 0 g.
Sin eallpredi atesq withp=q areatom-terminating,itfollowsbyThm.4.2
that there annot be an innite suÆx of withoutany stepswhere an atom
q(u;v ) su h thatq p isresolved. We showthat forall i0, ifthesele ted
atom 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 implies that is nite, and, as the
hoi e of theinitial queryQ
0
=p(s;t)wasarbitrary,pis atom-terminating.
Consideri0 and let C =q(v
0 ;u m+1 ) q 1 (u 1 ;v 1 );:::;q m (u m ;v m ) be the
lause, q(u;v ) thesele ted atom and theMGU usedinQ
i ;Q i+1 . If p = q, then p = q j
for all j 2 f1;:::;mg and hen e by () it follows that
Size(Q
i+1
)Size(Q
i ).
Now onsider q p. Sin e C is a ICD-a eptable lause, jjq(v
0 ;u m+1 )jj > jjq j (u j ;v j
)jjforalljwithq
j
p. Thistogetherwith()impliesSize(Q
i+1 )<
Size(Q
i
p=q,inwhi h asetriviallyallpredi atesq withp=qareatom-terminating.
Example 5.1 We now give a few examples. We denote the term size of a
termt, that isthe numberof fun tion and onstant symbols that o urin t,
asTSize(t).
The lauses deningappend(I;I;O) (Ex.4.1) are ICD-a eptable, where
jappend(s 1 ;s 2 ;t)j = TSize(s 1
). Thus append(I;I;O) is atom-terminating.
Thesame holdsforappend(O;O;I),deningjappend(t
1 ;t
2
;s)j=TSize(s).
The lauses deningdelete(I;O;O)(Ex.1.2) areICD-a eptable, where
jdelete(s;t
1 ;t
2
)j = TSize(s). Thus delete(I;O;O) is atom-terminating.
Thesame holdsfordelete(O;I;I),deningjdelete(t;s
1 ;s 2 )j=TSize(s 2 ).
In a similar way, we an show that permute(O;I) is atom-terminating. 3
However, permute(I;O) isnotatom-terminating.
The bookon theGodellanguage [15 ,page 81℄shows aprogram that
on-tainsa lause, whi hinPrologwouldbewritten as
slowsort(X,Y)
:-permute(X,Y),
sorted(Y).
The meaning and the modes of the predi ates should be obvious from their
names, and there aredelayde larations to ensurethat derivationsare
input- onsuming. The predi ate slowsort is not atom-terminating. However it
ould be made atom-terminating by repla ing permute(X,Y) with
permute(Y,X), so that permute is used in the mode in whi h it is
atom-terminating.
Note that a ording to the Godel spe i ation, no guarantees are given
aboutthesele tionrulethatgobeyondensuringthatderivationsfortheabove
programareinput- onsuming. Hen etheprogramisnotguaranteedto
termi-nateevenfora\well-behaved"querysu hasslowsort([1;2℄;Y). Eventhough
Hilland Lloyddo not laim that theprogram terminates, one would still
ex-pe tittodoso. However,we anmodifytheprogramasstated,andguarantee
thatthemodiedprogram terminatesusingthemethodof thispaper.
Figure1showsafragment fromaprogramforthen-queensproblem. The
mode is fnqueens(I;O); sequen e(I;O); permute(I;O); safe(I); is(O;I);
safeaux(I;I;I); no diag(I;I;I); =\=(I;I)g. Again using aslevel mapping
the term size of one of the arguments, one an see that the lauses dening
fno diag;safeaux;safeg are ICD-a eptable and thus these predi ates are
atom-terminating. Note that for eÆ ien y reasons, this program relies on
input- onsumingderivationswhere atoms usingsafearesele ted asearly as
possible[23 ℄.
Asa more omplexexample, onsiderthefollowingprogram,whosemode
isfplus one(I);minus two(I);minus one(I)g.
3
Hereweassumethattheprogramismadewelland ni elymodedbyinter hangingthe
sequen e(N,Seq), permute(Seq,Sol), safe(Sol). 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.
Figure 1: A program forn-queens
plus_one(X) :- minus_two(su (X)). minus_two(su (X)) :- minus_one(X). minus_two(0). minus_one(su (X)) :- plus_one(X). minus_one(0). We dene
jplus one(s)j = 3TSize(s)+4
jminus two(s)j = 3TSize(s)
jminus one(s)j = 3TSize(s)+2
Then the program is ICD-a eptable and therefore all predi ates are
atom-terminating.
We see that whenever in some argument position of a lause head, there is
a ompound term of some re ursive data stru ture, su h as [XjXs℄, and all
re ursive alls in the body of the lause have a stri t subterm of that term,
su h as Xs, in the same position | then the lause is ICD-a eptable using
aslevelmappingthetermsizeofthatargumentposition. Sin ethissituation
o ursvery often, it an be expe ted thatan average program ontainsmany
atom-terminatingpredi ates. However,itisunlikelythatinanyrealprogram,
all predi atesare atom-terminating.
The last example shows that more omplex s enarios than the one
de-s ribedabovearepossible,butwedoubtthatthey wouldofteno urin
pra -ti e. Thereforelevelmappingssu hastheone usedintheexamplewillrarely
be needed.
ConsideragainDef.5.3. Givena lauseh a
1 ;:::;a n andanatoma i h, werequirejhj>ja i
jforallgroundingsubstitutions,ratherthanonlyfor
su hthat(a
1 ;:::;a
i 1
)isina ertainmodeloftheprogram. Thisisof ourse
a serious restri tion. In Ex. 1.2, assuming mode permute(I;O), there an
terminating.
Similarly,we an show that there annot be a modedlevel mappingsu h
that the usual re ursive lause for qui ksort, in the usual mode, is
ICD-a eptable, even though we onje ture that qui ksort is atom-terminating.
This shows a limitation of our method. The author is urrentlyworking on
waysofover omingthislimitation,butthefa tremainsthatmanypredi ates
arenotatom-terminating.
6 Applying the Method
Therequirementofinput- onsumingderivationsmerelyre e tsthevery
mean-ingofinput: an atommustonly onsumeits owninput,notprodu eit. Thus
ifonea eptsthat(appropriately hosen)modesareusefulforveri ationand
re e ttheprogrammer's intentions, thenone shouldalso a ept this
require-ment and regard any violation of it as pathologi al. This does not ex lude
multiplemodes, that is,the same program beingused ina dierent mode at
ea hrun.
The requirement of input- onsuming derivations is trivially met for
LD-derivationsofawellmodedqueryand program, 4
sin etheleftmostatom ina
wellmodedquery is ground in its inputpositions. It an also be ensuredby
usingdelay de larationsas inGodel [15 ℄ that requiretheinputargumentsof
anatomtobegroundbeforethisatom anbesele ted. Moreover, itmightbe
ensured usingguards as in GHC [26 ℄. Finally, it an be ensured usingdelay
de larationsthat he kforpartialinstantiationoftheinputarguments,su has
theblo kde larations ofSICStus. Note thatunder ertain onditions,delay
de larations an ensure input- onsuming derivations with respe t to several,
alternative modes[21 , Chapter 7℄[23 ℄.
Consequently, this paper is mainly aimed at logi programs with delay
de larations, but unlike previous work [2, 17 , 18 , 19 , 20 , 23 , 24 ℄, abstra ts
from the details of parti ular delay onstru ts. We only assume what we
see as the basi purpose of delay de larations: ensuring that derivations are
input- onsuming.
As we have said in the introdu tion, the lass of predi ates for whi h all
input- onsuming derivations terminate is quite limited. In an average
pro-gram, some predi ates are atom-terminating but some are not. In general,
one has to make stronger assumptions about the sele tion rule. We sket h
three ways inwhi h themethod presented heremight be in orporated into a
more omprehensive method forprovingtermination. Thisboilsdown to the
question: howdo we deal withpredi atesthat arenotatom-terminating?
Therstwayhasa tuallybeendevelopedalready[23 ℄. Wehavepreviously
onsideredatom-terminating predi ates ina more on rete setting thanhere
4
most Prolog implementations is assumed. It is exploited that the textual
position of atoms using robust predi ates in lause bodies is irrelevant for
termination. The otheratoms mustbepla edsu h thattheatomsprodu ing
theirinputo ur earlier.
Se ondly,we ouldbuildonate hniquedevelopedbyMartinandKing[19 ℄.
They onsider oroutining derivations, but impose a bound on the depth of
ea h sub-derivation by introdu ing auxiliary predi ates with an additional
argumentthatservesasdepth ounter. Applyingtheresultsofthispaper,we
onlyhave to impose this depth bound for the predi ates that are not
atom-terminating. Forthe atom-terminating predi ates, we an save theoverheads
involved inthiste hnique.
Thirdly,we oulduse delayde larationsasthey are providedforexample
inGodel[15 ℄. Fortheatom-terminatingpredi ates,itissuÆ ientto he kfor
partialinstantiationof theinputpositionsusingaDELAY:::UNTILNONVAR:::
de laration. For the other predi ates, it must be ensured that the input
po-sitions areground usinga DELAY:::UNTIL GROUND:::de laration. Note that
a ording to its spe i ation, Godel does not guarantee a (default)
left-to-right sele tion rule, and therefore delay de larations are ru ial for
termina-tion. Note also that a groundnesstest is usuallymore expensive than a test
forpartialinstantiation. To thebest of ourknowledge,there hasneverbeen
asystemati treatment ofthequestionwhen GROUNDde larationsareneeded,
and whenNONVARde larationsare suÆ ient.
7 Dis ussion
Wehaveidentiedthe lassofpredi atesforwhi hallinput- onsuming
deriva-tionsare nite. An input- onsumingderivation is a derivation where inea h
step,theinputargumentsofthesele tedatomarenotinstantiated. Predi ates
an be shown to be in that lass usingthe notions of level mapping and
a - eptable lauseinaverysimilarwaytomethodsforLD-derivations[7 ,10 ,12 ℄.
Most previous approa hes, in ludingapproa hes for programswith delay
de larations, an only show termination making stronger assumptions about
the sele tion rule [17 , 18 , 19℄. We have argued in the previous se tion that
knowingthepredi atesthatterminateunderourweakerassumptionsisuseful
even forprogramswherenot allpredi ates have thisproperty.
Thispaperbuildsonourownpreviouswork[23 ℄,butattemptstoformulate
theresultsmoreabstra tly,withoutgettinginvolvedinthedetailsofparti ular
delay onstru ts. For example, we previously imposed a restri tion that all
lause heads in a program must be input-linear, whi h is ne essary so that
blo kde larations an ensureinput- onsumingderivations. Inthispaper,we
do not impose this restri tion. Hen e if input- onsuming derivations an be
We have laimed that most other approa hes to termination rely on the
idea thatthesize ofan atom an be pinneddown whenthe atom issele ted.
Te hni ally,thisusuallymeansthattheatomisboundedwithrespe tto some
level mapping [4 , 6 , 12, 19 ℄. There are ex eptions though [8 , 10 ℄, where
ter-mination an be shown for the query, say, append([X℄;[℄;Zs) using as level
mappingtheterm sizeofthe rst argument,even though thetermsizeof [X℄
isnotbounded. However,themethodonlyworksforLD-derivationsandrelies
on thefa t thatany future instantiation of X annot ae t the derivation for
append([X℄;[℄;Zs). Thereforeit is ee tively possibleto pin down the sizeof
append([X℄;[℄;Zs).
In ontrast, we show that under ertain onditions, it is enough to rely
on a relative de rease in the size of the sele ted atom, even though this size
annot be pinned down. This is ru ial to show termination of derivations
with oroutining. More pre isely, we exploit that an atom ina query annot
pro eed indenitelyunless itis repeatedly fed by some other atom o urring
earlierinthequery. Thisimpliesthatevery derivationforthequery isnite.
Bezem[6 ℄hasidentiedthe lassofstronglyterminatingprograms,whi h
areprogramsthat terminateunder any sele tionrule. While itis shownthat
every total re ursive fun tion an be omputed by a strongly terminating
program,thisdoesnot hangethefa tthatfewexistingprogramsarestrongly
terminating. Transformations are proposed for three example programs to
makethemstronglyterminating,butthetransformationsare ompli atedand
ad-ho .
On the whole, there seems to be a strong relu tan e to give up the idea
that the size of an atom must be pinned down when the atom is sele ted.
ThisistrueevenforBezem[6 ℄. Itisalso trueforMar hioriand Teusink[18 ℄,
whoassumealo al sele tionrule,thatisaruleunderwhi honlymostre ently
introdu edatoms anberesolvedinea hstep. MartinandKing[19 ℄a hievea
similaree t byboundingthedepthofthe omputationintrodu ingauxiliary
predi ates. It is more diÆ ult to assess Luttringhaus-Kappel [17 ℄ sin e his
ontributionismainlytogeneratedelayde larationsautomati allyratherthan
prove termination. 5
However in some ases, the delay de larations that are
generatedrequire anargument of anatom to be a rigidlistbefore thatatom
an be sele ted, whi h is similar to [18 , 19 ℄. Su h uses of delay de larations
go farbeyondensuring thatderivationsareinput- onsuming.
Of ourse, noneof theabove approa hes[6 , 17 , 18 ,19 ℄ an formallyshow
termination under the weak assumptions we make here, even for derivations
as trivial as the one in Ex. 1.1. Apt and Luitjes [2 ℄ give onditions for the
termination of append, but those are ad-ho and do not address the general
problem. Naish [20 ℄ gives heuristi s to ensure termination, but no formal
results.
5
thatthe atomsinthequery areordered 6
sothat there isa left-to-right
data- ow. Asatopi forfuturework,weenvisagetoproveterminationofprograms
wherethese onditionsarerelaxed,su hasprogramsusinglayeredmodes[13 ℄.
We believe that the ru ial idea will be the same as in this paper, namely
that one must rely on a relativede rease in sizeof the sele ted atom inea h
derivation step, rather than an absolute one. Therefore this paper should
providea good basisforthisextension.
A knowledgements
The author would like to thank Floren e Benoy forproofreading this paper,
and Sandro Etalle and Pat Hill for some helpful omments. This work was
fundedby EPSRCGrant No.GR/K79635.
Referen es
[1℄ K.R.Apt. From Logi ProgrammingtoProlog. Prenti eHall,1997.
[2℄ K.R.AptandI.Luitjes. Veri ationoflogi programswithdelayde larations.
InV.S.AlagarandM.Nivat, editors,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 eedings of the Symposium in Computational Logi , LNCS,
pages150{176.Springer-Verlag,1990.
[4℄ K. R. Apt and D. Pedres hi. Modular termination proofs for logi and pure
Prolog programs. InG. Levi, editor, Advan es in Logi Programming Theory,
pages183{229.OxfordUniversityPress,1994.
[5℄ K. R. Apt and A. Pellegrini. On the o ur- he kfree Prologprograms. ACM
Transa tions onProgramming Languages andSystems,16(3):687{726,1994.
[6℄ M.Bezem.Strongterminationoflogi programs.JournalofLogi Programming,
15(1&2):79{97,1993.
[7℄ D.DeS hreyeandS.De orte.Terminationoflogi programs: Thenever-ending
story. JournalofLogi Programming,19/20:199{260,1994.
[8℄ D. DeS hreye,K.Vers haetse,andM.Bruynooghe. Aframeworkforanalysing
theterminationofdenite logi programswithrespe tto allpatterns. In
Pro- eedingsof FGCS,pages481{488.ICOTTokyo,1992.
[9℄ S. De orteandD.De S hreye. Automati inferen eof norms: Amissing linkin
automati terminationanalysis. In Pro eedings of the 10th International Logi
ProgrammingSymposium,pages420{436.MITPress,1993.
[10℄ S. De orteandD. DeS hreye. Terminationanalysis: Somepra ti alproperties
ofthenormandlevelmappingspa e. InJ.Jaar,editor,Pro eedings ofthe15th
JICSLP,pages235{249.MITPress,1998.
6
for annotated logi programs. In Pro eedings of the 2nd International Logi
ProgrammingSymposium,pages29{38.MITPress,1985.
[12℄ S.Etalle,A.Bossi,andN.Co o.Terminationofwell-modedprograms. Journal
of Logi Programming,38(2):243{257,1999.
[13℄ S. Etalle and M. Gabbrielli. Layered modes. Journal of Logi Programming,
39:225{244,1999.
[14℄ M.Fitting. First-orderLogi andAutomatedTheoremProving. Springer-Verlag,
1996.
[15℄ P. M. Hill and J. W. Lloyd. The Godel Programming Language. MIT Press,
1994.
[16℄ J.W.Lloyd. Foundationsof Logi Programming. Springer-Verlag,1987.
[17℄ S.Luttringhaus-Kappel.Controlgenerationforlogi programs.InD.S.Warren,
editor,Pro eedings of the10thInternational Conferen eonLogi Programming,
pages478{495.MITPress,1993.
[18℄ E. Mar hioriandF.Teusink. Provingterminationof logi programswith delay
de larations. InJ.W. Lloyd,editor, Pro eedings ofthe 12thInternational Logi
ProgrammingSymposium,pages447{461.MITPress,1995.
[19℄ J.C.MartinandA.M.King.GeneratingeÆ ient,terminatinglogi programs.In
M.BidoitandM.Dau het,editors,Pro eedings ofTAPSOFT'97, LNCS,pages
273{284.Springer-Verlag,1997.
[20℄ L.Naish.Coroutiningandthe onstru tionofterminatinglogi programs.T
e h-ni alReport92/5,UniversityofMelbourne,1992.
[21℄ J.-G. Smaus. Modes and Types in Logi Programming. PhD thesis,
University of Kent at Canterbury, O tober 1999. Draft available from
www. s.uk .a .uk/people/staff/jgs5/thesis.ps.
[22℄ J.-G.Smaus. Provingterminationofinput- onsuminglogi programs. InD.De
S hreye,editor, Pro eedings of the 16thInternational Conferen e on Logi
Pro-gramming.MITPress,1999. Toappear.
[23℄ J.-G. Smaus,P. M. Hill,and A. M. King. Terminationof logi programswith
blo kde larationsrunninginseveralmodes. InC.Palamidessi,editor,
Pro eed-ingsof PLILP/ALP,LNCS.Springer-Verlag,1998.
[24℄ J.-G. Smaus, P. M.Hill, and A. M. King. Preventinginstantiation errorsand
loops for logi programs with multiple modes using blo k de larations. In
P.Flener,editor,Pro eedings ofLOPSTR'98,LNCS.Springer-Verlag,1999.
[25℄ Z.Somogyi,F.Henderson,andT.Conway.Theexe utionalgorithmofMer ury,
an eÆ ient purely de larative logi programming language. Journal of Logi
Programming,29(1{3),1996.
[26℄ K. Ueda. Guarded Horn lauses. In E. Wada, editor, Pro eedings of the 4th
Japanese Conferen e on Logi Programming, LNCS, pages 168{179.