/
BasicResearchinComputerScienceRefocusinginReductionSemanticsOlivierDan BasicResearchinComputerScienceRefocusinginReductionSemanticsOlivierDan

BasicResearchinComputerScienceRefocusinginReductionSemanticsOlivierDan - PDF document

sherrill-nordquist
sherrill-nordquist . @sherrill-nordquist
Follow
362 views
Uploaded On 2017-11-23

BasicResearchinComputerScienceRefocusinginReductionSemanticsOlivierDan - PPT Presentation

BRICS ISSN09090878November2004BRICSRS0426DanvyNielsenRefocusinginReductionSemantics 2004OlivierDanvyLasseRNielsenBRICSDepartmentofComputerScienceUniversityofAarhusAllrightsreservedReproduc ID: 608250

BRICS ISSN0909-0878November2004BRICSRS-04-26Danvy&Nielsen:RefocusinginReductionSemantics 2004 OlivierDanvy&LasseR.Nielsen.BRICS DepartmentofComputerScienceUniversityofAarhus.Allrightsreserved.Reproduc

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "BasicResearchinComputerScienceRefocusing..." 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

BRICS BasicResearchinComputerScienceRefocusinginReductionSemanticsOlivierDanvyLasseR.NielsenBRICSReportSeriesRS-04-26 ISSN0909-0878November2004BRICSRS-04-26Danvy&Nielsen:RefocusinginReductionSemantics 2004,OlivierDanvy&LasseR.Nielsen.BRICS,DepartmentofComputerScienceUniversityofAarhus.Allrightsreserved.Reproductionofallorpartofthisworkispermittedforeducationalorresearchuseonconditionthatthiscopyrightnoticeisincludedinanycopy.SeebackinnerpageforalistofrecentBRICSReportSeriespublications.Copiesmaybeobtainedbycontacting:BRICSDepartmentofComputerScienceUniversityofAarhusNyMunkegade,building540DK–8000AarhusCTelephone:+4589423360Telefax:+4589423255Internet:BRICS@brics.dkBRICSpublicationsareingeneralaccessiblethroughtheWorldWideWebandanonymousFTPthroughtheseURLs:Thisdocumentinsubdirectory RefocusinginReductionSemanticsOlivierDanvyandLasseR.NielsenDepartmentofComputerScienceUniversityofAarhusNovember2004AbstractTheevaluationfunctionofareductionsemantics(i.e.,asmall-stepoperationalsemanticswithanexplicitrepresentationofthereductioncontext)iscanonicallyde nedasthetransitiveclosureof(1)decomposingatermintoareductioncon-textandaredex,(2)contractingthisredex,and(3)pluggingthecontractuminthecontext.Directlyimplementingthisevaluationfunctionthereforeyieldsaninterpreterwithaworst-caseoverhead,foreachstep,thatislinearinthesizeoftheinputterm.Wepresentsucientconditionsovertheconstituentsofareductionsemanticstocircumventthisoverhead,byreplacingthecompositionof(3)pluggingand(1)decomposingbyasingle\refocus"functionmappingacontractumandacontextintoanewcontextandanewredex,ifany.Wealsoshowhowtoconstructsucharefocusfunction,weprovethecorrectnessofthisconstruction,andweanalyzethecomplexityoftheresultingrefocusfunction.Therefocusedevaluationfunctionofareductionsemanticsimplementsthetransitiveclosureoftherefocusfunction,i.e.,a\pre-abstractmachine."Fusingtherefocusfunctionwiththetrampolinefunctioncomputingthetransitiveclosuregivesastate-transitionfunction,i.e.,anabstractmachine.Thisabstractmachineclearlyseparatesbetweenthetransitionsimplementingthecongruencerulesofthereductionsemanticsandthetransitionsimplementingitsreductionrules.Theconstructionofarefocusfunctionthereforeshowshowtomechanicallyobtainanabstractmachineoutofareductionsemantics,whichwasdonepreviouslyonacase-by-casebasis.WeillustraterefocusingbymechanicallyconstructingFelleisenetal.'sCKma-chinefromacall-by-valuereductionsemanticsofthelambda-calculus,andbycon-structingasubstitution-basedversionofKrivine'smachinefromacall-by-namereductionsemanticsofthelambda-calculus.Wealsomechanicallyconstructthreeone-passCPStransformersfromthreequadraticcontext-basedCPStransformersforthelambda-calculus.KeywordsReductionsemantics,refocusing,pre-abstractmachine,abstractmachine,defunc-tionalization,transformationintocontinuation-passingstyle(CPS). ApreliminaryversionofthisarticlewaspresentedatRULE2001[8].Currentaliation:ACUREA/S,Bytoften1,DK-8240Risskov,DenmarkBasicResearchinComputerScience(fundedbytheDanishNationalResearchFoundation.IT-parken,Aabogade34,DK-8200AarhusN,DenmarkE-mail: Contents1Introduction11.1Relatedwork.................................11.2Interpretersforreductionsemantics.....................11.3Acanonicalexample:the-calculus....................11.4Thiswork...................................22Refocusinginareductionsemantics42.1Thelanguage.................................42.2Reductionsemantics.............................42.2.1Values.................................42.2.2Reductioncontexts..........................42.2.3Decompositionsandpotentialredexes...............52.2.4Uniquedecomposition........................52.2.5Reductionrules............................62.3Requirements.................................62.3.1Noredundantconstructs.......................62.3.2Distinctvalueconstructorsandpotential-redexconstructors...72.3.3Left-to-rightevaluationofsub-terms................72.4Consequencesoftherequirements......................72.5Constructingarefocusfunction.......................92.6Correctness..................................112.7Complexity..................................122.8Summary...................................133The-calculusundercallbyvalue143.1Acall-by-valueinterpreter..........................143.1.1Theoriginalspeci cation......................143.1.2Therefocusedspeci cation.....................153.2SabryandFelleisen'sCPStransformer...................153.2.1Theoriginalspeci cation......................153.2.2Therefocusedspeci cation.....................163.3AsimplerCPStransformer.........................173.3.1Theoriginalspeci cation......................173.3.2Therefocusedspeci cation.....................173.4Refocusingeciently.............................183.4.1Thecall-by-valueinterpreter....................183.4.2SabryandFelleisen'sCPStransformer...............193.4.3ThesimplerCPStransformer....................193.5Analysisoftherefocusedcall-by-valueinterpreter.............193.5.1Apre-abstractmachine.......................193.5.2Fromthepre-abstractmachinetoanabstractmachine......193.5.3Aneval/applyabstractmachine..................203.5.4Apush/enterabstractmachine...................213.5.5Fromtheeval/applyabstractmachinetoabig-stepsemantics..213.6AnalysisoftherefocusedCPStransformers................213.7Summary...................................22 4The-calculusundercallbyname234.1Acall-by-nameinterpreter..........................234.1.1Theoriginalspeci cation......................234.1.2Therefocusedspeci cation.....................244.2AsimpleCPStransformer..........................244.2.1Theoriginalspeci cation......................244.2.2Therefocusedspeci cation.....................254.3Refocusingeciently.............................264.3.1Thecall-by-nameinterpreter....................264.3.2ThesimpleCPStransformer....................264.4Analysisoftherefocusedcall-by-nameinterpreter.............264.4.1Apre-abstractmachine.......................264.4.2Fromthepre-abstractmachinetoanabstractmachine......274.4.3Aneval/applyabstractmachine..................274.4.4Apush/enterabstractmachine...................284.4.5Fromtheeval/applyabstractmachinetoabig-stepsemantics..284.5AnalysisoftherefocusedCPStransformer.................284.6Summary...................................295Conclusion29AArithmeticexpressionswithprecedence30A.1Areductionsemantics............................30A.2Analternativerepresentationofcontexts..................31A.3Implementation................................32A.4Refocusing...................................36A.5Summary...................................41ListofFigures1Canonicalvs.refocusedevaluation.....................32Elementarycontexts,values,andpotentialredexes............83Abstractsyntaxofarithmeticexpressions.................334Reductioncontextsforarithmeticexpressions...............335Iterativeplugfunctionsforarithmeticexpressions.............346Redexesandtheresultofdecompositionforarithmeticexpressions...347Iterativedecompositionofanarithmeticexpression............358Canonicalevaluationofanarithmeticexpression.............369Refocusingoveranarithmeticexpression(signature)...........3910Refocusingoveranarithmeticexpression(de nition)...........4011Refocusedevaluationofanarithmeticexpression.............41 1IntroductionAreductionsemantics(a.k.a.syntactictheory)isasmall-stepoperationalsemanticswithanexplicitrepresentationofthereductioncontext[10{12].Weconsidertheprob-lemofimplementingtheevaluationfunctionofareductionsemanticsintheformofaninterpreter.Ouremphasis,however,isnotonautomatingthisprocess,asinXiaoandAriola'sSLproject[28,29].Instead,weobservethatthedirectimplementationofanevaluationfunctionentailsanoverheadandweshowhowtocircumventthisoverhead.1.1RelatedworkProbablybecauseeveryinterestingprogramminglanguagecorrespondstoaninter-estingmodelofcomputation,themeta-languageofformalsemanticshasconsistentlyinspiredarangeofprogramminglanguages|witnessdenotationalsemanticsandfunc-tionalprogramming[25,27],Moggi'scomputationalmonadsandmonad-basedfunc-tionalprogramming[26],operationalsemanticsandlogicprogrammingwithde niteclausegrammars[17],algebraicsemanticsandOBJ[15],etc.Thesesimilaritiesbetweenlanguageandmeta-languagemakeitpossibletowrite`executablespeci cations.'Forreductionsemantics,however,executablespeci cationsappearnottoscaleupinprac-tice[24,28].Weidentifyasourceofineciencyinthedirectimplementationofareductionsemanticsasaninterpreter,andweshowhowtobypassit.Theresultcanbeusedtomechanicallyconstructanabstractmachineoutofareductionsemantics,anissuethatisusuallydealtwithonacase-by-casebasis[11,Chapter7].1.2InterpretersforreductionsemanticsAreductionsemanticsisasmall-stepoperationalsemanticswhereevaluationisde nedasthetransitiveclosureofsinglereductions,eachperformedby(1)decomposingatermintoareductioncontextandapotentialredex,(2)contractingtheredex,ifpossible,and(3)pluggingthecontractumintothecontext.Mostreductionsemanticsarede-velopedfordeterministicprogramminglanguagesandsatisfyaunique-decompositionproperty.Theinterpreterforareductionsemanticsimplementsitsevaluationfunction.Itnaturallyconsistsofadecompose-contract-plugloop.Decompositionisusuallyim-plementedwithadepth- rstsearchintheabstract-syntaxtree.Thedecomposestepthereforeintroducesanoverheadthatisproportionaltothesizeoftheinputterm.Likewise,pluggingtakestimelinearinthesizeofthecontext.1.3Acanonicalexample:the-calculusHereisacall-by-valuereductionsemanticsofthe-calculus:TermstttValuesValueVariablesVarReductioncontexts::=[][[]]v[]]RedContPotentialredexesvvrPotRedex Notallpotentialredexesareactualreducibleexpressions|somearestuckterms[20]. Amongpotentialredexes,only-redexesareactualreducibleterms.Therefore,theonlyreductionruleisthefollowingone:e:(x:t)v]!C[tfv=xPluggingtheholeofareductioncontextwithatermisde nedbyinductiononthecontext,andthusitoperatesintimeproportionaltothesizeofthecontext:([])[[[]]t]=C[tt0](C[v[]])[]])[vt]Likewise,decompositionoperatesintimeproportional,intheworstcase,tothesizeofthetermtodecompose.LetusillustratethisoverheadwithChurchnumerals:theChurchnumeralforthenumbers:z:s )))andisnotedExample1(Churchnumeral)Weconsiderthetermwhereisanyvalue.Thistermreducesintwostepsto {z Fromthenon,eachdecompositionintoacontextandaredex(wheretheredexisalways)takestimeproportionaltothenumberofremainingapplications.ThetotaltimetakenbydecompositionduringevaluationisthusproportionaltoTheevaluationfunctionofareductionsemanticsisinecientbecauseitconstructsintermediateterms(seetheleftsideofFigure1).Weobserve,though,thatinthecourseofevaluation,eachdecomposestepalwaysfollowsaplugstep(evenforthe rststep,since([])[).Onecouldthereforedeforestintermediatetermsbyfusingtheplugstepandthedecomposestepintoone`refocus'step(seetherightsideofFigure1).Ratherthandeforestingpluganddecomposeonacase-by-casebasis,weseekgeneralconditionsovertheconstituentsofareductionsemanticstoconstructsuchanecientrefocusstep.1.4ThisworkWestateconditionsunderwhichconsecutiveplug-and-decomposeoperationscanbere-placedbyamoreecient`refocus'operationwheretheintermediatetermisdeforestedaway.Theseconditionspertaintotheorderinwhicharedexoccursinthedepth- rsttraversalofthedecomposeoperation.Weshowthattheseconditionsholdifthere-ductionsemanticsisgiveninthe\standard"way,i.e.,byacontext-freegrammarofvaluesandreductioncontexts,andifitsatis esaunique-decompositionproperty.Wealsoshowhowtomechanicallyconstructsucharefocusfunction.Overview:Therestofthisarticleisstructuredasfollows.We rstlistsucientconditionstoobtaintherefocusfunctionofareductionsemantics(Section2).Theproofthattheseconditionsaresucientisconstructive.Itindicateshowtomechanicallyrephrasetheevaluationfunctionofareductionsemanticstocircumventtheplug-and-decomposeoverhead.Theseconditionsaregeneralenoughtomakerefocusinguseful decomposereducerefocus r0]contract r0]contract t00]plugyyssssssssssC0[t00]refocus decomposereduceducer1]contract r1]contract t01]plugyyssssssssssC1[t01]refocus decomposereduceducer2]contract r2]contract t02]plugyyssssssssssC2[t02]refocus decomposeFigure1:Canonicalvs.refocusedevaluation inpractice|forexample,theyareful lledinallthedeterministicreductionsemanticsdescribedinFelleisenandFlatt'slecturenotes[11]andalltheexamplesdocumentedintheSLproject[28,29].Wethenillustraterefocusingwithtworeductionsemanticsforthe-calculus,oneforcallbyvalueandoneforcallbyname(Sections3and4).Inthecall-by-valuecase,therefocusedevaluationfunctionimplementsFelleisenetal.'sCKmachine,andinthecall-by-namecase,therefocusedevaluationfunctionimplementsasubstitution-basedversionofKrivine'smachine.Wealsoconsiderthreecontext-based,quadraticCPStransformers(twoforcallbyvalueandoneforcallbyname)andwemakethemoperateinonepass. 2RefocusinginareductionsemanticsInthissectionweshowhowtoconstructfromscratcharefocusfunctionforareductionsemantics,asanalternativetoplugginganddecomposingforde ninganevaluationfunction.Weprovethatthisfunctioncomputesthecorrectresultandwegiveanexactmeasureofitscomputationalcomplexity.Finallyweshowthatrefocusingisalwaysatleastasecientaspluggingandthendecomposing.2.1ThelanguageAprogramminglanguageisde nedbyitssyntaxanditssemantics.Here,thesemanticsisspeci edbyareductionsemantics.Withoutlossofgeneralityweassumethattheabstractsyntaxisspeci edbyacontext-freegrammar(orBNF)withonlyproductionsoftheform;:::;whererangesoverasetofconstructornamesand;:::;arenon-terminalscorrespondingtothesyntacticcategoriesofthelanguage.Eachconstructormayoccuronlyonceinagrammar.2.2ReductionsemanticsAreductionsemanticsisaspeci cationofasmall-stepoperationalsemantics,i.e.,itspeci esareductionrelationbetweenterms.Reductionsemanticsusuallycomewithcontext-freegrammarsforvaluesandreductioncontexts,anotionofdecompositionandpotentialredex,oftenaunique-decompositionlemma,and nallyreductionrulesoftheformormr]!t,wherethetermdenotesaredex.Letusrevieweachoftheseconceptsinturn.2.2.1ValuesThegrammarofvaluesextendstheBNFofthelanguagewithonenewnon-terminal,,pernon-terminal.Thesetofvaluesrangedoverbyaisincludedinthesetoftermsrangedoverbythematching.Theproductionsforvaluesarealloftheform;:::;xwhere;:::;)isaproductionofthelanguagegrammarandeachiseitherIfareductionsemanticsofthelanguagecontainsonlyvalues,thenitisirrelevantwhetherweuseinplaceof.Fromhereonwewillconsistentlyuseaforsuchasyntacticcategory.2.2.2ReductioncontextsReductioncontexts(oftencalled`evaluationcontexts')arealsospeci edbycontext-freegrammars,andtheirmeaningisgivenbyanassociatedplugfunction.Forexample,thereductioncontextsofthe-calculusundercallbyvalueandtheassociatedplugfunctionwereshowninSection1.3.Allthereductioncontextsofareductionsemanticscanbewrittenasthecomposi-tionofelementaryreductioncontexts.Compositionisabinaryfunctiononreduction contexts,,thattogetherwiththeplugfunctionsatis es((t]=C1[C2[t]],andisthusassociative.Elementarycontextsarethosethatcannotthemselvesbewrittenascompositionsofothernon-emptycontexts.Forexample,forthe-calculusundercallbyvalue(seeSection3),theelemen-tarycontextsare([])and[]).Theconstructionofreductioncontextscorrespondstocomposinganelementarycontexttotherightofanothercontext,e.g.,,app([])]=([]).Inmanyarticlesaboutreductionsemantics,though,compoundcontextsareconstructedbycomposinganelementarycontextontheleftratherthanontheright[11,13].Forthe-calculusundercallbyvalue,thegrammarofreductioncontextsthenreadsasfollows.::=[]Thisnotationinducesthesameelementarycontexts.2.2.3DecompositionsandpotentialredexesIfatermistheresultofplugginganothertermintoareductioncontext,i.e.,i.e.,t]=t0,thenwesaythatandformadecomposition(intoareductioncontextandaterm)of,oralternativelythatcanbedecomposedintoand.Ingeneral,atermcanbedecomposedinmanydi erentways.s.t]thenthedecompositionistrivialifeitheristheemptycontextorisavalue.Weassumethatvaluesarenormalforms:theycannothaveanon-valuesub-terminapositionwhereitcanbeevaluated,soalltheirdecompositionsmustbetrivial.Non-valuetermsthatcanonlybedecomposedtriviallyarecalledpotentialredexes.Forthe-calculusundercallbyvalue,thepotentialredexesareexactlythetermsoftheformormt]thenthedecompositioniscompleteisapotentialredex.Thereductionrulesofareductionsemanticscontainonlycompletedecompositions.Ifatermhasadecomposition,n,t1],thatisnotcomplete,theneitherisavalueoritcanbefurtherdecomposedinanon-trivialwayasst2].Then((t2]isagainanon-trivialdecompositionoftheoriginalterm.Thecontextofacompletedecompositionismaximalinthesensethatfurtherdecompositionswouldbetrivial.2.2.4UniquedecompositionUniquedecompositionisapropertyofreductionsemanticsthatguaranteestheexis-tenceanduniquenessofcompletedecompositionsforarbitraryterms.De nition1(Uniquedecomposition)Areductionsemanticsissaidtosatisfytheunique-decompositionpropertyifanynon-valuetermtcanbeuniquelydecomposedasasr]whererisapotentialredex.Uniquedecompositionissofundamentaltoreductionsemanticsfordeterministiclanguagesthatitisalmostalwaysthe rstpropertytobeestablished.Itsproofis Wenotethatreductioncontexts,togetherwithcompositionandtheemptycontext,formamonoid,whichexplainswhytheycanindi erentlyberepresented\outsidein"or\insideout"[7,11,13].Rep-resentingcontextsinsideoutleadsonetoastackimplementation:extendingacontextisimplementedbypushing,anddecomposingtheinnermostcontextisimplementedbypoppinganddispatching.Thisdoesnotpreclude,e.g.,weakheadnormalformsorlazypairs. oftentechnicallysimple,butbecauseofitsmanysmallcases,ittendstobetediousanderror-prone.Thisstateofa airsmotivatedXiao,Sabry,andAriolatodevelopautomatedsupportforprovingunique-decompositionproperties[29].2.2.5ReductionrulesThereductionrulesofareductionsemanticsareoftheformormr]!twhereisapotentialredexanddependsonlyonandonthesub-termsof.Ofteniswrittenittent0]forsomedependingonThepotentialredexesthatoccurinareductionrulearetheactualreducibletermsofthereductionsemantics.Theremainingpotentialredexesarestuck,tousePlotkin'sterminology[20].Stucktermsencompasstype-incorrectterms(e.g.,theapplicationofaliteral)andunde nedterms(e.g.,theapplicationofanidenti er).Theonlyreductionruleofthe-calculusundercallbyvalueisisapp(lam(x;t);v)]!C[tfv=xg]andthus)isareducibleterm.Theremainingpotentialredexes(oftheform))arestuckterms.2.3RequirementsWestatethreerequirementsthataresucientforconstructingarefocusfunction.WeconsiderreductionsemanticswhosestructureisasdescribedinSection2.2andthatsatisfyuniquedecomposition.2.3.1NoredundantconstructsAreductionsemanticsspeci esareductionrelation.Anypartofaspeci cationthatdoesnota ectthespeci edrelationisredundantandcanbeignored.Speci cally:Ifthelanguagehasagrammarproduction;:::;;:::;)andthesyn-tacticcategoryrangedoverbycontainsonlyvalues,thenanelementaryreduc-tioncontextoftheform;:::;xx;xi+1;:::;x)isredundant.Sinceonlyvaluescanbepluggedinthehole,andvaluescanonlybetriviallyde-composed,thennoreductioncontextconstructedbycomposingthiselementarycontextcaneverbepartofacompletedecomposition.Ifasyntacticcategoryrangedoverbycontainsnovalues,i.e.,thecorrespondingvaluesrangedoverbyistheemptyset,thenanyoccurrenceofinarulemakesthatruleredundant.(Syntacticcategorieswithnovaluesarenotuseless;theycanoccurmeaningfullyin,e.g.,languageswithcontrole ects.)Ifthesyntacticcategoryrangedoverbyisempty,thenthatentiresyntacticcategoryandallotherproductionscontainingareredundantandcansafelybeignored. Xiao,Sabry,andAriolaalsopointoutthatprovinguniquedecompositionreducestoprovingequivalenceandunambiguityofcontext-freegrammars|twoundecidableproperties.IntheirsystemSL,theyreducetheproblemtoregulartreelanguages,forwhichequivalenceandunambiguityaredecidable.Similarly,thegrammarsweconsiderhereareregulartreegrammars. Theabovepropertiesarealldecidable.Decidingwhetherthesetoftermsrangedoverbyanon-terminalisemptyisdecidableforcontext-freegrammars.Thespeci cstructureoftheproductionsofvaluesguaranteesthatvaluesmustbeasubsetofterms,andthatitisdecidablewhetherandgeneratethesamesetofterms,i.e.,whetheronlyrangesovervalues.2.3.2Distinctvalueconstructorsandpotential-redexconstructorsByde nition,potentialredexesaredistinctfromvalues,andvaluesarede nedbyacontext-freegrammaroftheformshowninSection2.2.1.Ifaninstanceofasyntacticconstructcanbecomeavaluebyevaluatingitssub-terms,thenanotherinstancemustnotalsobeabletobecomearedex,andvice-versa.Theonlywayasyntacticconstructcanbecomebothavalueandapotentialredexisifthevalueisgivenbyaproductionoftheform;:::)andthereisnoelementarycontextoftheformform;:::)withaholeinthethposition.Then;:::)isapotentialredexwhennotavalue.Thereareseveralwaystoverifythepropertythatnosyntacticconstructcanbecomebothavalueandapotentialredex.Weusetheequivalentrequirementthatthepoten-tialredexescanbespeci edbyacontext-freegrammarwithproductionsofthesametypeasforvalues.Inotherwords,theproductionsareoftheform;:::;xwhereiseither2.3.3Left-to-rightevaluationofsub-termsWithoutlossofgenerality,weassumethatsub-termsofasyntacticconstructareor-deredsothatevaluatingthemproceedsfromlefttoright.Inotherwords,theuniquedecompositionintoreductioncontextandpotentialredexwillalwayshavetheholeofthecontextoccurringintheleft-mostnon-valuesub-term,intheorderingofsub-termschosenfortheabstractsyntax.Finally,weassumethatinanelementarycontext,ifthesyntacticcategoryoccurstotheleftofthehole,thenthecorrespondingcategoryactuallycontainsnon-valueterms.2.4ConsequencesoftherequirementsTherequirementsofSection2.3guaranteethatareductionsemanticscontainselemen-taryreductioncontexts,values,andpotentialredexesofaspeci cform.ThisformisdescribedinFigure2.AnexamplewheretheinFigure2isstrictlysmallerthanisaconditionalexpressionsuchas).Theonlyelementaryreductioncontextis([]),sincetheothertwosub-termsshouldnotbeevaluateduntiltheconditionalexpressionhasitselfbeenreduced.Anotherexampleisthe-calculusundercallbynamewhereonlythefunctionpartofanapplicationisevaluated.Lemma1AreductionsemanticssatisfyingtherequirementsstatedinSection2.3con-tainsproductionscorrespondingtoFigure2.Proof(sketch):Taketheproduction;:::;Ifthereisavalueproduction;:::;)orapotential-redexproduction;:::;),then=0andbecomesavalueorapotentialredex. Forasyntacticconstructwithsub-terms,;:::;),thereisanumber0suchthattheelementaryreductioncontextsfor([];:::;;;t3;:::;;:::;:::;;tm+1;:::;Iftermsoftheform;:::;;:::;)exist(i.e.,thesyntacticcategoriesrangedoverby;:::allcontainvalues)thentheyareeitherallvaluesorallpotentialredexes.Inotherwords,either;:::;;:::;;:::;;:::;isaproduction,butnotboth.Wethensaythatneedstoevaluate.If;:::;;:::;)isavaluewesaythatbecomesavalue.IfitisapotentialredexwesaythatbecomesapotentialredexFigure2:Elementarycontexts,values,andpotentialredexes Ifthereisnosuchproductionthen,sinceisnotredundant,theremustexistaterm;:::;)thathasanon-trivialdecompositionandthustheremustexistanelementaryreductioncontext;:::;:::;;ti+1;:::;).Weassumethatevalu-ationproceedsfromlefttoright,sotheholemustbeintheleft-mostterm,i.e.,theelementarycontextis([];:::;Assumethatthereexistsanelementaryreductioncontextoftheform;:::;:::;;ti+1;:::;Threecasesoccur:1.Ifonlyrangesovernon-valuesthenandbecomesneitheravaluenorapotentialredex.2.Ifrangesovervaluesandthereexistsaproduction;:::;;:::;;:::;;:::;andbecomeseitheravalueorapotentialredex(sinceitcannotbeboth).3.Ifrangesovervalues,buttermsoftheform;:::;;:::;)arenotvaluesorpotentialredexes,thentheymusthavenon-trivialdecompositions,so thereisacorrespondingelementaryreductioncontext.Underleft-to-rightevalu-ation,thecontextmustbe;:::;;;ti+2;:::;Inotherwords,either(1);:::;;:::;)doesnotexist,oritisavalueorapotentialredex,andthen,or(2)thereexistsanelementaryreductioncontext;:::;:::;;ti+2;:::;),andthen�miAninductionargumentshowsthatisthesmallestsuchthat(1)holds.Thereexistssuchasmallest:atermoftheform;:::;)eitherdoesnotexistorithasonlytrivialdecompositions,i.e.,iseitheravalueorapotentialredex,andthusasrequired.WehaveshownthatareductionsemanticssatisfyingtherequirementscontainstheproductionsofFigure2.Wedonotshowthattherearenofurtherproductions.However,weshowinthenextsectionthatonecancomputetheuniquedecompositionofanytermusingonlytheproductionsofFigure2,andthusanyfurtherproductionswouldeitherberedundantorviolatetheunique-decompositionproperty.2.5ConstructingarefocusfunctionWeconstructafunction,refocus,thatisextensionallyequivalenttothecompositionoftheplugfunctionandthedecomposefunction.Wechoosetomakeituseastackofelementarycontextstorepresentreductioncontexts.Suchastackallowsanecientimplementationofcomposinganelementaryreductioncontextandpluggingaterminacontext.Weuse[]fortheemptycontext/stackand;:::;;;ti+1;:::;forcomposing/pushinganelementarycontext.Therefocusingfunctionisde nedwithtwomutuallyrecursivefunctions.The rst,refocus,takesatermandastackofelementaryreductioncontexts,andisde nedbycasesontheterm;ithasthesametypeasdecompose.Theotherfunction,refocustakesastackofelementarycontextsandavalueasarguments,andisde nedbycasesonthetop-mostelementaryreductioncontextonthestack.Foreach;:::;)inthelanguagegrammar,thereexistsonecorrespondingruleinrefocus.Ifneedstoevaluatesub-termsthentherearerulesinrefocuscorrespondingtotheelementarycontexts([];:::;)through;:::;:::;;tm+1;:::;).Ifrefocusandrefocusareimplementedinatypedsetting(e.g.,ML),thereisonerefocusandonerefocusforeachsyntacticcategoryofthelanguage.Therulesofrefocusmentionedabovegointherefocusfunctionscorrespondingtothesyntacticcategoryrangedoverby.Therulesofrefocusgointheauxiliaryrefocusfunctionscorrespondingtothesyntacticcategoryofthehole,whichisthesameasthesyntacticcategoryofthevalueargument.1.Ifneedstoevaluatezerosub-terms,thenweknowthat;:::;)isavalueorapotentialredex.(a)Ifbecomesavalue,thenrefocus;:::;refocus;:::;(b)Ifinsteadbecomesapotentialredex,thenrefocus;:::;;:::;esincewehavefoundthedecomposition. 2.Ifneedstoevaluatemorethanzerosub-termsthenthe rsttermmustbereduced rst,andwesimplyrefocusonit:refocus;:::;refocus([];:::;Likewise,therefocusfunctionisde nedbycasesonthereductioncontextontopofthestack.If;:::;;;ti+1;:::;)isthetop-mostelementarycontextonthestack,thenthecorrespondingcaseisoneofthefollowing.1.Ifneedstoevaluateexactlysub-terms,then;:::;;:::;),ifsuchatermexists,iseitheravalueorapotentialredex.(a)Ifbecomesavaluethenthecaseisrefocus;:::;:::;;ti+1;:::;refocus;:::;;:::;(b)Ifbecomesapotentialredexthenwehavefoundadecompositionintoreductioncontextandpotentialredex,andthecaseisrefocus;:::;:::;;ti+1;:::;;:::;;:::;(c)Ifrangesoveronlynon-valuesthenthereisnorule.Inatypedsettingthereisnorefocuscorrespondingtotheconstructorsofthatsyntacticcategory.2.Ifneedstoevaluatemorethansub-terms,thenwecontinuesearchingforapotentialredexinthenextsub-term,andtheruleis:refocus;:::;;;ti+1;:::;refocus;:::;;;tn))3.Finallythereisonerulefortheemptycontext.refocus([]Thisbasecaseaccountsforthesituationwheretheentiretermisavalue,sothedecompositionhastoreturnavalueratherthanacontextandapotentialredex.InAppendixA,weillustratetheconstructionofarefocusfunctionforareductionsemanticsofarithmeticexpressionswithprecedence.Inthefollowingsectionweshowthattherefocusfunctiongeneratedbytheaboverulescomputesacorrectdecompositionofatermintoareductioncontextandapo-tentialredex,andthatitdoessoatleastasecientlyasthecombinationofpluganddecompose 2.6CorrectnessByconstruction,refocuscanonlyreturneitheravalueorapairofareductioncontextandapotentialredex,sincetheremainingcasesallperformatailcall.Bothrefocusandrefocusarepassedadecompositionofaterm,i.e.,areductioncontextandanotherterm,andiftheymakearecursivecall,itisonanotherdecompositionofthesameterm.Therefore,ifrefocus)returnsadecomposition,thenitisacompletedecompositionofft].Itthussucestoprovethatrefocusterminatesonanyargument.Letusshowthatifift]=C0[r],whereisapotentialredex,thenrefocus)performs)tail-recursivecalls,whereandarede nedasfollows:RedCont([])=0;:::;:::;;tk+1;:::;))=1+(1+ValPotRedex;:::;;:::;))=1+(1+Givenareductioncontext,computesthenumberofedgestraversedtogofromtheroottotheholeinadepth- rstleft-to-righttraversal,countingtheedgestovaluesbothonthewaydownandonthewayup.Thistraversalisillustratedbythefollowingpicture: @@@@@@@@~~  v�� vOO c ========  v?? c�������� �� tc ========��  v@@ tAsfor,itcomputesthenumberofedgesfollowedbyafulltraversalofacompositevalue.Allfullytraversedsub-termsmustbevalues.Withthisde nition,theresultof)isatmosttwicethenumberofnodesvisitedonsuchatraversal.Weusethefunctiontomeasurehowfartherefocusfunctionhasprogressedinitstraversalofitsargument.Lemma2(Termination)IfCCt]=C0[r]thenrefocusterminatesaftertail-recursivecalls.Proof:Letususetode neaprogressmeasureonalltheleft-handsidesandright-handsidesofthede nitionofrefocusandrefocus Progressrefocus)))=Progressrefocus))=ProgressProgressWiththisde nition,allchoicesofargumentstorefocusandrefocusgivearight-handsidewithaprogressvalueonegreaterthantheleft-handside.Weomitthedetailsandgiveonlyonecaseasexample.needstoevaluatesub-termstobecomeavalueand0m,thenrefocuscontainsthefollowingcase:refocus;:::;:::;;tk+1;tk+2;:::;refocus;:::;;;tk+2;:::;Takingtheprogressmeasureonboththeleft-handsideandtheright-handsidegivestheexpectedone-greatervalueontheright-handside:Progressrefocus;:::;;;tk+1;:::;;:::;:::;;tk+1;:::;))+=1+(1+))+andProgressrefocus;:::;;;tk+2;:::;;:::;:::;;tk+2;:::;=1+(1+=1+(1+))+Sinceeachrecursivecallincreasestheprogressmeasurebyone,andthereisonlya nitepossiblenumberofdi erentsuchcalls(eachcallistooneoftwofunctionsonadecompositionofthesameterm,andatermhasonly nitelymanydecompositions),therecursionmusteventuallyend.Whenthishappens,thecumulativeincreaseintheprogressmeasureisalsothenumberofrecursivecallsperformedtoreachit.ThisnumberisexactlyProgressProgressrefocus))=Lemma2tellsusboththatrefocusisatotalfunctionandhowmanycallsittakesto ndtheresult.InSection2.7,weuseittoshowthatrefocusisalwaysatleastasecientasusingpluganddecompose2.7ComplexityInordertoshowthatrefocusismoreecientthanthecompositionofpluganddecompose,wemust rstdecideonarelevantcomplexitymeasure,andwemust ndthecomplexityofpluganddecomposeFormeasuringthetimecomplexityofrefocusweusethenumberofrecursivecalls,asinSection2.6.Eachcallperformsaboundednumberofbasicoperationsonthesyntax(eitherconstructingatermordeconstructingatermwhilenamingthesub-terms|thelatterisperformedimplicitlysincethefunctionisde nedbycases).Ifeach suchoperationtakesconstanttime,thetimetakentocomputetheresultofrefocusproportionaltothenumberofrecursivecalls(i.e.,boundedbyaconstantfactortimesthenumberofcalls).LetusinformallyarguethatanyimplementationofafunctiondecomposeValRedContPotRedex) ndingtheuniquecompletedecompositionofterms(inasyntacticcategorysatisfyingourrequirements)mustperformatleast(2basicoperationsonthesyntaxtocomputedecomposeer])=().Ifitusesfeweroperations,itcannotinspectallthevaluesofthereductioncontextandofthepotentialredex.Ifwechangedsuchavaluetoanon-value,thentheholeofthereductioncontextshouldbeinthenewnon-valueterm,butthefunctioncannotseethiswithoutinspectingthevalueandthusitmustgenerateanerroneousresult,contradictingtheassumptionthatitcomputestheuniquecompletedecomposition.plugfunctionisimplementedintimeproportionaltothedepthoftheholeinthereductioncontext.Sincethetimecomplexityofdecomposeisalwaysgreater,weignorepluginourcomparison.Insummary,thecomplexityofcomputingdecomposeet])==r]isatleastpro-portionalto),whereasthecomplexityofcomputingrefocussr]isproportionalto).Forreductionsemanticswhererewritesareoftenlocal,thedi erencebetween)and)isoftensigni cantlysmallerthanthevalueof)itself.Forexample,intheChurch-numeralexampleofSection1.3(Example1),thedi erencebetween)and)isconstantwhereas)aloneisproportionaltothesizeoftheinputterm.Insomecases,refocusdoesnobetterthandecompose,e.g.,whenthecontextargu-menttorefocusisalwaysempty(e.g.,fortail-recursiveorcontinuation-passingstyle-terms,andfortrampoline-likeprogramswithcontroloperatorswherethecontextisdiscardedineachstep).Likewise,ifthesizeofthecontextisbounded,thesavingisatmostaconstantfactor.2.8SummaryWehavepresentedafewmildrequirementstoconstructarefocusfunctionforare-ductionsemantics.Wehavealsoproventhecorrectnessofthisconstructionandchar-acterizedthecomplexityoftheconstructedfunction.Refocusingisatleastasecientas rstpluggingandthendecomposing,anditisoftensigni cantlymoreecient. 3The-calculusundercallbyvalueLetusgobacktothe-calculusasinitiallyconsideredinSection1.3.We rstre-statethegrammarsofthelanguageandofthereductionsemanticsintheformatusedinSection2.ThesegrammarscanbeexpresseddirectlyasMLdatatypesandthecorrespondingpluganddecomposefunctionsasMLfunctions(seeAppendixA).TermsvarValuesvarValVariablesVarReductioncontexts::=[]]app([]]app(v;[])]RedContPotentialredexesv;vPotRedexWemakeplugginganddecompositionexplicitwithtwofunctions:plugRedContdecomposeValRedContPotRedexTherefocusingfunctionrefocusisde nedasthecompositionofdecomposeandplug.Itstypeisthus:refocusRedContValRedContPotRedexWenowconsideracall-by-valueinterpreterandthentwocall-by-valueCPStrans-formersforthe-calculus(Sections3.1,3.2,and3.3).Eachusesdecomposeandplugwhichwefuseintoamoreecientrefocusfunction(Section3.4).3.1Acall-by-valueinterpreterWestartfromatraditionalcall-by-valuereductionsemanticsforthe-calculus[10{12].Thecorrespondinginterpreterisde nedasthetransitiveclosureof(1)decomposingatermintoareductioncontextandapotentialredex,(2)contractingthisredexifpossible,and(3)pluggingthecontractumintothecontext.Werestatethisinterpretersothatthedecompositionfunctionisalwaysappliedtotheresultoftheplugfunction.3.1.1Theoriginalspeci cationThefollowinginterpreterimplementstheevaluationfunctionofthereductionseman-tics.Ittakesatermasargumentandrepeatedlydecomposes,contracts,andplugsuntileitheravalueorastucktermisreached,ifany:evaluateValRedContPotRedexevaluateiteratedecomposeiterateValRedContPotRedexValRedContPotRedexiterateiterate))=evaluateplugv=xiteratevar))=(varTheevaluationofatermevaluate).(NB:Thelastclauseofiterateisusedforstuckterms.) Theinterpretercontainstwocallstoevaluate:oneinthesecondclauseofiterateandoneintheinitialcall.Inthesecondclauseofiterate,theargumentofevaluatetheresultofplug,andthesameholdsintheinitialcall,sinceplug[]).InthatdecomposeisalwayscalledwiththeresultofplugLetusre-expresstheinterpreterwitharefocusingfunctionthatcombinesthee ectsdecomposeandplug3.1.2Therefocusedspeci cationWechangetheinterpretertouserefocusinsteadofdecomposeandplug.Insteaddecompose)above,wewritedecomposeplug[])),i.e.,refocus[]);andin-steadofevaluateplugv=x)),weinlinethe(old)de nitionofevaluateandwriteiteratedecomposeplugv=x))),i.e.,iteraterefocusv=xevaluateValRedContPotRedexevaluateiteraterefocus[]))iterateValRedContPotRedexValRedContPotRedexiterateiterate))=iteraterefocusv=xiteratevar))=(varTheevaluationofatermevaluateProposition1Theoriginalinterpreterandtherefocusedinterpreterimplementthesameevaluationfunction.Proof:Immediate.Wearenowfreetouseanyimplementationofrefocusthatisextensionallyequivalentdecomposeplug3.2SabryandFelleisen'sCPStransformerIntheirworkonreasoningaboutprogramsincontinuation-passingstyle(CPS),SabryandFelleisendesignedanewCPStransformation[23,De nition5].ThisCPStransfor-mationintegratesanotionofgeneralizedreductionandthusyieldsverycompactCPSprograms[6].Itisalsounusualinthesensethatitbuildsonthenotionofareductionsemantics.Therefore,itisde nedasthetransitiveclosureofdecomposing,perform-inganelementaryCPStransformation,andplugging,whichmakesitacandidateforrefocusing.3.2.1Theoriginalspeci cationDe nition2(SabryandFelleisen,1993)ThefollowingCPStransformerusesthreemutuallyrecursivefunctions:(andtheauxiliaryfunction)totransformterms,totransformvalues,andtotransformreductioncontexts.Thefunctionsandareparameterizedoveravariablethatrepresentsthecurrentcontinuation.decompose ValRedContPotRedexvarvar))=var))=plugValValvar))=var))=)))forafreshRedCont([])=varrapp(var[])])=varrapp(lam(x;t);[])])=pluggapp([])])=plugvarforafreshTheCPStransformationofatermtis,forafreshTheCPStransformercontains vecallsto(countingtheinitialone).Inthreecases,theargumentofistheresultofplug,andintwocases,theargumentis.AsinSection3.1.1,andsinceplug[]),wecansaythatdecompose,inthede nition,isalwayscalledwiththeresultofplugIftheyareimplementedliterally,decompositionandpluggingentailatimefactorforeachtransformationstepthatislinearinthesizeoftheinputterm,intheworstcase.Overall,theworst-casetimecomplexityofthisCPStransformationisquadraticinthesizeoftheinputterm.Letusre-expresstheCPStransformerwitharefocusingfunctionthatcombinesthee ectsofdecomposeandplug3.2.2Therefocusedspeci cationWechangetheCPStransformertouserefocusinsteadofdecomposeandplugrefocus[]))ValRedContPotRedexvarvar))=var))=refocusValValvar))=var))=forafreshRedCont([])=varrapp(var[])])=varrapp(lam(x;t);[])])=refocussapp([])])=refocusvarforafresh TheCPStransformationofaterm)),forafreshProposition2TheoriginalCPStransformerandtherefocusedCPStransformerim-plementthesametransformationfunction.Proof:Immediate.Wearenowfreetouseanyimplementationofrefocusthatisextensionallyequivalentdecomposeplug3.3AsimplerCPStransformerWepresentasimpli ed,lesscompacting,versionofSabryandFelleisen'scontext-basedCPStransformer,onethatproducesCPStermsalaPlotkin(x:k::::)ratherthanalaFischer(k:x::::)[6].Wethenrestateitsothatthedecompositionfunctionisalwaysappliedtotheresultoftheplugfunction.3.3.1Theoriginalspeci cationThefollowingCPStransformationrepeatedlydecomposesasourcetermintoacontextandtheapplicationofonevaluetoanothervalue,CPStransformstheapplication,andplugsafreshvariableinthecontext.Thisprocesscontinuesuntilthesourcetermisavalue.De nition3(Context-basedCPStransformation)decomposeValRedContPotRedexvarv;v))=ValValvar))=var))=)))forafreshRedContValplugvar)))forafreshTheCPStransformationofatermtis,forafreshAgain,andforthesamereasonsasinSection3.2.1,theworst-casetimecomplexityofthisCPStransformationisquadraticinthesizeoftheinputterm.3.3.2Therefocusedspeci cationWechangetheCPStransformertouserefocusinsteadofdecomposeandplug.In-steadofdecompose)above,wewritedecomposeplug[])),i.e.,refocus[]);andinsteadofplugvar)),wewritedecomposeplugvar))),i.e.,wewriterefocusvar)): refocus[]))ValRedContPotRedexvarv;v))=ValValvar))=var))=)))forafreshRedContValrefocusvar)))forafreshTheCPStransformationofaterm)),forafreshProposition3TheoriginalCPStransformerandtherefocusedCPStransformerim-plementthesametransformationfunction.Proof:Immediate.Wearenowfreetouseanyimplementationofrefocusthatisextensionallyequivalentdecomposeplug3.4RefocusingecientlyApplyingtheconstructionofSection2.5yieldsthefollowingfunctions:refocusRedContValRedContPotRedexrefocusrefocusrefocusrefocussapp([])])refocusRedContValValRedContPotRedexrefocus([]refocussapp([]refocussapp(v;[])])refocussapp(v;[])]v;vByconstruction,refocusimplementsadepth- rstsearchforthe rstapplicationofonevaluetoanother,byrecursivelydescendingintoatermandaccumulatingthecorrespondingcontext.Asforrefocus,itdispatchesontheaccumulatedcontext.Thefollowingde nitionofdecomposeholdsasacorollary:decomposeValRedContPotRedexdecomposerefocus[])3.4.1Thecall-by-valueinterpreterProposition4Thenewrefocusedinterpreterandthepreviousoneimplementthesameevaluationfunction.Proof:Acorollaryofthecorrectnessoftherefocusconstruction. LetusreturntoChurch-numeralexampleofSection1.3.Whenevaluatingatermsuchas,thetimetakentoecientlyrefocusfromacontractumandacontexttoanewcontextandaredexisindependentofthenumberofremainingapplications.Thenewinterpreterthereforeoperatesmoreecientlythantheoriginalone.3.4.2SabryandFelleisen'sCPStransformerProposition5ThenewrefocusedCPStransformerandthepreviousoneimplementthesametransformationfunction.Proof:Acorollaryofthecorrectnessoftherefocusconstruction.IncontrasttotheoriginalCPStransformer,thenewrefocusedCPStransformeroperatesinonepassoveritsinput.Incidentally,thetransformationcanbeoptimizedtoreadasfollows::app([])])=refocussapp(var[])])))Thisway,eachvar)isnotinspectedasaterm.3.4.3ThesimplerCPStransformerProposition6ThenewrefocusedCPStransformerandthepreviousoneimplementthesametransformationfunction.Proof:Acorollaryofthecorrectnessoftherefocusconstruction.IncontrasttotheoriginalCPStransformer,thenewrefocusedCPStransformeroperatesinonepassoveritsinput.3.5Analysisoftherefocusedcall-by-valueinterpreterTherefocusedinterpretertakestheformofa\pre-abstractmachine"(Section3.5.1).Wesuccessivelyshowhowtotransformthispre-abstractmachineintoanabstractmachine(Section3.5.2),howtoputthisabstractmachineineval/applyform(Sec-tion3.5.3),andhowtoputitinpush/enterform(Section3.5.4).Wealsoexhibitthecorrespondingbig-stepsemantics(Section3.5.5).3.5.1Apre-abstractmachineInSection3.4.1,therefocusedinterpreterinaparticularform,whichwenamepre-abstractmachine,andwhichinvolvesatransitionfunctionanda`trampoline'[14]:refocusandrefocus(inSection3.4)de neonetransitionfunctionanditerateSection3.1.2)de nesatrampoline,i.e.,anothertransitionfunctionthatkeepsacti-vatingtheotheruntilavalueisobtained,ifthereisany.Thetrampolinefunctioncomputesthetransitiveclosureofthetransitionfunction.3.5.2Fromthepre-abstractmachinetoanabstractmachineInthepre-abstractmachine,iterateisalwayscalledontheresultofrefocus.Letusfusethesetwofunctionsintoonetransitionfunctionsothatrefocusiscalledtail-recursivelyandthatiterateisappliedtoitsresult(andtotheresultofrefocus evaluateValRedContPotRedexevaluaterefocus[])iterateValRedContPotRedexValRedContPotRedexiterateiterate))=refocusv=xiteratevar))=(varrefocusRedContValRedContPotRedexrefocusrefocusrefocusrefocussapp([]refocusRedContValValRedContPotRedexrefocus([]iteraterefocussapp([]refocussapp(v;[])])refocussapp(v;[])]iteratev;vTheresultisa(tail-recursive)state-transitionfunction,i.e.,anabstractmachine[21].Proposition7Thepre-abstractmachineandtheabstractmachineimplementthesameevaluationfunction.Proof:Immediate.Theformoftheabstractmachineisratheridealbecauseiterateimplementsthereductionrulesofthereductionsemanticsandrefocusandrefocusimplementitscongruencerules|adistinctionthatusuallyrequiresanon-trivialanalysistoestablishforexistingabstractmachines[16].3.5.3Aneval/applyabstractmachineiterateyieldsaneval/applyabstractmachine[18]whichwerecognizetobeFelleisenetal.'sCKmachine[10{12]:evaluateValRedContPotRedexevaluaterefocus[])refocusRedContValRedContPotRedexrefocusrefocusrefocusrefocussapp([])])refocusRedContValValRedContPotRedexrefocus([]refocussapp([]refocussapp(v;[])])refocussapp(lam(x;t);[])]refocusv=xrefocussapp(var[])])=(varProposition8Theabstractmachineandtheeval/applyabstractmachineimplementthesameevaluationfunction.Proof:Immediate. 3.5.4Apush/enterabstractmachinerefocusyieldsapush/enter[18]versionoftheCKmachine:evaluateValRedContPotRedexevaluaterefocus[])refocusRedContValRedContPotRedexrefocus[])=refocussapp([])])=refocussapp(v;[])])refocussapp(lam(x;t);[])])=refocusv=xrefocussapp(var[])])=(varrefocusrefocussapp([]Proposition9Theeval/applyabstractmachineandthepush/enterabstractmachineimplementthesameevaluationfunction.Proof:Immediate.3.5.5Fromtheeval/applyabstractmachinetoabig-stepsemanticsAsalreadyobservedelsewhere[1,5],theeval/applyCKmachineofSection3.5.3isindefunctionalizedform[7,22]:thereductioncontexts,togetherwithrefocus,arethe rst-ordercounterpartofafunction(or,moreprecisely,ofacontinuation).Thehigher-ordercounterpartofthisabstractmachineisacontinuation-passingevaluationfunction.Writingitindirectstyle[4]yieldsanevaluationfunctionthatimplementsatraditionalbig-stepoperationalsemanticsofthe-calculusundercallbyvalue[19,24].Westateitbelowwithoutproofandinaformwherethecontextsareconstructedinside-outincaseofstuckterms: v+vt+(t)t0+v0t00fv0a var ([]var (t;t0)+(app(C;t0))t+vt0+(C;r) 3.6AnalysisoftherefocusedCPStransformersTherefocusedCPStransformersalsotaketheformofpre-abstractmachines,i.e.,ofatrampolinefunctioncomputingthetransitiveclosureofatransitionfunction.Wecanfusethesetwofunctionsintoanabstractmachine.Thisabstractmachineisindefunc-tionalizedform,andwecanwriteitshigher-ordercounterpart,obtainingatraditionalone-passCPStransformer,aswehaveshownelsewhere[9]. 3.7SummaryWehavedescribedhowtoecientlyimplementtheevaluationfunctionofacall-by-valuereductionsemanticsforthe-calculus,bydeforestingtheintermediatetermsproducedineachdecompose-contract-plugcycle.Asabyproduct,wehaveshownhowrefocusingmakesitpossibletomechanicallyobtainanarrayofabstractmachines|includingtheCKmachine|outofthisreductionsemantics.Fromtheseabstractma-chines,wehaveexhibitedthecorrespondingbig-stepoperationalsemantics.Itisalsosimpletowalkbackfromabig-stepoperationalsemanticstoanabstractmachine,fromthisabstractmachinetoarefocusedinterpreter,andfromthisrefocusedinterpretertoareductionsemantics.Wehavealsoshownhowtorefocusquadratic-timecontext-basedCPStransformersintolinear-timeones.Intheliterature[11],thedecomposefunctionisusuallyleftunspeci ed.Ourworksuggeststhataniterativede nitionwithanaccumulatorisconvenientsinceitconnectsone-stepreductionandevaluationintheformofanabstractmachine. 4The-calculusundercallbynameWebrie yillustratethecall-by-namecounterpartofSection3:acall-by-nameinter-preterandasimplecall-by-nameCPStransformerforthe-calculus.We rststatethegrammarsofthelanguageandofthereductionsemantics.TermsvarValuesValVariablesVarReductioncontexts::=[]]app([]RedContPotentialredexesvarPotRedexconstructorisusedforvariablesthatdenotevalues(e.g.,literals)ratherthancomputations|forthose,thevarconstructorisused.Plugginganddecompositionareachievedwiththetwofollowingfunctions:plugRedContdecomposeValRedContPotRedexWenowconsideracall-by-nameinterpreterandthenacall-by-nameCPStrans-formerforthe-calculus.Eachusesdecomposeandplug,whichwefuseintoamoreecientrefocusfunction:refocusRedContValRedContPotRedex4.1Acall-by-nameinterpreterWestartfromatraditionalreductionsemanticsforthe-calculusundercallbyname[11].Thecorrespondinginterpreterisde nedasthetransitiveclosureof(1)decomposingatermintoareductioncontextandapotentialredex,(2)contractingthisredex,ifpossible,and(3)pluggingthecontractuminthecontext.Werestatethisinterpretersothatthedecompositionfunctionisalwaysappliedtotheresultoftheplugfunction.4.1.1Theoriginalspeci cationThefollowinginterpreterimplementstheevaluationfunctionofthereductionseman-tics.Ittakesatermasargumentandrepeatedlydecomposes,contracts,andplugsuntileitheravalueorastucktermisreached,ifany.evaluateValRedContPotRedexevaluateiteratedecomposeiterateValRedContPotRedexValRedContPotRedexiterateiterate))=(iterate))=evaluateplugiteratevar))=(varTheevaluationofatermevaluate).(NB:Thesecondandfourthclausesofiterateareusedforstuckterms.) Theinterpretercontainstwocallstoevaluate:oneinthethirdclauseofiterateandoneintheinitialcall.Inthethirdclauseofiterate,theargumentofevaluateistheresultofplug,andthesameholdsintheinitialcall,sinceplug[]).Therefore,decomposeisalwayscalledwiththeresultofplugLetusre-expresstheinterpreterwitharefocusingfunctionthatcombinesthee ectsdecomposeandplug4.1.2Therefocusedspeci cationWechangetheinterpretertouserefocusinsteadofdecomposeandplug.Insteaddecompose)above,wewritedecomposeplug[])),i.e.,refocus[]);andin-steadofevaluateplug)),wewriteiteratedecomposeplugiteraterefocusevaluateValRedContPotRedexevaluateiteraterefocus[]))iterateValRedContPotRedexValRedContPotRedexiterateiterate))=(iterate))=iteraterefocusiteratevar))=(varTheevaluationofatermevaluateProposition10Theoriginalinterpreterandtherefocusedinterpreterimplementthesameevaluationfunction.Proof:Immediate.Wearenowfreetouseanyimplementationofrefocusthatisextensionallyequivalentdecomposeplug4.2AsimpleCPStransformerWepresentthecall-by-nameanalogueofthecontext-basedCPStransformerofSec-tion3.3.Wethenrestateitsothatthedecompositionfunctionisalwaysappliedtotheresultoftheplugfunction.4.2.1Theoriginalspeci cationThefollowingCPStransformationrepeatedlydecomposesasourcetermintoacontextandtheapplicationofonevaluetoanothervalue,CPStransformstheapplication,andplugsafreshvariable(onethatdenotesavalue)intothecontext.Thisprocesscontinuesuntilthesourcetermisavalue.De nition4(Context-basedCPStransformation)decompose ValRedContPotRedexvar))=forafreshvar))=varValVal))=))=forafreshRedContValplug)))forafreshTheCPStransformationofatermtis,forafreshAsinSection3,theworst-casetimecomplexityofthisCPStransformationisquadraticinthesizeoftheinputterm.4.2.2Therefocusedspeci cationWechangetheCPStransformertouserefocusinsteadofdecomposeandplug.Insteaddecompose)above,wewritedecomposeplug[])),i.e.,refocus[]);andinsteadplug)),wewritedecomposeplug))),i.e.,refocusrefocus[]))ValRedContPotRedexvar))=forafreshvar))=varValVal))=))=forafreshRedContValrefocus)))forafreshTheCPStransformationofaterm)),forafreshProposition11TheoriginalCPStransformerandtherefocusedCPStransformerimplementthesametransformationfunction.Proof:Immediate.Wearenowfreetouseanyimplementationofrefocusthatisextensionallyequivalentdecomposeplug 4.3RefocusingecientlyApplyingtheconstructionofSection2.5yieldsthefollowingfunctions:refocusRedContValRedContPotRedexrefocusrefocusrefocusrefocussapp([])])refocusvar)=(varrefocusRedContValValRedContPotRedexrefocus([]refocussapp([])=(Byconstruction,refocusimplementsadepth- rstsearchforthe rstapplicationofonevaluetoanother,byrecursivelydescendingintoatermandaccumulatingthecorrespondingcontext.Asforrefocus,itdispatchesontheaccumulatedcontext.Thefollowingde nitionofdecomposeholdsasacorollary:decomposeValRedContPotRedexdecomposerefocus[])4.3.1Thecall-by-nameinterpreterProposition12Thenewrefocusedinterpreterandthepreviousoneimplementthesameevaluationfunction.Proof:Acorollaryofthecorrectnessoftherefocusconstruction.AsinSection3.4.1,thenewrefocusedinterpreteroperatesmoreecientlythantheoriginalone,e.g.,ontheChurch-numeralsexampleofSection1.3.4.3.2ThesimpleCPStransformerProposition13ThenewrefocusedCPStransformerandthepreviousoneimplementthesametransformationfunction.Proof:Acorollaryofthecorrectnessoftherefocusconstruction.IncontrasttotheoriginalCPStransformer,thenewrefocusedCPStransformeroperatesinonepassoveritsinput.4.4Analysisoftherefocusedcall-by-nameinterpreterAsinSection3.5,therefocusedinterpretertakestheformofa\pre-abstractmachine".Wesuccessivelyshowhowtotransformthispre-abstractmachineintoanabstractmachine,howtoputthisabstractmachineineval/applyform,andhowtoputitinpush/enterform.Wealsoexhibitthecorrespondingbig-stepsemantics.4.4.1Apre-abstractmachineAsinSection3.1.2,therefocusedinterpreterisintheformofapre-abstractmachine:iterateisatrampolinefunctioncomputingthetransitiveclosureofthetransitionfunc-tionde nedbyrefocusandrefocus 4.4.2Fromthepre-abstractmachinetoanabstractmachineInthepre-abstractmachine,iterateisalwayscalledontheresultofrefocus.Letusfusethesetwofunctionsintoonetransitionfunctionsothatrefocusiscalledtail-recursivelyandthatiterateisappliedonitsresult(andtotheresultofrefocusevaluateValRedContPotRedexevaluaterefocus[])iterateValRedContPotRedexValRedContPotRedexiterateiterate))=(iterate))=refocusiteratevar))=(varrefocusRedContValRedContPotRedexrefocusrefocusrefocusrefocussapp([]refocusvariteratevarrefocusRedContValValRedContPotRedexrefocus([]iteraterefocussapp([]iterateProposition14Thepre-abstractmachineandtheabstractmachineimplementthesameevaluationfunction.Proof:Immediate.AsinSection3.5.2,theformoftheabstractmachineisratheridealbecauseiterateimplementsthereductionrulesofthereductionsemanticsandrefocusandrefocusimplementitscongruencerules.4.4.3Aneval/applyabstractmachineiterateyieldsthefollowingeval/applyabstractmachine:evaluateValRedContPotRedexevaluaterefocus[])refocusRedContValRedContPotRedexrefocusrefocusrefocusrefocussapp([]refocusvar)=(varrefocusRedContValValRedContPotRedexrefocus([]refocussapp([]))=(refocussapp([]))=refocusProposition15Theabstractmachineandtheeval/applyabstractmachineimplementthesameevaluationfunction.Proof:Immediate. 4.4.4Apush/enterabstractmachinerefocusandobtainapush/enterabstractmachinewhichwerecognizetobe(asubstitution-basedversionof)Krivine'smachine[2,3]:evaluateValRedContPotRedexevaluaterefocus[])refocusRedContValRedContPotRedexrefocus[])=refocusvarrapp([])])=(varrefocussapp([])])=refocusrefocusrefocussapp([]refocusvarvarProposition16Theeval/applyabstractmachineandthepush/enterabstractma-chineimplementthesameevaluationfunction.Proof:Immediate.4.4.5Fromtheeval/applyabstractmachinetoabig-stepsemanticsAsinSection3.5.5,theeval/applymachineofSection4.4.3isindefunctionalizedform:thereductioncontexts,togetherwithrefocus,arethe rst-ordercounterpartofafunction(or,moreprecisely,ofacontinuation).Thehigher-ordercounterpartofthisabstractmachineisacontinuation-passingevaluationfunction.Writingitindirectstyleyieldsanevaluationfunctionthatimplementsatraditionalbig-stepoperationalsemanticsofthe-calculusundercallbyname,asinSection3.5.5.Westateitbelowwithoutproofandinaformwherethecontextsareconstructedinside-outincaseofstuckterms: v+vt+lam(t)t00ft0a (t;t0)+at+(x) ([] (t;t0)+(app(C;t0)) var([]var4.5AnalysisoftherefocusedCPStransformerAsinSection3.6,therefocusedCPStransformeralsotakestheformofapre-abstractmachine.Wecanfusethetrampolinefunctionandthetworefocusfunctionsintoanabstractmachine.Again,thisabstractmachineisindefunctionalizedform,andwecanwriteitshigher-ordercounterpart,obtainingatraditionalone-passCPStransformer. 4.6SummaryWehavedescribedhowtoecientlyimplementtheevaluationfunctionofareductionsemanticsforthe-calculusundercallbyname,bydeforestingtheintermediatetermsproducedineachdecompose-contract-plugcycle.Asabyproduct,wehaveshownhowrefocusingmakesitpossibletomechanicallyobtainanarrayofabstractmachines|including(asubstitution-basedversionof)Krivine'smachine|outofthisreductionsemantics.Fromtheseabstractmachines,wehaveexhibitedthecorrespondingbig-stepoperationalsemantics.AsinSection3,itisalsosimpletowalkbackfromabig-stepoperationalsemanticstoanabstractmachine,fromthisabstractmachinetoarefocusedinterpreter,andfromthisrefocusedinterpretertoareductionsemantics.Wehavealsoshownhowtorefocusaquadratic-timecontext-basedCPStransformerintoalinear-timeone.5ConclusionWehavepresentedastructuralresultaboutreductionsemanticswithcontext-freegrammarsofvalues,reductioncontexts,andredexes,andsatisfyingaunique-decom-positionproperty.Theseconditionsarequitegeneral:theyholdfordeterministiclanguagesandalsofororacle-basednon-deterministiclanguages,asillustratedinAp-pendixA;theyhoweverdonotholdwhenthenextredexissearchednon-deterministically.Ourstructuralresultenablesonetomechanicallyconstructarefocusfunctionthatiterativelygoesfromredexsitetoredexsiteandavoidstheoverheadof rstplug-gingandthendecomposinginanevaluationfunction,asillustratedinFigure1.Therefocusedevaluationfunctionimplementsastate-transitionfunction,i.e.,anabstractmachine.WehaveillustratedthispropertybymechanicallyconstructingFelleisenetal.'sCKmachineandasubstitution-basedversionofKrivine'smachineoutoftwore-ductionsemanticsofthe-calculus.Wehavealsomechanicallyturnedcontext-basedquadratic-timeprogramtransformationsintoprogramtransformationsthatoperateinonepass.Theconstructionoftherefocusfunctionsuggestsaconvenientde nitionofthedecomposefunctionthatdirectlyconnectsone-stepreductionandevaluationintheformofanabstractmachine.Italsosuggestsapracticalmethodtoobtainareductionsemanticsoutofanabstractmachine.Acknowledgments:WearegratefultoDanielDamian,BerndGrobauer,FritzHen-glein,andJuliaLawallforcommentingtheinitialversionofthisarticle.ThanksarealsoduetoMadsSigAger,JuliaLawall,KevinMillikin,KristianStvringSrensen,andtheanonymousreviewersforfurthercomments;toMatthiasFelleisenforpointingoutthatrefocusingsystematizestheconstructionofanabstractmachineoutofareductionsemantics;toAmrSabryforencouragingustostresstheconnectionbetweenrefocusanddecompose;toMitchellWandforencouragingustostressthatarefunctionalizedanddirect-style-transformedabstractmachineimplementsabig-stepsemantics;andtoMa lgorzataBiernackaandMitchellWandforrekindlingourinterestindocumentingthisworkproperly.ThisworkissupportedbytheESPRITWorkingGroupAPPSEM()andbytheDanishNaturalScienceResearchCouncil,Grantno.21-03- AArithmeticexpressionswithprecedenceThissectiontreatsacomprehensiveexampleillustratingallthecasesoftheconstruc-tionofarefocusfunctionaspresentedinSection2.5.Weconsiderarithmeticexpres-sionswithaddition,multiplication,conditionalexpressionscheckingwhethertheir rstargumentiszero,parenthesizedexpressions,literals,andoraclesreturning0or1,non-deterministically.(Theoraclesareonlytheretoillustrateacaseoftheconstruction.)Thegrammarisunambiguousandhierarchic,asoftengiveninundergraduatecom-pilercourses.Itspeci esexpressions,terms,andfactors,andreadsasfollows:ExprIfzeeeFactAprogramisanexpression.Therestofthisappendixisstructuredasfollows.We rstpresentareductionsemanticsforarithmeticexpressions(SectionA.1),wereviewhowtorepresentreduc-tioncontextsoutside-inorinside-out(SectionA.2),andwepresentadetailedimple-mentationofthereductionsemantics(SectionA.3).WethenapplythealgorithmofSection2.5andconstructarefocusfunction(SectionA.4).A.1AreductionsemanticsWede nethereductionsemanticsofarithmeticexpressionsbyspecifyingitsvalues,itscomputations,itsreductioncontexts,itsredexesanditsreductionrules.Values(trivialterms):ExprValTermValFactValComputations(seriousterms):ExprCompIfzeeeFactCompReductioncontexts:ExprEvCont::=[]Ifz::=[]FactEvCont::=[] Redexes:ExprRedexIfzTermRedexFactRedexReductionrules:s:n1+n2]!Ee[n3]whereisthesumofanddIfzze1]iffIfzze2]iffn1n2]!Ee[n3]whereistheproductofandd ip]!Ee[0]] ip]!Ee[1]](n)]!Ee[n]Thereductionrulesarede nedonlyondecompositionsthat\makesense",i.e.,onlyanexpressionispluggedinto[],onlyaterminto[]andafactorinto[].Theresultofareductionisanexpression.Thisreductionsemanticssatis esthreeunique-decompositionlemmas,i.e.,decom-posinganexpression(resp.atermandafactor)intoareductioncontextandaredexyieldsauniqueresult.Weprovetheselemmasbystructuralinductiononthesyntax.Thelanguageissimpleenoughthatthenumberofcasesismanageable.Therearenostuckterms,andreductionalwaysyieldsanexpression.Thereduc-tionrelation,however,isnotafunctionfromexpressionstoexpressions,eventhoughdecompositionsareunique,becauseoftheoracles.A.2AnalternativerepresentationofcontextsInSectionA.1,thegrammarofreductioncontextsembodiesleftcomposition,i.e.,theconstructionofcontextsbycompositionwithanelementarycontextontheleft.Inotherwords,eachproductionexceptfortheemptycontext,e.g.,,couldbewrittenas::=(+[].Sincecompositionofcontextsisassociative,wecouldde nethesamecontextsusingrightcomposition,givingaproductionoftheform+[]).Wewriteit,however,inthemorecommonway::vt+[]Wetransformthegrammarofcontextsintoonerepresentingcompositionontheright,andwedothisinacompletelymechanicalway.Theexamplejustaboveshowsthegeneralidea,thoughitdoesnotillustratethecasewherethesub-contextisnotofthesametypeasthegeneratedcontext.Wehavethreegroupsofreductioncontexts,groupedbythesyntacticcategorytheyproducewhenplugged.Taketheelementarycontext[].Ifweleft-composeanotherreductioncontextwiththiselementarycontext,werequirethattheothercontextproducesterms.Ifweright-composethiselementarycontext,however,werequiretheothercontexttoacceptexpressionsinthehole.Tocapturethisrestrictioninthegrammar,wegrouptheproductionsbythetypeoftheholeinstead.Soforexample,theproductionistransformedinto[[] Ingeneral,thetransformationrewritesaproductionoftheform;:::;;:::;x)intooc(x1;:::;;b;:::;x)],anditkeepstheproductionsofemptycontexts.Performingthistransformationonthegrammarofreductioncontextsabovegivesthefollowinggrammar.Reductioncontexts:ExprEvCont::=[]]vt+[]]Ifzzeee]jEf[([])]::=[][[]]vf[]t]jEeEf2FactEvCont::=[][[]Intheoriginalrepresentation,rangedoverallcontextsthatgeneratedexpression,butmadenorestrictiononthetypeofthehole.Thesecondrepresentationlikewiseletsrangeoverallcontextswithaholeacceptinganexpression,butmakesnorestrictiononthetypeoftheresultofaplug.Usingthissecondrepresentation,wemustrequirethatthereductioncontextsappearinginthereductionrulesmustoutputexpressions,i.e.,weruleouttheemptycontextsfromandinthegrammarofreductioncontexts.Theresultingreductioncontextsandreductionrulesreadasfollows.Reductioncontexts:ExprEvCont::=[]]vt+[]]Ifzzeee]jEf[([])][[]]vf[]t]jEeEf2FactEvCont[[]Reductionrules:s:n1+n2]!Ee[n3]whereisthesumofanddIfzze1]iffIfzze2]iffn1n2]!Et[n3]whereistheproductofandd ip]!Ef[0]] ip]!Ef[1]](n)]!Ef[n]A.3ImplementationFigure3displaystheBNFofarithmeticexpressionsinStandardML.Asusualwithreductionsemantics,wedistinguishbetweenvalues(trivialterms)andcomputations(seriousterms).Anexpression()isthustrivial( )orserious( aterm()istrivial( )orserious( );andafactor()istrivial )orserious( ).Theonlyvaluesareintegers,hencevaluesarede nedwiththehierarchyoftypes val,term val,fact ,and.Computationsaresimilarlyembedded,hencethehierarchyoftypes comp,term ,and Figure4displaysthereductioncontextsandFigure5,thecorrespondingplugfunc-tions.Figure6displaystheimplementationofredexesandtheresultofdecomposition,andFigure7,thecorrespondingdecompositionfunctions. datatypeexpr=EXPR_VALofexpr_val|EXPR_COMPofexpr_compandexpr_val=TERM_VAL'ofterm_valandexpr_comp=ADDofterm*expr|IFZofexpr*expr*expr|TERM_COMP'ofterm_compandterm=TERM_VALofterm_val|TERM_COMPofterm_compandterm_val=FACT_VAL'offact_valandterm_comp=MULoffact*term|FACT_COMP'offact_compandfact=FACT_VALoffact_val|FACT_COMPoffact_compandfact_val=INTofintandfact_comp=FLIP|PARENSofexprFigure3:Abstractsyntaxofarithmeticexpressions datatypeexpr_evcont=EEC0|EEC1ofterm_val*expr_evcont|EEC2ofexpr*expr*expr_evcont|EEC3offact_evcontandterm_evcont=TEC1ofexpr*expr_evcont|TEC2offact_val*term_evcont|TEC3ofexpr_evcontandfact_evcont=FEC1ofterm*term_evcont|FEC2ofterm_evcontFigure4:Reductioncontextsforarithmeticexpressions (*plug_expr:expr*expr_evcont�-expr*)(*plug_term:term*term_evcont�-expr*)(*plug_fact:fact*fact_evcont�-expr*)plug_expr(e,EEC0)|plug_expr(e,EEC1(tt,eec))=plug_expr(EXPR_COMP(ADD(TERM_VALtt,e)),eec)|plug_expr(e,EEC2(e1,e2,eec))=plug_expr(EXPR_COMP(IFZ(e,e1,e2)),eec)|plug_expr(e,EEC3fec)=plug_fact(FACT_COMP(PARENSe),fec)plug_term(t,TEC1(e,eec))=plug_expr(EXPR_COMP(ADD(t,e)),eec)|plug_term(t,TEC2(tf,tec))=plug_term(TERM_COMP(MUL(FACT_VALtf,t)),tec)|plug_term(TERM_VALtt,TEC3eec)=plug_expr(EXPR_VAL(TERM_VAL'tt),eec)|plug_term(TERM_COMPst,TEC3eec)=plug_expr(EXPR_COMP(TERM_COMP'st),eec)plug_fact(f,FEC1(t,tec))=plug_term(TERM_COMP(MUL(f,t)),tec)|plug_fact(FACT_VALtf,FEC2tec)=plug_term(TERM_VAL(FACT_VAL'tf),tec)|plug_fact(FACT_COMPsf,FEC2tec)=plug_term(TERM_COMP(FACT_COMP'sf),tec)Figure5:Iterativeplugfunctionsforarithmeticexpressions datatypeexpr_redex=ADD_REDEXofterm_val*expr_val|IFZ_REDEXofexpr_val*expr*exprdatatypeterm_redex=MUL_REDEXoffact_val*term_valdatatypefact_redex=FLIP_REDEX|PARENS_REDEXofexpr_valdatatypedecomposed=VALUEofexpr_val|EXPR_DECOMPOSITIONofexpr_evcont*expr_redex|TERM_DECOMPOSITIONofterm_evcont*term_redex|FACT_DECOMPOSITIONoffact_evcont*fact_redexFigure6:Redexesandtheresultofdecompositionforarithmeticexpressions (*decompose_expr:expr�-decomposed*)(*decompose_expr_comp:expr_comp*expr_evcont�-decomposed*)(*decompose_term_comp:term_comp*term_evcont�-decomposed*)(*decompose_fact_comp:fact_comp*fact_evcont�-decomposed*)decompose_expr(EXPR_VALte)=VALUEte|decompose_expr(EXPR_COMPse)=decompose_expr_comp(se,EEC0)decompose_expr_comp(ADD(TERM_VALtt,EXPR_VALte),eec)=EXPR_DECOMPOSITION(eec,ADD_REDEX(tt,te))|decompose_expr_comp(ADD(TERM_VALtt,EXPR_COMPse),eec)=decompose_expr_comp(se,EEC1(tt,eec))|decompose_expr_comp(ADD(TERM_COMPst,e),eec)=decompose_term_comp(st,TEC1(e,eec))|decompose_expr_comp(IFZ(EXPR_VALte,e1,e2),eec)=EXPR_DECOMPOSITION(eec,IFZ_REDEX(te,e1,e2))|decompose_expr_comp(IFZ(EXPR_COMPse,e1,e2),eec)=decompose_expr_comp(se,EEC2(e1,e2,eec))|decompose_expr_comp(TERM_COMP'st,eec)=decompose_term_comp(st,TEC3eec)decompose_term_comp(MUL(FACT_VALtf,TERM_VALtt),tec)=TERM_DECOMPOSITION(tec,MUL_REDEX(tf,tt))|decompose_term_comp(MUL(FACT_VALtf,TERM_COMPst),tec)=decompose_term_comp(st,TEC2(tf,tec))|decompose_term_comp(MUL(FACT_COMPsf,t),tec)=decompose_fact_comp(sf,FEC1(t,tec))|decompose_term_comp(FACT_COMP'sf,tec)=decompose_fact_comp(sf,FEC2tec)decompose_fact_comp(FLIP,fec)=FACT_DECOMPOSITION(fec,FLIP_REDEX)|decompose_fact_comp(PARENS(EXPR_VALte),fec)=FACT_DECOMPOSITION(fec,PARENS_REDEXte)|decompose_fact_comp(PARENS(EXPR_COMPse),fec)=decompose_expr_comp(se,EEC3fec)Figure7:Iterativedecompositionofanarithmeticexpression (*evaluate:expr�-expr_val*)(*iterate:decomposed�-expr_val*)evaluatee=iterate(decompose_expre)iterate(VALUEte)=te|iterate(EXPR_DECOMPOSITION(eec,ADD_REDEX(FACT_VAL'(INTn1),TERM_VAL'(FACT_VAL'(INTn2)))))=evaluate(plug_expr(EXPR_VAL(TERM_VAL'(FACT_VAL'(INT(n1+n2)))),|iterate(EXPR_DECOMPOSITION(eec,IFZ_REDEX(TERM_VAL'(FACT_VAL'(INT0)),e1,e2)))=evaluate(plug_expr(e1,eec))|iterate(EXPR_DECOMPOSITION(eec,IFZ_REDEX(TERM_VAL'(FACT_VAL'(INTn)),e1,e2)))=evaluate(plug_expr(e2,eec))|iterate(TERM_DECOMPOSITION(tec,MUL_REDEX(INTn1,FACT_VAL'(INTn2))))=evaluate(plug_term(TERM_VAL(FACT_VAL'(INT(n1*n2))),tec))|iterate(FACT_DECOMPOSITION(fec,FLIP_REDEX))=evaluate(plug_fact(FACT_VAL(INT(Oracle.flip())),fec))|iterate(FACT_DECOMPOSITION(fec,PARENS_REDEX(TERM_VAL'(FACT_VAL'(INTn)))))=evaluate(plug_fact(FACT_VAL(INTn),fec))Figure8:Canonicalevaluationofanarithmeticexpression Figure8displaystheevaluationfunction,whichattemptstodecomposeitsinputexpressionintoareductioncontextandaredex.Iftheexpressionisavalue(andthuscannotbedecomposed),thentheresultisfound.Otherwise,theredexiscontracted,thecontractumispluggedintothecontext,andevaluationisiterated.Contractingaredexamountstoaddingtwointegers,selectingbetweentwoexpressions,multiplyingtwointegers,callinganoracle(whichisunspeci edhere;ourimplementationisstate-based),orskippingparentheses.Notermsarestuck.A.4RefocusingWenowconstructtherefocusfunctions.WestartfromtheMLde nitionofthegram-mar,inFigure3,which tstheformatexpectedfortheconstruction.Letusdeterminethereductionsequenceofeachsyntacticconstruct.Themainsyntacticconstructs:Boththeadditionandthemultiplicationevaluatetheirargumentsfromlefttoright.Theconditionalexpressionisspecialinthatitonlyevaluatesits rstargument.Theoraclehasnoargument.Theparenthe-seshaveoneargumentandevaluateit.Allofthesesyntacticconstructscreateredexes. Theauxiliarysyntacticconstructs:Thecoercionsbetweentermsandexpressionsandbetweenfactorsandexpressionshaveoneargument.Thisargumentiseval-uated.Therefocusfunctionsfollowthegrammaticalstructureofthesourcelanguage.Theirskeletonisthusasfollows.funrefocus_expr(EXPR_VALte,eec)=refocus_expr_val(te,eec)|refocus_expr(EXPR_COMPse,eec)=refocus_expr_comp(se,eec)andrefocus_expr_val(te,eec)=...andrefocus_expr_comp(ADD(t,e),eec)=...|refocus_expr_comp(IFZ(e0,e1,e2),eec)=...|refocus_expr_comp(TERM_COMP'st,eec)=...andrefocus_term(TERM_VALtt,tec)=refocus_term_val(tt,tec)|refocus_term(TERM_COMPst,tec)=refocus_term_comp(st,tec)andrefocus_term_val(tt,tec)=...andrefocus_term_comp(MUL(f,t),tec)=...|refocus_term_comp(FACT_COMP'sf,tec)=...andrefocus_fact(FACT_VALtf,fec)=refocus_fact_val(tf,fec)|refocus_fact(FACT_COMPsf,fec)=refocus_fact_comp(sf,fec)andrefocus_fact_val(tf,fec)=...andrefocus_fact_comp(FLIP,fec)=...|refocus_fact_comp(PARENSe,fec)=...Intherestofthissection,wecompleteeachmissingcaseinthisde nition.1.Ifthelengthofthereductionsequenceofaproductioniszero,thentheresultoftheproductionisavalueoraredex.(a)Thecaseofvaluesisalreadytakencareofbecausethegrammardi erentiatesbetweenvaluesandcomputations.Allfunctions x x ifgivenavalue,andcall x ifgivenacomputation.(b)Iftheresultofaproductionisaredex,thenwehavefoundadecomposition.Here,onlytheoracle tsthebill.Wethusreturnadecomposition.refocus_fact_comp(FLIP,fec)=FACT_DECOMP(fec,FLIP_REDEX) 2.Ifthelengthofthereductionsequenceisnon-zero,thenthe rstsub-expressionmustbeevaluated.refocus_expr_comp(ADD(t,e),eec)=refocus_term(t,TEC1(e,eec))|refocus_expr_comp(IFZ(e0,e1,e2),eec)=refocus_expr(e0,EEC2(e1,e2,eec))|refocus_expr_comp(TERM_COMP'st,eec)=refocus_term_comp(st,TEC3eec)refocus_term_comp(MUL(f,t),tec)=refocus_fact(f,FEC1(t,tec))|refocus_term_comp(FACT_COMP'sf,tec)=refocus_fact_comp(sf,FEC2tec)|refocus_fact_comp(PARENSe,fec)=refocus_expr(e,EEC3fec)3.Likewise,each x isde nedbycasesontheinnerelementaryreductioncontext.refocus_expr_val(te,EEC0)=...|refocus_expr_val(te,EEC1(tt,eec))=...|refocus_expr_val(te,EEC2(e1,e2,eec))=...|refocus_expr_val(te,EEC3fec)=...refocus_term_val(tt,TEC1(e,eec))=...|refocus_term_val(tt,TEC2(tf,tec))=...|refocus_term_val(tt,TEC3eec)=...refocus_fact_val(tf,FEC1(t,tec))=...|refocus_fact_val(tf,FEC2tec)=...(a)Ifthelengthofthereductionsequenceofaproductionisreachedandtheproductionconstructsavalue,werefocusonthisvalue.|refocus_term_val(tt,TEC3eec)=refocus_expr_val(TERM_VAL'tt,eec)|refocus_fact_val(tf,FEC2tec)=refocus_term_val(FACT_VAL'tf,tec)(b)Ifthelengthofthereductionsequenceofaproductionisreachedandtheproductionconstructsaredex,wehavefoundadecomposition. |refocus_expr_val(te,EEC1(tt,eec))=EXPR_DECOMP(eec,ADD_REDEX(tt,te))|refocus_expr_val(te,EEC2(e1,e2,eec))=EXPR_DECOMP(eec,IFZ_REDEX(te,e1,e2))|refocus_expr_val(te,EEC3fec)=FACT_DECOMP(fec,PARENS_REDEXte)|refocus_term_val(tt,TEC2(tf,tec))=TERM_DECOMP(tec,MUL_REDEX(tf,tt))(c)Ifthelengthofthereductionsequenceofaproductionisnotreached,werefocusonthenextsub-expressiontobereduced.refocus_term_val(tt,TEC1(e,eec))=refocus_expr(e,EEC1(tt,eec))refocus_fact_val(tf,FEC1(t,tec))=refocus_term(t,TEC2(tf,tec))4.Finally,weturntotheemptycontext:refocus_expr_val(te,EEC0)=VALUEteTherefocusfunctionsarenowcomplete(seeFigures9and10). (*refocus_expr:expr*expr_evcont�-decomposed*)(*refocus_expr_val:expr_val*expr_evcont�-decomposed*)(*refocus_expr_comp:expr_comp*expr_evcont�-decomposed*)(*refocus_term:term*term_evcont�-decomposed*)(*refocus_term_val:term_val*term_evcont�-decomposed*)(*refocus_term_comp:term_comp*term_evcont�-decomposed*)(*refocus_fact:fact*fact_evcont�-decomposed*)(*refocus_fact_val:fact_val*fact_evcont�-decomposed*)(*refocus_fact_comp:fact_comp*fact_evcont�-decomposed*)Figure9:Refocusingoveranarithmeticexpression(signature) funrefocus_expr(EXPR_VALte,eec)=refocus_expr_val(te,eec)|refocus_expr(EXPR_COMPse,eec)=refocus_expr_comp(se,eec)andrefocus_expr_val(te,EEC0)=VALUEte|refocus_expr_val(te,EEC1(tt,eec))=EXPR_DECOMPOSITION(eec,ADD_REDEX(tt,te))|refocus_expr_val(te,EEC2(e1,e2,eec))=EXPR_DECOMPOSITION(eec,IFZ_REDEX(te,e1,e2))|refocus_expr_val(te,EEC3fec)=FACT_DECOMPOSITION(fec,PARENS_REDEXte)andrefocus_expr_comp(ADD(t,e),eec)=refocus_term(t,TEC1(e,eec))|refocus_expr_comp(IFZ(e0,e1,e2),eec)=refocus_expr(e0,EEC2(e1,e2,eec))|refocus_expr_comp(TERM_COMP'st,eec)=refocus_term_comp(st,TEC3eec)andrefocus_term(TERM_VALtt,tec)=refocus_term_val(tt,tec)|refocus_term(TERM_COMPst,tec)=refocus_term_comp(st,tec)andrefocus_term_val(tt,TEC1(e,eec))=refocus_expr(e,EEC1(tt,eec))|refocus_term_val(tt,TEC2(tf,tec))=TERM_DECOMPOSITION(tec,MUL_REDEX(tf,tt))|refocus_term_val(tt,TEC3eec)=refocus_expr_val(TERM_VAL'tt,eec)andrefocus_term_comp(MUL(f,t),tec)=refocus_fact(f,FEC1(t,tec))|refocus_term_comp(FACT_COMP'sf,tec)=refocus_fact_comp(sf,FEC2tec)andrefocus_fact(FACT_VALtf,fec)=refocus_fact_val(tf,fec)|refocus_fact(FACT_COMPsf,fec)=refocus_fact_comp(sf,fec)andrefocus_fact_val(tf,FEC1(t,tec))=refocus_term(t,TEC2(tf,tec))|refocus_fact_val(tf,FEC2tec)=refocus_term_val(FACT_VAL'tf,tec)andrefocus_fact_comp(FLIP,fec)=FACT_DECOMPOSITION(fec,FLIP_REDEX)|refocus_fact_comp(PARENSe,fec)=refocus_expr(e,EEC3fec)Figure10:Refocusingoveranarithmeticexpression(de nition) (*evaluate:expr�-expr_val*)(*iterate:decomposed�-expr_val*)evaluatee=iterate(refocus_expr(e,EEC0))iterate(VALUEte)=te|iterate(EXPR_DECOMPOSITION(eec,ADD_REDEX(FACT_VAL'(INTn1),TERM_VAL'(FACT_VAL'(INTn2)))))=iterate(refocus_expr(EXPR_VAL(TERM_VAL'(FACT_VAL'(INT(n1+n2)))),eec))|iterate(EXPR_DECOMPOSITION(eec,IFZ_REDEX(TERM_VAL'(FACT_VAL'(INT0)),e1,e2)))=iterate(refocus_expr(e1,eec))|iterate(EXPR_DECOMPOSITION(eec,IFZ_REDEX(TERM_VAL'(FACT_VAL'(INTn)),e1,e2)))=iterate(refocus_expr(e2,eec))|iterate(TERM_DECOMPOSITION(tec,MUL_REDEX(INTn1,FACT_VAL'(INTn2))))=iterate(refocus_term(TERM_VAL(FACT_VAL'(INT(n1*n2))),tec))|iterate(FACT_DECOMPOSITION(fec,FLIP_REDEX))=iterate(refocus_fact(FACT_VAL(INT(Oracle.flip())),fec))|iterate(FACT_DECOMPOSITION(fec,PARENS_REDEX(TERM_VAL'(FACT_VAL'(INTn)))))=iterate(refocus_fact(FACT_VAL(INTn),fec))Figure11:Refocusedevaluationofanarithmeticexpression TherefocusedevaluationfunctionisdisplayedinFigure11.Ratherthandecompos-ingtheresultoftheplugfunctions,asinFigure8,refocuseseachcontractumanditerates.Fusingandeachoftherefocusfunctionsyieldsanabstractma-chineforarithmeticexpressions.A.5SummaryWehaveconsideredarithmeticexpressionswithprecedenceandwehavespeci edtheirmeaningwithareductionsemantics.WehavethenappliedthealgorithmofSection2.5towriterefocusingfunctionsthatmapareductioncontextandasyntacticentityintoeitheravalueoradecompositionintoareductioncontextandapotentialredex.Theconstructionsuggestsanalternativede nitionofdecomposition:fundecompose_expr_alte=refocus_expr(e,EEC0) [1]MadsSigAger,DariuszBiernacki,OlivierDanvy,andJanMidtgaard.Afunctionalcorrespondencebetweenevaluatorsandabstractmachines.InDaleMiller,editor,ProceedingsoftheFifthACM-SIGPLANInternationalConferenceonPrinciplesandPracticeofDeclarativeProgramming(PPDP'03),pages8{19.ACMPress,August2003.[2]PierreCregut.Anabstractmachineforlambda-termsnormalization.InMitchellWand,editor,Proceedingsofthe1990ACMConferenceonLispandFunctionalProgramming,pages333{340,Nice,France,June1990.ACMPress.[3]Pierre-LouisCurien.Anabstractframeworkforenvironmentmachines.TheoreticalComputerScience,82:389{402,1991.[4]OlivierDanvy.Backtodirectstyle.ScienceofComputerProgramming,22(3):183{195,1994.[5]OlivierDanvy.Onevaluationcontexts,continuations,andtherestofthecom-putation.InHayoThielecke,editor,ProceedingsoftheFourthACMSIGPLANWorkshoponContinuations,TechnicalreportCSR-04-1,DepartmentofComputerScience,QueenMary'sCollege,pages13{23,Venice,Italy,January2004.Invitedtalk.[6]OlivierDanvyandLasseR.Nielsen.CPStransformationofbeta-redexes.InAmrSabry,editor,ProceedingsoftheThirdACMSIGPLANWorkshoponContinu-ations,Technicalreport545,ComputerScienceDepartment,IndianaUniversity,pages35{39,London,England,January2001.AcceptedforpublicationinInfor-mationProcessingLetters(2004).[7]OlivierDanvyandLasseR.Nielsen.Defunctionalizationatwork.InHaraldSndergaard,editor,ProceedingsoftheThirdInternationalACMSIGPLANCon-ferenceonPrinciplesandPracticeofDeclarativeProgramming(PPDP'01),pages162{174,Firenze,Italy,September2001.ACMPress.ExtendedversionavailableasthetechnicalreportBRICSRS-01-23.[8]OlivierDanvyandLasseR.Nielsen.Syntactictheoriesinpractice.InMarkvandenBrandandRakeshM.Verma,editors,InformalproceedingsoftheSecondInternationalWorkshoponRule-BasedProgramming(RULE2001),volume59.4ElectronicNotesinTheoreticalComputerScience,Firenze,Italy,September[9]OlivierDanvyandLasseR.Nielsen.Onone-passCPStransformations.TechnicalReportBRICSRS-02-3,DAIMI,DepartmentofComputerScience,UniversityofAarhus,Aarhus,Denmark,January2002.AcceptedforpublicationintheJournalofFunctionalProgramming.[10]MatthiasFelleisen.TheCalculiof-v-CSConversion:ASyntacticTheoryofControlandStateinImperativeHigher-OrderProgrammingLanguages.PhDthe-sis,DepartmentofComputerScience,IndianaUniversity,Bloomington,Indiana,August1987. [11]MatthiasFelleisenandMatthewFlatt.Programminglanguagesandlambdacalculi.Unpublishedlecturenotes.http://www.ccs.neu.edu/home/matthias/3810-w02/readings.html,1989-2003.[12]MatthiasFelleisenandDanielP.Friedman.Controloperators,theSECDmachine,andthe-calculus.InMartinWirsing,editor,FormalDescriptionofProgrammingConceptsIII,pages193{217.ElsevierSciencePublishersB.V.(North-Holland),Amsterdam,1986.[13]MatthiasFelleisen,MitchellWand,DanielP.Friedman,andBruceF.Duba.Ab-stractcontinuations:Amathematicalsemanticsforhandlingfullfunctionaljumps.InRobert(Corky)Cartwright,editor,Proceedingsofthe1988ACMConferenceonLispandFunctionalProgramming,pages52{62,Snowbird,Utah,July1988.ACMPress.[14]StevenE.Ganz,DanielP.Friedman,andMitchellWand.Trampolinedstyle.InPeterLee,editor,Proceedingsofthe1999ACMSIGPLANInternationalConfer-enceonFunctionalProgramming,pages18{27,Paris,France,September1999.ACMPress.[15]JosephGoguenandGrantMalcolm.AlgebraicSemanticsofImperativeProgramsTheMITPress,1996.[16]ThereseHardin,LucMaranget,andBrunoPagano.Functionalruntimesystemswithinthelambda-sigmacalculus.JournalofFunctionalProgramming,8(2):131{172,1998.[17]GillesKahn.Naturalsemantics.TechnicalReport601,INRIA,SophiaAntipolis,France,February1987.[18]SimonMarlowandSimonL.PeytonJones.Makingafastcurry:push/entervs.eval/applyforhigher-orderlanguages.InKathleenFischer,editor,Proceedingsofthe2004ACMSIGPLANInternationalConferenceonFunctionalProgram-ming,pages4{15,Snowbird,Utah,September2004.ACMPress.[19]HanneRiisNielsonandFlemmingNielson.SemanticswithApplications,aformalintroduction.WileyProfessionalComputing.JohnWileyandSons,1992.[20]GordonD.Plotkin.Call-by-name,call-by-valueandthe-calculus.TheoreticalComputerScience,1:125{159,1975.[21]GordonD.Plotkin.Astructuralapproachtooperationalsemantics.TechnicalReportFN-19,DAIMI,DepartmentofComputerScience,UniversityofAarhus,Aarhus,Denmark,September1981.[22]JohnC.Reynolds.De nitionalinterpretersforhigher-orderprogramminglan-guages.Higher-OrderandSymbolicComputation,11(4):363{397,1998.Reprintedfromtheproceedingsofthe25thACMNationalConference(1972),withafore-word.[23]AmrSabryandMatthiasFelleisen.Reasoningaboutprogramsincontinuation-passingstyle.LispandSymbolicComputation,6(3/4):289{360,1993. [24]PeterSestoft.Demonstratinglambdacalculusreduction.InTorben.Mogensen,DavidA.Schmidt,andI.HalSudborough,editors,TheEssenceofComputation:Complexity,Analysis,Transformation.EssaysDedicatedtoNeilD.Jones,number2566inLectureNotesinComputerScience,pages420{435.Springer-Verlag,2002.[25]JosephStoy.Somemathematicalaspectsoffunctionalprogramming.InJohnDar-lington,PeterHenderson,andDavidA.Turner,editors,FunctionalProgramminganditsApplications.CambridgeUniversityPress,1982.[26]PhilipWadler.Theessenceoffunctionalprogramming(invitedtalk).InAn-drewW.Appel,editor,ProceedingsoftheNineteenthAnnualACMSymposiumonPrinciplesofProgrammingLanguages,pages1{14,Albuquerque,NewMexico,January1992.ACMPress.[27]MitchellWand.Semantics-directedmachinearchitecture.InRichardDeMillo,editor,ProceedingsoftheNinthAnnualACMSymposiumonPrinciplesofPro-grammingLanguages,pages234{241.ACMPress,January1982.[28]YongXiao,ZenaM.Ariola,andMichelMauny.Fromsyntactictheoriestointer-preters:Aspeci cationlanguageanditscompilation.InNachumDershowitzandClaudeKirchner,editors,InformalproceedingsoftheFirstInternationalWork-shoponRule-BasedProgramming(RULE2000),Montreal,Canada,Septem-ber2000.Availableonlineathttp://www.loria.fr/~ckirchne/=rule2000/[29]YongXiao,AmrSabry,andZenaM.Ariola.Fromsyntactictheoriestointer-preters:Automatingproofsofuniquedecomposition.Higher-OrderandSymbolicComputation,14(4):387{409,2001. RecentBRICSReportSeriesPublicationsRS-04-26OlivierDanvyandLasseR.Nielsen.RefocusinginReductionSemantics.November2004.iii+44pp.ThisreportsupersedesBRICSreportRS-02-04.ApreliminaryversionappearsintheinformalproceedingsoftheSecondInternationalWorkshoponRule-BasedProgramming,RULE2001,ElectronicNotesinTheoreticalComputerScience,Vol.59.4.RS-04-25MayerGoldberg.OntheRecursiveEnumerabilityofFixed-PointCombinators.November2004.7pp.RS-04-24LucaAceto,WillemJanFokkink,AnnaIngottir,andSumitNain.BisimilarityisnotFinitelyBasedoverBPAwithInterrupt.October2004.30pp.RS-04-23HansHuttelandJiSrba.Recursionvs.ReplicationinSim-pleCryptographicProtocols.October2004.26pp.ToappearinVojtas,editor,31stConferenceonCurrentTrendsinTheoryandPracticeofInformatics,SOFSEM'05Proceedings,LNCS,RS-04-22GianLucaCattaniandGlynnWinskel.Profunctors,OpenMapsandBisimulation.October2004.64pp.ToappearinMathematicalStructuresinComputerScienceRS-04-21GlynnWinskelandFrancescoZappaNardelli.New-HOPLA—AHigher-OrderProcessLanguagewithNameGeneration.Oc-tober2004.38pp.RS-04-20MadsSigAger.FromNaturalSemanticstoAbstractMachinesOctober2004.21pp.PresentedattheInternationalSymposiumonLogic-basedProgramSynthesisandTransformation,LOP-STR2004,Verona,Italy,August26–28,2004.RS-04-19BoletteAmmitzbøllMadsenandPeterRossmanith.MaximumExactSatisability:NP-completenessProofsandExactAlgo-rithms.October2004.20pp.RS-04-18BoletteAmmitzbøllMadsen.AnAlgorithmforExactSatis-abilityAnalysedwiththeNumberofClausesasParameterSeptember2004.4pp.RS-04-17MayerGoldberg.ComputingLogarithmsDigit-by-DigitSeptember2004.6pp.RS-04-16KarlKrukowandAndrewTwigg.DistributedApproximationofFixed-PointsinTrustStructures.September2004.25pp.

Related Contents


Next Show more