Context-Moving Transformations for Funtion Veriation
Jurgen Giesl
Department of ComputerSiene, DarmstadtUniversity of Tehnology
Alexanderstr. 10,64283 Darmstadt,Germany
E-mail: gieslinformatik.tu-dar msta dt.d e
Abstrat
Several indution theorem provers have been developed whih supportmehanized
veriationoffuntionalprograms. Unfortunately,amajorproblemisthattheyoftenfail
inverifyingtailreursivefuntions(whihorrespondtoimperativeprograms). However,
inpratieimperativeprogramsareusedalmostexlusively.
Wepresent anautomatitransformation totaklethisproblem. Ittransformsfun-
tionswhiharehardtoverifyintofuntionswhoseorretnessanbeshownbytheexist-
ingprovers.Inontrasttolassialprogramtransformations,theaimofourtehniqueis
nottoinreaseeÆieny,buttoinreaseveriability. Therefore,thispaperintroduesa
novelappliationareaforprogramtransformationsanditshowsthatsuhtehniquesan
infatsolvesomeofthemosturgenturrenthallengeproblemsinautomatedveriation
andindutiontheoremproving.
1 Introdution
Toguaranteetheorretnessofprograms,aformalveriationisrequired. However,mathe-
matialorretnessproofsareusuallyveryexpensiveandtime-onsuming. Therefore,program
veriationshould beautomated as faraspossible.
Asindution 1
istheessentialproofmethod neededforsuh veriations,severalsystems
havebeendevelopedforautomatedindutiontheoremproving. Thesesystemsaresuessfully
used for veriation of funtional programs in many areas, but a major problem for their
pratial appliation is that they are often not suitable for handling imperative programs.
Thereasonisthatthetranslationofimperativeprogramsinto thefuntional inputlanguage
of these systems alwaysyields tail reursive funtions whih are partiularly hardto verify.
Thus, developingtehniques forproofs about tailreursivefuntions isurrentlyone ofthe
mostimportantresearhtopisin thisarea.
InSetion 2wepresentourfuntionalprogramminglanguage. Wealsogiveabriefintro-
dutionto indution theoremprovingandweillustratethat thereasonfor thediÆulties in
verifyingtailreursivefuntionsisthattheyusuallyhaveanaumulatorparameterwhihis
initializedwithsomexed value,but thisvalueishangedin thereursivealls.
Thispaperintroduesanewframeworkformehanizedveriationofsuhfuntionsbyrst
transformingthemintofuntions whiharebettersuitableforveriationandbyafterwards
applyingtheexistingindutionproversfortheirveriation. Tosolvetheveriationproblems
with tailreursivefuntions,theontext around reursiveaumulatorargumentshasto be
shiftedaway,suhthattheaumulatorparameterisnolongerhangedinreursivealls. For
TehnialReportIBN99/51,DarmstadtUniversityofTehnology,Germany,1999. Extendedversionofa
paperwhihappearedintheProeedingsofthe9thInternationalWorkshoponLogi-basedProgramSynthesis
andTransformation(LOPSTR'99),Venie,Italy,LetureNotesinComputerSiene1817,Springer-Verlag,
2000. ThisworkwassupportedbytheDFGundergrantGI274/4-1.
1
Inthispaper,\indution"standsformathematialindution,i.e.,itshouldnotbeonfusedwithindution
inthesenseofmahinelearning.
transformtail reursioninto non-tailreursion. Our transformationsprovedsuessful ona
representativeolletionoftailreursivefuntions,f.AppendixB. Inthisway,orretnessof
manyimperativeprogramsan beprovedautomatially withouttheneed forinventingloop
invariantsorgeneralizations.
2 Funtional Programs and their Veriation
Weonsiderarstorderfuntionallanguagewitheagersemantisand(non-parameterizedand
free)algebraidatatypes. Asanexample,regardthedatatypenatfornaturalnumberswhose
objetsarebuiltwiththeonstrutors 0ands:nat!nat(forthesuessorfuntion). Thus,
theonstrutor groundterms representthedata objetsofthe respetivedata type. Inthe
following,weoftenwrite\1"insteadof\s(0)",et. Foreveryn-aryonstrutortherearen
seletor funtionsd
1
;:::;d
n
whihserveasinversefuntionsto(i.e.,d
i ((x
1
;:::;x
n ))x
i ).
Forexample,fortheunaryonstrutorswehavetheseletorfuntionpsuhthatp(s (m))m
(i.e.,pisthepredeessorfuntion).
Inpartiular, every program F ontainsthe type bool whose objets are built with the
(nullary)onstrutorstrueandfalse. Moreover,thereisabuilt-inequalityfuntion=: !
boolforeverydatatype. Todistinguishthefuntion symbol=from theequalityprediate
symbol, we denote the latter by \". The funtions of a funtional program F have the
followingform.
funtion f(x
1 :
1
;:::;x
n :
n
): (
ifb
1
thenr
1
.
.
.
ifb
m thenr
m
Here,\ifb
i
thenr
i
"isalled thei-thase off withonditionb
i
andresult r
i
. Forfuntions
withjust oneaseofthe form\iftrue thenr"wewrite\funtion f(x
1 :
1
;:::;x
n :
n ):
( r". To ease readability, if b
m
is true, then we often denote the last ase by \else
r
m
". Asanexample,onsiderthefollowingfuntion(whihallsanauxiliaryalgorithm+for
addition).
funtiontimes(x;y:nat):nat (
ifx6=0theny+times(p(x);y)
else 0
Ifafuntionf isalledwithatupleofgroundtermst
asarguments,thent
isevaluated
rst(toonstrutorgroundtermsq
). Nowtheonditionb
1 [x
=q
℄oftherstaseisheked.
Ifitevaluatestotrue,thenr
1 [x
=q
℄isevaluated. Otherwise,theonditionoftheseondase
is heked, et. So the onditions of a funtional program asabove are tested from top to
bottom.
Nowouraimis to verify statementsaboutthealgorithmsof afuntionalprogram F. In
thispaperweonlyonsideruniversallyquantiedequationsoftheform8...standweoften
omitthequantierstoeasereadability. Lets;tontainthetupleofvariablesx
. Thenst
isindutively true for theprogramF, denoted F j=
ind
st,iffor allthose dataobjetsq
whereevaluationofs[x
=q
℄ orevaluationoft[x
=q
℄ isdened,evaluationoftheotherterm
t[x
=q
℄ resp.s[x
=q
℄ is dened aswell, and ifbothevaluations yield the sameresult. For
example,let\"beanabbreviationfortimes. Thentheonjeture
(xy)zx(yz) (1)
isindutivelytrue,sine(xy)zandx(yz)evaluatetothesameresultforallinstantiations
withdataobjets.
theoremproving.Foranextensionofindutivetruthtomoregeneralformulasandforamodel
theoretiharaterization(usinginitialalgebras)seee.g.[ZKK88,Wal94, BR95,Gie99b℄.
Toproveindutive truthautomatially,several indution theorem provers havebeende-
veloped, e.g. [BM79, KM87, ZKK88, BSH +
93, Wal94, BR95℄. For instane, these systems
anproveonjeture (1)usingastrutural indution with xastheindution variable. Ifwe
abbreviate(1) by'(x;y;z), then in theindution base asethey would prove'(0;y;z)and
in thestep ase(where x 6=0), theywouldshowthat the indution hypothesis '(p (x);y;z)
impliestheindutiononlusion'(x;y;z).
However,oneofthemainproblemsfortheappliationoftheseindutiontheoremprovers
in pratieis that most of them anonly handle funtional algorithms with reursion, but
theyarenotdesignedtoverifyimperativealgorithmsontainingloops.
The lassial tehniques for the veriation of imperative programs (like the so-alled
Hoare-alulus[Hoa69℄)allowtheproofofpartialorretnessstatementsoftheform
f'
pre gP f'
post g:
Thesemantisof thisexpressionisthatinaseoftermination,theprogramP transformsall
programstateswhihsatisfythepreondition'
pre
intoprogramstatessatisfyingtheposton-
dition'
post
. Asanexample,regardthefollowingimperativeprogramformultipliation.
proeduremultiply(x;y;z:nat)(
z:=0;
whilex6=0do x:=p(x);
z:=y+z od
Toverifythat thisimperativeprogramis equivalenttothefuntionalprogramtimes, one
hastoprovethestatement
fxx0^yy0^z0g whilex6=0dox:=p(x);z:=y+zod fzx0y0g :
Here,x
0 and y
0
are additionalvariableswhih representtheinitial valuesof thevariablesx
and y. However, in the Hoare-alulus, for that purpose one needs a loop invariant whih
is a onsequene of the preondition and whih (together with the exit onditionx = 0 of
theloop)impliesthepostonditionz x
0 y
0
. Inourexample,theproofsueedswiththe
followingloopinvariant.
z+xyx
0 y
0
(2)
Thesearhfor loopinvariantsisthe maindiÆultywhenverifyingimperativeprograms.
Of ourse, it would be desirable that programmers develop suitable loop invariants while
writingtheirprograms,butin realitythisisstilloftennotthease. Thus, foranautomation
of program veriation, suitable loop invariants would have to be disoveredmehanially.
However, while there exist some heuristis and tehniques for the hoie of loop invariants
[SI98℄,in generalthistaskseemsdiÆulttomehanize[Dij85℄.
Therefore,in thefollowingwepresentanalternativeapproah forautomatedveriation
ofimperativeprograms. Forthat purposeouraimwasto usetheexistingpowerfulindution
theoremprovers. Astheinputlanguageofthesesystemsisrestritedtofuntionalprograms,
onerst has to translate imperativeprograms into funtional ones. Suh a translation an
easilybedoneautomatially,f. [MC60,Gie99a℄.
Inthistranslation,everywhile-loopistransformedintoaseparatefuntion. Fortheloop
oftheproeduremultiplyweobtainthefollowingalgorithmmultwhihtakestheinputvalues
ofx,y,andzasarguments. Iftheloop-onditionissatised(i.e.,ifx6=0),thenmultisalled
reursivelywith thenew valuesofx, y, andz. Otherwise,multreturns thevalueof z. The
thesamenamewhihallstheauxiliaryfuntion multwiththeinitialvaluez=0.
funtionmultiply(x;y:nat):nat (
mult(x;y;0)
funtionmult(x;y;z:nat):nat (
ifx6=0thenmult(p(x);y;y+z)
else z
Nowindutionproversmaybeusedtoverifyonjeturesaboutthefuntionsmultiplyand
mult. However, it turns out that the funtional algorithms resulting from this translation
haveaertainharateristiformwhihmakesthemunsuitableforveriationtasks. Infat,
thisdiÆultyorrespondstotheproblemofndingloopinvariantsfortheoriginalimperative
program.
To verify the equivalene between multiply and times using the transformed funtions
multiplyandmult,onenowhasto provemultiply(x;y)xy or,inotherwords,
mult(x;y;0)xy: (3)
Usingstruturalindutiononx,thebaseformula mult(0;y;0)0yaneasilybeproved,
but there isaproblem withtheindution step. Inthe asex6=0wehaveto showthat the
indutionhypothesis
mult(p(x);y;0)p(x)y (IH)
impliestheindutiononlusionmult(x;y;0)xy. Usingthealgorithmsofmultandtimes,
theindutiononlusionanbetransformedinto
mult(p(x);y;y)y+p(x)y. (IC)
However, thedesired proof fails, sine theindution hypothesis (IH) annot be suessfully
usedfortheproofof(IC).
Thereasonforthisfailureisduetothetailreursiveformofmult(i.e.,thereisnoontext
aroundmult'sreursiveall). Instead,itsresultisomputedintheaumulator parameterz.
Inthe beginning, theaumulator z is initializedwith 0. Forthat reason, wealso havethis
instantiation in ouronjeture (3) and in the orrespondingindution hypothesis (IH). But
asthevalueofzishangedineahreursiveallofwhile,intheindutiononlusion(IC)we
havethenewvalueyinsteadof0. Thus, theindutiononlusiondoesnotorrespondtothe
original onjeture (3)any moreand hene,the indution hypothesis (where z 0) annot
beused toprove(IC)(wherezy). Hene,tailreursivealgorithms likemultaremuhless
suitableforveriationtasksthanalgorithmsliketimes.
The lassial solution for this problem is to generalize the onjeture (3) to a stronger
onjeture whih is easier to prove. For instane, in our example one needs the following
generalizationwhihanbeprovedbyasuitableindution.
mult(x;y;z)z+xy (4)
Thus,developinggeneralizationtehniques isoneofthemain hallengesinindutionthe-
orem proving [Aub79, BM79, HBS92, Wal94, IS97, IB99℄. Note that the generalization (4)
orrespondsto theloopinvariant(2) thatonewould needforadiret veriationoftheim-
perativeprogrammultiplyintheHoare-alulus. Soinfat,ndingsuitablegeneralizationsis
loselyrelatedtothesearhforloopinvariants.
2
2
Adierenebetweenverifyingfuntionalprogramsbyindutionandverifyingimperativeprogramsbyloop
invariantsand indutiveassertionsisthatfor imperativeprogramsoneusesa\forward"indution starting
withthe initialvaluesof the programvariablesand for funtionalprogramsa \reversed"indution isused
whihgoesbakfromtheir nalvaluestothe initialones. However, the requiredloop invariantsresp.the
orrespondinggeneralizationsareeasilyinterhangeable,f.[RY76℄.
invariants. Theideaistotransformfuntionslikemult,whiharediÆulttoverify,intoalgo-
rithmsliketimeswhiharemuhbetteramenabletoautomatedindutionproofs. Forexample,
thewell-knownindutiontheoremprovingsystemnqthm[BM79,BM98℄failsinproving(3),
whereasafteratransformationofmultiplyandmultintotimesthisonjeturebeomestrivial.
Thisapproahofverifyingimperativeprogramsviaatranslationinto funtionalprogramsis
basedontheobservationthatin funtional languagesthere oftenexistsaformulationofthe
algorithmswhihis easytoverify(whereasthisformulationannotbeexpressedin iterative
form). Theaimofourtehniqueistondsuhaformulationautomatially.
Ourapproahhastheadvantagethat thetransformationsolvestheveriationproblems
resulting from a tail reursive algorithm one and for all. On the other hand, when using
generalizationsorloopinvariantsonehastondanewgeneralization(oranewloopinvariant,
respetively) for everynewonjeture about suh an algorithm. Moreover, mosttehniques
forndinggeneralizationsorloopinvariantshavetobeguidedbythesystemuser,sinethey
rely on the presene of suitable lemmata. By these lemmata the user oftenhas to provide
themainideaforthegeneralizationresp.theloopinvariant. Inontrast,ourtransformation
worksautomatially.
Inpartiular,automatigeneralizationtehniquesfailformanyonjetureswhihontain
several ourrenes of a tail reursive funtion. As an example, regard the assoiativity of
multiplyor,inotherwords,
mult(mult(x;y;0);z;0)mult(x;mult (y;z;0);0): (5)
Similarto (3), adiret proof bystrutural indution onx doesnotsueed. So again,the
standardsolutionwouldbetogeneralizetheonjeture(5)byreplaing thexedvalue0by
suitableterms. Forexample,onemaygeneralize(5)to
mult(mult(x;y;v);z;0)mult(x;mult(y;z;0);mult(v;z;0)):
Toeasereadability,wehaveunderlinedthosetermswherethegeneralizationtookplae. While
theproofofthisonjetureisnottoohard(usingthedistributivityof+overmultiply),weare
not aware of any tehniquewhih would nd this generalization(or theorrespondingloop
invariant) automatially, beause it is diÆult to synthesize the orret replaement of the
third argumentin the right-handside (by mult(v;z;0)). The problem isthat thedisturbing
0's ourring in (5) annot just be generalized to new variables, sine this would yield a
awedonjeture. Thus, ndinggeneralizationsforonjetureswithseveralourrenesof a
tail reursivefuntion is often partiularly hard, as dierent ourrenesof an instantiated
aumulator may have to be generalized to dierent new terms.
3
On the other hand, our
transformationallowsus toprovesuhonjetureswithoutuser interation. Essentially,the
reason isthat while generalizationsand loopinvariantsdepend onboththe algorithms and
theonjeturestobeproved,thetransformationonlydependsonthealgorithms.
Thearea of program transformationis a well examined eld whih has found manyap-
pliations in software engineering, program synthesis, and ompiler onstrution. For sur-
veys see e.g. [BW82, Par90, MPS93, PP96℄. However, the transformations developed for
these appliations had a goal whih is fundamentally dierent from ours. Our aim is to
transform programs into new programs whih are easier to verify. In ontrast to that, the
lassial transformation methods aim to inrease eÆieny. Suh transformations are un-
suitable for our purpose, sine a more eÆient algorithm is often harder to verify than a
less eÆient easier algorithm. Moreover, we want to transform tail reursive algorithms
3
Analternativegeneralizationof(5)ismult(mult(x;y;0);z;v)mult(x;mult(y;z;0);v):Thisgeneralization
iseasierto nd(as wejustreplaedboththirdargumentsoftheleft- andright-handsidebythe samenew
variable v). However, it isnot easy to verify (its proof isessentiallyas hard as the proof of the original
onjeture(5)).
tailreursiveprogramsaretransformedinto tailreursiveones(\reursionremoval", f. e.g.
[Coo66,DB76,BD77, Wan80, BW82, AK82,HK92℄).
Asthegoalsoftheexistingprogramtransformationsareoftenoppositetoours,apromising
approahisto usethese lassialtransformationsinthe reversediretion. Toourknowledge,
suh an appliation of these transformationsfor the purpose of veriation has rarely been
investigatedbefore. Inthisway,weindeedobtainedvaluableinspirationsforthedevelopment
of ourtransformation rules in Setion 3- 5. However, ourrules go farbeyond the reversed
standardprogram transformation methods, beausethese methods hadto be modied sub-
stantiallytobeappliablefortheprogramsresultinginourontext.
3 Context Moving
The only dierene between the algorithms mult and times is that the ontext y+::: to
omputetheresultoftimesisoutsideofthereursiveall,whereasinmulttheontexty+:::
isin thereursiveargumentfor theaumulatorvariable z. This hangeof theaumulator
inreursiveallsisresponsiblefortheveriationproblemswithmult.
Forthatreason,wenowintrodueatransformationrulewhihallowstomove theontext
away from reursive aumulator arguments to a position outside of the reursive all. In
thisway,theformerresultmult(p (x);y;y+z)anbereplaed byy+mult(p(x);y;z). Sothe
algorithmmultistransformedinto
funtionmult(x;y;z:nat):nat (
ifx6=0theny +mult(p (x);y;z)
else z.
Todeveloparuleforontextmoving,wehavetondsuÆientriteriawhihensurethat
suhatransformationisequivalenepreserving. Forourrule,weregardalgorithmsoftheform
(6) where the last argument z is used asan aumulator. Our aim is to movethe ontexts
r
1
;:::;r
k
ofthereursiveaumulatorargumentstothetop,i.e.,totransformthealgorithm
(6)into(7).
funtion f(x
:
;z:): (
ifb
1
thenf(r
1
;r
1 )
.
.
.
ifb
k
thenf(r
k
;r
k
) (6)
ifb
k +1
thenr
k +1
.
.
.
ifb
m
thenr
m
funtion f(x
:
;z:): (
ifb
1
thenr
1 [z=f(r
1
;z)℄
.
.
.
ifb
k
thenr
k [z=f(r
k
;z)℄ (7)
ifb
k +1 thenr
k +1
.
.
.
ifb
m
thenr
m .
Wedemand m>k1,buttheorderofthef-asesisirrelevantandthetransformationmay
also be applied if the aumulator z is not the last parameter of f (we just use the above
formulationtoeasereadability).
Firstof all,notethat theintermediatevaluesoftheparameterz arenotthesameinthe
twoversions off. Thus, in orderto guaranteethatevaluationof bothversionsof f leadsto
thesameasesinthesameorder,wemustdemandthat theaumulatorzdoesnotourin
theonditionsb
1
;:::;b
m
orinthereursiveargumentsr
1
;:::;r
k
fortheotherparametersx
.
Letu
;wbeonstrutorgroundterms. Nowforbothversionsoff,evaluationoff(u
;w)
leads to the samef-ases i
1
;:::;i
d
where i
1
;:::;i
d 1
2 f1;:::;kgand i
d
2fk+1;:::;mg
(providedthattheevaluationisdened). Lett[r
;s℄abbreviatet[x
=r
;z=s℄(whereforterms
tontainingatmostthevariablesx
,wealsowritet[r
℄)andleta
h
=r
ih [r
ih
1 [:::[r
i1 [u
℄℄:::℄℄,
where a
0
=u
. Thenwith theolddenition off weobtaintheresult(8)and withthenew
r
i
d [a
d 1
;r
i
d 1 [a
d 2
;:::r
i
2 [a
1
;r
i
1 [a
0
;w℄℄::: ℄℄ (8)
r
i1 [a
0
;r
i2 [a
1
;:::r
i
d 1 [a
d 2
;r
i
d [a
d 1
;w℄℄::: ℄℄: (9)
Forexample,theoriginalalgorithmmultomputesaresultoftheform
y
x +(y
x 1
+(:::(y
2 +(y
1
+z)):::))
where y
i
denotesthe numberwhih isadded in thei-th exeutionof thealgorithm. Onthe
otherhand,thenewversionofmultomputestheresult
y
1 +(y
2
+(:::(y
x 1 +(y
x
+z)):::)):
Therefore,theruialonditionforthesoundnessofthistransformationistheleft-ommutati-
vity of theontexts r
1
;:::;r
k
moved, f.[BW82℄. Inother words,for alli2f1;:::;mgand
alli 0
2f1;:::;kgwedemand
r
i [x
;r
i 0
[y
;z℄℄r
i 0
[y
;r
i [x
;z℄℄:
Then (8) and (9) are indeed equal as an be proved by subsequently moving the inner
r
ij [a
j 1
;:::℄ontextsof(8)tothetop. Soformult,weonlyhavetoprovex + (y+ z)y+ (x + z)
andy+zy+z (whihaneasily beveriedbytheexistingindution theoremprovers).
Notealsothat sinein theshema(6), r
1
;:::;r
m
denote arbitraryterms,suhaontext
movingwould alsobepossibleifonewould exhange theargumentsof +in mult'sreursive
all. Then r
1
would be z+y and the required left-ommutativity onditions would read
(z+y)+x(z+x)+y andz+yz+y.
However,ontextmovingmayonlybedone,ifalltermsr
1
;:::;r
m
ontaintheaumulator
z. Otherwise f's new denition ould be total although the original denition was partial.
Forexample,iff hasthe(rst)ase
ifx6=0thenf(x;0)
thenf(x;z)doesnotterminateforx6=0. However,ifwewouldnotdemandthatz ourred
inthereursiveaumulatorargument,thenontextmovingouldtransformthisaseinto\if
x 6=0 then0". The resultingfuntion islearly notequivalent tothe originalone, beause
nowtheresultof f(x;z)is0forx6=0.
Similarly,z mustalso ourin theresultsofnon-reursiveasesasanbedemonstrated
withthefollowingexample.
funtionf(x;z:nat):nat (
if x6=0thenf(p(x);g(z))
else 0
funtiong(x:nat):nat (
ifx6=0theng(x)
else 0
Therequired left-ommutativity onditions are fullled and thus, ontext movingwould
transformfinto
funtionf(x;z:nat):nat (
ifx6=0theng(f (p(x);z))
else 0.
However,withtheoriginalalgorithm,f (1;1)resultsintheallg(1)andhene,itisundened.
Ontheotherhand,in thenewalgorithmf(1;1)is0.
Finally, we also have to demand that in r
1
;:::;r
m
, the aumulator z may not our
withinargumentsoffuntionsdependentonf. Here,everyfuntionisdependent onitselfand
f.
Soinpartiular,thisrequirementexludesnestedreursiveallswiththeargumentzandit
alsoexludesorrespondingallsoffuntionswhiharemutuallyreursivewithf. Otherwise,
the transformation would not preserve the semantis. As an example regard the following
funtion,wherethealgorithmone(z)returns1forallargumentsz.
funtion f(x;z:nat):nat (
ifx6=0thenf (p(x);f (z;0))
else one(z)
Bymovingtheontextf(:::;0)tothetop,theresultoftherstasewouldbetransformedinto
f(f (p(x);z);0). Theoriginalalgorithmsatises allpreviouslydevelopedonditions. However,
theoriginalalgorithmistotal,whereasafterthetransformationf (x;z)doesnotterminateany
moreforx6=0.
Similarly,theourreneoffuntionsdependentonf intheresultsr
k +1
;:::;r
m
alsogives
risetoounterexamples.
funtionf(x;z:nat):nat (
if x6=0thenf(p(x);p (z))
else g(z)
funtiong(z:nat):nat (
ifz6=0thenf(z;z)
else 0
Notethat wehavef (x;z)0and g(z)0for allnumbersx and z. Thus, therequired
left-ommutativityonditionsaresatisedand ontextmovingwould yield
funtionf(x;z:nat):nat (
ifx6=0thenp(f (p(x);z))
else g(z).
However,inontrasttotheoriginalversionoff ,thisalgorithmisnolongertotal,sineevalu-
ationoff(1;1)isnotterminating.
Undertheaboverequirements,thetransformationof(6)into(7)issound.
4
Theorem1(Soundness ofContext Moving) Let F be a funtional program ontaining
the algorithm(6)andletF 0
resultfromF byreplaing (6)with(7). Thenfor alldataobjets
t
, t, and q, f(t
;t) evaluates to q in the program F i it does so in F 0
, provided that the
followingrequirementsarefullled:
(A) z62V(b
1
)[:::[V(b
m )
(B) z62V(r
1
)[:::[V(r
k )
(C) For alli2f1;::: ;mg,i 0
2f1;:::;kg: F j=
ind r
i [x
;r
i 0[y
;z℄℄r
i 0[y
;r
i [x
;z℄℄
(D)z2V(r
1
)\:::\V(r
m )
(E) Inr
1
;:::;r
m
,z does notour inargumentsoffuntionsdependenton f.
Inontrast to the original version of mult, thealgorithm obtained by ontext moving is
muh better suited for veriation tasks. The reason is that the(former) aumulator z is
initialized with0 andit is no longerhanged in thealgorithm mult. Forthat reason,z an
nowbeeliminatedfromthefuntionmultbyreplaingallitsourrenesby0. Thesemantis
ofthemainfuntion multiplyremainsunhangedbythistransformation.
funtionmultiply(x;y:nat):nat (
mult(x;y)
funtionmult(x;y:nat):nat (
ifx6=0theny+mult(p(x);y)
else 0
Nowmultindeedorrespondstothealgorithmtimesandthus,theompliatedgeneralizations
orloopinvariantsofSetion2arenolongerrequired. Thus,theveriationproblemsforthese
proeduresaresolved.
4
TheproofsforthetheoremsanbefoundinAppendixA.
funtionplus(x;z:nat):nat (
ifx6=0thenplus(p(x);s (z))
else z
into
funtionplus(x;y:nat):nat (
ifx6=0thens(plus(p (x);z))
else z,
whih is muh better suited for veriation tasks. Here, for ondition(C) we only have to
proves(s(z))s(s (z))ands(z)s(z)(whihistrivial).
Toapplyontextmovingmehanially,theonditions(A)-(E)foritsappliationhaveto
behekedautomatially. For(A),(B),(D),and(E)thisiseasilydone,sinetheseonditions
arejust syntati. Theleft-ommutativityondition(C) hastobehekedbyanunderlying
indutiontheoremprover. Inmanyases,thisisnotahardtask,sineforalgorithmslikeplus
thetermsr
i [x
;r
i 0[y
;z℄℄andr
i 0[y
;r
i [x
;z℄℄arealreadysyntatiallyequalandforalgorithms
likemult,therequiredleft-ommutativityfollowsfromtheassoiativityandommutativityof
\+". Toeasetheproofofsuhonjeturesaboutauxiliaryalgorithms,wefollowthestrategy
toapplyourtransformationstothosealgorithmsrstwhihdependonfewotheralgorithms.
Thus, we would attempt to transform \+" before transforming mult. In this way, one an
usually avoid the need for generalizationswhen performing the requiredleft-ommutativity
proofs. Finally,notethat ofourse,ontextmovingshouldonlybedoneifat leastoneofthe
reursiveargumentsr
1
;:::;r
k
isdierentfromz (otherwisethealgorithmwouldnothange).
Our ontext moving rule has some similarities to the reversal of a tehnique known in
programtransformation(operand ommutation,f. e.g.[Coo66,DB76,BW82℄). However,our
rulegeneralizesthis(reversed)tehniquesubstantially.
For example, diretly reversingthe formulation in [BW82℄ would resultin a rule whih
wouldalsoimposeappliabilityonditionsonthefuntionsthatall thetransformedfuntion
f (bydemandingthatf'saumulatorwouldhavetobeinitializedinaertainway). Inthis
way,theappliabilityofthereversedrulewouldbeunneessarilyrestrited(andunneessarily
diÆult to hek). Therefore, wedeveloped arule where ontext moving is separated from
the subsequent replaementof the (former) aumulator by initial values like0. Moreover,
in[BW82℄ theproblemsonerningtheourreneof theaumulatorz andofnestedreur-
sivealls are notexamined (i.e., therequirements(D) and (E)are missing there). Another
important dierene is that our rule allowsthe use of several dierent reursivearguments
r
1
;:::;r
k
andtheuseofseveral non-reursiveaseswitharbitrary results(whereasreversing
theformulationin[BW82℄ wouldonlyallowonesinglereursiveaseanditwouldonlyallow
the non-reursiveresult z instead of the arbitrary terms r
k +1
;:::;r
m
). Note that for this
reasoninourrulewehavetoregardall asesofanalgorithmatone.
Asan exampleonsider thefollowingalgorithmto ompute themultipliation ofall ele-
mentsin alist, where howeverourring0'sare ignored. Weuseadata typelist for listsof
naturals withthe onstrutorsnil:listand ons:natlist!list, where ar:list!nat and
dr:list!list aretheseletorsto ons.
proedureprod(l:list;z:nat)(
z:=s(0);
whilel6=nil do ifar(l)6=0thenz:=ar(l)z;
l:=dr(l) od
This proedure an be translated automatially into the following funtions (here, we re-
orderedtheasesofprtoeasereadability).
funtion prod(l:list):nat (
pr(l;s(0))
funtion pr(l:list;z:nat):nat (
ifl=nil thenz
ifar(l)6=0thenpr(dr (l);ar(l)z)
else pr(dr (l);z)
Totransformthe algorithm pr, weindeed need atehniquewhih anhandle algorithms
s(0)resultsin
funtion prod(l:list):nat (
pr(l)
funtion pr(l:list):nat (
ifl=nil thens(0)
ifar(l)6=0thenar(l)pr(dr(l))
else pr(dr (l)).
Further algorithms with several reursive and non-reursive ases where ontext moving is
requiredarepresentedin Appendix B.
Moreover,asomewhatrelatedtehniquewasdisussedin[Moo75℄. However,inontrastto
ourrule,histransformationisnotequivalene-preserving,butitorrespondsto ageneraliza-
tion of theonjeture. Forthat reasonthisapproahfaes thedangerofover-generalization
(e.g., the assoiativitylawfor multiply is generalizedinto aawed onjeture). Itturns out
that foralmost allalgorithms onsideredin [Moo75℄ ourtransformationtehniques angen-
erateequivalent algorithmsthatare easytoverify. Soforsuhexamples,generalizationsare
nolongerneeded.
4 Context Splitting
Beause of therequired left-ommutativity, ontext movingis notalways appliable. As an
exampleregardthefollowingimperativeproedure foruniting lists. Weuseadatatypellist
forlistsoflist's. Itsonstrutorsareemptyandaddwiththeseletorshd andtl. Soadd(z;k)
representsthe insertion of thelist z in front of the list of listsk and hd(add(z;k))yields z.
Moreover,weuseanalgorithmappforlist-onatenation. Thenafter exeutionofunion(k;z),
thevalueofz istheunionofalllistsink.
proedureunion(k:llist;z:list)(
z:=nil;
whilek6=emptydoz:=app(hd(k);z);
k:=tl(k) od
Translationofunion intofuntionalalgorithmsyields
funtionunion(k:llist):list (
uni(k;nil)
funtionuni(k:llist;z:list):list (
ifk6=emptythenuni(tl(k);app(hd(k);z))
else z.
These funtions are again unsuitedfor veriation, beause the aumulator z of uni is
initially alled with nil, but this value is hanged in the reursive alls. Context moving
is not possible, beause the ontext app(hd(k);:::) is not left-ommutative. This motivates
the development of the followingontext splitting transformation. Given alist of lists k =
[z
1
;:::;z
n
℄,theresultofuni(k;nil)is
app(z
n
;app(z
n 1
;:::app(z
3
;app(z
2
;z
1
)):::)): (10)
Inorderto movetheontextofuni's reursiveaumulatorargumentto thetop,ouraim
isto omputethis resultinawaysuh that z
1
ismovedasfarto the\outside"in thisterm
aspossible(whereasz
n
maybemovedtothe\inside"). Althoughappisnotommutative,it
isatleastassoiative. So(10)isequalto
app(app(:::app(app(z
n
;z
n 1 );z
n 2 ):::;z
2 );z
1
): (11)
This gives an idea on how the algorithm uni may be transformed into a new (unary) al-
gorithm uni 0
suh that uni 0
(k) omputes uni(k;nil). The result of uni 0
([z
1
;:::;z
n
℄) should
beapp(uni([z
2
;:::;z
n
℄);z
1
). Similarly, uni([z
2
;:::;z
n
℄) app(uni([z
3
;:::;z
n
℄);z
2
), et. Finally,
uni 0
([z
n
℄)isapp(uni 0
(empty);z
n
). Toobtaintheresult(11),app(uni 0
(empty);z
n
)mustbeequal
to z
n
. Hene, uni 0
(empty) should yield app's neutral argumentnil. Thus, weobtainthe fol-
lowingnewalgorithms,whih arewellsuitedforveriationtasks.
funtionunion(k:llist):list (
uni 0
(k)
funtionuni 0
(k :llist):list (
ifk6=emptythenapp(uni 0
(tl (k));hd(k))
else nil
Sotheideaisto splitup the formerontextapp(hd(k);:::) into anouter partapp(:::;:::)
and an inner part hd(k). If the outer ontext is assoiative, then one an transform tail
reursiveresultsoftheformf(:::;app(hd(k);z))intoresultsoftheformapp(f 0
(:::);hd(k)). In
general, ourontextsplitting rule generates anew algorithm (13)from analgorithm of the
form(12).
funtion f(x
:
;z:): (
ifb
1
thenf(r
1
;p[r
1
;z℄)
.
.
.
ifb
k
thenf(r
k
;p[r
k
;z℄) (12)
ifb
k +1
thenp[r
k +1
;z℄
.
.
.
ifb
m
thenp[r
m
;z℄
funtion f 0
(x
:
): (
ifb
1
thenp[f 0
(r
1 );r
1
℄
.
.
.
ifb
k
thenp[f 0
(r
k );r
k
℄ (13)
ifb
k +1
thenr
k +1
.
.
.
ifb
m
thenr
m .
Here, p is a term of type ontaining exatly the two new variables x
1 and x
2
of type
andp[t
1
;t
2
℄abbreviatesp[x
1
=t
1
;x
2
=t
2
℄. Thenourtransformationsplitstheontextsintotheir
ommon top part p and their spei part r
i
and it movesthe ommon part pto the top
of reursiveresults. (This allowsan elimination of the aumulator z.) If there are several
possiblehoiesforp,thenweusetheheuristitohoosepassmallandr
i
asbigaspossible.
Letebeaonstrutorgroundtermwhihisaneutralargumentofp,i.e.,F j=
ind
p[x;e℄x
andF j=
ind
p[e;x℄x. Then in(12),onemayalsohavez insteadof p[e;z℄. Forexample,in
uniwehadthenon-reursiveresultz insteadofapp(nil;z). Moreoverwedemand m>k1,
buttheorderofthef-asesisagainirrelevantandtherulemayalsobeappliedifz isnotthe
last parameteroff.
We want to ensure that all ourrenes of f(t
;e) in other algorithms g (that f is not
dependenton)maybereplaedbyf 0
(t
). Forthesoundnessofthistransformation,similarto
ontextmoving,theaumulatorzmustnotourinonditionsorin thesubtermsr
1
;:::;r
k
orr
1
;:::;r
m
. Thenforonstrutorgroundtermsu
,theevaluationoff(u
;e)andoff 0
(u
)
leadsto thesameasesi
1
;:::;i
d
wherei
1
;:::;i
d 1
2f1;:::;kgandi
d
2fk+1;:::;mg. For
1hdleta
h ber
ih [r
i
h 1 [:::[r
i
1 [u
℄℄:::℄℄. Thentheresultoff(u
;e)is(14)andtheresult
off 0
(u
)is(15).
p[a
d
;p[a
d 1
;:::p[a
2
;a
1
℄:::℄℄ (14)
p[p[:::p[p[a
d
;a
d 1
℄;a
d 2
℄:::a
2
℄;a
1
℄ (15)
To ensure the equality of these two results, p must be assoiative. The following theorem
summarizesourruleforontextsplitting.
5
Theorem2(Soundnessof Context Splitting) LetF beafuntionalprogramontaining
(12) and let F 0
result from F by adding the algorithm (13). Then for all data objets t
andq,f(t
;e)evaluates toq in F i f 0
(t
) evaluatestoq in F 0
,provided that the following
requirementsarefullled:
(A) z62V(b
1
)[:::[V(b
m )
5
Again,theproofanbefoundinAppendixA.
(B) z62V(r
1
)[:::[V(r
k )[V(r
1
)[:::[V(r
m )
(C) F j=
ind p[p[x
1
;x
2
℄;x
3
℄p[x
1
;p[x
2
;x
3
℄℄
(D) F j=
ind
p[x;e℄x andF j=
ind
p[e;x℄x.
Context splitting is only applied if there is a term f(t
;e) in some other algorithm g
that f is not dependent on. In this ase, the onditions (C) and (D) are heked by an
underlyingindutiontheoremprover(whereusuallyassoiativityiseveneasiertoprovethan
(left-) ommutativity). Conditions (A) and (B) are just syntati. In ase of suess, f 0
is
generatedandthetermf(t
;e)in thealgorithmg isreplaedbyf 0
(t
).
Similartoontextmoving,avariantoftheaboveruleifoftenusedinthereverse diretion
(re-braketing,f.e.g.[Coo66,DB76,BD77,Wan80,BW82,PP96℄). Again,insteadofdiretly
reversingthetehnique,wemodied andgeneralizedthis method, e.g.,by regardingseveral
tailreursiveand non-tailreursiveases. An algorithmwhere this generalformof ourrule
is needed will be presented in Setion 5 and several others an be found in Appendix B.
Moreover,inthenextsetionwewillalsointrodueimportantrenementswhihinreasethe
appliabilityofontext splittingonsiderablyand whih havenoounterpartin thelassial
re-braketingrules.
5 Rened Context Splitting
Arenementofourontextsplittingtehniqueanbeusedforexampleswheretheontextp
isnotyetin therightform. Regardthefollowingimperativeproedureforreversinglists.
proedurereverse(l;z:list)(
z:=nil;
whilel6=nildo z:=ons(ar(l);z);
l:=dr(l) od
Bytranslatingreverseintofuntionalform oneobtains
funtion reverse (l:list):list(
rev (l;nil)
funtion rev (l;z:list):list(
ifl6=nilthenrev (dr(l);ons(ar (l);z))
else z.
Inorder to eliminatethe aumulator z, wewouldlike to apply ontextsplitting. Here,
thetermpin(12)wouldbeons(x
1
;x
2
). Butthenx
1
wouldbeavariableoftypenat(instead
oflistasrequired)andhene,theassoiativitylawisnotevenwelltyped.
Whenever p has the form (x
1
;:::;x
1
;x
2
) for some onstrutor , where x
1
is of the
\wrong" type, then one may use the following reformulation of the algorithm. (Of ourse,
here x
2
does not have to be the last argument of .) The idea is to \lift" x
1
;:::;x
1 to
an objetlift
(x
1
;:::;x
1
) of type and to dene a new funtion 0
: ! suh that
0
(lift
(x
1
;:::;x
1 );x
2 )(x
1
;:::;x
1
;x
2
). Moreover,in order tosplit ontexts afterwards, 0
shouldbeassoiative.
Asaheuristi,weusethefollowingonstrutionforlift
and
0
,providedthat apartfrom
thedata type just hasaonstantonstrutor
on
. Thefuntion lift
(x
1
;:::;x
n
) should
yield the term (x
1
;:::;x
n
;
on
) and the funtion 0
is dened by the following algorithm
(whered
1
;:::;d
n+1
aretheseletorsto ).
funtion 0
(x;z:): (
ifx=(d
1
(x);:::;d
n (x);d
n+1
(x))then(d
1
(x);:::;d
n (x);
0
(d
n+1 (x);z))
else z
Then 0
(lift
(x
1
;:::;x
n
);z)(x
1
;:::;x
n
;z),
on
is aneutralargumentfor 0
, and 0
is
assoiative. Soforrev ,weobtainlift
ons (x
1
)ons(x
1
;nil)and
funtion ons(x;z:list):list (
ifx=ons(ar(x);dr (x))thenons(ar(x);ons 0
(dr (x);z))
else z.
Notethatin thisexample,ons 0
orrespondsto theonatenationfuntionapp.
Thus,thetermons(ar(l);z)inthealgorithmrevmaybereplaedbyons 0
(lift
ons
(ar (l));
z), i.e., by ons 0
(ons(ar(l);nil);z). Now the rule for ontext splitting is appliable whih
yields
funtion reverse (l:list):list(
rev 0
(l)
funtion rev 0
(l:list):list(
ifl6=nilthenons 0
(rev 0
(dr(l ));ons (ar(l );nil))
else nil.
In ontrast to the original versions of reverse and rev, these algorithms are well suited for
veriation.
Of ourse, there are also exampleswhere the ontext p has the form g(x
1
;x
2
) for some
algorithm g (instead of aonstrutor ) and where x
1
hasthe \wrong" type. For instane,
regardthefollowingimperativeproeduretolterallevenelementsoutofalistl. Itusesan
auxiliaryalgorithmeven andanalgorithm atend(x;z)whihinsertsanelementx at theend
ofalistz.
funtion atend(x:nat;z:list):list(
ifz=nilthenons(x;nil)
else ons(ar(z);atend(x;dr (z)))
Nowtheproedurelterreadsasfollows.
proedurelter(l;z:list)(
z:=nil;
whilel6=nil do ifeven(ar(l))thenz:=atend(ar(l);z);
l:=dr(l) od
Translatingthis proedureintofuntionalalgorithmsyields
funtion lter(l:list):list(
l(l;nil)
funtion l(l;z:list):list(
ifl=nil thenz
ifeven(ar(l))thenl(dr (l);atend(ar(l);z))
else l(dr (l);z).
Toapplyontext splittingforl, pwouldbeatend(x
1
;x
2
)andthus, x
1
wouldbeoftype
natinsteadoflistas required. Whileforonstrutorslikeons,suh aproblemanbesolved
bythe lifting tehniquedesribedabove, nowthe root of pisthealgorithm atend. Forsuh
examples,thefollowingparameter enlargement transformationoftenhelps.
Inthealgorithmatend,outsideofitsownreursiveargumenttheparameterxonlyours
in the term ons(x;nil) and the value of ons(x;nil) does not hange throughout the whole
exeution of atend (as the value of x does not hange in any reursive all). Hene, the
parameter x an be \enlarged" into a new parameter y whih orresponds to the value of
ons(x;nil). Thus, weresultin thefollowingalgorithm atend 0
, whereatend 0
(ons(x;nil);z)
atend(x;z).
funtion atend 0
(y;z:list):list(
ifz=niltheny
else ons(ar(z);atend 0
(y;dr(z)))
Ingeneral,leth(x
;z
)beafuntionwheretheparametersx
arenothangedinreursive
alls and where x
only ourwithin the termst
1
;:::;t
m
outside of their reursivealls in
the algorithm h. If V(t
i
) fx g for all i and if the t
i
only ontain total funtions (like
onstrutors), then one may onstrut a new algorithm h 0
(y
1
;::: ;y
m
;z
) by enlarging the
parameters x
into y
1
;:::;y
m
. The algorithm h 0
results from h by replaing all t
i by y
i ,
wheretheparametersy
i
againremainunhangedintheirreursivearguments. Thenwehave
h 0
(t
1
;:::;t
m
;z
) h(x
;z
). Thus, in all algorithms f that his not dependent on, we may
replaeanysubtermh(s
;p
)byh 0
(t
1 [x
=s
℄;:::;t
m [x
=s
℄;p
). (Theonlyrestritionforthis
replaementisthat allpossiblyundenedsubtermsofs
muststillourinsomet
i [x
=s
℄.)
Hene,inthealgorithml, thetermatend(ar (l);z)anbereplaedbyatend 0
(ons(ar(l);
nil);z). It turnsoutthat atend 0
(l
1
;l
2
) onatenatesthelists l
2 and l
1
(i.e., itorrespondsto
app(l
2
;l
1
)). Therefore, atend 0
is assoiativeand thus, ontext splitting an be applied to l
now. Thisyieldsthefollowingalgorithmswhih arewellsuitedforveriation.
funtionlter(l:list):list(
l 0
(l)
funtionl 0
(l:list):list(
ifl=nil thennil
ifeven(ar(l))thenatend 0
(l 0
(dr (l));ons(ar(l);nil))
else atend 0
(l 0
(dr (l));nil)
Ofourse,bysubsequentunfolding(or\symbolievaluation")ofatend 0
,thealgorithml 0
anbesimpliedto
funtion l 0
(l:list):list(
ifl=nil thennil
ifeven(ar(l))thenons(ar(l);l 0
(dr(l)))
else l 0
(dr (l)).
Notethathereweindeedneededaontextsplittingrulewhihanhandlealgorithmswith
several tailreursiveases. Thus,adiretreversalofthelassialre-braketingrules[BW82℄
wouldfail forbothreverseandlter(sinetheserulesarerestritedtojust onereursivease
andmoreover,theylaktheoneptsof liftingandofparameterenlargement).
Theexamplesunion,reverse ,andltershowthatontextsplittinganhelpinaseswhere
ontextmovingisnotappliable. Ontheotherhandforalgorithmslikeplus,ontextmovingis
suessful,butontextsplittingisnotpossible. Sononeofourtwotransformationssubsumes
theotherandtoobtainapowerfulapproah,weindeedneedboth ofthem. Buttherearealso
severalalgorithmswheretheveriationproblemsanbesolvedbybothontextmovingand
splitting. Forexample,thealgorithmsresultingfrommultbyontextmovingorsplittingonly
dierin the order ofthe argumentsof +in mult's rstreursivease. Thus, both resulting
algorithmsarewellsuitedforveriationtasks.
6 Conlusion
We have presented a new transformationalapproah for the mehanized veriation of im-
perative programs and tail reursive funtions. By our tehnique, funtions that are hard
to verify are automatially transformedinto funtions where veriation issigniantlyeas-
ier. Hene, for many programs the invention of loop invariants or of generalizations is no
longer requiredand an automatedveriationis possibleby theexisting indution theorem
provers. As our transformations generate equivalent funtions, this transformational veri-
ation approah is not restrited to partial orretness, but it an also be used to simpli-
fy total orretness and terminationproofs [Gie95, Gie97, GWB98, AG99, BG99℄. See Ap-
pendixBforaolletionofexamplesthat demonstratesthepowerofourapproah. Itshows
thatourtransformationindeedsimpliestheveriationtaskssubstantiallyformanyprati-
allyrelevantalgorithmsfromdierentareasofomputersiene(e.g.,arithmetialalgorithms
orproeduresforproessing(possiblymultidimensional)listsinludingalgorithmsformatrix
multipliationand sortingalgorithms likeseletion-, insertion-,andmerge-sort,et.). Based
tionsautomatially[Gie99a℄.
Theeld ofmehanized veriationand indution theorem provingrepresentsanewap-
pliationareaforprogramtransformationtehniques. Itturnsoutthatourapproahoftrans-
formingalgorithmsoftenseemstobesuperiortothelassialsolutionofgeneralizingtheorems.
Forinstane, ourtehniqueautomatially transformsall(rstorder) tailreursivefuntions
treatedinreentgeneralizationtehniques[IS97,IB99℄intonon-tailreursiveoneswhosever-
iation is very simple. On the other hand, the tehniques for nding generalizations are
mostlysemi-automati(sinetheyareguidedbythesystemuserwhohastoprovidesuitable
lemmata). Obviously, by formulating the right lemmata(interatively), in priniple gener-
alization tehniques an dealwith almost every onjeture to be proved. Butin partiular
foronjetureswhihinvolveseveral ourrenesofatailreursivefuntion,ndingsuitable
generalizations is often impossible for fully automati tehniques. Therefore, our approah
representsasigniantontributionfor mehanizedveriationofimperativeandtailreur-
sive funtional programs. Nevertheless, of ourse there also exist tail reursive algorithms
where our automati transformations are not appliable. For suh examples, (interative)
generalizationsarestill required.
Furtherwork will inludean examinationofother existing programtransformationteh-
niquesinordertodeterminewhethertheyanbemodiedintotransformationssuitableforan
appliationintheprogramveriationdomain. Moreover,infutureworktheappliationarea
ofprogramveriationmayalsogiveriseto newtransformationswhihhavenoounterpart
atallin lassialprogramtransformations.
A Proofs
Theorem1(Soundnessof Context Moving) Let F be a funtional program ontaining
the algorithm(6)andletF 0
resultfromF byreplaing (6)with(7). Thenfor alldataobjets
t
, t, and q, f(t
;t) evaluates to q in the program F i it does so in F 0
, provided that the
followingrequirementsarefullled:
(A) z62V(b
1
)[:::[V(b
m )
(B) z62V(r
1
)[:::[V(r
k )
(C) For alli2f1;::: ;mg,i 0
2f1;:::;kg: F j=indri[x
;r
i 0
[y
;z℄℄r
i 0
[y
;ri[x
;z℄℄
(D)z2V(r
1
)\:::\V(r
m )
(E) Inr
1
;:::;r
m
,z does notour inargumentsoffuntionsdependenton f.
Proof. For the\if"-diretion,werstprovethefollowingontextmovinglemmaforall on-
strutorgroundtermsu
, v
,w,q andalli 0
2f1;:::;kg:
IfF j=
ind r
i 0[v
;f(u
;w)℄q,thenF j=
ind f(u
;r
i 0[v
;w℄)q. (16)
Weuseanindutiononthelengthofr
i 0
[v
;f(u
;w)℄'sevaluation. DuetoCondition(D),
we have z 2 V(r
i 0
) and thus, evaluation of f(u
;w) is dened as well. Hene, there is an
i 2f1;:::;mg suh that b
i [u
℄
F
true andb
j [u
℄
F
false for all1j <i, where s
F t
abbreviatesF j=
ind
st. Ifik+1,then
r
i 0
[v
;f(u
;w)℄
F r
i 0
[v
;r
i [u
;w℄℄
F r
i [u
;r
i 0
[v
;w℄℄; by(C)
F f(u
;r
i 0
[v
;w℄); sinez2V(r
i
)(by(D)).
Ifik,thenwehave
r
i 0
[v
;f(u
;w)℄
F r
i 0
[v
;f(r
i [u
℄;r
i [u
;w℄)℄
F f(r
i [u
℄;r
i 0
[v
;r
i [u
;w℄℄); bytheindution hypothesis
F f(r
i [u
℄;r
i [u
;r
i 0
[v
;w℄℄); by(C)
F f(u
;r
i 0
[v
;w℄); sinez2V(r
i
)(by(D)).
indution on the length of f(t
;t)'s evaluation in F 0
. There must be an i 0
2 f1;:::;mg
suh that b
i 0[t
℄
F
0 true and b
j 0[t
℄
F
0 false forall 1j 0
<i 0
. Theindution hypothesis
impliesb
i 0[t
℄
F
trueand b
j 0[t
℄
F
falseaswell.
Ifi 0
k+1,thentheonjeturefollowsfromf(t
;t)
F 0
r
i 0
[t
;t℄,f(t
;t)
F r
i 0
[t
;t℄,and
theindutionhypothesis. Ifi 0
k,thenwehavef(t
;t)
F 0
r
i 0
[t
;f(r
i 0
[t
℄;t)℄
F 0
qforsome
onstrutorgroundtermq. Bytheindutionhypothesisweobtainr
i 0
[t
;f(r
i 0[t
℄;t)℄
F qand
Lemma(16)impliesf(r
i 0
[t
℄;r
i 0
[t
;t℄)
F r
i 0
[t
;f(r
i 0
[t
℄;t)℄. Asf(t
;t)
F f(r
i 0
[t
℄;r
i 0[t
;t℄),
the\if"-diretionofThm.1isproved.
Theproofforthe\onlyif"-diretionhasasimilarstruture,butinsteadofanindutionon
thelengthoftheevaluation,weneedanindutionw.r.t.therelation
f
. Here,u
f q
holds
fortheonstrutorgroundtermsu
andq
ithereexistonstrutorgroundtermsuandqsuh
thatf(u
;u)isdenedinF andsuhthatF-evaluationoff(u
;u)leadstothereursiveall
f(q
;q). Thereasonforthisasymmetryintheproofisthattheleft-ommutativityondition
(C)isonlydemanded fortheoriginalprogramF.
Notethatbytherequirements(A),(B),and(E),u
f q
impliesthatforall onstrutor
groundtermsuwheref(u
;u) isdened,thereexistsaonstrutorgroundtermqsuh that
evaluationof f(u
;u)leadsto evaluationof f(q
;q). Hene,
f
is wellfounded (i.e.,it may
indeedbeusedforindutionproofs). NowthereversediretionofLemma(16)anbeproved
byindutionw.r.t.
f .
IfF j=
ind f(u
;r
i 0
[v
;w℄)q,thenF j=
ind r
i 0
[v
;f(u
;w)℄q. (17)
The proof of (17) is analogous to the one of (16), but if evaluation of f(u
;r
i 0
[v
;w℄)
leads to exeution of a ase i with i k, then we need the indution hypothesis to infer
f(r
i [u
℄;r
i 0
[v
;r
i [u
;w℄℄)
F r
i 0
[v
;f(r
i [u
℄;r
i [u
;w℄)℄. This would not be possible if we
performedindution on thelength of theevaluation, but it anbedonewith our indution
relation,siner
i [u
℄
F q
forsomeonstrutorgroundtermsq
withu
f q
.
Finally, the \only if"-diretion of the theorem is also proved by indution w.r.t.
f . If
F-evaluation off(t
;t) leadstothei 0
-thaseand i 0
k+1,thentheproofisanalogous to
the\if"-diretion. Ifi 0
k,thenwehavef(t
;t)
F f(r
i 0
[t
℄;r
i 0[t
;t℄)
F r
i 0[t
;f(r
i 0[t
℄;t)℄
byLemma(17). Notethatforallf-subtermsf(s
;s)inthisterm,s
evaluatestoonstrutor
ground terms q
with t
f q
. Forf-subterms where the root is in r
i 0
, this follows from
Condition (E). (However, the length of the evaluation r
i 0
[t
;f(r
i 0
[t
℄;t)℄ is not neessarily
smallerthantheoneoff(t
;t), i.e.,wereallyneedanindutionw.r.t.
f .)
Then by the indution hypothesis, r
i 0
[t
;f(r
i 0
[t
℄;t)℄
F
q for some onstrutor ground
termqimpliesr
i 0
[t
;f(r
i 0
[t
℄;t)℄
F 0
q andhene,f(t
;t)
F 0
q. 2
Theorem2(Soundnessof Context Splitting) LetF beafuntionalprogramontaining
(12) and let F 0
result from F by adding the algorithm (13). Then for all data objets t
andq,f(t
;e)evaluates toq in F i f 0
(t
) evaluatestoq in F 0
,provided that the following
requirementsarefullled:
(A) z62V(b
1
)[:::[V(b
m )
(B) z62V(r
1
)[:::[V(r
k )[V(r
1
)[:::[V(r
m )
(C) F j=
ind p[p[x
1
;x
2
℄;x
3
℄p[x
1
;p[x
2
;x
3
℄℄
(D) F j=
ind
p[x;e℄x andF j=
ind
p[e;x℄x.
Proof. Notethatevaluationoff isthesamein F andF 0
. Moreover,Conditions(C)and(D)
alsoholdforF 0
. Weprovethe(stronger)onjeture
f(t
;t)
F 0
q i p[f 0
(t
);t℄
F 0
q (18)
forallonstrutorgroundtermst ,t,andq.
The\onlyif"-diretionof(18)isprovedbyindutiononthelengthoff(t
;t)'sevaluation.
Theremustbeani2f1;:::;mgsuhthatb
i [t
℄
F
0 trueandb
j [t
℄
F
0 falseforall1j<i.
Ifik+1,thenwehave
f(t
;t)
F 0
p[r
i [t
℄;t℄
F 0
p[f 0
(t
)t℄:
Ifik,thenweobtain
f(t
;t)
F 0
f(r
i [t
℄;p[r
i [t
℄;t℄)
F 0
p[f 0
(r
i [t
℄);p[r
i [t
℄;t℄℄; bytheindution hypothesis
F 0
p[p[f 0
(r
i [t
℄);r
i [t
℄℄;t℄; by(C)
F 0
p[f 0
(t
);t℄:
Forthe\if"-diretionof(18)weuseanindution w.r.t.therelation
f 0,
whereu
f 0
q
holdsfortwotuplesofonstrutor groundtermsu
andq
ievaluation off 0
(u
)is dened
anditleadsto evaluation off 0
(q
).
As x
1
2 V(p), evaluation of f 0
(t
) is dened and thus, it results in exeution of some
asei. Nowtheproofisanalogoustothe\onlyif"-diretion. (Notethat ifik,toonlude
p[f 0
(r
i [t
℄);p[r
i [t
℄;t℄℄
F 0 f(r
i [t
℄;p[r
i [t
℄;t℄),wereallyneedanindutionw.r.t.
f
0,whereas
anindutiononthelengthoftheevaluationdoesnotwork.) 2
B Examples
This setion ontains a olletion of 55 tail reursive algorithms where ontext moving or
ontextsplitting anbeappliedin orderto transformthem intoalgorithmswhihare better
suitedfor(possiblymehanized)veriation.
B.1 plus
Thisalgorithmaddstwonumbers.
funtion plus(x;z:nat):nat (
ifx=0thenplus(p(x);s (z))
else z
Contextmovingandreplaingzwith0resultsin
funtion plus(x;z:nat):nat (
ifx=0thens(plus(p(x);z))
else z.
Inthefollowing,weoftenabbreviatepluswith+.
B.2 multiply
The followingtail reursivemultipliationalgorithm wasusedto introduethe tehniqueof
ontextmovingin thepaper.
funtion multiply(x;y:nat):nat ( mult(x;y;0)
funtion mult(x;y;z:nat):nat (
ifx6=0thenmult(p(x);y;y+z)
else z
z inthealgorithmmultanbereplaedby0.
funtion multiply(x;y:nat):nat ( mult(x;y)
funtion mult(x;y:nat):nat (
ifx6=0theny+mult(p (x);y)
else 0
Ofourse,in thisandallotherorrespondingexamples,onemayalsoexhangeases,ex-
hangetheparametersxandy,and(resp.or)exhangetheargumentsoftheleft-ommutative
funtion (\+"in theaboveexample). Theorrespondingtransformation byontext moving
would still bepossible. Inthe following, we often abbreviatemultipliation algorithms like
timesormultiplywith.
Notethatasuitabletransformationofmultiplywouldalsobepossiblebyontextsplitting.
Thiswouldyield
funtion multiply(x;y:nat):nat ( mult 0
(x;y)
funtion mult 0
(x;y:nat):nat (
ifx6=0thenmult 0
(p(x);y)+y
else 0.
Bothresultingversionsofmultiplyarewellsuitedforveriationtasks. Similarly,inmany
ofthefollowingexamples(wherewehaveabinary left-ommutativeauxiliaryfuntionwhose
bothargumentsareof thesametype),insteadofontext movingoneouldalso useontext
splitting.
B.3 multiply2
This algorithm also omputesmultipliation, but in ontrast to multiply it does notuse an
auxiliary algorithm for addition. Instead, the addition is enoded into the multipliation
algorithmaswell.
funtion multiply2(x;y:nat):nat ( mult2(x;y;y;0)
funtion mult2(x;y;r;z:nat):nat (
ifx=0thenz
ifr=0 thenmult2(p(x);y;y;z)
else mult2(x;y;p(r);s (z))
Notethatthisalgorithmrequirestheuseofatransformationrulewhihanhandleseveral
reursiveases. Contextmovingandreplaementoftheparameterz by0yields
funtion multiply2(x;y:nat):nat ( mult2(x;y;y)
funtion mult2(x;y;r:nat):nat (
ifx=0then0
ifr=0 thenmult2(p(x);y;y)
else s(mult2(x;y;p(r))).
Thenextalgorithm dupliatesnaturalnumbers.
funtion double(x:nat):nat ( do(x;0)
funtion do(x;z:nat):nat (
ifx=0thenz
else do(p(x);s (s(z)))
Here,ontextmoving(andreplaingzwith0) resultsin
funtion double(x:nat):nat ( do(x)
funtion do(x:nat):nat (
ifx=0then0
else s(s (do(p(x)))).
B.5 half
Thenextalgorithm halvesnaturalnumbers,i.e.,half(x) omputesb x
2 .
funtion half(x:nat):nat ( ha(x;0)
funtion ha(x;z:nat):nat (
ifx=0 thenz
ifx=s(0)thenz
else ha(p(p(x));s (z))
Contextmoving(andreplaingz with0)resultsin
funtion half(x:nat):nat ( ha(x)
funtion ha(x:nat):nat (
ifx=0 then0
ifx=s(0)then0
else s(ha(p(p(x)))).
B.6 half2
Similarly, the following algorithm also halves natural numbers, but it works from \top to
bottom".
funtion half2(x:nat):nat ( ha2(x;x)
funtion ha2(x;z:nat):nat (
ifx=0 thenz
ifx=s(0)thenp(z)
else ha2(p (p(x));p (z))
Note that here we need our ontext moving rule whih an deal with several dierent
non-reursiveresults. Inthis way,weresultin
funtion half2(x:nat):nat ( ha2(x;x)
funtion ha2(x;z:nat):nat (
ifx=0 thenz
ifx=s(0)thenp(z)
else p(ha2(p(p(x));z)).
The following is again a multipliation algorithm, but this time even numbers are treated
dierentlyfromoddones.
funtion multiply3(x;y:nat):nat ( mult3(x;y;0)
funtion mult3(x;y;z:nat):nat (
ifx=0 thenz
ifeven(x)thenmult3(half(x);double(y);z)
else mult3(p(x);y;y+z)
Notethat thisalgorithm again requires atransformation rulethat andealwith several
reursiveases. Ourontextmovingruleyields thefollowingalgorithms(where wereplaed
allourrenesofz by0again).
funtion multiply3(x;y:nat):nat ( mult3(x;y)
funtion mult3(x;y;z:nat):nat (
ifx=0 then0
ifeven(x)thenmult3(half(x);double(y))
else y+mult3(p(x);y)
B.8 multiply su
Thefollowingalgorithmomputesxy+1.
funtion multiply su(x;y:nat):nat ( multsu(x;y;0)
funtion multsu(x;y;z:nat):nat (
ifx6=0thenmultsu(p(x);y;y+z)
else s(z)
Althoughthenon-reursiveresulthasadierentontextsthanthereursiveaumulator
argument,weanstillapplyontextmoving. Forthedesiredleft-ommutativeooperationof
r
2 and r
1
onehastoprove
s(y+z)y+s(z);
whih is in fat true. Subsequently, all ourrenes of z in the algorithm multsu an be
replaedby0.
funtion multiply su(x;y:nat):nat ( multsu(x;y)
funtion multsu(x;y :nat):nat (
ifx6=0theny+multsu(p(x);y)
else s(0)
B.9 minus
Similartohalfand half2oneanalsotransformorrespondingsubtrationalgorithms. Here,
weuseanauxiliaryalgorithm>fortheusualgreater-relationonnaturals.
funtion minus(x;y:nat):nat ( mi(x;y;0)
funtion mi(x;y;z:nat):nat (
ifx>y thenmi(p(x);y;s(z))
else z.
funtion minus(x;y:nat):nat ( mi(x;y)
funtion mi(x;y:nat):nat (
ifx>y thens(mi(p(x);y))
else 0.
B.10 minus2
Analogously,thisalternativesubtrationalgorithmworksfrom \toptobottom".
funtion minus2(x;y:nat):nat (
ify=0thenx
else minus2(p(x);p (y))
Aspisalsoleft-ommutative,ontext movingyields
funtion minus2(x;y:nat):nat (
ify=0thenx
else p(minus2(x;p(y))).
B.11 logarithm
The following algorithm omputesthe trunated logarithm w.r.t. base 2using an auxiliary
algorithm>.
funtion logarithm(x:nat):nat ( log(x;0)
funtion log(x;z:nat):nat (
ifx>s(0)thenlog(half(x);s (z))
else z
Contextmovingandreplaementoftheparameterz by0yields
funtion logarithm(x:nat):nat ( log(x)
funtion log(x:nat):nat (
ifx>s(0)thens(log(half(x)))
else 0.
B.12 power two
Thenextfuntion omputesthegreatestpowerof2thatislessthanorequalto x.
funtion powertwo(x:nat):nat ( pt(x;s(0))
funtion pt(x;z:nat):nat (
ifx>s(0)thenpt(half(x);double(z))
else z
Contextmovinganbeusedto movetheauxiliaryfuntion doubleto theoutside. After-
wards,areplaementoftheparameterz bys(0)yields
funtion powertwo(x:nat):nat ( pt(x)
funtion pt(x:nat):nat (
ifx>s(0)thendouble(pt(half(x)))
else s(0).
Thefollowingalgorithm omputesthetrunated divisionb x
y
usinganalgorithm for om-
paringnaturalnumbers. Here,\ "abbreviatesthealgorithmminus.
funtion quotient(x;y:nat):nat ( quot(x;y;0)
funtion quot(x;y;z:nat):nat (
ifxy thenquot(x y;y;s(z))
else z
Contextmovingandreplaementoftheparameterz by0yields
funtion quotient(x;y:nat):nat ( quot(x;y)
funtion quot(x;y :nat):nat (
ifxy thens(quot(x y;y))
else 0.
B.14 quotient2
This algorithm also omputes trunated division, but in ontrast to quotient this time the
subtration isenoded into thedivision algorithm aswell(this issimilar to the enoding of
additioninto themultipliationalgorithm multiply2inExample B.3). Theauxiliaryboolean
algorithmandforonjuntionisabbreviatedby^.
funtion quotient2(x;y:nat):nat ( quot2(x;y;y;0)
funtion quot2(x;y;r;z:nat):nat (
ifx=0^r=0thens(z)
ifx=0^r6=0thenz
if r=0thenquot2(x;y;y;s(z))
else quot2(p(x);y;p (r);z)
Notethatthisalgorithmrequirestheuseofatransformationrulewhihanhandleseveral
reursiveandnon-reursiveases. Context movingand replaementof theparameterzby 0
yields
funtion quotient2(x;y:nat):nat ( quot2(x;y;y)
funtion quot2(x;y;r:nat):nat (
ifx=0^r=0thens(0)
ifx=0^r6=0then0
if r=0thens(quot2(x;y;y))
else quot2(p(x);y;p (r)).
B.15 length
Thisalgorithmomputesthelengthofalist.
funtion length(l:list):nat ( len(l;0)
funtion len(l:list;z:nat):nat (
ifl=nilthenz
else len(dr (l);s(z))
funtion length(l:list):nat ( len(l)
funtion len(l:list):nat (
ifl=nilthen0
else s(len(dr (l))).
B.16 index
Thefuntion index(x;l)omputestherstindexz,suhthatthez-thelementoflisx. Here,
theleftmostelementoflhasindex0. Weagainuseanauxiliaryalgorithmandforonjuntion
(whih weabbreviateby^).
funtion index(x:nat;l:list):nat ( ind(x;l;0)
funtion ind(x:nat;l:list;z:nat):nat (
ifl6=nil^ ar(l)6=xthenind(x;dr (l);s(z))
else z
Contextmovingandreplaingzwith0resultsin
funtion index(x:nat;l:list):nat ( ind(x;l)
funtion ind(x:nat;l:list):nat (
ifl6=nil^ ar(l)6=xthens(ind(x;dr (l)))
else 0.
B.17 sum
Thefuntionsum omputesthesumofallelementsofalist.
funtion sum(l:list):nat ( su(l;0)
funtion su(l:list;z:nat):nat (
ifl=nilthenz
else su(dr (l);ar(l)+z)
Bytheleft-ommutativityof+,ontextmovingandreplaingz with0resultsin
funtion sum(l:list):nat ( su(l)
funtion su(l:list):nat (
ifl=nilthen0
else ar(l)+su(dr(l)).
B.18 weight
Similartothepreviousalgorithm, thefollowingalgorithmomputestheweighted sumofthe
elementsin alist. Inotherwords,wehaveweight([a
0
;:::;a
n
℄)= P
i=0;:::;n ia
i .
funtion weight(l:list):nat ( we(l;0;0)
funtion we(l:list;i;z:nat):nat (
ifl=nilthenz
else we(dr(l);s(i);iar(l)+z)
funtion we(l:list):nat ( we(l;0)
funtion we(l:list):nat (
ifl=nilthen0
else iar(l)+we(dr (l);s(i)).
B.19 ount even
This algorithm ounts the number of even elements in a list (using an auxiliary algorithm
even).
funtion ounteven(l:list):nat ( e(l;0)
funtion e(l:list;z:nat):nat (
ifl=nil thenz
ifeven(ar(l))thene(dr (l);s(z))
else e(dr (l);z)
Totransformthisalgorithm,weneedatehniquewhihanhandlealgorithmswithseveral
reursiveases. Contextmovingandreplaingz with0resultsin
funtion ounteven(l:list):nat ( e(l)
funtion e(l:list;z:nat):nat (
ifl=nil then0
ifeven(ar(l))thens(e(dr (l)))
else e(dr (l)).
Analogously,ontext movingwouldalsowork forsimilaralgorithms(i.e., a\ount" algo-
rithmwhere even elements are ounted twie whereas oddones are just ounted one, ora
\sum"algorithmwhih onlyaddstheevenelementsofalist).
B.20 prod
This algorithm (fromSetion 3) omputes themultipliation ofall elements in alist, where
howeverourring0'sareignored.
funtion prod(l:list):nat ( pr(l;s(0))
funtion pr(l:list;z:nat):nat (
ifl=nil thenz
ifar(l)6=0thenpr(dr(l);ar(l)z)
else pr(dr(l);z)
Totransformthisalgorithm,weagainneedatehniquewhihanhandlealgorithmswith
severalreursiveases. Sineisleft-ommutative,ontextmovingandreplaingzwiths(0)
resultsin
funtion prod(l:list):nat ( pr(l)
funtion pr(l:list):nat (
ifl=nil thens(0)
ifar(l)6=0thenar(l)pr(dr (l))
else pr(dr(l)).
Thefollowingalgorithmsumsalldigitsofanaturalnumber. Itusesthealgorithmsdiv 10and
mod10fortrunateddivisionby10andforomputingxmod10.
funtion sum digits(x:nat):nat ( sumd(x;0)
funtion sumd(x;z:nat):nat (
ifx=0thenz
else sumd(div 10(x);mod10(x)+z)
Dueto theleft-ommutativityof+,ontextmoving(andreplaingz with0)resultsin
funtion sum digits(x:nat):nat ( sumd(x)
funtion sumd(x:nat):nat (
ifx=0then0
else mod10(x)+sumd(div10(x)).
B.22 fatorial
Thenextalgorithmomputesthefatorialofx.
funtion fatorial(x:nat):nat ( fa(x;s(0))
funtion fa(x;z:nat):nat (
ifx=0thenz
else fa(p(x);xz)
Asisleft-ommutative,ontextmoving(andreplaingz withs(0))resultsin
funtion fatorial(x:nat):nat ( fa(x)
funtion fa(x:nat):nat (
ifx=0thens(0)
else xfa (p(x)).
B.23 exponent
Thenextalgorithm omputesx y
.
funtion exponent(x;y:nat):nat ( exp (x;y;s(0))
funtion exp(x;y;z:nat):nat (
ify=0thenz
else exp(x;p(y);xz)
Similarto fatorial, asis left-ommutative,ontext moving(and replaingz withs(0))
resultsin
funtion exponent(x;y:nat):nat ( exp (x;y)
funtion exp(x;y :nat):nat (
ify=0thens(0)
else xexp(x;p(y)).