/
212.PROGRAMCORRECTNESSItisappropriateinourstudyofmodernprogramminglang 212.PROGRAMCORRECTNESSItisappropriateinourstudyofmodernprogramminglang

212.PROGRAMCORRECTNESSItisappropriateinourstudyofmodernprogramminglang - PDF document

conchita-marotz
conchita-marotz . @conchita-marotz
Follow
376 views
Uploaded On 2016-05-07

212.PROGRAMCORRECTNESSItisappropriateinourstudyofmodernprogramminglang - PPT Presentation

412PROGRAMCORRECTNESSTable121SummaryofPredicateLogicNotation NotationMeaning truefalseBooleantruthconstantspqBooleanvariablespxyqxyBooleanfunctionspNegationofppqConjuncti ID: 309133

412.PROGRAMCORRECTNESSTable12.1:SummaryofPredicateLogicNotation NotationMeaning true falseBoolean(truth)constantsp;q;:::Booleanvariablesp(x;y:::);q(x;y:::);:::Booleanfunctions:pNegationofpp^qConjuncti

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "212.PROGRAMCORRECTNESSItisappropriateino..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

212.PROGRAMCORRECTNESSItisappropriateinourstudyofmodernprogramminglanguagestoexaminethequestionoflanguagefeaturesthatsupportthedesignofreliablesoftwaresystemsandhowthosefeaturesextendtheexpressivepowerofconventionallanguages.Thischapterthusaddressestheissueofprogramcorrectnessfromtheimportantperspectiveoflanguagefeaturesandprogrammingparadigms.A"correct"programisonethatdoesexactlywhatitsdesignersandusersintendittodo{nomoreandnoless.A"formallycorrect"programisonewhosecorrectnesscanbeprovedmathematically,atleasttoapointthatdesignersandusersareconvincedaboutitsrelativeabsenceoferrors.Foraprogramtobeformallycorrect,theremustbeawaytospecifypre-cisely(mathematically)whattheprogramisintendedtodo,forallpossiblevaluesofitsinput.Theseso-calledspeci cationlanguagesarebasedonmathe-maticallogic,whichwereviewinthenextsection.Aprogramminglanguage'sspeci cationlanguageisbasedaconceptcalledaxiomaticsemantics,whichwas rstsuggestedbyC.A.R.Hoareoverthreedecadesago[Hoare1969].Theuseofaxiomaticsemanticsforprovingthecorrectnessofsmallprogramsisintroducedinthethirdsectionofthischapter.Formallyprovingthecorrectnessofasmallprogram,ofcourse,doesnotaddressthemajorproblemfacingsoftwaredesignerstoday.Modernsoftwaresystemshavemillionsoflinesofcode,representingthousandsofsemanticstatesandstatetransitions.Thisinnatecomplexityrequiresthatdesignersuserobusttoolsforassuringthatthesystembehavesproperlyineachofitsstates.Untilveryrecently,softwaremodelinglanguageshadbeendevelopedassep-aratetools,andwerenotfullyintegratedwithpopularcompilersandlanguagesusedbyreal-worldprogrammers.Instead,theselanguages,liketheUniversalModelingLanguage(UML)[Booch1998],provideagraphicaltoolthatincludesanObjectConstraintLanguage(OCL)[Warmer1998]formodelingpropertiesofobjectsandtheirinterrelationshipsinasoftwaredesign.Becauseoftheirsepa-rationfromthecompiledcode,thesemodelinglanguageshaveservedmainlyforsoftwaredocumentationandasartifactsforresearchinsoftwaremethodology.However,withtherecentemergenceofEi el[Meyer1990],ESC/Java[Flana-gan2002],Spark/Ada[Barnes2003],JML[Leavens2004],andthenotionofdesignbycontract[Meyer1997],thissituationischangingrapidly.Thesenewdevelopmentsprovideprogrammerswithaccesstorigoroustoolsandveri cationtechniquesthatarefullyintegratedwiththerunitimesystemitself.Designbycontractisaformalismthroughwhichinteractionsbetweenobjectsandtheirclientscanbepreciselydescribedanddynamicallychecked.ESC/JAVAisacode-levellanguageforannotatingandstaticallycheckingaprogramforawidevarietyofcommonerrors.TheJavaModelingLanguage(JML)providescodelevelextensionstotheJavalanguagesothatprogramscanincludesuchformalspeci cationsandtheirenforcementatruntime.Spark/Adaisaproprietarysystemthatprovidessimi-larextensionstotheAdalanguage.Toexploretheimpactofthesedevelopmentsonprogramcorrectness,weillustratetheuseofJMLanddesignbycontractinthefourthsectionofthischapter.Functionalprograms,becauseoftheircloseapproximationtomathematical 412.PROGRAMCORRECTNESSTable12.1:SummaryofPredicateLogicNotation NotationMeaning true,falseBoolean(truth)constantsp;q;:::Booleanvariablesp(x;y:::);q(x;y:::);:::Booleanfunctions:pNegationofpp^qConjunctionofpandqp(x)_q(x)Disjunctionofpandqp(x))q(x)Implication:pimpliesqp(x),q(x)Logicalequivalenceofpandq8xp(x)Universallyquanti edexpression9xp(x)Existentiallyquanti edexpressionp(x)isvalidPredicatep(x)istrueforeveryvalueofxp(x)issatis ablePredicatep(x)istrueforatleastonevalueofxp(x)isacontradictionPredicatep(x)isfalseforeveryvalueofx Apredicatecombinesthesekindsoffunctionsusingtheoperatorsofthepropositionalcalculusandthequanti ers8(meaning\forall")and9(meaning\thereexists").Herearesomeexamples:0x^x1|trueifxisbetween0and1,inclusive;otherwisefalse.speaks(x;Russian)^speaks(y;Russian))communicateswith(x;y)|trueifthefactthatbothxandyspeakRussianimpliesthatxcommunicateswithy;otherwisefalse.8x(speaks(x;Russian))|trueifeveryoneontheplanetspeaksRussian;falseotherwise.9x(speaks(x;Russian))|trueifatleastonepersonontheplanetspeaksRussian;falseotherwise.8x9y(speaks(x;y))|trueifeverypersonontheplanetspeakssomelan-guage;falseotherwise.8x(:literate(x))(:writes(x)^:9y(book(y)^hasread(x;y))))|trueifeveryilliteratepersonxdoesnotwriteandhasnotreadabook.Table12.1summarizesthemeaningsofthedi erentkindsofexpressionsthatcanbeusedinpropositionalandpredicatelogic.Predicatesthataretrueforallpossiblevaluesoftheirvariablesarecalledvalid.Forinstance,even(x)_odd(x)isvalid,sinceallintegersxareeitherevenorodd.Predicatesthatarefalseforallpossiblevaluesoftheirvariablesarecalledcontradictions.Forinstance,even(x)^odd(x)isacontradiction,sincenointegercanbebothevenandodd. 612.PROGRAMCORRECTNESSTable12.3:InferenceRulesforPredicatesInferenceRuleMeaning Modusponensp;p)q`qModustollensp)q;:q`:pConjunctionp;q`p^qSimpli cationp^q`pAdditionp`p_qUniversalinstantiation8xp(x)`p(a)Existentialinstantiation9xp(x)`p(a)Universalgeneralizationp(x)`8xp(x)Existentialgeneralizationp(a)`9xp(x) predicateintheproofmustbetheargument'sconclusionq.Eachpredicateinthesequenceisaccompaniedbya\justi cation,"whichisabriefnotationofwhatderivationruleandwhatpriorstepswereusedtoarriveatthispredicate.SomeofthekeyinferencerulesforpredicatesaresummarizedinTable12.3.Tointerprettheserules,iftheexpression(s)ontheleftof`appearinaproof,theycanbereplacedlaterinthesequencebytheexpressionontheright(butnotviceversa).Belowisadirectproofofthefollowingargument:Everystudentlikescrosswordpuzzles.Somestudentslikeicecream.Therefore,somestudentslikeicecreamandcrosswordpuzzles.Supposeweassignthefollowingnamestothepredicatesinthisproblem:S(x)=\xisastudent"C(x)=\xlikescrosswordpuzzles"I(x)=\xlikesicecream"Thentheargumentcanberewrittenas:8x(S(x)!C(x))^9x(S(x)^I(x))!9x(S(x)^C(x)^I(x))Hereisadirectproofofthisargument:1.8x(S(x)!C(x))Hypothesis2.9x(S(x)^I(x))Hypothesis3.S(a)^I(a)2,Existentialinstantiation4.S(a)!C(a)1,Unversalinstantiation5.S(a)3,Simpli cation6.C(a)4,5,Modusponens7.S(a)^C(a)^I(a)3,6,Addition8.S(a)^I(a)^C(a)7,Commutativity9.9x(S(x)^I(x)^C(x))8,ExistentialgeneralizationThenotationsintheright-handcolumnarejusti cationsfortheindividualstepsintheproof.Eachjusti cationincludeslinenumbersofpriorstepsfromwhichitisinferredbyapropertyorinferencerulefromTable12.2or12.3. 812.PROGRAMCORRECTNESSintMax(inta,intb)fintm;if(a�=b)m=a;elsem=b;returnm;gFigure12.1:AC++LiteMaxFunctionde nesawiderangeofintegervalues{somethinglike4millionofthem.Sotocallthisfunction16trilliontimes,eachwithadi erentpairofvaluesforaandb,toproveitscorrectnesswouldbeaninfeasibletask.Axiomaticsemanticsprovidesavehicleforreasoningaboutprogramsandtheircomputations.Thisallowsprogrammerstopredictaprogram'sbehaviorinamorecircumspectandconvincingwaythanrunningtheprogramseveraltimesusingrandomchoicesofinputvaluesastestcases.12.3.1FundamentalConceptsAxiomaticsemanticsisbasedonthenotionofanassertion,whichisapredicatethatdescribesthestateofaprogramatanypointduringitsexecution.Anasser-tioncande nethemeaningofacomputation,asinforexample\themaximumofaandb,"withoutconcernforhowthatcomputationisaccomplished.ThecodeinFigure12.1isjustonewayofalgorithmicallyexpressingthemaximumcomputation;evenforafunctionthissimple,thereareothervaria-tions.Nomatterwhichvariationisused,thefollowingassertionQcanbeusedtodescribethefunctionMaxdeclaratively:Qm=max(a;b)Thatis,thispredicatespeci esthemathematicalmeaningofthefunctionMax(a,b)foranyintegervaluesofaandb.Itthusdescribeswhatshouldbetheresult,ratherthanhowitshouldbecomputed.Toprovethatthepro-graminFigure12.1actuallycomputesmax(a;b),wemustprovethatthelogicalexpressionQisvalidforallvaluesofaandb.Inthisformalveri cationexercise,QiscalledapostconditionfortheprogramMax.Axiomaticsemanticsallowsustodevelopadirectproofbyreasoningaboutthebehaviorofeachindividualstatementintheprogram,beginningwiththepostconditionQandthelaststatementandworkingbackwards.The nalpred-icate,sayP,thatisderivedinthisprocessiscalledtheprogram'sprecondition.Thepreconditionthusexpresseswhatmustbetruebeforeprogramexecutionbeginsinorderforthepostconditiontobevalid.InthecaseofMax,thepostconditionQcanbesatis edforanypairofinteger 1012.PROGRAMCORRECTNESSftruegif(a�=b)m=a;elsem=b;fm=max(a;b)gFigure12.2:TheGoalforProvingtheCorrectnessofMax(a,b)hand,proofofterminationforawhileloopisoftennotpossible,sincethetestconditionforcontinuingtheloopmightnotsubmittoformalanalysis.Forexample,terminationoftheloopwhile(p(x))srevertstothequestionofwhetherornotp(x)everbecomesfalse,whichissometimesnotprovable.Theseconsiderationsnotwithstanding,wecanprovethe(partial)correctnessofaprogrambyplacingitspreconditioninfrontofits rststatementanditspostconditionafteritslaststatement,andthensystematicallyderivingaseriesofvalidpredicatesaswesimulatetheexecutionoftheprogram'scodeoneinstructionatatime.Foranystatementorseriesofstatementss,thepredicatefPgsfQgformallyrepresentstheideathatsispartiallycorrectwithrespecttothepre-conditionPandthepostconditionQ.ThisexpressioniscalledaHoaretripleandasserts\executionofstatementss,beginninginastatethatsatis esP,resultsinastatethatsatis esQ."5Toprovethepartialcorrectnessofourexampleprogram,weneedtoshowthevalidityoftheHoaretripleinFigure12.2.WedothisbyderivingintermediateHoaretriplesfPgsfQgthatarevalidfortheindividualstatementssintheprogram,beginningwiththelaststatementandtheprogram'spostcondition.ThisprocesscontinuesuntilwehavederivedaHoaretripleliketheoneinFigure12.2,whichcompletesthecorrectnessproof.HowaretheseintermediateHoaretriplesderived?Thatisdonebyusingrulesofinferencethatcharacterizewhatweknowaboutthebehaviorofthedif-ferenttypesofstatementsinthelanguage.ProgramsinC++Lite-likelanguageshavefourdi erenttypesofstatements:Assignments,Blocks(sequences),Con-ditionals,andLoops.Eachstatementtypehasaninferencerulewhichde nesthemeaningofthatstatementtypeintermsofthepre-andpostconditionsthatitsatis es.TherulesforC++LitestatementtypesareshowninTable12.4.AsforthenotationinTable12.4,wenote rstthatall veoftheserulesareoftheformp`q,whichissimilartothatusedintheprevioussection'sdiscussionofthepredicatecalculus.Second,wenotethatthecomma(,)inrulesoftheformp1;p2`qdenotesconjunction.Thus,thisformshouldberead,\ifp1andp2arevalidthenqisvalid." 5TheseformsarecalledHoaretriplessincetheywere rstcharacterizedbyC.A.R.Hoareintheoriginalproposalforaxiomatizingthesemanticsofprogramminglanguages[Hoare1969]. 1212.PROGRAMCORRECTNESSTheruleofconsequencealsosuggeststhatanyoneofseveralalternativepreconditionsmightbederivedfromagivenHoaretriple,usingvariousproper-tiesthatweknowfromthemathematicalandlogicaldomainsofthevariablesthatareinplay.Thatpreconditionwhichistheleastrestrictiveonthevari-ablesinplayiscalledtheweakestprecondition.Forinstance,thepreconditionfabgistheweakestpreconditionfortheassignmentm=a;anditspostcon-ditionfm=max(a;b)g.Findingweakestpreconditionsisimportantbecauseitenablessimpli cationoftheproofatvariousstages.AstrategyforprovingthepartialcorrectnessoftherestoftheprograminFigure12.1workssystematicallyfromthepostconditionbackwardsthroughtheif,andthenthroughthetwoassignmentstatementsinthethen-andelse-parttowardaderivationofthepreconditionforthatprogram.Ifthatstrategyissuccessful,theprogramissaidtobecorrectwithrespecttoitsgivenpre-andpostconditions.Let's nishtheproofofthisprogram.Weuserules1and5againwiththepostconditionontheassignmentintheelsepartoftheifstatement,toobtain:fabgm=b;fm=max(a;b)gSinceabisimpliedbyab^true(usingrule5again),wecanapplyrule3tothisconditionalstatementandestablishthefollowinginference:fab^truegm=a;fm=max(a;b)g;fab^truegm=b;fm=max(a;b)g`ftruegif&#x-278;(a=b)m=a;elsem=b;fm=max(a;b)gThus,wehaveproventhecorrectnessoftheentireprograminFigure12.1byderivingtheHoaretripleinFigure11.2usingtheinferencerulesofprogrambehavior.Inthenextsection,weconsidertheissueofcorrectnessforprogramsthatcontainloops.12.3.2CorrectnessofProgramswithLoopsThe(partial)correctnessofaloopdependsnotonlyonlogicallyconnectingthepre-andpostconditionsofitsHoaretriplewiththerestoftheprogram,butalsoonthecorrectnessofeachiterationoftheloopitself.Forthatpurpose,weintroducetheideaofaloopinvariantanduseinductiontoassistwiththeproof.Toillustratetheseideas,supposewewanttoprovethattheC/C++functionFactorialinFigure12.3actuallycomputesasitsresultn!,foranyintegernwheren1,assumingthefunctionterminatesnormally.Byn!wemeantheproduct12n.ThepreconditionPforFactorialis1n,whilethepostconditionisf=n!.Ingeneral,aprograminvolvingaloopusesrule4ofTable12.4tobreakthecodeintothreeparts,asshowninFigure12.4.There,Pistheprogram'sprecondition,Qisitspostcondition,andRisknownastheloopinvariant. 1412.PROGRAMCORRECTNESSThisstepreducestheproblemofprovingthecorrectnessoftheoriginalprogramtothethreesmallerproblems:(1)provingtheinitializationpart;(2)proving(inductively)thatthepremiseRofrule4isvalidforalliterationsoftheloop;and(3)provingthe nalizationpart.Thesesubproblemsmaybeprovedinanyconvenientorder.Thethirdsubproblemiseasiest,sinceitinvolvesonlytheSkipstatement.Sincethatstatementdoesnothing,itspreconditionmustdirectlyimplyitspost-condition.Thiscanbeshownbyrepeatedapplicationsofrule5andusingouralgebraicskills:in^1i^in^f=i!)(i=n)^f=i!)f=n!Thatis,sinceinandin,itfollowsthati=n.Astrategyforsolvingthe rstsubproblemusesrule2tobreakaBlockintoitsindividualcomponentsandthen ndthelinkingassertionfR'g:f1ngf=1;fR0gi=1;f1i^in^f=i!gThelinkingassertionR0canbefoundbyusingrule1withthesecondassign-ment,sothatR0=f11^1n^f=1!g.SonowwecaninsertthisexpressionforR0andapplyrule1tothe rstassignment:f1ngf=1;f11^1n^f=i!gobtainingf11^1n^1=1!g,whichsimpli esto1n.Thus,wehaveprovedthevalidityoftheBlockbyshowingthevalidityof:f1ngf=1;f11^1n^f=1!g;f11^1n^f=1!gi=1;f1i^in^f=i!g`f1ngf=1;i=1;f1i^in^f=i!gSolvingthesecondsubproblemrequiresthatwevalidaterule4forourin-variantRandeveryiterationoftheloop.Sowemustvalidate:fs:test^Rgs:bodyfRg`fRgsf:s:test^Rg;wheresisaloopstatement. 1612.PROGRAMCORRECTNESSWecansafelydividebothsidesoff(i+1)=(i+1)!byi+1,sincei1,resultingin:in^1i^in^f=i!)f=i!Thisisvalid,sinceitsconsequentappearsasaterminitsantecedent.Thislaststepamountstoaninductionproof,inwhichweshowboth:(1)thebasisstepinwhichR(1)isestablished,and(2)theinductionstepinwhichR(i))R(i+1)isestablishedforinvariantR(i)overalli=fi;:::ng.Sinceloopshaveindeterminatelength,theinvariantRisexpressedasafunctionR(i)onthenumberofiterationsithathavetakenplace.Thebasisstep,inwhichR(1)isvalid,correspondstothevalidityofRbeforethe rstiteration.Thisconcludesourproofofthe(partial)correctnessoftheFactorialfunctioninFigure12.3.Notethatourproofdoesnotaddresscorrectnesswhenthecalculationofn!cannotbecompletedbecausetoolargeavaluefornwaspassed.Wereturntothisimportantissuesinalatersection.12.3.3PerspectivesonFormalMethodsAxiomaticsemanticsandthecorrespondingtechniquesforprovingthecorrect-nessofimperativeprogramsweredevelopedinthelate1960sandearly1970s.Atthattime,manyexpectedthatmostprogramswouldroutinelybeprovencorrect,andthatsoftwareproductswouldbecomemorereliableingeneral.Giventhecurrentstateofthesoftwareindustrytoday,itisclearthattheseexpectationshavecomenowhereneartobeingful lled.Tofurtheradvancethisdiscussion,theemergenceofa eldcalledformalmethodsinsoftwaredesignhasemergedduringthelasttwentyyears.This eldattemptstodevelopandapplycorrectnesstoolsandtechniquestotwodi erentphasesofthesoftwaredevelopmentprocess{softwarerequirementsanalysisandsoftwarevalidation(testing).ToolsliketheUniversalModelingLanguage(UML)andtheJavaModelingLanguage(JML),forexample,haveemergedtohelpdesignersspecifymoreformallythebehaviorofcomponentsinlargesystems.Techniqueslikedesignbycontract[Meyer1990]havebeenproposedtoprovideabasisuponwhichsoftwarecomponentscanbevalidatedwithahigherdegreeofreliabilitythanthevarioustestingtechniquesofthepast.Withinthissetting,theutilityandimportanceofcorrectnessproofsinsoft-waredesignhascontinuedtobeasubjectofheateddebate,especiallythrough-outthemostrecentdecade.Manysoftwareengineersrejecttheuseofformalmethodsforsoftwarevalidation[DeMillo1979],arguingthatitistoocomplexandtime-consumingaprocessformostprogrammerstomaster.Insteadtheysuggestthatmoreelaboratetestingmethodsbeusedtoconvincedesignersandusersthatthesoftwarerunscorrectlymostofthetime.Acounter-argumenttothisviewwasmademanyyearsagobyDijkstra[1972],whosimplyrecognizedthattestingcouldonlyprovethepresenceofbugs,nevertheirabsence.Forexample,asimpleprogramthatinputstwo32-bitintegers,computessomefunction,andoutputsa32-bitintegerhas264possibleinputs(approximately1020),sothatevenifonecouldtestandverify 1812.PROGRAMCORRECTNESSf0beginIndexendIndexn^s=s0s1:::sn�1gs.substring(beginIndex,endIndex);fs=s0s1:::sn�1^result=sbeginIndexsbeginIndex+1:::sendIndex�1gFigure12.5:Formalspeci cationoftheJavasubstringMethod.latedintoalogicalrepresentationsothatfollowingquestionscanbeansweredmoreclearlyandprecisely?WhatarethevalidvaluesforbeginIndexandendIndex?Foragivenstrings=s0s1:::sn�1,whatresultisnormallyreturned?Whathappensintheabnormalcase,wheneitherindexisnotvalid?Aprogrammerinterestedinproducingevenaninformalproofofanimple-mentationofsubstringwouldatleastrequireamoreformaldescriptionofthismethod'spre-andpostconditions.Figure12.5showsonesuchdescrip-tion(whichomits,forsimplicity,theabnormalcase).Unliketheinformalde-scription,thisdescriptionformallyspeci estheacceptablevaluesofbeginIndex,endIndex,andthelengthnofthestringsforwhichsubstringiswellde ned,aswellastheexactnatureoftheresultitself.Inthenextsection,wediscussrecentimprovementsinlanguagedesignandsoftwaremethodologythatarehelpingdevelopersaddressthesekindsofprob-lemsmoree ectively.12.3.4FormalMethodsTools:JMLDuringthelastseveralyears,newtoolsandmodelingtechniqueshavebeende-velopedtoassistsoftwaredevelopersinmakingspeci cationsmorerigorousanddesignsmorereliable.OnerecentlydevelopedtooliscalledtheJavaModelingLanguage(JMLforshort),whichisfullyimplementedandadaptabletoavarietyofsoftwaredesignandveri cationactivities.Apromisingmodelingtechniqueiscalleddesignbycontract[Meyer1997],whichprovidesanoperationalframeworkwithinwhichobject-orientedprogramscanbereliablydesigned.Thesetwoworktogether.Thatis,JMLprovidesalanguageforincorporatingandcheckingformalspeci cationsinJavaprograms,whiledesignbycontractprovidestheoperationalguidelineswithinwhichspeci cationscanbeusedtoensuresystemintegritywhenclassesinteractwitheachother.Inthissection,weintroducethefeaturesofJMLastheyapplytotheformalspeci cationandveri cationofanindividualfunction,suchastheFactorialfunctionthatwespeci edandveri edbyhandintheprevioussection.WealsoshowhowJMLallowsustospecifyrun-timeexceptions,providingamorerobustvehiclethanthepureHoaretriplesinarealcomputationalsettingwhereexceptionsactuallyoccur.ConsidertheJML-annotatedversionoftheFactorialfunctionshowninFigure12.6.Thisversiondi ersfromtheC/C++programinFigure12.3inonlyonesigni cantway.Thatis,thefunctionFactorialisannotatedbytwostylized 2012.PROGRAMCORRECTNESSTable12.5:SummaryofJMLExpressionsJMLExpressionMeaning requiresp;pisapreconditionforthecallensuresp;pisapostconditionforthecallsignals(Ee)p;WhenexceptiontypeEisraisedbythecall,thenpisapostconditionloop invariantp;pisaloopinvariantinvariantp;pisaclassinvariant(seenextsection)nresult==eeistheresultreturnedbythecallnold(v)thevalueofvatentrytothecall(nproductintx;p(x);e(x))Qx2p(x)e(x);i.e.,theproductofe(x)(nsumintx;p(x);e(x))Px2p(x)e(x);i.e.,thesumofe(x)(nminintx;p(x);e(x))minx2p(x)e(x);i.e.,theminimumofe(x)(nmaxintx;p(x);e(x))maxx2p(x)e(x);i.e.,themaximumofe(x)(nforalltypex;p(x);q(x))8x2p(x):q(x)(nexiststypex;p(x);q(x))9x2p(x):q(x)p�==qp)qpqq)pp&#x==00;qp,qp&#x=!=0;q:(p,q) comments(written/*@...@*/),onecontainingrequiresandensuresandtheotherbeginningloop invariant.The rstcommentistheJMLencodingforthepre-andpostconditionsPandQthatareusedtoformaHoaretripleoutoftheFactorialfunctioninpreparationforitscorrectnessproof.ThesecondcommentistheJMLencodingoftheassertionRthatrepresentstheloopinvariantinthatproof.Eachoneoftherequires,ensures,andloop invariantclauseshasaJava-stylebooleanexpressionasitsmainelement.Variablesmentionedintheseclauses,liken,aretheordinaryvariablesandparametersthatarevisibletotheFactorialfunction'scodeitself.Additionalnamesmentionedintheseclausesareoftwotypes,localvariables(likeiandjinthisexample)andJMLreservedwords(likenresultandnproductinthisexample).TheimportantcaveatforJMLclausesliketheseisthattheirexecutionmusthavenosidee ectonthestateofthecomputation.InJML,thereservedwordnresultuniquelyidenti estheresultreturnedbyanon-voidfunction.Thereservedwordnproductisamathematicalquanti er(asummaryofthekeyJMLquanti ersandoperatorsappearsinTable12.5),andcarriesthesamemeaningasinmathematicalexpressions.Therestoftheensuresclausede nesthelimitsonthecontrollingvariableiandtheexpressionthatisthesubjectofthecalculationoftheproduct.Thus,theJMLexpres-sion(nproductinti;1&&ii)isequivalenttothemathematicalexpressionQni=1i. 2212.PROGRAMCORRECTNESSTable12.6:SomeofthePrede nedJMLExceptionsJMLExceptionMeaning JMLEntryPreconditionErrorAmethodcall'sparametersdonotsatisfythemethod'srequiresclause.JMLNormalPostconditionErrorAmethodcallexitsnormally,butitsresultdoesnotsatisfythemethod'sensuresclause.JMLExceptionalPostconditionErrorAmethodcallexitsabnormally,raisinganexceptionde nedbythemethod'ssignalsclause.JMLLoopInvariantErrorSomeexecutionofaloop'sbodydoesnotsatisfyitsloop invariantclause.JMLInvariantErrorSomecalltoamethodorconstructordoesnotleavetheobjectinastatethatsatis estheinvariantclause. Inthe rstrun,theprogramexecutesnormally,withonlytheresultandnoadditionalerrorsreported.Forthesecondrun,anattempttocomputethefactorialof-5ismetwithaJMLEntryPreConditionError,whichsaysthatthecalltothemethodmyFactorial.Factorialviolatesthatmethod'sprecondition1n;itreportsthattheactualargument'n'is-5.SincethiseventisaninstanceofJavaexceptionhandling,atraceofthemethodcallsthatareactiveforthisJMLerrorisalsoprovided.Thethirdandfourthrunsshowsomeofthevulnerabilityofthespeci ca-tionstoidiosynchrasiesinJavaitself.SinceJavahasnoArithmeticOverflowexception,thecalculationofanyintvaluethatexceeds231�1=2147483647willgiveanincorrectresult.10Thelargestintvalueofnforwhichn!231�1is12.Lookingattheresultsofthethirdandfourthruns,wecannowunderstandhownoerrorwasreported.Thatis,thewhileloopgivesthesamespuriousresultasthatcalculatedbytheJMLrun-timecheckthatwasspeci edbythepostcondition.Thus,twoequallyincorrectanswerscreatetheillusionthatalliswellwiththisfunctionforthearguments21and32.Inthenextsection,werevisitthehandlingofrun-timeexceptionsusingJMLspeci cations.TheexceptionJMLEntryPreConditionErrorisjustoneofseveraltypesofexceptionsthatcanoccurwhenrunningJML-annotatedprograms.AbriefdescriptionofthisandotherkeyJMLexceptionsisgiveninTable12.6.However,supposethewhileloopinFigure12.4werechangedeversoslightly 10ForJavatypelong,themaximumvalueis263�1=9223372036854775807,andfortypeBigIntegerthemaximumvalueisunlimited.SopracticalapplicationsthatcomputefactorialswilllikelyuseBigIntegervaluesinordertoruleoutpossibilitiesforover ow.WehaveavoidedusingtheBigIntegerclassherebecausetodosowouldhaveintroducedanenormousamountofextrabaggageintotheJavacode,makingourdiscussionofformalspeci cationsalmostunreadable.Forthisreason,wewillstickwiththesimpletypeint. 2412.PROGRAMCORRECTNESSorg.jmlspecs.jmlrac.runtime.JMLLoopInvariantError:LOOPINVARIANT:bymethodmyFactorial.FactorialregardingspecificationsatFile"myFactorial.java",line9,character24when'n'is3atmyFactorial.internal$Factorial(myFactorial.java:101)atmyFactorial.Factorial(myFactorial.java:573)atmyFactorial.main(myFactorial.java:209)[dhcp-53-152:~/desktop/pl/correctness]allen%Butthistime,itistheinvariantthatneedstobecorrectedandnotthecode.Anotherbene tofrun-timepre-andpost-conditioncheckingisthattheprogrammercanslideadi erentimplementationofafunctionintotheprogram,andthentestitusingthesamepre-andpostconditions.Forexample,supposewedecidetoimplementFactorialrecursivelyratherthaniteratively,withthefollowingcode:staticintFactorial(intn)fif(n2)returnn;elsereturnnFactorial(n�1);gBothoftheJMLrequiresandensuresclausesremainintactwhilewecompileandrunthisversion;thusitssatisfactionofthepreconditionsandpostconditionscanbeimmediatelytested.JMLExceptionHandlingFormalmethodsforprogramcorrectnessshouldsupportthespeci cationofconditionsunderwhichexceptionsoccur.Tothatend,JMLprovidesasignalsclause:signals(exception)expression;thatcanappeartogetherwithafunction'srequiresandensuresclauses.Whenthatexceptionoccurs,theexpressionischecked;ifthatexpressionisnottrue,theexceptionisdisplayedandtheprogramisinterrupted.Figure12.6showsavariantoftheFactorialfunctionthatincorporatestheseideas:Nowwhenwerunthisprogramtocomputethefactorialofanumberthatwillcausearithmeticover ow,anexceptionisraised:%jmlracmyFactorial13Exceptioninthread"main"java.lang.ArithmeticExceptionatmyFactorial.internal$Factorial(myFactorial.java:9)atmyFactorial.Factorial(myFactorial.java:610)atmyFactorial.main(myFactorial.java:213)Observantreaderswillnoticethatsignalsclausescanbeavoidedinmanycasessimplybywritingstrongerpreconditions{onesthatsoconstraintheinputtothecallthattheexceptioncannotoccur.Forinstance,intheFactorial 2612.PROGRAMCORRECTNESSs.substring(intbeginIndex,intendIndex)throwsStringIndexOutOfBoundsExceptionThisspeci cationisaslightabbreviationofthefullJMLspeci cationsforsubstringthatde netheentireJavaclasslibrary.Inparticular,theline"s[beginIndex]s[beginIndex+1]...s[endIndex-1]"isourinformalalge-braicspeci cationforthevalueofthestringobjectthatisreturnedbysubstring.Infact,thatlineappearsintheJMLspeci cationas:this.stringSeq.subsequence(beginIndex,endIndex);Here,stringSeqisaJMLclassthatde nesstringsassequencesofcharacters,andsubsequenceisamethodinthatclass.Interestedreadersshouldconsulthttp://www.jmlspecs.orgformoredetailsabouttheseconventions.Thenextsectionconsiderstheuseofformalmethodsandcorrectnesscon-ceptswithinanobject-orientedframework.12.4CORRECTNESSOFOBJECT-ORIENTEDPROGRAMSObject-orientedprogramsarecollectionsofclasses.Eachclassde nesakindofobjectandasetoffeatures(methods)thatcantransformthatkindofobject.Whenimplementinganobject-orientedprogram,theprogrammerneedstohavestandards,ortoolsbywhichs/hecanformallyverifythattheentireprogramisdoingwhatitisintendedtodo.Inadditiontotheformalizationofindivid-ualfunctions,asdescribedintheforegoingsection,object-orientedprogramsprovidetwoadditionaltoolsbywhichprogrammerscanensurecorrectness.First,eachinteractioninwhichanobjectinoneclassisaccessedormodi edbyamethodcallfromaso-calledclientclass,mustbeguidedbycertain\rulesofengagement."Theserulesensurethattheclientprovidesthecalledmethodwithappropriatevaluesforitsparameters,andthatthecalledmethodreturnsaresulttotheclientthatisconsistentwiththepurposeofthemethod.Theserulesofengagementarecalledacontractbetweentheclassandtheclient.Whenalltheinteractionsamongclassesinasoftwaredesignfollowstheserules,thesoftwareissaidtohavebeendesignedbycontract.Second,wheneveranobjectinaclassistransformed,itmustmaintainthesameinternalconsistency,orsetofpropertiesthatidenti esitasamemberofthatparticularclass,thatithadwhenitwascreated.Thisinternalconsistencycanbeformallycharacterizedastheclassinvariant.Wede neandillustratetheuseofdesignbycontractandtheclassinvariantinthenexttwosections.12.4.1DesignByContractThemethodologyofdesignbycontractwasdevelopedbyBertrandMeyer[Meyer1990].Designbycontractisaformalframeworkthatestablishesso- 2812.PROGRAMCORRECTNESS12.4.2TheClassInvariantAclassinvariantisatoolforensuringthatallobjectsintheclassretaintheirintegritythroughouttheirlifetime,nomatterwhatmethodsareappliedtothem.Indiscussingclassinvariants,wefollowtheapproachof[Meyer1997].WeillustratethisapproachwiththeformalizationoftheMyStackclassthatwasoriginallyintroducedinChapter7(Figure7.7).AclassinvariantisaBoolean-valuedexpressionthatspeci esthecondi-tionsunderwhichanobjectinthatclassremainswell-de ned.Thisexpressiondescribestheinternalstateoftheobjectusingtheclass'spublicandprivateinstancevariables.AnexpressionINVisacorrectclassinvariantforclassCifitmeetsthefollowingtwoconditions:EverycalltoaconstructorCwithargumentsthatsatisfyC'sprecondition,createsanewobjectwithastatethatsatis esINV.EverycalltoapublicmethodMwithargumentsthatsatisfyM'sprecon-dition,leavestheobjectinastatethatsatis esINV.Thus,theclassinvariantmustbecometruewhentheobjectiscreatedbyaconstructor,anditmustremaintrueafteranypublicmethodintheclassiscalled.Duringtheexecutionofthecodeinsideacall,theclassinvariantmaybetemporarilybroken;however,suchaconditionmustberepairedbythetimethecalliscompleted.Forexample,considertheclassMyStackinFigure7.7,whichwehaverecre-atedandexpandedinFigure12.9.Thisnewversionhasaclassinvariant,anadditionalprivateinstancevariablen,threenewpublicmethods,andappro-priatepre-andpostconditionsaddedtoallmethods.Thenewprivateinstancevariablenisacountofthenumberofelementsinthestack,andtheinstancevariabletheStackisareferencetothetopmostelementinthestack.Forthetimebeing,letusconcentrateonthespeci cationoftheclassin-variant,whichhasthefollowinggeneralforminJML:publicinvariantexpression;TheinvariantischeckedautomaticallybyJMLeachtimeaconstructorormethodcallisenteredorexited,andaJMLInvariantErrorexceptionisraisedwhenevertheinvariant'sexpressionisnottrue.ConsidertheJMLspeci cationfortheinvariantfortheclassmyStackinFigure12.9:/@publicmodelNodeS;privaterepresentsS�theStack;publicinvariantS==nulljjn==this.size();@/private/@spec public@/NodetheStack=null;private/@spec public@/intn=0;Here,weuseaso-calledmodelvariableS,whichisknownonlytotheJMLspeci cationsandhasnorun-timefunctionalitywithintheJavaprogram.The 3012.PROGRAMCORRECTNESSUsingtheseconventions,acompletesetofspeci cationsforthemethodsintheMyStackclassareshowninFigure12.9.Thisincludespre-andpostcondi-tionsforthepush,pop,top,isEmpty,andsizemethods,theclassinvariant,andtheuseofthemodelvariableSthroughout.TestingtheContractAnnotatingtheMyStackclasswithpre-andpostconditionsandaclassinvariantprovidesanexecutableenvironmentinwhichthecontractbetweentheclassanditsclientscanbecontinuouslytested.Moreover,theseannotationsprovideamechanismforassigningblamewhenthecontractisbrokenbytheclassoritsclient.Toillustratethistestingactivity,wewrotethesimpledriverprogramshowninFigure12.10thatcanexercisethemethodsoftheMyStackclass.Thefollow-ingcommandwasusedtoruntheprogram.%jmlracmyStackTest3456Stacktop=6IsStackempty?falseStacksize=3Stackcontents=654IsStackemptynow?trueThe rstparametercountsthenumberofvaluestobepushedontothestack,andtheremainingparametersprovidethosevalues.Thenormaloutputproducedbythisprogramfollowsthecommand.Inordertoexercisevariousaspectsofthecontractbetweentheclassanditsclient,wethenranthreedi erenttests./@requiresn�0;ensuresnresult==nold(S).val&&S==nold(S).next&&n==nold(n)�1;@/public/@pure@/intpop()fintresult=theStack.val;theStack=theStack.next;n=n�1;returnresult;gFigure12.8:StackpopMethodwithSpeci cationsAdded 3212.PROGRAMCORRECTNESSpublicclassmyStackTestfpublicstaticvoidmain(String[]args)fMyStacks=newMyStack();intval;intn=Integer.parseInt(args[0]);for(inti=1;i=n;i++)s.push(Integer.parseInt(args[i]));System.out.println("Stacktop="+s.top());System.out.println("IsStackempty?"+s.isEmpty());System.out.println("Stacksize="+s.size());System.out.println("Stackcontents=");for(inti=1;i=n;i++)fSystem.out.println(s.top());s.pop();gSystem.out.println("IsStackemptynow?"+s.isEmpty());ggFigure12.10:ADriverProgramforTestingtheJML-Speci edMyStackClass.The rsttest,whoseresultsareshownbelow,illustrateswhathappenswhenthetopmethoderroneouslyremovesthetopelementaswellasreturningit{i.e.,itincorrectlyactslikeapop.Exceptioninthread"main"org.jmlspecs.jmlrac.runtime.JMLNormalPostconditionError:bymethodMyStack.topregardingspecificationsatFile"MyStack.java",line31,character26when'\old(S)'isMyStack$Node@5ff48b'\result'is5'this'isMyStack@affc70atMyStack.checkPost$top$MyStack(MyStack.java:999)atMyStack.top(MyStack.java:1078)atmyStackTest.main(MyStackTest.java:15)Totriggerthiserror,weaddedtwoextralinestothetopmethodinFigure12.9sothatitsbodylookedlikethatofthepopmethod.Sincetop'sresultnowfailedtosatisfyitspostconditionS==nold(S),aJMLNormalPostconditionErrorwasraisedandthevaluesofnold(S)andnresultwerereportedbyJML.Withthisinformation,blamefortheerrorcouldbeassignedtotothetopmethodratherthantoitscaller.Forthesecondtest,weexcludedthelinen=n-1;fromthepopmethodshowninFigure12.9,thuscreatingasituationinwhichthemethod'spostcon-ditionwassatis edbuttheclassinvariantwasviolated.Belowistheoutcome. 3412.PROGRAMCORRECTNESSCorrectnessoftheMyStackClassWhataboutthecorrectnessoftheMyStackclass?Annotatingitwithpre-andpostconditionsandaclassinvariant,andthentestingthecontractwithadriverprogram,surelydoesn'tguaranteecorrectnessinaformalsense.Informally,aclassiscorrectif,foreveryobjectintheclassandeverycon-structorormethodcallthatsatis esitsprecondition,completionofthecallsatis esitspostconditionandleavestheobject'sinstancevariablesinastatethatsatis estheclassinvariant.Thisideaassumesthatnoconstructorormethodcallwillresultinanin niteloop,andthusitisastatementaboutpartialcorrectness.Let'stryforamoreformalizedde nitionofclasscorrectness,12usingthenotationofHoaretriplesthatweintroducedatthebeginningofthechapter.LetRdenoteaclass'sinvariant,andPiandQidenotethepreconditionandpostconditionforitsithconstructorCiormethodMi.Thenwecansaythataclassiscorrectwithrespecttoitsassertionsifboth:1.ForeverysetofvalidargumentsxtoeveryconstructorCi,fPi(x)gCi:bodyfQi(x)^INVg,and2.ForeverysetofvalidargumentsxtoeverymethodMi,fPi(x)^INVgMi:bodyfQi(x)^INVg.Rule1says,ine ect,thatexecutionofanyconstructorforanobjectintheclassshouldestablishthevalidityoftheclassinvariant.Rule2saysthatexecutionofanymethodcallinwhichtheclassinvariantisvalidattheoutsetshouldpreservethevalidityoftheinvariantuponcompletionofthecall.Thus,thisde nitionrequiresustoprovethecorrectnessofeveryconstructorandpublicmethodindividually.EachsuchproofisconductedinawaysimilartothatdevelopedfortheFactorialmethodinSection12.3.2.LetusillustratetheseideasbydevelopingsomeoftheproofthatourlinkedlistimplementationoftheMyStackclassisformallycorrect.First,wenotethatthedefaultclassconstructorMyStack()establishestheinstancevariables'valuestheStack==nullandn==0.TheclassinvariantINVitselfisstatedintermsofthepublicmethodsize.Veri cationofthebodyofthesizemethodwiththisinvariantestablishedshouldthereforesatisfyitspostconditionandpreservetheinvariant.Formally,wewanttoprove:ftheStack=null^n=0gsize.bodyftheStack=null^n=0^nresult=ngInformally,wenotethatthelocalvariablespandcountforsizeareini-tializedatnulland0,respectively.Sotheloopisnotexecutedatallandtheresult0isreturned,establishingthevalidityoftheaboveHoaretriple.(Afor-malproofwouldhavemorerigorouslyappliedallthestepsoftheproofmethoddescribedinSection12.3.2;wehaveshort-circuitedthatprocesshereinordertokeepourmainfocusonclassveri cation.) 12Thisformalizationisadaptedfrom[Meyer1997]. 3612.PROGRAMCORRECTNESSInsummary,weconcludethatthecommunityofinterestindevelopingbetterformalmethodsforsoftwaredesignhasgainedsubstantialmomentumintherecentpast.Surelytheuseofformalmethodsbyitselfisnopanaceaforthesoftwarecrisis,butitdoesprovidealevelorrigorforthesoftwaredesignprocessthatisbadlyneeded.Forthatreasonalone,weexpectthatmoreprogramminglanguagetoolslikeJML,ESC/JAVA,andLOOPwillcontinuetoevolveandmaketheirimpactonthesoftwaredesignprocessinthefuture.12.5CORRECTNESSOFFUNCTIONALPROGRAMSThissectionaddressesthequestionofprogramcorrectnessfromthepointofviewoffunctionalprogramming.Werevisitthequestionofwhatmakesaprogramcorrectforthespecialcasewhenitiswritteninapurefunctionalprogram{onethatisstate-lessandreliesinsteadonfunctionalcompositionandrecursionasafoundationforitssemantics.The rstsectionbelowillustratesthisprocessbymakingastrongconnectionbetweenarecursivefunctionandaninductiveproofofitscorrectness.Thesecondsectionprovidesthreeadditionalexamples,payingparticularattentiontotheuseofstructuralinduction{thatis,aninductionondatastructureslikelistsandstrings,ratherthanontheintegers.12.5.1RecursionandInductionWhenconsideringthequestionofcorrectnessforprogramswritteninafunc-tionallanguage,suchasHaskell,we ndourselvesinaverydi erentplace.First,absentthenotionofprogramstateandassignmentinpurefunctionalprograms,weneednotwriteHoaretriplestokeeptrackofthestatetransformationsaswewouldwithprogramswritteninimperativeandobject-orientedlanguages.Instead,functionalprogramsarewrittenascollectionsoffunctionsthatarewellgroundedinthemathematicsoffunctionsandrecurrencerelations.ThisallowsustobasecorrectnessproofsforHaskellfunctionsonthewell-worntech-niqueofmathematicalinduction,ratherthandirectproofsthatrelyonreasoningaboutstatetransformationsateverystep.Overall,theveri cationoffunctionalprogramsisamuchmorestraightforwardprocessthantheveri cationofim-perativeandobject-orientedprograms.Forasimpleexample,considertheHaskellfunctionthatcomputesthefac-torialofanonnegativeintegern:�factn�|n==1=1--fact.1(basisstep)�|n�1=n*fact(n-1)--fact.2(inductionstep)Supposewewanttoprovethatthisfunctioncomputestheproductofthe rstnnonnegativeintegers,givenn.Thatis,wewanttoprovethat: 3812.PROGRAMCORRECTNESS�cat[]ys=ys--cat.1�cat(x:xs)ys=x:(catxsys)--cat.2��rev[]=[]--rev.1�rev(x:xs)=cat(rev(xs))[x]--rev.2Supposewewanttoprovethefollowingpropertyabouttherelationshipbetweenthesetwofunctions:rev(catxsys)=cat(revys)(revxs)Forinstance,ifthetwolists(strings)are\hello"and\world,"thenthefollowingistrue:rev(cat"hello""world")=cat(rev"world")(rev"hello")="dlrowolleh"Toprovethispropertybyinduction,webeginwiththebasisstepandusethede nitionsofthesetwofunctions.Sowe rstneedtoshowthat:rev([]++ys)=rev(ys)++rev([])Usingvariouslinesinthede nitionsofthesefunctions,weprovethisbysub-stitutionasfollows(justi cationsforeachstepareshownontheright):rev(cat[]ys)}=rev(ys)(fromcat.1)=cat(rev(ys)[])(fromrev.2)=cat(rev(ys)rev[])(fromrev.1)Theinductionhypothesisforthisproofiswrittenbystatingtheconclusionforanytwolistsxsandys.rev(catxsys)=catreverse(ys)reverse(xs)Nowtheinductionstepcanbecompletedbyshowinghowaslightlylonger(by1element)listx:xsobeysthesamerule,asfollows:rev(cat(x:xs)ys)=cat(revys)(rev(x:xs))Here,wetransformtheleft-handsideofthisexpressionusingourhypothesisandvariouslinesinthede nitionsofthefunctionsrevandcat,toachievethefollowing:rev(cat(x:xs)ys)=rev(x:(catxsys))(fromcat.2)=rev(cat(catxsys)[x])(fromrev.2)=cat(cat(revys)(revxs))[x](fromourhypothesis)=cat(revys)(cat(revxs)[x])(associativityofcat)=cat(revys)(rev(x:xs))(fromrev.2)Finally,noticethatthefourthlineinthisderivationassumesassociativityfortheoperatorcat,whichcanbeseparatelyprovedbyinduction.Thisisleftasanexercise. 4012.PROGRAMCORRECTNESSlen(catx:xsys)=lenx:(catxsys)bycat.2=1+len(catxsys)bylen.2=1+lenxs+lenysbyhypothesis=lenx:xs+lenysbylen.2Thiscompletestheproof.Astheseexamplesillustrate,Haskellprovidesespeciallystrongsupportforcorrectnessproofsincomplexsoftwaresystems.While,unfortunately,notalargenumberofsoftwaresystemsareimplementedinHaskell,thosethatareenjoyagenerallyhighlevelofreliability.However,functionallanguageslikeHaskellarebeingconsideredmoreandmoreseriouslybysoftwaredesignersasvehiclesforde ningprecisespeci cationsforsoftwareprototypes.ConventionallanguageslikeC++andAdahavebeeninadequateforthispurpose[Hudak1994].EXERCISES1.Suggestadi erentwaytowritethefunctionMax(a,b)inFigure12.1withoutchangingthemeaningofthefunction.2.BelowisaHoaretriplethatincludesaC++Liteprogramfragmenttocomputetheproductzoftwointegersxandy.fy0gz=0;n=y;while(n�0)fz=z+x;n=n�1;gfz=xyg(a)WhatinferencerulesinTable3.1andadditionalknowledgeaboutalgebracanbeusedtoinferthatthepreconditioninthisHoaretripleisequivalenttotheassertionfy0^0=x(y�y)g?(b)Usingtheassignmentinferencerule,completethefollowingHoaretripleforthe rsttwostatementsinthisprogramfragment:fy0^0=x(y�y)gz=0;n=y;fy0^g 4212.PROGRAMCORRECTNESS(a)Translatethatde nitiontoaformalpre-andpostcondition.(b)Nowtranslateyourspeci cationintoJMLrequiresandensuresclauses.7.GivearecursiveC/C++implementationofthefunctionFactorialinFig-ure12.3.Provethepartialcorrectnessofyourrecursiveimplementationforallvaluesofn�0.Note:toprovethecorrectnessofarecursivefunc-tion,inductionmustbeused.Thatis,thebasecaseandrecursivecallinthefunctionde nitioncorrespondwiththebasisstepandinductionstepintheproof.8.Aprogramhastotalcorrectnessifit(completesitsexecutionand)satis esitspostconditionforallinputvaluesspeci edinitsprecondition.SupposewealteredthefunctionFactorialinFigure12.3sothatitsargumentandresulttypesarelongratherthanint.(a)ExperimentallydeterminethelargestvalueofnforwhichyouralteredversionofFactorialwilldeliveraresult.Whathappenswhenitdoesnot?(b)Re nethepreconditionforthisversionofFactorialsothatitscor-rectnessproofbecomesaproofoftotalcorrectness.(c)Howisthecorrectnessproofitselfalteredbythesechanges,ifatall?Explain.9.AltertheJMLversionoftheFactorialfunctionde nitioninFigure11.6sothatitsargumentandresulttypesarelongratherthanint.AddexceptiongeneratingcapabilitiestothisfunctionsothatitraisesanArithmeticErrorexceptionwheneverthefactorialcannotbecorrectlycomputed.Finally,addaJMLsignalsclausetothespeci cationthatcoversthisevent.10.ReimplementtheFactorialfunctionsothatitreturnsavalueoftypeBigInteger.InwhatwaysisthisimplementationsuperiortotheversionpresentedinFigure12.6?11.ReimplementtheFactorialfunctioninHaskell.InwhatwaysisthisimplementationsuperiortotheJavavariationsinFigure12.6andthepreviousquestion?Inwhatwaysisitinferior?12.GiveaninductionproofforthecorrectnessofyourHaskellimplementationoftheFactorialfunctioninthepreviousexercise.Forthis,youshouldrelyonthemathematicalde nitionoffactorial.13.Discussthetradeo sthatexistbetweenthechoicesofre ningtheprecon-ditionandaddingasignalsclausewhenspecifyingafunction'sresponsetoaninputvalueforwhichitcannotcomputeameaningfulresult.E.g.,thesechoicesareillustratedintheforegoingtwoexercises. 4412.PROGRAMCORRECTNESS(b)Analternativede nitionoftheFibonaccicalculationcanbemadeinthefollowingway.De neafunctionfibPairthatgeneratesa2-elementpairthatcontainsthenthFibonaccinumberanditssuc-cessor.De neanotherfunctionfibNextthatgeneratesthenextsuchtuplefromthecurrentone.ThentheFibonaccifunctionitself,optimisticallynamedfibFast,canbede nedbyselectingthe rstmemberofthenthfibPair.InHaskell,thisiswrittenasfollows:�fibPairn�|n==0=(1,1)�|n�0=fibNext(fibPair(n-1))�fibNext(m,n)=(n,m+n)�fibFastn=fst(fibPair(n))TryrunningthefunctionfibFasttocomputethe25thand50thFibonaccinumbers.ItshouldbeconsiderablymoreecientthanfibSlow.Explain.(c)Provebyinductionthat8n0: bFast(n)= bSlow(n).

Related Contents


Next Show more