412PROGRAMCORRECTNESSTable121SummaryofPredicateLogicNotation NotationMeaning truefalseBooleantruthconstantspqBooleanvariablespxyqxyBooleanfunctionspNegationofppqConjuncti ID: 309133
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.
212.PROGRAMCORRECTNESSItisappropriateinourstudyofmodernprogramminglanguagestoexaminethequestionoflanguagefeaturesthatsupportthedesignofreliablesoftwaresystemsandhowthosefeaturesextendtheexpressivepowerofconventionallanguages.Thischapterthusaddressestheissueofprogramcorrectnessfromtheimportantperspectiveoflanguagefeaturesandprogrammingparadigms.A"correct"programisonethatdoesexactlywhatitsdesignersandusersintendittodo{nomoreandnoless.A"formallycorrect"programisonewhosecorrectnesscanbeprovedmathematically,atleasttoapointthatdesignersandusersareconvincedaboutitsrelativeabsenceoferrors.Foraprogramtobeformallycorrect,theremustbeawaytospecifypre-cisely(mathematically)whattheprogramisintendedtodo,forallpossiblevaluesofitsinput.Theseso-calledspecicationlanguagesarebasedonmathe-maticallogic,whichwereviewinthenextsection.Aprogramminglanguage'sspecicationlanguageisbasedaconceptcalledaxiomaticsemantics,whichwasrstsuggestedbyC.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,withtherecentemergenceofEiel[Meyer1990],ESC/Java[Flana-gan2002],Spark/Ada[Barnes2003],JML[Leavens2004],andthenotionofdesignbycontract[Meyer1997],thissituationischangingrapidly.Thesenewdevelopmentsprovideprogrammerswithaccesstorigoroustoolsandvericationtechniquesthatarefullyintegratedwiththerunitimesystemitself.Designbycontractisaformalismthroughwhichinteractionsbetweenobjectsandtheirclientscanbepreciselydescribedanddynamicallychecked.ESC/JAVAisacode-levellanguageforannotatingandstaticallycheckingaprogramforawidevarietyofcommonerrors.TheJavaModelingLanguage(JML)providescodelevelextensionstotheJavalanguagesothatprogramscanincludesuchformalspecicationsandtheirenforcementatruntime.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)Universallyquantiedexpression9xp(x)Existentiallyquantiedexpressionp(x)isvalidPredicatep(x)istrueforeveryvalueofxp(x)issatisablePredicatep(x)istrueforatleastonevalueofxp(x)isacontradictionPredicatep(x)isfalseforeveryvalueofx Apredicatecombinesthesekindsoffunctionsusingtheoperatorsofthepropositionalcalculusandthequantiers8(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.1summarizesthemeaningsofthedierentkindsofexpressionsthatcanbeusedinpropositionalandpredicatelogic.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^qSimplicationp^q`pAdditionp`p_qUniversalinstantiation8xp(x)`p(a)Existentialinstantiation9xp(x)`p(a)Universalgeneralizationp(x)`8xp(x)Existentialgeneralizationp(a)`9xp(x) predicateintheproofmustbetheargument'sconclusionq.Eachpredicateinthesequenceisaccompaniedbya\justication,"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,Simplication6.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-handcolumnarejusticationsfortheindividualstepsintheproof.EachjusticationincludeslinenumbersofpriorstepsfromwhichitisinferredbyapropertyorinferencerulefromTable12.2or12.3. 812.PROGRAMCORRECTNESSintMax(inta,intb)fintm;if(a=b)m=a;elsem=b;returnm;gFigure12.1:AC++LiteMaxFunctiondenesawiderangeofintegervalues{somethinglike4millionofthem.Sotocallthisfunction16trilliontimes,eachwithadierentpairofvaluesforaandb,toproveitscorrectnesswouldbeaninfeasibletask.Axiomaticsemanticsprovidesavehicleforreasoningaboutprogramsandtheircomputations.Thisallowsprogrammerstopredictaprogram'sbehaviorinamorecircumspectandconvincingwaythanrunningtheprogramseveraltimesusingrandomchoicesofinputvaluesastestcases.12.3.1FundamentalConceptsAxiomaticsemanticsisbasedonthenotionofanassertion,whichisapredicatethatdescribesthestateofaprogramatanypointduringitsexecution.Anasser-tioncandenethemeaningofacomputation,asinforexample\themaximumofaandb,"withoutconcernforhowthatcomputationisaccomplished.ThecodeinFigure12.1isjustonewayofalgorithmicallyexpressingthemaximumcomputation;evenforafunctionthissimple,thereareothervaria-tions.Nomatterwhichvariationisused,thefollowingassertionQcanbeusedtodescribethefunctionMaxdeclaratively:Qm=max(a;b)Thatis,thispredicatespeciesthemathematicalmeaningofthefunctionMax(a,b)foranyintegervaluesofaandb.Itthusdescribeswhatshouldbetheresult,ratherthanhowitshouldbecomputed.Toprovethatthepro-graminFigure12.1actuallycomputesmax(a;b),wemustprovethatthelogicalexpressionQisvalidforallvaluesofaandb.Inthisformalvericationexercise,QiscalledapostconditionfortheprogramMax.Axiomaticsemanticsallowsustodevelopadirectproofbyreasoningaboutthebehaviorofeachindividualstatementintheprogram,beginningwiththepostconditionQandthelaststatementandworkingbackwards.Thenalpred-icate,sayP,thatisderivedinthisprocessiscalledtheprogram'sprecondition.Thepreconditionthusexpresseswhatmustbetruebeforeprogramexecutionbeginsinorderforthepostconditiontobevalid.InthecaseofMax,thepostconditionQcanbesatisedforanypairofinteger 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)correctnessofaprogrambyplacingitspreconditioninfrontofitsrststatementanditspostconditionafteritslaststatement,andthensystematicallyderivingaseriesofvalidpredicatesaswesimulatetheexecutionoftheprogram'scodeoneinstructionatatime.Foranystatementorseriesofstatementss,thepredicatefPgsfQgformallyrepresentstheideathatsispartiallycorrectwithrespecttothepre-conditionPandthepostconditionQ.ThisexpressioniscalledaHoaretripleandasserts\executionofstatementss,beginninginastatethatsatisesP,resultsinastatethatsatisesQ."5Toprovethepartialcorrectnessofourexampleprogram,weneedtoshowthevalidityoftheHoaretripleinFigure12.2.WedothisbyderivingintermediateHoaretriplesfPgsfQgthatarevalidfortheindividualstatementssintheprogram,beginningwiththelaststatementandtheprogram'spostcondition.ThisprocesscontinuesuntilwehavederivedaHoaretripleliketheoneinFigure12.2,whichcompletesthecorrectnessproof.HowaretheseintermediateHoaretriplesderived?Thatisdonebyusingrulesofinferencethatcharacterizewhatweknowaboutthebehaviorofthedif-ferenttypesofstatementsinthelanguage.ProgramsinC++Lite-likelanguageshavefourdierenttypesofstatements:Assignments,Blocks(sequences),Con-ditionals,andLoops.Eachstatementtypehasaninferencerulewhichdenesthemeaningofthatstatementtypeintermsofthepre-andpostconditionsthatitsatises.TherulesforC++LitestatementtypesareshowninTable12.4.AsforthenotationinTable12.4,wenoterstthatallveoftheserulesareoftheformp`q,whichissimilartothatusedintheprevioussection'sdiscussionofthepredicatecalculus.Second,wenotethatthecomma(,)inrulesoftheformp1;p2`qdenotesconjunction.Thus,thisformshouldberead,\ifp1andp2arevalidthenqisvalid." 5TheseformsarecalledHoaretriplessincetheywererstcharacterizedbyC.A.R.Hoareintheoriginalproposalforaxiomatizingthesemanticsofprogramminglanguages[Hoare1969]. 1212.PROGRAMCORRECTNESSTheruleofconsequencealsosuggeststhatanyoneofseveralalternativepreconditionsmightbederivedfromagivenHoaretriple,usingvariousproper-tiesthatweknowfromthemathematicalandlogicaldomainsofthevariablesthatareinplay.Thatpreconditionwhichistheleastrestrictiveonthevari-ablesinplayiscalledtheweakestprecondition.Forinstance,thepreconditionfabgistheweakestpreconditionfortheassignmentm=a;anditspostcon-ditionfm=max(a;b)g.Findingweakestpreconditionsisimportantbecauseitenablessimplicationoftheproofatvariousstages.AstrategyforprovingthepartialcorrectnessoftherestoftheprograminFigure12.1workssystematicallyfromthepostconditionbackwardsthroughtheif,andthenthroughthetwoassignmentstatementsinthethen-andelse-parttowardaderivationofthepreconditionforthatprogram.Ifthatstrategyissuccessful,theprogramissaidtobecorrectwithrespecttoitsgivenpre-andpostconditions.Let'snishtheproofofthisprogram.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-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)provingthenalizationpart.Thesesubproblemsmaybeprovedinanyconvenientorder.Thethirdsubproblemiseasiest,sinceitinvolvesonlytheSkipstatement.Sincethatstatementdoesnothing,itspreconditionmustdirectlyimplyitspost-condition.Thiscanbeshownbyrepeatedapplicationsofrule5andusingouralgebraicskills:in^1i^in^f=i!)(i=n)^f=i!)f=n!Thatis,sinceinandin,itfollowsthati=n.Astrategyforsolvingtherstsubproblemusesrule2tobreakaBlockintoitsindividualcomponentsandthenndthelinkingassertionfR'g:f1ngf=1;fR0gi=1;f1i^in^f=i!gThelinkingassertionR0canbefoundbyusingrule1withthesecondassign-ment,sothatR0=f11^1n^f=1!g.SonowwecaninsertthisexpressionforR0andapplyrule1totherstassignment:f1ngf=1;f11^1n^f=i!gobtainingf11^1n^1=1!g,whichsimpliesto1n.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,correspondstothevalidityofRbeforetherstiteration.Thisconcludesourproofofthe(partial)correctnessoftheFactorialfunctioninFigure12.3.Notethatourproofdoesnotaddresscorrectnesswhenthecalculationofn!cannotbecompletedbecausetoolargeavaluefornwaspassed.Wereturntothisimportantissuesinalatersection.12.3.3PerspectivesonFormalMethodsAxiomaticsemanticsandthecorrespondingtechniquesforprovingthecorrect-nessofimperativeprogramsweredevelopedinthelate1960sandearly1970s.Atthattime,manyexpectedthatmostprogramswouldroutinelybeprovencorrect,andthatsoftwareproductswouldbecomemorereliableingeneral.Giventhecurrentstateofthesoftwareindustrytoday,itisclearthattheseexpectationshavecomenowhereneartobeingfullled.Tofurtheradvancethisdiscussion,theemergenceofaeldcalledformalmethodsinsoftwaredesignhasemergedduringthelasttwentyyears.Thiseldattemptstodevelopandapplycorrectnesstoolsandtechniquestotwodierentphasesofthesoftwaredevelopmentprocess{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:::sn1gs.substring(beginIndex,endIndex);fs=s0s1:::sn1^result=sbeginIndexsbeginIndex+1:::sendIndex1gFigure12.5:FormalspecicationoftheJavasubstringMethod.latedintoalogicalrepresentationsothatfollowingquestionscanbeansweredmoreclearlyandprecisely?WhatarethevalidvaluesforbeginIndexandendIndex?Foragivenstrings=s0s1:::sn1,whatresultisnormallyreturned?Whathappensintheabnormalcase,wheneitherindexisnotvalid?Aprogrammerinterestedinproducingevenaninformalproofofanimple-mentationofsubstringwouldatleastrequireamoreformaldescriptionofthismethod'spre-andpostconditions.Figure12.5showsonesuchdescrip-tion(whichomits,forsimplicity,theabnormalcase).Unliketheinformalde-scription,thisdescriptionformallyspeciestheacceptablevaluesofbeginIndex,endIndex,andthelengthnofthestringsforwhichsubstringiswelldened,aswellastheexactnatureoftheresultitself.Inthenextsection,wediscussrecentimprovementsinlanguagedesignandsoftwaremethodologythatarehelpingdevelopersaddressthesekindsofprob-lemsmoreeectively.12.3.4FormalMethodsTools:JMLDuringthelastseveralyears,newtoolsandmodelingtechniqueshavebeende-velopedtoassistsoftwaredevelopersinmakingspecicationsmorerigorousanddesignsmorereliable.OnerecentlydevelopedtooliscalledtheJavaModelingLanguage(JMLforshort),whichisfullyimplementedandadaptabletoavarietyofsoftwaredesignandvericationactivities.Apromisingmodelingtechniqueiscalleddesignbycontract[Meyer1997],whichprovidesanoperationalframeworkwithinwhichobject-orientedprogramscanbereliablydesigned.Thesetwoworktogether.Thatis,JMLprovidesalanguageforincorporatingandcheckingformalspecicationsinJavaprograms,whiledesignbycontractprovidestheoperationalguidelineswithinwhichspecicationscanbeusedtoensuresystemintegritywhenclassesinteractwitheachother.Inthissection,weintroducethefeaturesofJMLastheyapplytotheformalspecicationandvericationofanindividualfunction,suchastheFactorialfunctionthatwespeciedandveriedbyhandintheprevioussection.WealsoshowhowJMLallowsustospecifyrun-timeexceptions,providingamorerobustvehiclethanthepureHoaretriplesinarealcomputationalsettingwhereexceptionsactuallyoccur.ConsidertheJML-annotatedversionoftheFactorialfunctionshowninFigure12.6.ThisversiondiersfromtheC/C++programinFigure12.3inonlyonesignicantway.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==00;qp,qp=!=0;q:(p,q) comments(written/*@...@*/),onecontainingrequiresandensuresandtheotherbeginningloop invariant.TherstcommentistheJMLencodingforthepre-andpostconditionsPandQthatareusedtoformaHoaretripleoutoftheFactorialfunctioninpreparationforitscorrectnessproof.ThesecondcommentistheJMLencodingoftheassertionRthatrepresentstheloopinvariantinthatproof.Eachoneoftherequires,ensures,andloop invariantclauseshasaJava-stylebooleanexpressionasitsmainelement.Variablesmentionedintheseclauses,liken,aretheordinaryvariablesandparametersthatarevisibletotheFactorialfunction'scodeitself.Additionalnamesmentionedintheseclausesareoftwotypes,localvariables(likeiandjinthisexample)andJMLreservedwords(likenresultandnproductinthisexample).TheimportantcaveatforJMLclausesliketheseisthattheirexecutionmusthavenosideeectonthestateofthecomputation.InJML,thereservedwordnresultuniquelyidentiestheresultreturnedbyanon-voidfunction.Thereservedwordnproductisamathematicalquantier(asummaryofthekeyJMLquantiersandoperatorsappearsinTable12.5),andcarriesthesamemeaningasinmathematicalexpressions.Therestoftheensuresclausedenesthelimitsonthecontrollingvariableiandtheexpressionthatisthesubjectofthecalculationoftheproduct.Thus,theJMLexpres-sion(nproductinti;1&&ii)isequivalenttothemathematicalexpressionQni=1i. 2212.PROGRAMCORRECTNESSTable12.6:SomeofthePredenedJMLExceptionsJMLExceptionMeaning JMLEntryPreconditionErrorAmethodcall'sparametersdonotsatisfythemethod'srequiresclause.JMLNormalPostconditionErrorAmethodcallexitsnormally,butitsresultdoesnotsatisfythemethod'sensuresclause.JMLExceptionalPostconditionErrorAmethodcallexitsabnormally,raisinganexceptiondenedbythemethod'ssignalsclause.JMLLoopInvariantErrorSomeexecutionofaloop'sbodydoesnotsatisfyitsloop invariantclause.JMLInvariantErrorSomecalltoamethodorconstructordoesnotleavetheobjectinastatethatsatisestheinvariantclause. Intherstrun,theprogramexecutesnormally,withonlytheresultandnoadditionalerrorsreported.Forthesecondrun,anattempttocomputethefactorialof-5ismetwithaJMLEntryPreConditionError,whichsaysthatthecalltothemethodmyFactorial.Factorialviolatesthatmethod'sprecondition1n;itreportsthattheactualargument'n'is-5.SincethiseventisaninstanceofJavaexceptionhandling,atraceofthemethodcallsthatareactiveforthisJMLerrorisalsoprovided.Thethirdandfourthrunsshowsomeofthevulnerabilityofthespecica-tionstoidiosynchrasiesinJavaitself.SinceJavahasnoArithmeticOverflowexception,thecalculationofanyintvaluethatexceeds2311=2147483647willgiveanincorrectresult.10Thelargestintvalueofnforwhichn!2311is12.Lookingattheresultsofthethirdandfourthruns,wecannowunderstandhownoerrorwasreported.Thatis,thewhileloopgivesthesamespuriousresultasthatcalculatedbytheJMLrun-timecheckthatwasspeciedbythepostcondition.Thus,twoequallyincorrectanswerscreatetheillusionthatalliswellwiththisfunctionforthearguments21and32.Inthenextsection,werevisitthehandlingofrun-timeexceptionsusingJMLspecications.TheexceptionJMLEntryPreConditionErrorisjustoneofseveraltypesofexceptionsthatcanoccurwhenrunningJML-annotatedprograms.AbriefdescriptionofthisandotherkeyJMLexceptionsisgiveninTable12.6.However,supposethewhileloopinFigure12.4werechangedeversoslightly 10ForJavatypelong,themaximumvalueis2631=9223372036854775807,andfortypeBigIntegerthemaximumvalueisunlimited.SopracticalapplicationsthatcomputefactorialswilllikelyuseBigIntegervaluesinordertoruleoutpossibilitiesforover ow.WehaveavoidedusingtheBigIntegerclassherebecausetodosowouldhaveintroducedanenormousamountofextrabaggageintotheJavacode,makingourdiscussionofformalspecicationsalmostunreadable.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.Anotherbenetofrun-timepre-andpost-conditioncheckingisthattheprogrammercanslideadierentimplementationofafunctionintotheprogram,andthentestitusingthesamepre-andpostconditions.Forexample,supposewedecidetoimplementFactorialrecursivelyratherthaniteratively,withthefollowingcode:staticintFactorial(intn)fif(n2)returnn;elsereturnnFactorial(n1);gBothoftheJMLrequiresandensuresclausesremainintactwhilewecompileandrunthisversion;thusitssatisfactionofthepreconditionsandpostconditionscanbeimmediatelytested.JMLExceptionHandlingFormalmethodsforprogramcorrectnessshouldsupportthespecicationofconditionsunderwhichexceptionsoccur.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)throwsStringIndexOutOfBoundsExceptionThisspecicationisaslightabbreviationofthefullJMLspecicationsforsubstringthatdenetheentireJavaclasslibrary.Inparticular,theline"s[beginIndex]s[beginIndex+1]...s[endIndex-1]"isourinformalalge-braicspecicationforthevalueofthestringobjectthatisreturnedbysubstring.Infact,thatlineappearsintheJMLspecicationas:this.stringSeq.subsequence(beginIndex,endIndex);Here,stringSeqisaJMLclassthatdenesstringsassequencesofcharacters,andsubsequenceisamethodinthatclass.Interestedreadersshouldconsulthttp://www.jmlspecs.orgformoredetailsabouttheseconventions.Thenextsectionconsiderstheuseofformalmethodsandcorrectnesscon-ceptswithinanobject-orientedframework.12.4CORRECTNESSOFOBJECT-ORIENTEDPROGRAMSObject-orientedprogramsarecollectionsofclasses.Eachclassdenesakindofobjectandasetoffeatures(methods)thatcantransformthatkindofobject.Whenimplementinganobject-orientedprogram,theprogrammerneedstohavestandards,ortoolsbywhichs/hecanformallyverifythattheentireprogramisdoingwhatitisintendedtodo.Inadditiontotheformalizationofindivid-ualfunctions,asdescribedintheforegoingsection,object-orientedprogramsprovidetwoadditionaltoolsbywhichprogrammerscanensurecorrectness.First,eachinteractioninwhichanobjectinoneclassisaccessedormodiedbyamethodcallfromaso-calledclientclass,mustbeguidedbycertain\rulesofengagement."Theserulesensurethattheclientprovidesthecalledmethodwithappropriatevaluesforitsparameters,andthatthecalledmethodreturnsaresulttotheclientthatisconsistentwiththepurposeofthemethod.Theserulesofengagementarecalledacontractbetweentheclassandtheclient.Whenalltheinteractionsamongclassesinasoftwaredesignfollowstheserules,thesoftwareissaidtohavebeendesignedbycontract.Second,wheneveranobjectinaclassistransformed,itmustmaintainthesameinternalconsistency,orsetofpropertiesthatidentiesitasamemberofthatparticularclass,thatithadwhenitwascreated.Thisinternalconsistencycanbeformallycharacterizedastheclassinvariant.Wedeneandillustratetheuseofdesignbycontractandtheclassinvariantinthenexttwosections.12.4.1DesignByContractThemethodologyofdesignbycontractwasdevelopedbyBertrandMeyer[Meyer1990].Designbycontractisaformalframeworkthatestablishesso- 2812.PROGRAMCORRECTNESS12.4.2TheClassInvariantAclassinvariantisatoolforensuringthatallobjectsintheclassretaintheirintegritythroughouttheirlifetime,nomatterwhatmethodsareappliedtothem.Indiscussingclassinvariants,wefollowtheapproachof[Meyer1997].WeillustratethisapproachwiththeformalizationoftheMyStackclassthatwasoriginallyintroducedinChapter7(Figure7.7).AclassinvariantisaBoolean-valuedexpressionthatspeciesthecondi-tionsunderwhichanobjectinthatclassremainswell-dened.Thisexpressiondescribestheinternalstateoftheobjectusingtheclass'spublicandprivateinstancevariables.AnexpressionINVisacorrectclassinvariantforclassCifitmeetsthefollowingtwoconditions:EverycalltoaconstructorCwithargumentsthatsatisfyC'sprecondition,createsanewobjectwithastatethatsatisesINV.EverycalltoapublicmethodMwithargumentsthatsatisfyM'sprecon-dition,leavestheobjectinastatethatsatisesINV.Thus,theclassinvariantmustbecometruewhentheobjectiscreatedbyaconstructor,anditmustremaintrueafteranypublicmethodintheclassiscalled.Duringtheexecutionofthecodeinsideacall,theclassinvariantmaybetemporarilybroken;however,suchaconditionmustberepairedbythetimethecalliscompleted.Forexample,considertheclassMyStackinFigure7.7,whichwehaverecre-atedandexpandedinFigure12.9.Thisnewversionhasaclassinvariant,anadditionalprivateinstancevariablen,threenewpublicmethods,andappro-priatepre-andpostconditionsaddedtoallmethods.Thenewprivateinstancevariablenisacountofthenumberofelementsinthestack,andtheinstancevariabletheStackisareferencetothetopmostelementinthestack.Forthetimebeing,letusconcentrateonthespecicationoftheclassin-variant,whichhasthefollowinggeneralforminJML:publicinvariantexpression;TheinvariantischeckedautomaticallybyJMLeachtimeaconstructorormethodcallisenteredorexited,andaJMLInvariantErrorexceptionisraisedwhenevertheinvariant'sexpressionisnottrue.ConsidertheJMLspecicationfortheinvariantfortheclassmyStackinFigure12.9:/@publicmodelNodeS;privaterepresentsStheStack;publicinvariantS==nulljjn==this.size();@/private/@spec public@/NodetheStack=null;private/@spec public@/intn=0;Here,weuseaso-calledmodelvariableS,whichisknownonlytotheJMLspecicationsandhasnorun-timefunctionalitywithintheJavaprogram.The 3012.PROGRAMCORRECTNESSUsingtheseconventions,acompletesetofspecicationsforthemethodsintheMyStackclassareshowninFigure12.9.Thisincludespre-andpostcondi-tionsforthepush,pop,top,isEmpty,andsizemethods,theclassinvariant,andtheuseofthemodelvariableSthroughout.TestingtheContractAnnotatingtheMyStackclasswithpre-andpostconditionsandaclassinvariantprovidesanexecutableenvironmentinwhichthecontractbetweentheclassanditsclientscanbecontinuouslytested.Moreover,theseannotationsprovideamechanismforassigningblamewhenthecontractisbrokenbytheclassoritsclient.Toillustratethistestingactivity,wewrotethesimpledriverprogramshowninFigure12.10thatcanexercisethemethodsoftheMyStackclass.Thefollow-ingcommandwasusedtoruntheprogram.%jmlracmyStackTest3456Stacktop=6IsStackempty?falseStacksize=3Stackcontents=654IsStackemptynow?trueTherstparametercountsthenumberofvaluestobepushedontothestack,andtheremainingparametersprovidethosevalues.Thenormaloutputproducedbythisprogramfollowsthecommand.Inordertoexercisevariousaspectsofthecontractbetweentheclassanditsclient,wethenranthreedierenttests./@requiresn0;ensuresnresult==nold(S).val&&S==nold(S).next&&n==nold(n)1;@/public/@pure@/intpop()fintresult=theStack.val;theStack=theStack.next;n=n1;returnresult;gFigure12.8:StackpopMethodwithSpecicationsAdded 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-SpeciedMyStackClass.Thersttest,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-ditionwassatisedbuttheclassinvariantwasviolated.Belowistheoutcome. 3412.PROGRAMCORRECTNESSCorrectnessoftheMyStackClassWhataboutthecorrectnessoftheMyStackclass?Annotatingitwithpre-andpostconditionsandaclassinvariant,andthentestingthecontractwithadriverprogram,surelydoesn'tguaranteecorrectnessinaformalsense.Informally,aclassiscorrectif,foreveryobjectintheclassandeverycon-structorormethodcallthatsatisesitsprecondition,completionofthecallsatisesitspostconditionandleavestheobject'sinstancevariablesinastatethatsatisestheclassinvariant.Thisideaassumesthatnoconstructorormethodcallwillresultinaninniteloop,andthusitisastatementaboutpartialcorrectness.Let'stryforamoreformalizeddenitionofclasscorrectness,12usingthenotationofHoaretriplesthatweintroducedatthebeginningofthechapter.LetRdenoteaclass'sinvariant,andPiandQidenotethepreconditionandpostconditionforitsithconstructorCiormethodMi.Thenwecansaythataclassiscorrectwithrespecttoitsassertionsifboth:1.ForeverysetofvalidargumentsxtoeveryconstructorCi,fPi(x)gCi:bodyfQi(x)^INVg,and2.ForeverysetofvalidargumentsxtoeverymethodMi,fPi(x)^INVgMi:bodyfQi(x)^INVg.Rule1says,ineect,thatexecutionofanyconstructorforanobjectintheclassshouldestablishthevalidityoftheclassinvariant.Rule2saysthatexecutionofanymethodcallinwhichtheclassinvariantisvalidattheoutsetshouldpreservethevalidityoftheinvariantuponcompletionofthecall.Thus,thisdenitionrequiresustoprovethecorrectnessofeveryconstructorandpublicmethodindividually.EachsuchproofisconductedinawaysimilartothatdevelopedfortheFactorialmethodinSection12.3.2.LetusillustratetheseideasbydevelopingsomeoftheproofthatourlinkedlistimplementationoftheMyStackclassisformallycorrect.First,wenotethatthedefaultclassconstructorMyStack()establishestheinstancevariables'valuestheStack==nullandn==0.TheclassinvariantINVitselfisstatedintermsofthepublicmethodsize.Vericationofthebodyofthesizemethodwiththisinvariantestablishedshouldthereforesatisfyitspostconditionandpreservetheinvariant.Formally,wewanttoprove:ftheStack=null^n=0gsize.bodyftheStack=null^n=0^nresult=ngInformally,wenotethatthelocalvariablespandcountforsizeareini-tializedatnulland0,respectively.Sotheloopisnotexecutedatallandtheresult0isreturned,establishingthevalidityoftheaboveHoaretriple.(Afor-malproofwouldhavemorerigorouslyappliedallthestepsoftheproofmethoddescribedinSection12.3.2;wehaveshort-circuitedthatprocesshereinordertokeepourmainfocusonclassverication.) 12Thisformalizationisadaptedfrom[Meyer1997]. 3612.PROGRAMCORRECTNESSInsummary,weconcludethatthecommunityofinterestindevelopingbetterformalmethodsforsoftwaredesignhasgainedsubstantialmomentumintherecentpast.Surelytheuseofformalmethodsbyitselfisnopanaceaforthesoftwarecrisis,butitdoesprovidealevelorrigorforthesoftwaredesignprocessthatisbadlyneeded.Forthatreasonalone,weexpectthatmoreprogramminglanguagetoolslikeJML,ESC/JAVA,andLOOPwillcontinuetoevolveandmaketheirimpactonthesoftwaredesignprocessinthefuture.12.5CORRECTNESSOFFUNCTIONALPROGRAMSThissectionaddressesthequestionofprogramcorrectnessfromthepointofviewoffunctionalprogramming.Werevisitthequestionofwhatmakesaprogramcorrectforthespecialcasewhenitiswritteninapurefunctionalprogram{onethatisstate-lessandreliesinsteadonfunctionalcompositionandrecursionasafoundationforitssemantics.Therstsectionbelowillustratesthisprocessbymakingastrongconnectionbetweenarecursivefunctionandaninductiveproofofitscorrectness.Thesecondsectionprovidesthreeadditionalexamples,payingparticularattentiontotheuseofstructuralinduction{thatis,aninductionondatastructureslikelistsandstrings,ratherthanontheintegers.12.5.1RecursionandInductionWhenconsideringthequestionofcorrectnessforprogramswritteninafunc-tionallanguage,suchasHaskell,wendourselvesinaverydierentplace.First,absentthenotionofprogramstateandassignmentinpurefunctionalprograms,weneednotwriteHoaretriplestokeeptrackofthestatetransformationsaswewouldwithprogramswritteninimperativeandobject-orientedlanguages.Instead,functionalprogramsarewrittenascollectionsoffunctionsthatarewellgroundedinthemathematicsoffunctionsandrecurrencerelations.ThisallowsustobasecorrectnessproofsforHaskellfunctionsonthewell-worntech-niqueofmathematicalinduction,ratherthandirectproofsthatrelyonreasoningaboutstatetransformationsateverystep.Overall,thevericationoffunctionalprogramsisamuchmorestraightforwardprocessthanthevericationofim-perativeandobject-orientedprograms.Forasimpleexample,considertheHaskellfunctionthatcomputesthefac-torialofanonnegativeintegern:factn|n==1=1--fact.1(basisstep)|n1=n*fact(n-1)--fact.2(inductionstep)Supposewewanttoprovethatthisfunctioncomputestheproductoftherstnnonnegativeintegers,givenn.Thatis,wewanttoprovethat: 3812.PROGRAMCORRECTNESScat[]ys=ys--cat.1cat(x:xs)ys=x:(catxsys)--cat.2rev[]=[]--rev.1rev(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,webeginwiththebasisstepandusethedenitionsofthesetwofunctions.Sowerstneedtoshowthat:rev([]++ys)=rev(ys)++rev([])Usingvariouslinesinthedenitionsofthesefunctions,weprovethisbysub-stitutionasfollows(justicationsforeachstepareshownontheright):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-handsideofthisexpressionusingourhypothesisandvariouslinesinthedenitionsofthefunctionsrevandcat,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,functionallanguageslikeHaskellarebeingconsideredmoreandmoreseriouslybysoftwaredesignersasvehiclesfordeningprecisespecicationsforsoftwareprototypes.ConventionallanguageslikeC++andAdahavebeeninadequateforthispurpose[Hudak1994].EXERCISES1.SuggestadierentwaytowritethefunctionMax(a,b)inFigure12.1withoutchangingthemeaningofthefunction.2.BelowisaHoaretriplethatincludesaC++Liteprogramfragmenttocomputetheproductzoftwointegersxandy.fy0gz=0;n=y;while(n0)fz=z+x;n=n1;gfz=xyg(a)WhatinferencerulesinTable3.1andadditionalknowledgeaboutalgebracanbeusedtoinferthatthepreconditioninthisHoaretripleisequivalenttotheassertionfy0^0=x(yy)g?(b)Usingtheassignmentinferencerule,completethefollowingHoaretripleforthersttwostatementsinthisprogramfragment:fy0^0=x(yy)gz=0;n=y;fy0^g 4212.PROGRAMCORRECTNESS(a)Translatethatdenitiontoaformalpre-andpostcondition.(b)NowtranslateyourspecicationintoJMLrequiresandensuresclauses.7.GivearecursiveC/C++implementationofthefunctionFactorialinFig-ure12.3.Provethepartialcorrectnessofyourrecursiveimplementationforallvaluesofn0.Note:toprovethecorrectnessofarecursivefunc-tion,inductionmustbeused.Thatis,thebasecaseandrecursivecallinthefunctiondenitioncorrespondwiththebasisstepandinductionstepintheproof.8.Aprogramhastotalcorrectnessifit(completesitsexecutionand)satisesitspostconditionforallinputvaluesspeciedinitsprecondition.SupposewealteredthefunctionFactorialinFigure12.3sothatitsargumentandresulttypesarelongratherthanint.(a)ExperimentallydeterminethelargestvalueofnforwhichyouralteredversionofFactorialwilldeliveraresult.Whathappenswhenitdoesnot?(b)RenethepreconditionforthisversionofFactorialsothatitscor-rectnessproofbecomesaproofoftotalcorrectness.(c)Howisthecorrectnessproofitselfalteredbythesechanges,ifatall?Explain.9.AltertheJMLversionoftheFactorialfunctiondenitioninFigure11.6sothatitsargumentandresulttypesarelongratherthanint.AddexceptiongeneratingcapabilitiestothisfunctionsothatitraisesanArithmeticErrorexceptionwheneverthefactorialcannotbecorrectlycomputed.Finally,addaJMLsignalsclausetothespecicationthatcoversthisevent.10.ReimplementtheFactorialfunctionsothatitreturnsavalueoftypeBigInteger.InwhatwaysisthisimplementationsuperiortotheversionpresentedinFigure12.6?11.ReimplementtheFactorialfunctioninHaskell.InwhatwaysisthisimplementationsuperiortotheJavavariationsinFigure12.6andthepreviousquestion?Inwhatwaysisitinferior?12.GiveaninductionproofforthecorrectnessofyourHaskellimplementationoftheFactorialfunctioninthepreviousexercise.Forthis,youshouldrelyonthemathematicaldenitionoffactorial.13.Discussthetradeosthatexistbetweenthechoicesofreningtheprecon-ditionandaddingasignalsclausewhenspecifyingafunction'sresponsetoaninputvalueforwhichitcannotcomputeameaningfulresult.E.g.,thesechoicesareillustratedintheforegoingtwoexercises. 4412.PROGRAMCORRECTNESS(b)AnalternativedenitionoftheFibonaccicalculationcanbemadeinthefollowingway.DeneafunctionfibPairthatgeneratesa2-elementpairthatcontainsthenthFibonaccinumberanditssuc-cessor.DeneanotherfunctionfibNextthatgeneratesthenextsuchtuplefromthecurrentone.ThentheFibonaccifunctionitself,optimisticallynamedfibFast,canbedenedbyselectingtherstmemberofthenthfibPair.InHaskell,thisiswrittenasfollows:fibPairn|n==0=(1,1)|n0=fibNext(fibPair(n-1))fibNext(m,n)=(n,m+n)fibFastn=fst(fibPair(n))TryrunningthefunctionfibFasttocomputethe25thand50thFibonaccinumbers.ItshouldbeconsiderablymoreecientthanfibSlow.Explain.(c)Provebyinductionthat8n0:bFast(n)=bSlow(n).