;     TeX output 1995.10.19:1430                                       ⍠?      ddN ff    cmbx12StrictnessffAnalysisI4aGrandeVitesse:  RewritingfftherulesoftheEvaluationTfransformersgame5XQ ff    cmr12Second/draft:D>OctobdCer19,1995.Commentsarewelcomed.=
!", 
   
   cmsy10y @(K`y 
3 
   cmr10JulianfSew!ard
5)JDepartmen!tfofComputerScience,UniversityofManchester,M139PL,UK >?7<x 
3 
   cmtt10sewardj@cs.man.ac.uk  "  kAH 	   
   cmssbx10Abstracto 	   	   cmr9ThislpapAerpresen9tsthedesignofastrictnessanalyserpri-
  marilyuin9tendedtoassistintheparallelisationofHaskellprograms.Theqanalysergeneratesdetailedev|raluationtrans-former'informationsuitableforuseinaparallelgraphre-ductionssmac9hine.6BytuningthedesigntohandlecommoncasesH'rapidly:,Tw9eachievegoAodH'performanceo9verarangeofrealistic~testinputs,.ofsizesuptoathousandlines.P9er-formance/guresarepresen9ted. F:rommeasuringthetimeit!Stak9esGlasgowHaskell0.10tocompilethosesamepro-grams,itw3isapparen9tthattheanalyserissucientlyquicktoߥbAeapproac9hingthepoin9twhereincorporatingitin9toaHask9ellTcompilerisaviablepropAosition.
Ourstrictnessanalysercon9tainsthreema jorinnov|rations.Firstly:,w9e employamixedforwardandbackwardsanaly-sis,l
whic9h'allowsustodopro jectionanalysiseveninthepresenceFofhigherorderfunctions.ESecondly:,w9esolvetheresultingչrecursiv9edomainequationsusingasophisticatedtermrewritingsystem,Nlwhic9h,asfarasweknow,Nlhasabilitiesfar9~bAey9ondpreviousrewritebasedsolversinabstractinter-pretationsystems.Finally:,xw9eavoidmanyofthedicultiesof|higherorderanalysisb9yautomaticallytransformingoutmostThigherorderfunctionsbAeforeanalysisbegins.-1IntroFfductionHigher-order,Znon-
at,dstrictnessanalysistec9hniqueshaveac-quiredareputationforbAeingtooexpensiv9eforuseinpro-ductionscompilers. Thisisapit9y:,sincemanysuchfunctionsbAeha9veinrelativ9elysimpleways,~whichsuggeststheirab-stractTbAeha9viourcouldbedivinedwithoutm9uchTdiculty:.
Oneofthemainthemeswhic9hcharacterisedthepastdecade'sadv|rancesinhardw9areandsoftwarepAerformanceis5thatofmeasuremen9t-leaddesign.}\ThisschoAolofthoughtbasesdesignonmeasuringwhatprogramsdomostoften,andWQmakingthesecommonactivitiesasfastaspAossible,}Rev9enattheexpAenseofslo9wingdownlesscommonopAerations.These,ideas,relabAoratedinHennessy&P9atterson[HP90z],   ff _34
+br0n       cmsy5YٓR       cmr7My}^ap7ologiesforthedog-roughtypesetting.|Thiswillbexedin  laterversionsofthepap7er.fh"   pla9yedacen9tralroleintheRISC{revolution,HandhavebAeen
   tak9en
uprecentlybythefunctionalprogrammingcommu- nit9yT[PHHP93#][Par92].
 W:epresen9t,Zindetail,thedesignofafaststrictnessanalyser forHask9ell,dealingwithhigher-orderfunctionsandgen- eratingvev|raluationtransformerinformationsuitableforuse inUparallelgraphreductionsystems[Bur87][Bur91].sPre- liminary5expAerimen9tshavebAeenencouraging.}F:orexample, runningincompiledHask9ellonaSunSparc-10,	a618line program}Xw9asanalysedin44seconds.T|Ofthis,Yroughlyhalf w9asdevotedtoparsing,UdesugaringandtypAechecking,Uex- pAensesRwhic9hanycompilerwouldincur.ҨAsanaiverst implemen9tation,jthereisamplescopAeforperformanceim- pro9vement. ThisXpapAerarguesinfa9vourXofameasuremen9t-leadapproach forqtheimplemen9tationofsemanticanalysistechniquesfor functionallanguages.
UAma joremphasisistofeedtheanal- yserLthekindsofprogramspAeoplereallywrite,Zratherthan basingdesigndecisionsontheusualMic9keyMouseexam- plesoAccurringsofrequen9tlyinpapersonthesub ject.xT:o thisend,testinputsha9vebAeentak9enfromthebenc9hmark suitesTofHartel[HL92l]andP9artain[Par92]. Suc9h?anapproachrevealssomeinterestingfacts.~F:orex- ample,w9ecdiscoveredthemainlimitationonanalyserpAer- formance#w9asnotthenecessitytoiteratetoanddetectx- pAoin9ts,ashadbeenassumedb9ysomanytheoretics.Rather, itaw9asthesheersizeofthetermsgeneratedduringtheab- stractcBin9terpretationphase.;ByintroAducingalittlemore in9telligenceGintothatphase,8termsizeiscutdramatically:, givingTacorrespAondingperformanceincrease. Similarly:,hpAolymorphismXisdealtwithb9ythecrudemecha- nismofamonomorphisationpassbAeforeanalysis./Previous w9orkers,pincludingmyself,assumedthisw9asa\badthing" (see[HH91>]and[Sew93/]),гandputm9ucheortin9todevising pAolymorphicanalysismethods[Bar91U].5Y:etthefearedcode explosion,қitseems,simplydoAesnothappen. Measuremen9ts b9y<MarkJonesona13000lineHaskellprogram{thesource coAdeTDofthisanalyser{rev9ealthatonlyaveryfewpAoly- morphicGfunctions,TforexampleMߤN  	   	   cmtt9MmapandMfoldr,areusedat alargen9umbAerofinstances.Certainly:,monomorphisation doAeswnotcausean9ynoticeableperformanceproblemsforthis analyser.#Am m9uchmbAetterreasonfordislikingmonomorphic analyses#isthattheysignican9tlycomplicatelifewhenmoAd- ulesTappAearonthescene.                                          *⍠?      1.1GOverviewLofpapFfermTheIremainderofthein9troAductionisdevotedtoanoverview
  ofTtheanalyser,henceforthreferredtoasNt: 	   	   cmbx9NAnna.
Section2dealswithtec9hnicalpreliminaries./Inparticular,w9enexaminehowtypAesinthesourceprogramaremappedtoabstract
domainssuitableforthecon9trolofparallelev|ralua-tion.The~abstractin9terpretationusedformsthesub jectofsec-tione<3.'Adv|rarian9tofthepro jectionanalysisdescribAedinsection,6of[Hug87'],rthetec9hniqueisamixedbackwardsandforw9ardsanalysis,withtheaimofpAerformingback-w9ards4analysis.Bysupplyingjustenough\forwards"infor-mationltoturnfunctionsin9torstclasscitizens,theanalysisdeals sensiblywithhigher-orderfunctions,kpartialapplica-tionsTandfunctionsinsidedatastructures.Section4presen9ts,/$indetail,theelabAoratetermrewritingsystemlusedtodetectxedpAoin9tsintherecursivedomainequationsTgeneratedb9ytheabstractinterpreter.F:unctionalfprogrammersha9veflongobserv9edthatlargepartsofztheprogramstheywritecanbAemec9hanicallytransformedtoeha9venohigher-orderfunctions.(AnnaexploitsthistogoAodeect,transforminga9wayasman9yhigher-orderfunc-tionsiaspAossiblebeforeanalysis."Commonhigherorderfunc-tionsc|whic9hencapsulateparticularformsofrecursion,wsuchasgMfoldr,{aretriviallyremo9ved.Evengmoredicultforms,lik9eP$themonadssobAelovedincertainquarters[W:ad92]aretransformable.)Nev9ertheless,someodicultiesremain.Sec-tiono5discussesallthisindetail. W:ealsoloAokbrie
yatthemonomorphiser.Finally:,/in9section6,allthesegoAodies9aredra9wntogetherwith@adiscussionofthesystem'spAerformance,kandofrelatedandTfurtherw9ork.1.2GOverviewLoftheanalyser'sfrontendmAnnapisalargeHask9ellprogram,Bconsistingofmorethan130007lines.OpAerationissimple.Annareadsasourcepro-gramCyonthestandardinput,OandpAerformsextensiv9etrans-formationsontheprogram,prin9tingitoutatv|rariouspAointson1thew9ay:.qFinally,8the1strictnessinformationisgeneratedandTprin9ted.TheylanguageacceptedisasubsetofHask9ell.IfMissingfea-turesarean9ythingtodowithoverloading,CmoAdulesorarrays.Becauseofthese,+oeringuparbitraryHask9ellprogramsforanalysisisadiculttask:Gallo9verloadinghastobAeresolv9edb9yhand,*atediousbusiness.ThelackofmoAdulesupportdoAesrnotpro9vermuchofaproblem,(sincemultimoAduleinputsarensimplyconcatenatedin9toonemassiveprogram,moAdulosolving|theoAddrenamingproblemalongthew9ay:.RAnnakno9ws`YnothingabAouttheHaskellprelude,sandtherelev|rantpartsofthistoAoneedtobeinsertedin9totheinputs.Averyfew(opAerationsaretak9enasprimitive:AM(+),lM(-),M(*)(andM(/),~all{oft9ypAeMInt->Int->Int,comparisons{M(<),M(<=),M(==),nM(/=),M(>)EandM(>=),noft9ypAeMInt->Int->Bool,andcon9version=functionsMchrandMordoft9ypAeMInt->Char=andMChar->IntͺrespAectiv9ely:.Av|ralidprogrammustsupplyabindingforMmain,butunlik9eaHaskellprogram,thismaybAeofTan9ytypAe.Despiteithismeagrecollectionofprimitiv9es,AnnaknowsabAoutfmostofthebuilt-inHask9elltypAes,includingbooleans,c9haracters,Tstrings,listsGandtuples.AlthoughsomeimpAor-   tan9tܻfeaturesofHaskellaremissing,
thesubsetallowsAnna
   to:CbAefedreal-w9orldprogramsofconsiderablecomplexity:, albAeitTaftersomeconsiderablemassaging.
 Probablyg)thebAestw9ayg)tothinkofAnnaisasaframew9ork forItryingoutnewanalysistec9hniques.NHence,Fthesystem logically%consistsoft9wo%parts:=theanalysispropAer,)andthe suppAortinguframew9ork.=TheinterfacebAetweenthetwois reasonablyVclean,Ӽsoc9hangingthenatureoftheanalysiscan bAeudonewithoutm9uchuupheav|ral.DThissectionfoAcusseson theTsuppAortingframew9ork. Because'w9ewanttoexercisetheanalysesonfunctionalpro- gramsT'ofrealisticsize,zthesuppAortingframew9orkisnecessar- ilylargeandcomplex.Indeed,΍theanalysispartiscurren9tly thesmallerofthet9wo.TheframeworkcontainsagoAodly partofwhatonemigh9texpAecttondinafull-scalecom- pilerTforthesamelanguage:OP 	   	   cmsy9P:F:ollo9wing=
theparsingstage,desugaringandpattern:matc9hing0transformationsarecarriedout.oThesepro-:duceyNCore,Oaminimalfunctionallanguageusedas:an
-in9termediateformintheGlasgowHaskellcom-:piler[PHHP93#],\andt9ypicaloftheintermediateforms:of|v|rariousothercompilers,forexampletheChalmers:Hask9ell-B}Compiler[Aug87']. hAllfurthertransforma-:tionspriortostrictnessanalysispropAerareCore-to-:CoreTtransformations.34P:AMdepAendancyNanalysisphasesplitstheprogramup:in9toyminimalmutuallyrecursivegroups,andmarks:non-recursiv9eM>bindingsassuch..Allsubsequenttrans-:formationsBarerequiredtomain9taindepAendancyorder.P:Azcrude͌buteectiv9eCoresimplicationpassremoves:un9used
bindings,andsubstitutesinconstantbindings:only:usedonce.Thishelpstocleanuptherathermessy:output`-ofthedesugarer.Theformerfeatureisuseful:for;debuggingtheanalyser.BecauseabindingforMmain:m9ustbAesupplied,thesimplierwilleventuallyremove:allbindingsnotreac9hablefromMmain.Iftheanalyseris:seentomalfunction,arbitrarysubsectionsoftheinput:programcanbAediscardedsimplyb9ychangingthebAody:ofMmain,un9tilwhatremainsissmallenoughtomake:debuggingTviable.P:Remo9ving.nestedenvironmentsmakessubsequent:transformationsiandanalysessimpler.9T:othisend,the:programVis
attenedoutb9yamoAdiedJohnsson-style:lam9bAda-lifter[Joh859],!followedbyanotherdepAendancy:analysisTpass.P:Theprogramisno9wtypAechecked,usingastandard:Milner-Hindleyinferencerderiv9edfromChapter9of:P9eytonuJones'bAooku[Pey87H].lEverynoAdeintheCore:tree;hasat9ypAeexpressionattached.hAlthoughacom-:pletemannotationisratherexpAensiv9e, itisessentialfor:subsequen9tTpasses.P:TheNsinglemostcomplicatedtransformation,8higher-:orderfunctionremo9v|ral(alsoknownasspAecialisation:orzrstication)no9wfollows.(Thepresentnaiveim-:plemen9tation,|xdescribAedginSection5,isslo9wbutcor-:rect.cMostifnotallofthehigher-ordernessoft9ypi-:calQprogramscanbAeremo9ved.>ThisQtransformationis:complicatedyb9ytheneedtomaintaintypAeannotations:correctly:.   j2                                         ⍠?      P:Finally:,Stheprogramismonomorphised.gThispassis
  :quic9kandrelativelypainless,\eventhoughathirdtrip:throughӕthedepAendancyanalyserissubsequen9tlyre-:quired.ٍMostcompilersw9ouldwanttomangletheoutputofthedesugarer5rinquitedieren9twaystogenerategoAod5rcode.F:or-tunately:,itiseasytoseeho9wtheoutputofthestrictnessanalyserpropAerpertainstothedesugaredprogram.)Onlyt9woTtransformationsgiv9emuchtrouble:؍P:Lam9bAda-liftingpsimplymovesbindingsfrominnerlev-:elsVtothetoplev9el,|andaddsextraparameters.Witha:littlebbAookk9eeping,_itispossibletok9eeptrackofwhere:nestedpbindingsendedup,rsothatstrictnessinforma-:tionTcanbAerelatedbac9ktothem.xP:Higher-order1tfunctionremo9v|ralwillonlyeverremove:higher-orderNTfunctionswhic9hhavebAecomeirrelev|rant:bAecauseGofspecialisation.Allrst-orderfunctionsare:preserv9ed.
gwW:e.Varereallyonlyinterestedinderiv-:ingXev|raluationtransformersfortherstorderfunc-:tions.$Thism}isbAecausethedemandpropagatedacross:a/higher-orderfunctionlargelydepAendsonwhatthe:higher-order@Eparameteris.kSoexploitingdemandprop-:agationXacrosshigher-orderfunctionsmeansrun9time:manipulationofev|raluationtransformers,|aserious:complicationTforparallelgraphreductionsystems.Buildingandmain9tainingtheframeworkisatiresome,timeconsumingztask.Onecouldalsoargueallthateortw9asun-necessarily:,%_bAecause"*theGlasgo9wHaskellteamhavespAeci-callydesignedtheircompilerasabasisforexpAerimen9tslikethis,5andf	v|ralian9tlysuppAortedthosebraveenoughtotakethemup[PHHP93#].InretrospAect,therearethreereasonswh9yTAnnawasnotbuiltintoGlasgowHaskell:؍1.:A9tthetimeworkonAnnabAegun,inthesummerof:1991,Glasgo9w'scompiler(version0.02)wasinstillin:theTproAcessofdev9elopment.x2.:Un9tilgFrecently:,theanalyserwasrelativelyfeeble,so:theneedtofeeditrealisticHask9ellprogramshasonly:recen9tlyTarisen.3.:ThemostimpAortan9treason,though,isthis:ԭAnnahad:bAeendev9elopedusingMarkJones'marv9ellousinterac-:tiv9e?environment,êGofer.iMergingAnnaintotheGlas-:go9w Haskellworldwouldhavemeantcompilingwith:ayHask9ellcompilerandthiswouldeasilyhaveputan:ordermofmagnitudeontheedit-compile-runcycletime.ٍAsŀAnnabAecomesmoreandmorepo9werful,wtheŀincentivetobuild'itin9toarealcompilergrows.ThisisdenitelyalongtermTob jectiv9e.	2T,echnicalLpreliminaries2.1GSomeLterminologymTheanalyser'sfron9tendproAducesaNCoresynCtaxtree, *inwhic9hReverynoAdeisdecoratedwithitstypAe.ҥThisisfedtotheoNabstractbinCterpreterpropAer,Bwhic9htranslatestoanabstract9=form:dBNrecursivCedomainequations.,TheNx-pKoinCtersolv9estheseequationsbyiteratingtotheirgreatest   xednpAoin9ts,Ndetectingequalityofadjacentapproximations
   b9yreducingthemtoNnormalformusingtheNtermrewrit- ingsystem,Tandcomparingthosenormalforms.
 ThereTaret9woTkindsofabstracten9tity:.OP:NConCtextsedenoteanamoun9tofev|raluationthatshould:bAeUappliedtoadatastructureorfunction.	}sThese:areDsometimesreferredtoasNdemandsorNbacCkwards:vhalues,butw9ewillstickwithNconCtextwherepAos-:sible.W:erlaterin9troAduceaHaskelltypAeMContextto:moAdelTcon9texts.34P:NAbstractCFvhalueszamoun9ttosometrickerywewillin-:troAducetodealwithhigherorderfunctions.Analter-:nativ9ename,['whichisagainavoidedwherepAossible,:is"NforwCard	vhalue.D*ThecorrespAondingHask9elltypAeis:MAbsVal. This?papAerisprimarilyconcernedwithdisco9vering?how source(languagefunctionsbAeha9ve(viz-a-vizcon9texts.sNev- ertheless,gtheoutputoftheabstractin9terpreterisoneab- stractEv|raluepAerCorefunction.GCon9textsandabstractvalues in9tertwine,fsotheMContextandMAbsValt9ypAesaremutually recursiv9e.Theabstractinterpreteritselfisdenedasthe functionTMZinsection3.6.1.
 Con9textsandabstractv|raluesare,Zinasense,stronglyt9ypAed. Eac9hBcontextisamembAerofaparticularNconCtext	udomain, andnSmostopAerationsoncon9textsareonlymeaningfuliftheir opAerands8aredra9wnfromparticulardomains.Abstractv|ral- ueszarealsostronglyt9ypAed.LAlthoughthedomainsforab- stractuv|raluesare,[strictlyspAeaking,dieren9tfromcontext domains,w9e]willignoreabstractv|raluedomains.Instead,w9e onlyconsidercon9textdomains,henceforthreferredtosim- plyTasNdomains,Tandpretendthatforeac9hdomainthereis aTfamilyofcon9texts,andafamilyofabstractv|ralues. F:orZ}eac9hMilner-HindleytypAe,kthereisacorrespondingdo- main.}+In5general,=therema9ybAemanydierenttypAeswhich maptothesamedomain.Thenextsectiondenes,ܾinfor- mally:,đthis`mapping.Wethenrenethemappingsligh9tlyin sectionT2.2.4,andformaliseitinsection2.2.5.5 2.2GDomainsLforprojectionanalysism A@primary@*aimoftheseanalysesistogenerateinformation usefulforexploitingaparallelmac9hine.RT:othisend,weuse domains9whic9harebAestviewedasageneralisationofthe ev|raluationtransformersin9troAducedbyBurn[Bur87].These areTin9troAducedbyexample. 2.2.1BaseLtypFfesm Baset9ypAesMIntandMChararemappedtoat9wopointdomain M2={0,1},8withM0meaning\donotev|raluatethis"andM1 meaningn\ev|raluatefully".Inthiscaseonly:,
fullevaluationis theUsameasev|raluationtow9eakheadnormalform(WHNF). 2.2.2Non-recursiveLstructuredtypFfesm ConsiderDthein9terpretationofafamiliarnon-recursivestruc- turedmBt9ypAe:MM(Int,Int).$;W:eneedtomodeltheev|raluators forthecompAonen9tsofthepairseparately:,sotheremustbAe aproAductin9volved:wM(2x2).%Anev|raluatorcorresponding   j3                                         <à⍠?      toAan9ysuchpAointwouldrsthavetoev|raluatethepairclo-
  sure~toWHNF,soitcouldgetitshandsontheindividualcompAonen9ts.
SowereallyneedafthpAointrepresentinganev|raluatorwhic9hdoAesnothingatall.Theoverallinterpreta-tionTisMLift(2x2).
A9tFthispAointitisconvenienttointroAduceanotationforpAoin9tstobeusedthroughoutthispaper.
KThebottompoin9toftheabAo9vedomainiswrittenasanunderscore,UM_.TheotherfourarewrittenintheformMU[x,y]wheretheMUstands\Vfor\gouptheMLift",VandtheMxandMyaretherelev|ran9tproAductcomponen9ts.5Theoverallcollectionofev|raluatorsisth9usZVwrittenM{_,U[0,0],U[0,1],U[1,0],U[1,1]}ZVwiththeTfollo9wingordering:O_ MU[1,1]Zg\/Y\>
U[0,1]%̰U[1,0]Zg\\Y/_ U[0,0]mM|mM_Ho9w \doAesthisgeneralisetoarbitrarynon-recursivestruc-tured%t9ypAes?KW:ell,(verysimply:.KA%non-recursivestructuredt9ypAeismodelledb9ythesingleliftingoftheproductofwhat-ev9er=FitstypAev|rariablesareboundto.GF:urtherdetailsareir-relev|ran9t.3That'sǎbAecauseweobservetheguidingrulethatallob jectscorrespAondingtoaparticulart9ypev|rariablearetreated6asasingleen9tity:.AThis6ruleisimpAosedforthepur-pAoseofk9eepingthingsreasonablystraightforward.kF:orex-ample,Tgiv9en:MdataFooab=MkFooab9TB|MkAa9TB|MkBbdataGrokabc=MkGrokabcG|GrokodileDundeeaaabbca~v|ralueofM(FooIntInt)~ismappAedtoMLift(2x2),andSM(GrokIntIntInt)toMLift(2x2x2).
|Morecomplicated{parameterisationsgiv9erisetomorecom-plicatedщdomains.QThet9ypAeM(GrokInt(FooIntInt)(GrokIntIntInt))ihasa91pAoin9tdomainMLift(2xLift(2x2)xLift(2x2x2)).
ItKisw9orthunderstandingthatthenumbAerofproductcom-pAonen9tsisequaltothenumbAeroftypAev|rariables,anden-tirelyunrelatedtothen9umbAerofparametersofan9ypartic-ularg[constructor.AgFcon9textMU[1,0,0]appliedtoanob jectoft9ypAeM(GrokIntIntInt)means:)1ev|raluatetheob jecttothe|rstconstructor.Then,ifitisaMMkGrok,ev|raluatetherst{5argumen9t.NOtherwise,itmustbAeaMGrokodileDundee,so&Eev|raluatetherstthreeparameters.ODW:etreattherstargumen9t΍toMMkGrokandtherstthreeofMGrokodileDundeeasdasingleen9titydbAecausetheyallcorrespondtothesamet9ypAeTv|rariable,Ma,inthedeclaration.52.2.3RecursiveLstructuredtypFfesmSoQQfar,`Qthingsarereasonablystraigh9tforward.hButQQdeningev|raluators1forrecursiv9etypAesisamineeld,8partlybecausethereexaresoman9yalternativeformulations[W:ad87][WH87].AsvithappAens,theform9ulationusedinAnnaisatrivial   v|rariationJoftherulefornon-recursiv9etypAes,sUbutjustication
   isTnotsoeasy:.
 The#ruleisiden9ticaltothenon-recursivecase,g;exceptfor thefollo9wingmoAdication:	thesingleliftingoftheproduct, written+MLift, isreplacedb9yadoublelifting,MLift2.No9w, giv9enTthepseudo-declarationOMdata[a]=[].m|a:[a] itTiseasytoseethatthedomainforM[Int]isMLift2(2),ca four@pAoin9tdomaincorrespondingpreciselytothein9terpreta- tionforthatt9ypAemadebyW:adler[Wad87]andlaterjusti- ed!b9yBurn[Bur87].Extendingthenotationoftheprevious section,Dqw9e7writethepAointsinthisdomainasM{_,U_,UU[0] andݮMUU[1]},understandingthemtodenotetheev|raluators whic9hTBurncalledM{E0,E1,E2TandME3}:P:M_:pDoTnotev|raluateatall(ME0).34P:MU_:Ev|raluateasfarastherstconstructor,thatis,to:w9eakTheadnormalform(ME1).P:MUU[0]:pEv|raluateTtheen9tirestructureofthelist(ME2).P:MUU[1]:˺Ev|raluatetheen9tirestructureofthelist,"and:allTtheelemen9ts(ME3).O InTgeneral,{!arecursiv9etypAeofMnparametershasev|raluatorsof theformM{_,U_andMUU[x1...xn]}.TheMUU[x1...xn] pAoin9tsOdenoteev|raluatingtheentirestructure,^,andthenap- plyingHev|raluatorMx1toeac9hob jectcorrespAondingtotherst parameter,WMx2toob jectscorrespAondingtothesecondpa- rameter,Cand`zsoon.W:ewillsee,inSection4,thatthis conceptualpartitioningofallrecursiv9edomainpAointsinto three#sectionsiscrucialtothew9orkingofthetermrewriting systembusedtodetectxpAoin9ts.Similarly:,thenon-recursive pAoin9tsmaybAepartitionedintotwo:7M{_andMU[x1...xn]}.
 Theguidingprinciple,#>originallystatedb9yW:adler,isto moAdelttherecursiv9etypAesbylettingthesub-ev|raluators in')MUU[...]v|raluesbAerepresen9tative')oftheleastdened elemen9tofthattypAeinthestructure.,Imaginewe ha9vealistoft9ypAeM[(Int,Int)],whichinducesdo- mainvMLift2(Lift(2x2)),Ͼandw9eknowthatev|raluator MUU[U[0,1]]isthestrongestthatcansafelybAeapplied(that is,mwithoutdangerofnon-termination)tothelist.zNo9w suppAosew9eobtainanotherlistforwhichMUU[U[1,0]]isthe strongestsafeev|raluator,MandappAendittotheoriginal.IWhat isHthebAestev|raluatorthatcanbeappliedtothenewlist? ItO}cannotbAeeitheroftheoriginals,sincethatrisksnon- termination.'HThenGmostw9ecanev|raluateanyparticularele- men9tluwhilstremainingsafeisMU[0,0],=sothebAestthatcan bAeappliedtothelistasawholeisMUU[U[0,0]]{thegreat- estflo9werbAoundofthev|raluesfortheoriginallists.W:adler summarisedSthisb9ystatingthatalistischaracterised\by itsleastdenedelemen9t"butweneedtobAemoreprecise: alistisc9haracterisedbythegreatestev|raluatorthatcan safelyDbAeappliedtoan9yelement,Peevenifastrongerev|ralua- torIcouldbAeappliedtospecicelemen9ts.~Thesameprinciple generalisesStostructuredt9ypAesofanynumbAerofparameters, with^thegreatest-lo9wer-bAound^characterisationoAccurringin- depAenden9tlyTforeachparameter. This(abstraction,Fwhilstsimple,assumesthatprogramstreat all	elemen9tsofthesametypAeinsideastructureinthesame   j4                                         [⍠?      w9ay:.Forexample,[itassumeslistproAcessingfunctionstreat
  allelemen9tsinthelistthesameway:.
Functionsnotplayingalongwiththisma9yinducebad,butsafe,results. ^Consider:OMtail(x:xs)=xsIf^w9eapplyaMUU[1]ev|raluatortoM(tailzs),whatcanwe
  ev|raluate%Mzswith?Unfortunately:,notMUU[1],sincetheele-men9t"thatMtailthrowsawaymightjusthavebAeentheone-and-onlynon-terminatingMIntinthelist.mErringonthesideofsafet9ythusrestrictstheev|raluatorforMzstoMUU[0],and%losesallthepAoten9tialparallelisminev|raluatingtheele-men9ts+intherestofthelist.3Oneupshotofthis, alsonotedb9y/RW:adler,uisthatdeningfunctionsdirectlybypattern-matc9hing	isessentialtogetgoAod	results.IntheexamplebAelo9w,the1analysergivesamuchbAetterresultforMsum1thanMsum2,Tdespitethemha9vingidenticalstrictnesspropAerties.OMsum1[]Y=0sum1(x:xs)	s,=x+sum1xssum2xsY=ifXnullxsBnthen	s,0Bnelse	s,headxs+sum2(tailxs)Arelated defectistheinabilit9yofthesedomainstocapturetheK@notionofheadstrictness.3AK2headstrictfunctionisonewhic9h>ev|raluatestherstiteminalistwheneveritev|raluatesthe'listasfarastherstconstructor,Ianddisco9vers'ittobAenon-nil.}Headstrictnessisusefulinasequen9tialimple-men9tation,soanextensionofthedomainstocapturethesepropAertiesTw9ouldincreasetheusefulscopeofthisanalyser.52.2.4MoFfdifyingLthenotationmThe,abAo9vemappingassignsdomainMLift()toallen9umeration	AtypAes,b:forexamplethefamiliartypAeMdataBool=False|True.<<Observ9eʘthatMLift()isiso-morphictothet9wo-pAointdomainusedforbaset9ypes,andrigh9tlyTso.pAfterall,wecould,conceptually:,deneOMdataInt=...-3|-2|-1|0|1|2|3...andTw9e'dcertainlyexpAectatwo-pAointdomainforit!
ThisisomorphismcanbAeusedtosimplifythedomainstruc-
  ture,~andth9usthestrictnessanalysisitself.W:eforgetabAoutdomainM2,andinsteadmapbaset9ypAesMIntandMChartoMLift(),with8pAoin9tsM{_,U[]}replacingM{0,1}.;Hence-forthTthenewnotationisused.2.2.5SummarymLetMD(t)denotethedomainforsomet9ypAeMt.-LetMtypeNamebAeV5thenameofsomestructuredt9ype,fmandMte1...tenV5besomeTarbitraryt9ypAeexpressions.pMDisdenedas:OMD(Int),=Lift()D(Char)	s,=Lift()D(typeNamete1...ten)
f=Lift	s,(D(te1)x...xD(ten))iftypeNamedenotesanon-recursivetype  
  f=Lift2(D(te1)x...xD(ten))iftypeNamedenotesarecursivetypeR Themconceptofafunction-v|raluedcon9textseemsrathermean- ingless,Tandisleftundenedun9tilsection3.2.! 2.2.6RestrictionsLonstructuredtypFfesm Theastutereaderma9yhavenoticedtheexamplesabAove ha9ve6bAeenratherrestricted.Inparticular,
noneofthemhad constan9t~typAesasanargumenttoanyconstructor.)Butthis situation7iscommonplace,forexampleastheMIntcon9veying balancingTinformationinthefollo9wingtreedeclaration:kҍMdataAVLTreeabf=ALeaff|ANodeInt(AVLTreeab)ab(AVLTreeab) Insteadiofextendingthedomain-generatingrulestoco9ver suc9hcases,zitissimplertofactoriseouttheoendingMInt, generatingTasecondt9ypAeMAVLTree2:MdataAVLTree2iabf=ALeaf2f|ANode2i(AVLTree2iab)ab(AVLTree2iab) (AVLTree2Intab)(isanisomorphic t9ypAe]toM(AVLTreeab),at]thesametypAebeingat9ypefor whic9htweknowhowtogenerateanabstractdomain.Conve- nien9tly:,ޱMilner-HindleyltypAecheckersareamenabletosuch substitutions.
 Finally:,yNobserv9eeOthattherearecertaintypAesforwhichitis hardTtodeviseasensiblesetofev|raluators,forexample:MdataFooabf=MkFooab(Foo(Fooab)(Fooab)) TheDsolutionadoptedinAnnaissimplytodeemtheseille- gal.W:erequirethat,inat9ypAedeclaration,argumen9tson constructorse"areeithersimplev|rariables(here,yMaorMb),ora simplerecursiv9einstanceofthestructure(here,MFooab). Thesewrestrictionsseeminconsequen9tialforrealprograms, andTha9vebAeenreportedquiteindependan9tlyin[KHL91(].! 2.3GTheLCoredatatypFfem The5extensiv9elymangledsourceprogrameventuallypassed totheabstractin9terpreterisatypAe-annotatedtree,Vrepre- sen9tingasimplefunctionallanguage.@EachnoAdeinthetree carriesFwithitanannotation.GTheHask9elldatatypAeused isparameterisedo9verbAoththet9ypeoftheannotations,4and theTt9ypAeoftheidentiernames:MtypeAnnExprabf=(b,AnnExpr'ab)dataAnnExpr'abf=AVaraf|AConstr	s,af|ALitIntf|AApY(AnnExprab)(AnnExprab)f|ALetBool[AnnBindab](AnnExprab)   j5                                         z⍠?      
fM|ACaseX(AnnExprab)[AnnAltab]
  
f|ALam[a](AnnExprab)typeAnnBindab
f=(a,AnnExprab)typeAnnAltab
f=(a,([a],AnnExprab))⍑TherstandsecondparametersonanMAnnExprt9ypAearefortheGiden9tierandannotationtypAesrespectiv9ely:.ForGexam-ple,Fif<Uthet9ypAeofidentiersisMId,FandthatoftypAeexpres-sionsJMTExpr,Xthet9ypAeofthecorrespondingCoreexpressionisTM(AnnExprIdTExpr).
Mostcasesarestraigh9tforward.TheMAVartermrepresen9tsaniden9tifer,!=whilstMAConstrrepresentsaconstructorname.Literal=v|raluesarerepresen9tedbyMALit,G
andapplicationsbyMAAp.Lam9bAdaStermsarerepresentedbyMALam,zFwhichcanbindanTarbitraryn9umbAerTofformalparameters.Thatllea9vesthetwotrickyones.]Alet/recexpressionisrepresen9tedc1byMALet,whichhasabAoolean
agindicatingwhether	thisisarecursiv9ebinding, Kalistofbindings,andamainexpressioninwhic9hthosebindingscanbAeused.DEachbindingSisaniden9tierpairedwiththev|ralueitisbAoundto._Caseexpressions,.denotedb9yMACase,con9tainaswitchexpression,Randzalistofalternativ9es.JEachzalternativeisatripleofconstructorname,constructorargumen9tsandtheappropriatevrigh9t-handside.Theuseofnestedpairsismorecon9venientTforcoAdingpurposes.All7phasesdo9wnstreamofthelambAda-lifterexploitcertainassumptions-abAouttheformoftheprogram.cThemostim-pAortan9t,arethattherearenonestedMALets,[0thattheprogramisfindepAendancyorder,kandthatnoiden9tierisundenedorTm9ultiplydenedinthesamescopAe.yx2.4GCompilingLparallelcoFfdemEv|raluationtransformersaresuppAosedlyexploitedb9ycom-pilingm9ultiplecopiesofeachfunction,۪uptoonecopyforeac9hkcontextinwhichtheresultmightbAedemanded.F:oreac9hcopy:,qcompile-timeanalysisindicateshowmuchde-mandpropagatestotheparametersofthefunction,:andth9usshowmuchtheargumentstothecallmaybAeev|raluatedbAeforethecall.Inthismanner,2demandpropagationispre-serv9edTasfarasthisstyleofstaticanalysismakespAossible.Ofcourse,0allthisisdoneinpursuitoftheo9verallgoal:maximisinga~a9v|railableparallelism. AnequallyimpAortantis-sue,2not,discussedhere,isho9wtoavoidexcessivene-grainparallelism.Allq.w9ellandgoAod,H#butq.thepAotentialforcoAdeexplo-sionxrendersanaiv9eimplementationimpractical.FbCon-sidersafunctiondeliv9eringaresultofthecontrivedtypAeM(GrokInt2(FooIntInt)(GrokIntIntInt))discussedinsection2.2.2.>Sincethedomainhas91pAoin9ts,itwouldappAearrnecessarytocompile90v9ersionsofthecode,omit-tingthev9ersionfornodemandatallontheoutput.
MBurn'searlyw9orksimplyignoredtheproblembyrestrictingitselftolistsofMInt,+Nforwhic9hatmost3copiesofcoAdearere-quired.7aQuitewhattodoabAoutcomplext9ypes,whichin-duce.proAductdomains,5ornon-trivialinstan9tiationsoflists,isTnotclear.Thisunsatisfactorystateofaairscantosomeexten9tbAealleviatedb9yrestrictingourselvestocompilingjustasubset   of"allthepAossiblev9ersionsofeachfunction.EThen,f=when
   theoutputofafunctionisdemandedinacon9textforwhich nov9ersionhasbAeencompiled,theversionusedisthatcom- piledkaforthegreatestdemandlessthanthedemandw9ere- quired.Observ9eEthatthechoiceofalternativeisnotneces- sarily3unique,`Qbut,pro9videdwecompiledinafullysequential (that4is,<WHNF4demand)v9ersion,analternativ9eisatleast guaran9teed9toexist.Ofcourse,2somepAotentialparallelism ma9ywellbAelost:!suchisthepriceforrestrictingthecoAde explosionTtoatolerablemagnitude.
 TheFcen9tralquestion,p%then,isFwhichversionstocompilecoAde for.NoOne{TpAersonwhohasv9entured{Tintothisquagmireis Min9tchev.F:orhisMScdissertation[Min92o],gMin9tchevbuilt a@sim9ulationofaparallelgraphreductionmachine,;which understandsthreelev9elsofdemand:6noneatall,	weakhead normalgformdemand,|gandfulldemand.Animmediatead- v|ran9tagelisthatthesepAointsapplytoallstructuredtypAes, including!tuplesandcomplexinstan9tiationsoftypAes,Randare th9usmorewidelyapplicablethanBurn'sscheme.[Encour- agingly:,$ev9enÔwithsofewev|raluators,Min9tchevÔfoundthat substan9tialamountsofparallelactivityweregenerated,мv|ral- idating&hisapproac9h.Recently&ithasbAeensuggestedthat a#fourthev|raluatormigh9tbAeprotablyincluded:9nevaluation ofKtheen9tirestructureofarecursivetypAe,7Ibutnoev|ralua- tionMofthecompAonen9ts.SThismakesnosense,[ofcourse,in aYTnon-recursiv9etypAe,jTor,alternatively:,oneYTcanregarditas equiv|ralen9tTtotheWHNFevaluator,inthiscase. A.further/complicationiswhattodoabAoutpolymor- phicfunctions.s|W:ema9ycompilethreeversionsofthe Mreversefunction,:w9orkingfromtheev|raluatorsofthesim- plestinstance,butthenwhatdow9edogivenanev|raluator MUU[U[1,0]]G*appliedtoauseofMreverseatnon-baseinstance M[(Int,Int)]->[(Int,Int)]?aSuce,}ittosa9ythata pAossiblesolutionisonlytocompilev9ersionsofpolymorphic functionsbasedontheirev|raluatorsforsimplestinstances, andausesafeappro9ximationtechniquesbasedonConcmaps to`handlethenon-baseinstances.See[HH91>],*section5,for an@in9troAductiontoConcmaps.ՆMyMScdissertation[Sew91/] indicates#ho9wConcmapsareusefulinmattersofpAolymor- phism,Tathemeexploredfurtherin[Sew93/]. No9w,ifthecompilerisonlygoingtomakecoAdeforafewof allthepAossibleev|raluatorsforafunctionreturninganob ject of)bcomplext9ypAe,.fwhatisthepoin9tofdoingstrictnessanal- ysisUwiththefullcomplemen9tofev|raluators?Afterall,ethis amoun9tsatodoingadetailedanalysis,thenthrowingaway mostofthedetailinthenalansw9er.)Itwouldcertainly bAeJm9uchquickerjusttoworkwiththosefewev|raluatorswe are\reallyin9terestedin.sNevertheless,doingthatriskslosing in9termediatedetail,and,ultimately:,parallelism,compared with/theexpAensiv9eapproach.Buildinganabstractinterpre- tationgXfortheelc9heapAoapproachmightalsobAeratherdif- cult,;andsthein9terpreterwouldhavetobAerewrittenevery timetheparticularsubsetofin9terestingev|raluatorschanged. Axnalin9terestingcaveatpAertainstohigher-orderfunctions. As6explainedto9wards6theendofsection1.2,=itloAoksdif- cult4toexploitparallelisminhigher-orderfunctionsifw9e donotw9anttoengageincomplicatedmanipulationofev|ral- uationtransformersatrun-time.xOnecanthereforerea- sonablyarguethatthehigher-orderremo9v|raltransformation (rstication)describAedinsection5enhancesparallelism. What&rsticationdoAesistodisco9ver&staticallysomeofthe functionalÈparameterspassedtohigher-orderfunctions,and spAecialise;themaccordingly:,Ltgeneratingrst-orderreplace-   j6                                         ⍠?      men9ts.KThesecanthenbAeparallelisedinthenormalway:,
  without8Vha9vingtoresorttocomplicatedrun-timemachinery:.Ma9ybAe,Ԧthen,thisztransformationshouldbeincorporatedasaTmatterofcoursein9togoAodTparallelisingcompilers.-3TheLabstractinterpretation3.1GPreliminariesm3.1.1TheLnotionofforwardsLandbackwardsSeman9tic`analysesoffunctionallanguagesseemtofallinto
  t9wovcamps:forwardsandbackwards.YT:oseetheintuitivemeaningTofthis,considerafunctionapplication:OM(fxyz)Aforw9ardanalysisgeneratesinformationabAoutMfwhich
  tellsMuspropAertiesoftheapplicationM(fxyz)MѺifw9eknowtheepropAertiesoftheindividualargumen9ts,)Mx,MyeandMz.ɤInotherٚw9ords,
theanalysispropagatesinformationRj 	   	   cmti9Rforwardsthroughfunctions.ܓF:orw9ardanalysestendtobAeexpensiv9ebAecauseзtheyha9veзtoconsiderallpossiblein9teractionsbe-t9weenarguments.[Ontheotherhand,onegetsaveryde-tailedTpictureofwhatisgoingon.
Abac9kward$analysis,sXbycontrast,sXgeneratesinformationabAoutMfwhic9htellsusthepropertiesoftheindividualargu-men9tsHMx,qMyandMzifweknowsomepropAertyoftheapplicationM(fxyz).That
is,Vabac9kwards
analysispropagatesprop-erties4Rbackwardsthroughfunctions.Bac9kwardanalysesmaybAe2c9heapertodo,_buttheyma9yalsogivelessdetailedresults.No9w,forٌreasonswhichwillshortlybAecomeapparent,AnnadoAesuacom9binedforwardandbackwardanalysis.Theprop-erties\>whic9hAnnapropagatesforwardsthroughfunctionsare{theabstractv|ralues,whilstthosewhic9h
owbackwardsareh
con9texts.T:osetthestage,observecriticallythatRAÎnna'smainpurposeistodeterminethebackwardsbehaviourofthesourcelanguagefunctions.Thezpresenceofforw9ard(ab-stract)v|raluesisanecessaryevilwhic9henablesustodealcleanly[withhigher-orderfunctions.kThediscussionwhic9hno9wsfollowsmakesmoresenseifyoukeepaclearnotionthatabstract=xv|raluescorrespAondtoaforw9ards
owofinformation,whilstTcon9textscorrespAondtoabackwards
ow.53.1.2ALfundamentalproblemwithbackwardsanalysismBac9kwards.strictnessanalysisw9ouldbAestraightforward,w9ere_itnotforthehigher-ordernatureofthelanguageunderanalysis.pT:oTseetheproblem,considerMapply:OMapplyfx=fxGiv9enhsomedemandonauseofapply:,}M(applygy),what
  demand[ma9ybAepropagatedtoMy?WithoutknowinghowMg8propagatesdemandtoitsargumen9t,1theonlysafeanswerisE\none".Ho9wever,knowingwhatMgisimplieshavingaforw9ard
owofinformation,aswellasthebackward
owofdemandTw9estartedwith.ThingsloAokgrimmerwhenw9eputfunctionsinsidedatastructures,Tthenshthemoutandapplythem:OM1+(headxs(y+1))   whereMxs::[Int->Int].$Thereisnow9aytotellwhat
   demandTcouldbAepropagatedtoMy.
 Thesolutionreallyliesinbuildingacom9binedbackwards andforw9ardsanalysis.W:ray[W:ra85:C]madeastartonthe problem,YbutLDittoAokthew9orkofHughes[Hug87']togener- aliseOW:ra9y'sresultstothepAointofgeneralapplicability:.ڂThe resultinganalysisisratherhardtounderstand,0)so,rather thanattemptingahead-onassault,w9eloAokrstatunder- lyingTissues,startingowithsomenewconcepts.獍 3.2GFunctionLcontextsm Dealing-withfunctionspropAerlymeansturningthemin9to rst-classlcitizensforthepurpAosesoftheabstractin9ter- preter.Section2.2discussedthenotionofdemand(orcon- text)Q/onadatastructure.W:eno9wextendthenotionof con9textTtofunctions. Since
acon9textreallydenotesademandforev|raluation,the ideaofafunctioncon9textseemsprettymeaningless:]after all,ho9wcanafunctionbAeev|raluated?Butimaginewede- ned#afunctioncon9textasapair,containingtheabstract v|ralueRoftheargumen9t,b<andthecontextfortheresultofan applicationofthefunction. Bymakingtheanalysisfully curriedv3fromno9won,kwecanconsiderallfunctionsashav- ing;justoneargumen9t.Then,forexample,thecon9textona functionToft9woTarguments,suchasMapply,loAokslike:YM(abstractvalueoffirstargument,f(abstractvalueofsecondargument,contextonresult)) Suc9hQaschemewouldsolvetheproblemoutlinedabAove,`by supplyingDthev|ralueoftherstparameter,allo9wingdemand tobAepropagatedon9tothesecondparameter.Thisabstract v|ralueaoftherstparameterisjusttherelevan9tcontextfunc- tion,ߞbutwhatoftheabstractv|ralueofthesecond,non- functionalͶparameter?W:ell,	w9earesimplynotinterestedin it,Tsow9emapittothe1-pAointdomain.
 Thew9orldnowbAecomespopulatedb9ytwospAeciesofv|ralues:P:NConCtexts(alsocalledbac9kwardsv|ralues,evaluatorsor:demands).QIn'whatfollo9ws,+}we'oftensa9y\context"or:\con9text+on"whenitwouldbAemorenaturaltosay:\demand"or\demandon".
Thiscon9ventionhasbAeen:adoptedbAecauseofawishtoha9vejustonetermfor:eac9hTconcept.:Con9textsrUaretherstkindofabstractentityreferred:to>insection2.1.QF:ornon-functionv|ralues,\theyare:as~discussedinsection2.2.F:orfunctionv|ralues,they:areHapairwhic9hwewriteasM(Fncac),whereHMFnc:remindsthatthisisaNFuNction}ConCtext,Maisthe:abstract3v|ralueoftheargumen9tandMcisthecontexton:the9
result.Henceforth,Av|rariablesdenotingcon9textsor:con9textTmapshave'c'astheirrstletter.܍P:NAbstract	@vhalues(alsocalledforw9ardsv|ralues).[These:arethesecondkindofabstracten9titydescribAedinsec-:tion2.1.Theyaredesignedpurelytocon9veycontexts:to=^an9yplaceinvolvingacalltoanunknownfunction,:suc9hasinthetwoproblematicexamplesabAove.zOThe:abstract+v|raluesofnon-functionob jectsarealw9ays+irrel-:ev|ran9tandaremappAedtoa1-poin9tdomain,`whosesin-:gleGpAoin9tisdenotedM#,pforthetimebeing.Theabstract   j7                                         7⍠?    dl΍⟾S4  ff̤͟wٚ ~٘  ff328ڌ͉  ffC,  
    fffg 
    ff33DeningTequation"V 
    ffpDisassem9blesTa..."  
    ff ߕ
proAducingTthe...a  
    fffg 
    fffh  ffC,  
    fffg 
    ffh 
    ff t  
    ffC,  
    fffg 
    ff
    
    fffg 
    ff33MFncA	s,(Fncac)=a33 
    ffpfunctionalTcon9text @O  
    ff ߕ
abstractTv|ralueoftheargumen9t'  
    fffg 
    ff  
    fffg 
    ff33MFncC	s,(Fncac)=c33 
    ffpfunctionalTcon9text @O  
    ff ߕ
con9textTontheresultPR  
    fffg 
    ff  
    fffg 
    ff33MFvalA(Fvalca)=a 
    ffpfunctionalTabstractv|ralue33  
    ff ߕ
abstractTv|raluemap:pargumen9ttoresult33  
    fffg 
    ff  
    fffg 
    ff33MFvalC(Fvalca)=c 
    ffpfunctionalTabstractv|ralue33  
    ff ߕ
con9textTmap:presulttoargument @O  
    fffg 
    ff  
    fffg 
    ffh 
    ff t  
    ffC,  
    fffg 
    ff  ffC,;̍ TT:ableT1:pSelectorfunctionsforfunctionalen9tities
  ff ~٘  ffx@   ff̎
Yd:v|ralue2&ofafunction-valuedob jectisalsoapair(but
  :quite7unrelatedtoMFncpairs),writtenM(Fvalca),:withJMFvalremindingusthisisaNFunctionaljabstract:VALue.=Thet9wocompAonentsarebAothmaps.=The:rstvcompAonen9t,Mc,mapsthecon9textonthefunction:to7;con9textontheargument,cwhilstMamapstheabstract:v|ralue5oftheargumen9ttotheabstractvalueofthere-:sult.
V:ariablesNdenotingabstractv|raluesorabstract:v|ralueTmapsha9veT'a'astheirrstletter.Noticenho9wthetwokindsofv|raluesaremutuallyrecursive.Theo9veralloutputoftheabstractinterpreterisoneab-stractB}v|raluepAerCorefunction.Eac9habstractvaluecon-tainsenoughinformationtopropagatedemandfromtheo9verallresulttoeac9hofthearguments,ueveninthepresenceofhfunctionalparameters.Theseconceptsareconfusing,}sosome>2examplesareinorder.ԺFirst,i9denefourselectorsMFncA,MFncC,؄MFvalAtandMFvalCtodisassem9bleMFncsandMFvals,withthebAeha9viourshowninT:able1.HopAefully,theirnameswillserv9eTasareminderoftheirmeaning.
Let's	startwiththesimplestfunctionimaginable:Mid::Int->Int.The
onlyremotelyin9terestingthingwecansa9yabAoutMidisthatitsimplypropagatesthecontextonits4resulttothecon9textonitsargument.z]So,<wsuppAosingweno9wXwritedownamappingfromthecontextontheresulttoTthecon9textontheargument,weget:yM(\c->c)Let's]bAeclearwhatthisis.It'sRnotacon9text,oandit'salso
  Rnot{anabstractv|ralue.It'samapfromcon9textstocontexts.Butthat'snotgoAodenough.aW:esaidearlierthatAnnaproAducesoneabstractv|ralueperCorefunction.32Sowhatdow9e(proAduceforMid?F:orastart,НsinceMidisafunction,w9em9ustWgetafunctionalabstractv|ralue:anMFvalterm.qItmustloAokTlik9e:Mid=Fvalcontext_map+'abstract_value_mapNo9w,thecontextmap,aswejustmentioned,mapsthecon-text]onMidtothecon9textonMid'sargument.7AndthecontextonMid,sinceMidisafunction,m9ustbAeafunctioncontext,oftheformM(Fncac),1whereMcisthebitw9e'rereallyafter.This&giv9esacontextmapofM(\c->FncCc),so&we'venowgot:Mid=Fval(\c->FncCc)+'abstract_value_mapd Whatoftheabstractv|raluemap?HIttellsuswhattheab-
   stractYv|ralueofMid'sresultisgiv9entheabstractvalueofMid's argumen9t.ݰBut,;/for ithisinstanceofMid,theresultt9ypAeis MInt.eAllnon-functiont9ypAeshaveacorrespAondingabstract v|ralue,denotedM#,ina1-pAoin9tdomain.:Sowedon'tactually care@whattheabstractv|ralueofMidis{itcanonlybAeM#an9y- w9ay:.oThatTmeans,afterinstallingtheabstractv|raluemap, w9eYcouldwriteeitherofthefollowing,jalthoughthesecond isTalittleclearer:OMid=Fval(\c->FncCc)3'(\a->a)id=Fval(\c->FncCc)3'(\a->#) If&y9ouareconfused,kEgonofurther!QItisbAettertoreturn totthestartofthissection,Kconsideragainthemeaningsof con9texts6andabstractv|ralues,?9anditerateuntiltheexample mak9esTsense.
 Mo9vingTontoM(+)::Int->Int->IntTgives:M(+)=Fval(\c1->FncC(FncCc1))7(\a1->Fval(\c2->FncCc2)uM(\a2->#)) Thisըtimecurryingcomesin9toplay:.]kThat'swhytheterm whic9hQmapstheabstractv|ralueoftherstargumenttothe abstractv|ralueoftheresultreturnsaMFvalterm:the\re- sult"oherehast9ypAeMInt->Int.+Clearly:,yM(+)oغsimplyprop- agates5con9textontheoverallresulttobAotharguments, whic9hiswhythecontextmapsforthetwoarguments are%+M(\c1->FncC(FncCc1))andM(\c2->FncCc2).KIf thisseemsalittlem9ysterious,*bAearinmindthatboth M(FncC(FncCc1))XandM(FncCc2)refertothecon9texton theOfnalresult.
ʧThat'sbAecauseMc1bindstoacon9text inMMInt->Int->Int,whic9hisnecessarilyoftheform M(Fnc#(Fnc#cc))ܺwhereMccisthecon9textonthenal result.eSimilarly:,nMc24isacon9textoftypAeMInt->Int,nhaving the~;formM(Fnc#cc)~;whereMccisagainthecon9textonthe nalTresult.
 No9w?forsomethingaltogethermoreadventurous:fthefamil- iarxMapplyfunction,att9ypAeM(Int->Int)->Int->Int. Thisexampleiseasiertofollo9wifonebAearsinmindthat M(applyfx)reducesimmediatelytoM(fx),soan9ycontext appliedtotheformerexpressionalsoappliesdirectlytothe latter.ZWhattheratherformidabletermbAelo9wdoesisto route[thecon9textfromtheresultofcallingMapplytothe resultTofcallingthehigher-orderparameter.   j8   	                                      r⍠?      Mapply=Fval(\c1->Fnc(FncA(FncCc1))
  rJ(FncC(FncCc1)))9TB(\a1->Fval(\c2->(FvalCa1) (Fnc(FncAc2) -~(FncCc2))v(\a2->(FvalAa1)a2))jFirstHfofall,*considerwhatthefunctioncon9textMc1willget3bAoundtom9ustlooklik9e:-M(Fnca_ho(Fnc#c_final))whereMa_houstheabstract(orforw9ard)v|ralueofthefunc-tionalparameterandMc_finalisthecon9textontheresultofapplyingthisfunctionalparametertosomething.4No9w,termNM(\c1->Fnc(FncA(FncCc1))(FncC(FncCc1)))maps;con9textonMapplytocontextontherstparameter.Asythisisafunctionalparameter,Bitmak9essensethatthisexpression4isbuiltfromaMFnc.XSojustwhatcon9textispropa-gatedntothefunctionalparameter?yW:ell,6theabstractv|raluem9ustbAethesameastheabstractv|ralueofthesecondpa-rametertoMapply,җandthisv|ralue(whic9hmustbAeM#)isex-tractedqb9ythetermM(FncA(FncCc1))qSimilarly:,8thecon-textssontheresultofthefunctionalparameterm9ustbAethesamesasthecon9textontheoverallresultofMapply,9givenbyM(FncC(FncCc1)).
Ev9erythingelseiseasiertofollow.ǅV:ariableMa1willgetbAoundtoctheabstractv|ralueofthefunctionalparameter,'whic9hm9ust"bAeaMFvalterm.
SoM(FvalCa1)returnsthemapusedb9ydthefunctionalparametertotranslatecontextonitselftocon9textonitsrstargument.ThemapisappliedtothesameYfunctioncon9textaswasbuiltintheprecedingpara-graph,;except3thatreferencestoM(FncCc1)arereplacedb9yMc2,Twhic9histhesamething.Finally:,theabstractv|ralueoftheresultisgiv9enbyapply-ingJtheabstractv|raluemapofthefunctionalparameter,M(FvalAa1),totheabstractv|ralueofthesecondparameter,Ma2.Tw9oAimprovementsarepAossible.Firstly:,Ltheabstractv|ralueof+theresultm9ustsimplybAeM#,0~sincetheresulttypAeisMInt.Secondly:,examinationC~ofthedenitionofMFncAC0andMFncCsho9wsu'thatM(Fnc(FncAc)(FncCc))u'isequiv|ralentsimplytoTMc.pTheimpro9vedTversionis:jMapply=Fval(\c1->FncCc1)9TB(\a1->Fval(\c2->(FvalCa1)c2)v(\a2->#))Themec9hanismfordealingwithfunctionsandapplicationsisjLthehardestpartoftheabstractin9terpretertounderstand.A1little2/timespAen9tmakingsenseofthislastexampleisawisein9vestment.
Wh9yGisitnecessarytopropagatedemandintofunctionalparameters?pW:ell,Tconsider:Madd1x=apply(+x)1If5demandisn'tpropagatedin9toMapply'sfunctionalparame-ter,$thereXwillbAenodemandontermM(+x)andnoneonMx,giving[theimpressionthatMadd1isnotstrict, whenreallyitis.
e3.3GMoreLabFfoutabstractvaluesmAll:onon-functionexpressionsyieldanabstractv|ralueinaunitdomain.3Ho9wever,{v|ralue@M#,usedintheexamplesabAo9ve,{is   toAoindiscriminating.=TheHask9elldeclarationforabstract
   v|raluesTloAoks(almost)lik9ethis:OMdataAbsValf=ANonRec	s,[AbsVal]f|ARec[AbsVal]f|FvalContextAbsValf|AbsVar,Idf|AbsLam,IdAbsValf|AbsApXAbsValAbsValf|FncAContextf|FvalAXAbsValf|SelAIntAbsValf|AMeetX[AbsVal] TheMARecandMANonRectermsdeneabstractv|ralues for3recursiv9eandnon-recursivetypAes,respectively:.
In bAothcases,theassociatedlistofMAbsValsaretheab- stractv|raluesoftheparametersofthet9ypAe.F:orex- ample,|atermoft9ypAeM[(Int,Int)]hasabstractv|ralue M(Rec[NonRec[NonRec[],NonRec[]]]),giv9enpthatMInt isNFtreatedasanen9umerationandthusmapstoM(NonRec[]). It
isimpAortan9ttorealisethatthisv|ralueisstillunitary:,Tlike M#,butHhastheaddedadv|ran9tagethatitcanbAedisassem- bled~torev9ealitsunitarysubAcomponents,vas~necessitatedby theabstractin9terpretationofMcasestatements.Constructor MSelATisusedforthis,withmeaning:OMSelAn(ARecX[a1...an...ak])	s,=anSelAn(ANonRec[a1...an...ak])	s,=an Fval,pMFncA^[and^nMFvalAw9ereintroAducedintheprevioussec- tion.MAbsVar,[
MAbsLam,{andMAbsApallo9wreferencestoabstract- v|raluedqvariables,8andforthecreationandapplicationof abstract-v|raluedg9mappings.Observ9ethatweoftenomit MAbsVarRandMAbsAp,$whenthemeaningisob9vious,andab- breviateTM(AbsLamae)toM(\a->e).
 ConsiderTagainOM1+(headxs(y+1)) wheretMxs::[Int->Int].:W:eexpAectMxstoha9vebAeen
   bAound*toanabstractv|raluewhic9hcansupplyasensible con9text-mapping:$function.Onceagain,CXwecharacterisethe listF0b9ytheleastelement,othistimetheleastcontextfunction, inTit.pSo,suppAosingOMxs=[id,id]whereidx=x theTabstractv|ralueofMxswillbAe:MARec[	s,Fval(\c1->FncCc1)
  ATB(\a1->ANonRec[])	s,] TheeectoftheMheadfunctionistowrapMSelA1around thisterm,makingtheabstractv|ralueofMida9vailablewhere itTisneeded.pBut,no9w,ifMxsweredenedasMxs=[id,const]whereidx=xpconstx	s,=42   j9   
                                      Ơ⍠?      w9eneedtobAemorecautious.Sincetheabstractinterpre-
  tationybcannotdistinguishitemsinlists,ew9emustarrangethatthefunctionwhic9hemergesfromthelistrepresentsthew9eakerbev|raluator:Mconst.=ThatrequiresthelistasawholetoTha9vev|ralue:ZMARec[	s,Fval(\c1->_)9TB(\a1->ANonRec[])	s,]The2upshotofallthisisthattheabstractv|ralueofalistcon9taining functionsischaracterisedbytheleastfunctioninʾthelist,withtheprincipleextendinganalogouslytoallother8structures.iInordertocarrythatout,agreatest-lo9wer-bAoundoperationisneededforabstractv|ralues.ThisiswhatTtheMAMeettermisfor.Í3.4GMoreLabFfoutcontextsmThis.isagoAod.poin9tatwhichtowheelintheHaskelldecla-ration0&forcon9texts.lUnfortunately:,6itisevenmorecumbAer-someTthantheMAbsValdeclaration.pNev9ertheless:MdataContext
f=Stop1
f|Up1Y[Context]
f|Stop2
f|Up2
f|UpUp2X[Context]
f|FncYAbsValContext
f|FncCContext
f|FvalCXAbsVal
f|CJoinX[Context]
f|CMeetX[Context]
f|CtxVar,Id
f|CtxLam,IdContext
f|CtxApXContextContext
f|SelUIntContext
f|SelUUXIntContext
f|CaseUXContextContextContext
f|CaseUU,ContextContextContextContext
f|DefUContext
f|DefUUXContextTheSrstsixareforbuildingliteralcon9texts.իMStop1andMUp1yOpAertaintopoin9tsinMLift(D1x...xDn),withyOMStop1represen9tingthebAottompoin9tM_,Y|andM(Up1[x1...xn])represen9tingthepAointMU[x1...xn].Similarly:,TMStop2,MUp2and$uM(UpUp2[x1...xn])represen9tthepAointsM_,h=MU_andMUU[x1...xn]&inthedomainMLift2(D1x...xDn).ɶMFnciseusedforbuildingfunction-v|raluedcon9texts,/asdiscussedinsectionHj3.2.Finally:,U0MDefUH]andMDefUUexisttohelpthetermrewritingTsystem,asdescribAedinsection4.4.
MFncC(and)!MFvalCw9erealsodiscussedinsection3.2.ʹMCJoinandMCMeet]=unsurprisinglydenotetheleastuppAerandgreatestlo9werTbAoundsoftheirrespectiv9eargumentlists.MCtxVar,MCtxLamL0andMCtxApareexactequiv|ralen9tstotheMAbsVar,"MAbsLamandMAbsApdiscussedinsection3.3.fTheypro9videawaytoreferencecontext-v|raluedvariables,andal-lo9w8thecreationandapplicationofcontext-v|raluedmaps.   Onceagain,notethatw9eoftenomitMCtxVarandMCtxAp,
   whenthemeaningisob9vious,ƺandabbreviateM(CtxLamce) toTM(\c->e).
 F:ar%anda9way%themostin9terestingconstructsarethelast four.yMCaseUAandBMCaseUUallo9wpartialdisassemblyofv|ralues in6mMLift(D1x...xDn)andMLift2(D1x...xDn)re- spAectiv9ely:,fin;themannerdiscussedinsection2.2.3.The exactTseman9ticsare:MCaseUStop1,xy	s,=xCaseU(Up1_)xy	s,=yCaseUUStop2xyz	s,=xCaseUUUp2!xyz	s,=yCaseUU(UpUp2_)xyz	s,=z Notedthattheswitc9hv|raluesarerestrictedtobAeingindo- mainsMLift(D1x...xDn)andMLift2(D1x...xDn) respAectiv9ely:.Switchv|raluesfroman9yotherdomainconsti- tute$anill-formedcon9text.JMCaseU$andMCaseUUtermsdenote amappingfromtheirswitc9hexpressionstooneoftheal- ternativ9es.(As<such,Cawell-formedMCaseUorMCaseUUm9ust denote7aamonotonicmapping,sow9eimpAosethesemantic constrain9tTthatMx
`PvMy	"PvMzK\.
 As~,y9oumightsuspAect,aMSelU~andMSelUUareselectorsinthe spiritTofMSelA,discussedinsection3.3.pSeman9ticsare:MSelU	s,n(Up1,[x1...xn...xk])=xnSelUUn(UpUp2[x1...xn...xk])=xn Butthereisav9erystrongsemanticconstrainthere:+itis illegal'toapplyMSelUorMSelUUtoav|ralueunlessthatvalueis pro9v|rablyEequivalentEtoanMUp1[...]orMUpUp2[...]v|ralue respAectiv9ely:.ThisCmeans,O
forsomearbitrarycontextMc,O
the follo9wingTexpressionsarelikelytobAeill-formed:MSelU	s,ncSelUUnc The>oneandonlyw9ay>tomak9ethemwell-formedistowrap therappropriatespAeciesofMCasetermaroundthem,lea9ving theTMSelinthegreatest-v|raluearm:MCaseU	s,c(...whatever...)(SelUnc)CaseUUc(...whatever...)(...whatever...)~(SelUUnc) InbAothcases,RthetermM(Selnc)ma9ynotappearinan9y placemark9ed\M...whatever...".[]NotethattheMSelterm ma9y2appAearanywherewithinthegreatest-v|raluearm,yand is|notrestrictedtothetoplev9el,asthisexampleseemsto suggest.' 3.5GConstructorLfunctionsandcasestatementsm Thesource-languagetrappingsofstructuredt9ypAesgiverise toNsomeofthemorein9terestingpartsoftheabstractinter- preter,NOandBw9arrantasectiontothemselves.1First,NOthough, someTterminology:.pAstructuredt9ypAeisdenedlikethis:MdatatypeNamev1...vk=C1t11...t1muM|...uM|Cnt1n...tnm   10                                        
⍠?      Thisdenesat9ypAecalledMtypeName,paramterisedbytypAe
  v|rariables@Mv1toMvk,xwithconstructorsMC1toMCn.Thet9ypAeex-pressionsMt11toMtnm,whic9hformtheargumentstothecon-structors,arehea9vilyconstrainedinthemannerdiscussedin
1section2.2.6:*theyma9yonlybAeeitheroneofthetypAev|rariables,i
Mv1...vk,orXLadirectrecursiv9ecalltothetypAe:M(typeNamev1...vk).
Becauseofthisconstrain9t,eachconstructorargumen9tinav|ralid&denitioncanbAeclassiedeitherasarecursiv9ecallMRec,orYasoneofthet9ypAev|rariables,jMVarnwhereMnisanumbAerdenotingTwhic9hv|rariable.pF:orexample,thedenitionOMdataAVLTreeiab
f=ALeaf
f|ANodei(AVLTreeiab)ab(AVLTreeiab)can,Tinprinciple,bAerewrittenasMdataAVLTree(of3typevariables)
f=ALeaf
f|ANode(Var1)Rec(Var2)(Var3)RecW:e)
no9wdenetwostrangefunctions,-MargkindandMupdate,toӎassistinthediscussionbAelo9w.	WNeitheraremeanttobAeimplemen9table.Rather,xtheyserveasconvenientnota-tionalRdevices,andarebAestillustratedb9yexample.jTheyarebAothmeaninglessunlesstheparticularconstructorap-plicationTtheyareassoAciatedwithisstated.
Margkindtellsuswhatpartofadatat9ypAeagivenconstruc-torargumen9tcorrespAondsto:eitheracertaintypAev|rariable,or3arecursiv9einstanceofthetypAe.eF:orexample,bearinginmind~thedeclarationabAo9ve,Pgiven~theconstructorapplica-tionTM(ANodeilabr):Margkindi=Var1argkindl=Recargkinda=Var2argkindb=Var3argkindr=RecupdateG	replacesaparticularv|ralueinasuppliedlistwithanotherv|ralue.Itndsoutwhic9hloAcationtoupdateb9yusingwMargkind,J@expAectinganansw9eroftheformM(Vari),whereupAonBMiisusedasthelocation.	Itisin9v|ralidtouseMupdateinaw9aywhichwouldcausethecalltoargkindto_returnMRec.	_Again,FusingtheconstructorapplicationM(ANodeilabr):Mupdatei"my",["the","cat","sat"]
f=["my",	s,"cat","sat"]updatea"dog"	s,["the","cat","sat"]
f=["the","dog","sat"]updateb"ran"	s,["the","cat","sat"]Z=["the","cat","ran"]ButMupdatelxxsupdaterxxsareTbAothillegalsinceMargkindl=Margkindr=MRec.   The$exampleusedMupdatetoreplacew9ordsinalistthereofto
   emphasiseC6Mupdate'spAolymorphicnature.NotethatMupdate isalw9aysusedwithaconstructorwrappAedroundthenal listargumen9t.<Thisconstructorisre-attachedtotheresult:Mupdatei"my"(SomeConstructor["the","cat","sat"])f=(SomeConstructor["my",	s,"cat","sat"]) F:or`
thesak9eofclarity:,rthisinconsequentialdetailishence- forthTignored.
 Recallwfromsection2.2.5thatfunctionMDwOreturnsthedo- main.assoAciatedwithaparticulart9ype.@F:ourmorehandy functionswcofsimilarilkareMtop,Mbot,MtopfvwcandMwhnf.BThe rstt9wosimplygeneratethegreatestandleastcontextsina particular5domain.Mtopfv(D)5pgeneratesthegreatestabstract v|ralueTindomainMD.Mtop(Lift	s,(D1x...xDn))f=Up1,[top(D1)...top(Dn)]top(Lift2(D1x...xDn))f=UpUp2[top(D1)...top(Dn)]top(Ds->Dt)f=(\c->top(Ds))bot(Lift	s,(D1x...xDn))f=Stop1bot(Lift2(D1x...xDn))f=Stop2bot(Ds->Dt)f=(\c->bot(Ds))topfv(Lift	s,(D1x...xDn))f=ANonRec[topfv(D1)...topfv(Dn)]topfv(Lift2(D1x...xDn))f=ARecX[topfv(D1)...topfv(Dn)]topfv(Ds->Dt)f=Fval(\c->top(Ds))3'(\a->topfv(Dt)) whnf(D)isthew9eakheadnormalformev|raluatorfordomain MD.TThisonlymak9essenseforcertainv|raluesofMD:Mwhnf(Lift	s,(D1x...xDn))f=,Up1[bot(D1)...bot(Dn)]whnf(Lift2(D1x...xDn))f=UpUp2[bot(D1)...bot(Dn)] Finally:,Tfortherecord,aCoreMcaseexpressionloAokslik9eMcaseswitchExpressionoffC1p11...p1m->rhs13'...fCnp1n...pnm->rhsn whereX%itisassumedthatallconstructorsarepresen9t.This isTassuredb9ythepattern-matchingphaseofthedesugarer.
 Thefourfollo9wingsectionsdoAcumentthe
owofabstract v|ralues^andcon9textsthroughconstructorapplicationsand Mcase'expressions.Insomew9ays,the'twoareoppAosites:con- structorkapplicationsbuildstructures,O1whilstMcaseexpres- sionsMdisassem9blethem.~ZAninterestingdualityarisesfrom this.The
o9wofabstractv|raluesthoughcaseexpressions isuncannilysimilartothe
o9wofcontextsv|raluesthrough constructors,Tandvicev9ersa.   11                                        &⍠?      3.5.1ConstructorLfunctions:fhabstractvaluepropagationmHo9w1doabstractv|ralues
owthroughaconstructor?4The
  discussionofsection3.3impliedthatthetheM(:)functionm9ustTbAehavesomethinglike:ehM(:)=\xxs->AMeet[xs,ARec[x]]Observ9ethattheapparentlypAolymorphicnatureofthisdef-
  initionisinciden9tal.7Ingeneral,givenanarity-nconstructorMCandargumen9tsMa1...anwhereM(Ca1...an)::tau,theTforw9ardbAehaviourofCis:ehM\a1...an->AMeet[e1...en]ei=aiifargkindai=Rec
f=ARec(updateaiaitopfv(D(tau)))if,argkindai==Varxand	s,Cisfromarecursivetype
f=ANonRec(updateaiaitopfv(D(tau)))if,argkindai==Varxand	s,Cisfromanon-recursivetypeNullaryfconstructorssimplyacquirethetopabstractv|ralueoftherelev|ran9tdomain(bAearinmindthat,foradomainnotcon9tainingfunctionspaces,thisisthesameasthebAottompAoin9t).pTheTM[]caseforM[Int],forexample,is:M[]=topfv(D([Int]))
f=topfv(Lift2(Lift()))
f=ARec[ANonRec[]]The3motiv9einallthisistoensurethattheabstractv|ralueofaconstructorapplicationisc9haracterised,foreachparame-terisingTt9ypAe,bytheleastv|ralueofthattypAe.
AsK[anexample,consideranob jectoft9ypAeM(AVLTreeIntIntInt).oContextsforthattypAearedra9wnfromthedomainMLift2(Lift()xLift()xLift()).
#W:eexpAecttheabstractv|raluereturnedb9ybAoththeMALeafandMANodeconstructorstobeoftheformMARec[ii,aa,bb]ͺwhereMiirepresen9tstheleastabstractv|ralueQofan9yob jectcorrespAondingtotypAev|rariableMiinthet9ypAeTAdenition,candsimilarlyforMaaandMbb.7So,atthisin-stan9tiation,Wtheabstractv|raluebAehaviouroftheconstructorsis:JMALeaf=ARec[ANonRec[],ANonRec[],ANonRec[]]ANode=\ilabr->ZAMeetZ[ARec[i,/?ANonRec[],ANonRec[]],l,ARec[ANonRec[],a,/?ANonRec[]],ARec[ANonRec[],ANonRec[],b*F],rZ]Non-recursiv9e`~typAesaredealtwithinanexactlyanalogousmanner.JF:or6example,c`thebAeha9viourofthepairingconstruc-torTatt9ypAeMInt->Int->(Int,Int)Tis  M(,)
  =\xy->
ZAMeet
Z[ANonRec[x,/?ANonRec[]],ANonRec[ANonRec[],y*F]
Z]q If_y9ourinstinctstellyouthisismuchadoabAoutnothing,you are;!correct.Sincealltheseexamplesbuildstructureswith- outem9bAeddedfunctionspaces,theresultv|raluesareunitary:, andTma9ybAewritten:M[]	s,=/?ARec[ANonRec[]](:)=\xxs->ARec[ANonRec[]](,)=\xy->ANonRec[ANonRec[],ANonRec[]]ALeaf=ARec[ANonRec[],ANonRec[],ANonRec[]]ANode=\ilabr->)TARec[ANonRec[],ANonRec[],ANonRec[]]? 3.5.2ConstructorLfunctions:fhcontextpropagationm TheQnameofthegamehereistosa9ywhatcontextpropagates fromManon-n9ullaryconstructortoitsarguments.fZIntuiting rstTonM[Int],M(:)exhibitsthefollo9wingbAehaviour: MDemandon(x:xs)YDemandonxDemandonxs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .UU[U[]]FU[]B&4UU[U[]] .UU[_]PR_K`UU[_] .U_^_K`_ ._c9N_K`_ AMUU[U[]]źcon9textcausesev|raluationoftheentirestructure of,pthelist,27andalltheMIntsinittoAo.aSow9emaypropagate MU[]!toMxandMUU[U[]]tothetailofthelist.Thesame reasoning9explainsthepropagationofaMUU[_]con9text.3Now, what`iofMU_?"Thisev|raluatorsimplyevaluatestoWHNF,that is,the,rstconstructor,andgiv9esup.Sozerocontextmay bAepropagatedtoeitherheadortail.Similarly:,Bzerocon9text propagatesTfromzerocon9textonM(x:xs).
 Is;thereapatternhere?Thecon9textonMxsisthatsameas theMcon9textonM(x:xs)exceptattheWHNFpAoint,
whilst the#'con9textonMxis\My"intheMUU[y]cases,&andnoneother- wise.ThisrlatteropAerationcouldberegardedasdropping ther double-lifting,*andselectingtherstproAductcompo- nen9t.W:ritingthecontextonM(x:xs)asMalpha,contextonMx andTMxsrespAectiv9elycouldbewrittenas:MDropUU1alphaZapWHNFalpha Implemen9tingZMDropUUandMZapWHNFdirectlycausesma jor problemsintheterm-rewritingsystem.F:ortunately,Jthe MCaseUUTandMSelUUprimitiv9escanbAeusedinstead: txMDropUUnalpha=CaseUUalpha__(SelUUnalpha) txZapWHNFalpha	s,=CaseUUalpha__alpha Analogisingtheinformalargumen9tleadstoageneralrule. Giv9en@anarity-MnconstructorMC?andargumentsMa1...an whereS$M(Ca1...an)::tau,con9textMalphaonthecon- structorTapplicationproAducescon9textonMaiasfollows:   12   
                                     =⍠?      Mai	s,=ZapWHNFalpha
  A(if,argkindai==Rec=DropUUxalphaA(if,argkindai==VarxA(and	s,Cisfromarecursivetype=DropUxalphaA(if,argkindai==VarxA(and	s,Cisfromanon-recursivetype'The}iMAVLTreeexampleatinstanceM(AVLTreeIntIntInt)bAeha9vesLqasfollo9wsforacontextMalphaappliedtoM(ANodeilabr):s]MVariable!Demand~~~~~~~~~~~~~~~~~~~~~~~~~~~~~iB&4DropUU1alphalB&4ZapWHNF	s,alphaaB&4DropUU2alphabB&4DropUU3alpharB&4ZapWHNF	s,alphaCon9text9%propagationfornon-recursivetypAesbeha9ves9%inasimilarNmanner,]exceptthatitisnolongerpAossibletogen-erate)]MZapWHNF,andthedrop-selectopAeratoronlydropsonepAoin9t,%insteadYoftwo.rThisopAerator,%calledMDropU,isimple-men9tedTas'MDropUnalpha	s,=CaseUalpha_(SelUnalpha)F:or7acon9textMalphaappliedtoM(x,y)::(Int,Int),the
  con9textspropagatedtoMxandMyareM(DropU1alpha)˺andM(DropU2alpha)TrespAectiv9ely:.
T:ranslationgvofMDropU,MDropUUgJandMZapWHNFin9totheMCaseandMSel
ݺprimitiv9esrequiressomepassingaroundofdomains,[sothattheappropriatekindofbAottomv|raluescanbeman9ufac-tured.3.5.3CaseLexpressions:fhabstractvaluepropagationmTheQtaskhereistogureoutwhatabstractv|raluestoat-tac9htoconstructorv|rariablesinacaseexpression,YgiventheabstractTUv|ralueoftheswitc9hexpression.rThesolutionisre-mark|rably`similartopropagationofcon9textstoconstructorargumen9ts,^3andOfollowsathemewhichshouldbAebecomingfamiliar.pGiv9enTacaseexpression'Mcaseswof
f...
fCa1...an->rhs
f...andLanabstractv|ralueassoAciatedwithMswofMfsw,ttheabstractv|ralueTassoAciatedwithMaiisMai	s,=fswA(if,argkindai==Rec=SelAxfswA(if,argkindai==VarxLetwtheabstractv|ralueoftheswitc9hexpressionbAedenotedMfsw.pF:orTM[Int]w9ehave:  Mcaseswof
  f[]->	s,rhs1f(x:xs)->	s,rhs2 givingTbindingsofMx	s,--->SelA1fsw
  xs--->	s,fsw (AVLTreeIntIntInt)Tgiv9es:McaseswoffALeaf8->rhs1fANodeilabr	s,->rhs2i	s,--->SelA1fswl	s,--->fswa	s,--->SelA2fswb	s,--->SelA3fswr	s,--->fsw Finally:,TM(Int,Int)giv9es:Mcaseswoff(x,y)	s,->rhs1x	s,--->SelA1fswy	s,--->SelA2fsw 3.5.4CaseLexpressions:fhcontextpropagationm Thissectionestablishesho9wcontextonaMcaseexpression propagatesktocon9textontheswitchexpression.First,a subsidiaryTresult. ForwardsLpropagationofcontextsthoughconstructorsm Giv9en5%aconstructorapplicationM(Ca1...an)::tau,athe methoAdGofsection3.5.2cantellusho9wcontextonthisap- plicationCmapstocon9textonMa1...an.However,OQweCnow needHgtoruntheproAcessinrev9erse.GivenHgsomecon9texts Mc1...cnLonMa1...an,w9eLwanttondthegreatestcon- textMalphathatma9ybAeputontheapplication,constrained sothatthecon9textsthatsection3.5.2indicateswouldthen propagatetoMa1...anarelessthanorequalMc1...cn respAectiv9ely:.
 Thefollo9wingschemeisoered,againwithoutjustication. IfTMCisfromarecursiv9etypAe:Malpha=CJoin[Up2,CMeet[e1...en]]ei=aiif,argkindai==Recf=updateaiaitop(D(tau))if,argkindai==Varx IfpMCPisfromanon-recursiv9etypAe,6M(argkindai)cannotbe MRec,Tsothissimpliesto:Malpha=CMeet[e1...en]ei=updateaiaitop(D(tau))if,argkindai==Varx   13                                        U⍠?      Finally:,Tforn9ullaryconstructors,likeM[]:kMalpha=ctop(D(tau))Examples:pgiv9enTM(a1,a2)::(Int,Int),w9egetMalpha=CMeet[Up1[c1,XU[]],
  GUp1[U[],,c2]](a1:a2)::[Int]Tgiv9esMalpha=CJoin[Up2,GCMeet[UpUp2[c1],mMc2]>
][]::[Int]Tgiv9esMalpha=UpUp2[Up1[]](ANodea1a2a3a4a5)::(ATreeIntIntInt)Tgiv9esMalpha=CJoin!T[Up2,+'CMeet[UpUp2[c1,XU[],,U[]],P0c2,P0UpUp2[U[],,c3,XU[]],P0UpUp2[U[],,U[],c4	s,],P0c5]!T]덑UsingLthelemmamAndino9wtoreturntothemaintheme.AtthispAoint,it'snecessary{toin9troAduceafunctionwewillseealotmoreoflater.TheyfunctionMCMtellsusho9wmuchcontextispropa-gateds]toav|rariableMxwhencon9textMalphaispropagatedtosome>arbitraryexpressionMe.Ofcourse,I3ifMxdoAesnotoccurfreeTinMe,theansw9erisnone.pW:ewritethisasMCx[e]rhoalphawiththeMeinsquarebrac9ketstoemphasisethatMCbregardsitmasasyn9tacticob ject.%fAsbAecomesapparentlater,MCmalsorequiresanen9vironmentMrhowhic9hsuppliesabstractv|raluesforTallfreev|rariablesinMe.
RecallTthataMcaseexpressionloAokslik9ethis:Mcaseswof
fC1p11...p1m->rhs1
f...
fCnp1n...pnm->rhsnNo9w,SgivencontextMalphaoverall,SwhatisthecontextonMsw?`aThe֤rststepistondthecon9textonMp11...pnm.TheseTcon9textaregivenby:M(Cp11[rhs1]rho1alpha),...(Cp1m[rhs1]rho1alpha)...(Cp1n[rhsn]rhonalpha),...(Cpnm[rhsn]rhonalpha)   F:orD=eac9hparticularconstructor,Otheoriginalenviron-
   men9tMrhoisaugmentedwithabstractv|raluebindingsfor the0v|rariablesassoAciatedwiththatconstructor,vgenerating Mrho1...rhon.Thesev|raluesarederiv9edfromtheabstract v|ralueoftheswitc9hexpression,asdescribAedinsection3.5.3.
 TheHnextstepistogureoutwhatcon9textcanbAesafely appliedwtoeac9hconstructor,hknowingthecontextsontheir individual.4argumen9ts.gThemethoAddescribedinthelemma is}applied,onceforeac9hconstructor,tothecon9textsfor Mp11...pnmjustcomputed,TJgivingMalpha1...alphan. These<mv|raluesarecom9binedtogivetheoverallcontexton MswTas:OMCMeet[alpha1...alphan] Using6uMCMeettomergethesev|raluesre
ectsthefactthatw9e
   cannotkno9wwhichalternativewillbAeselectedatcompile time.ThebAestsafev|raluewhic9hcanbeobtainedistheleast ofTan9yofalternatives. Unfortunately:,*there?isonespAecialcasewherethisform9u- lation"iswrong.Whentheswitc9hexpressionisofare- cursiv9etypAe,likeM[Int],onendsthatpropagatingzero con9textontotheMcaseexpressionproAducesnon-zerocontext onx!theswitc9hexpression.DThisunsaferesultcanbAetraced to7thecaseforrecursiv9etypAesbeingoftheformMalpha= MCJoin[Up2,...],swhic9h
impAosesaminimumv|ralueofMUp2 onthecon9textcontributedbyeachconstructor.Simply thro9wingoawaytheMUp2clampingbitcausesmoreproblems than@itsolv9es.kA@bAettersolutionistoexplicitlyimposethe requiredconditionthatzeroo9verallcontextproAduceszero con9text7ontheswitchexpression.RecallingthatMalphais theTo9verallcontext,thisisdonebywritingOMCaseUalpha_(CMeet[alpha1...alphan]) orMCaseUUalpha_(CMeet[alpha1...alphan])
  Jn(CMeet[alpha1...alphan]) depAendingConthedomainofMalpha.֞Thepossibleduplication oftheM(CMeet[alpha1...alphan])termisregrettable, and@EcouldpAoten9tiallycausema jorperformanceproblems. SectionT6.1sho9wshowthesemaybAeavoided.
 Thecomplicationsinthisbusinessseemendless.\W:eha9ve justTcreatedy9etanotherproblem.pConsider:Mlet	s,idy=yincaseeof)T[]Y->id)T(x:xs)	s,->id ThismMcaseexpressionreturnsafunction,whic9hispAerfectly legitimate.:Buttheo9verallcontextonit,ݨMalpha,willbAea functioncon9text,Iganditisquitemeaninglesstoscrutinise suc9hav|raluewithMCaseUorMCaseUU.Alittlethough9treveals ayDsimplesolution.H?TheMcaseexpressionreturnsafunction, whic9h^Cwill,eventually:,bAe^Cappliedtosomething.jWhatreally mattersJisthecon9textonthenalresultofthatapplication: ifnon-zero,MitmeanstheMcaseexpressionwillev9entuallyhave to5bAeen9tered,inordertogenerateafunctionwhichinturn generatessomeresulttosatisfythedemand.So,Ballw9eneed do,٪iffMalphaisafunctioncon9text,istestthenalcon9text   14                                        hp⍠?      encapsulatedYinMalpha,YratherthanMalphaitself.Gettingthe
  nalx\con9textoutofanMn-arityfunctioncontextiseasilydoneb9y̅wrappingMnFncCVselectorsroundit.BSocontextontheswitc9hTexpression,intermsofMalpha,nowloAokslike:MCaseUU(FncC(FncC.....(FncCalpha).....))_(CMeet[alpha1...alphan])(CMeet[alpha1...alphan])Then9umbAerofMFncCsisequaltothearityofMalpha,lifMalphahappAens+tobeafunctioncon9text._!Mcaseexpressionsreturn-ing=functionsseemtobAerarities,hsousuallytherewillbezeroMFncCs.TheZcorrespAondingmodicationoftheMCaseUAv9ersionisLob9vious,anditonlyremainstosaythatchoAosingbet9weenthe.t9wonowdepAendsonthenalcontextencapsulatedinMalphaTwhenMalphaisafunctioncon9text.
AslourlongjourneythroughtheforestofsuppAortingma-c9hinerycomestoaclose,sothenaldestinationdrawsintosigh9t:theKdenitionoftheabstractinterpreterpropAer.,W:epauseGbutbrie
ytotak9erespiteinthefollowingexample,thenTem9barkupAonthenalstraight:psection3.6.Mcasevsof
f[]Y->0
f(x:xs)	s,->xClearly:,kMvs::[Int]andtheo9veralltypAeisMInt.OSoacon-textMalphaplacedontheresultm9ustbAeindomainMLift(),withDtheresultingcon9textonMvsinMLift2(Lift()).Sec-tion3.5.4indicatesthattheM[]casecon9tributescontextMUpUp2[Up1[]].No9w,NpropagatingMalphatotheM(:)alter-nativ9eputscontextMalphaonMxandMStop2(thatis,'none)onMxs.Com9bining"thesetwo,againusingsection3.5.4,sho9wsthatTthecon9textpropagatedbythisalternativeis:ZMCJoin[Up2,CMeet[alpha,Stop2]]=CJoin[Up2,Stop2]=Up2ThisTgiv9esoverallcontextonMvsas:ZMCaseUalphaStop2>
(CMeet[UpUp2[Up1[]],Up2])=CaseUalphaStop2Up2That'sin9tuitivelycorrect:withnodemandontheresultingMInt,Rthere'sFno(MStop2)demandontheincominglist.Oth-erwise,w9e&mayev|raluatethelisttoWHNF(MUp2),thatis,todtherstconstructor.uItisapit9ythesedomainscan'ttellusw?abAoutthehead-strictnesshere:Ggiv9ennon-zerodemand,it's~ob9viouswecannotonlyev|raluatetotherstconstruc-tor, butcanalsoev|raluatetherstelemen9tofthelistifitisnon-empt9y:..3.6GDeningLtheabstractinterpretermSectionJ3.5.4in9troAducedthecontext-ndingfunctionMC.W:eno9waugmentthiswithMZ,theabstractinterpreteritself.dPMCtak9escJanyCoreexpression,acontextonthatexpression,andav|rariable,andreturnstheresultingcon9textonthevariable.MZtak9esanyCoreexpression,pandreturnstheabstractv|ralueofthatexpression.XSincetheforw9ardandbackward
owsofinformationarehea9vilyintertwined,
tMCۡandMZarem9utuallyrecursiv9e.pInTacalltoMCorMZ  Cx[e]rhoalpha
  Z,[e]rho xUisav|rariable,MeisaCoreexpression,Malphaisacon9text, andMrhoisanen9vironmentbindingallfreev|rariablesinMeto abstractv|ralues.1Asimplemen9ted,EbAothfunctionscarryan extra.parameterusedtohelpgeneratenewv|rariablenames. MCRalsoTcarriesthedomainofMxsoitcangeneratetheappro- priatebAottomv|raluewhenneeded.rRecallalsothataCore expressionisapair,therstpartofwhic9histhetypAeofthe expression,TandthesecondtheexpressionpropAer.- 3.6.1DenitionLofMZm The:abstractv|ralueofaliteralisavalueintheappropriate one-pAoin9tTdomain.MZ(tau,ALitn)rho	s,=ANonRec[] V:ariablesTha9vetheirv|raluesloAokedup.MZ(tau,AVarv)rho	s,=rhov Applicationsarealittlemoretric9ky:.\YFirst,ڟtheabstract v|ralueofthefunctioniscreated.PF:romthat,\theabstract- v|ralue-map0isextractedusingMFvalA,,andappliedtotheab- stractv|ralueoftheargumen9ttogivetheabstractv|ralueof theTresult.MZ(tau,AApfe)rhof=AbsAp(FvalA(Zfrho))(Zerho) Lam9bAdaytermsarealotmoretricky:.LetMaandMcdenote newTv|rariables.MZ(tau,ALam[x]e)rhof=Fval(CtxLamc(Cxerho_c(FncC(CtxVarc))))3'(AbsLama(Zerho_a))where)Trho_c=rho{x->FncA(CtxVarc)})Trho_a=rho{x->AbsVara} AnMFvalisreturned.!ItsrstcompAonen9tisamapfromthe functioncon9textMconM(\x.e)tothecontextonparameter Mx.i>BearinmindthatMcwillgetbAoundtoatermofthe formeM(Fncaacc),ywhereMaaistheabstractv|raluesupplied for Mx,andMccisthecon9textonMe.SothecontextonMx isfoundb9yndingMCAofMxinMe,withMrhoaugmentedby bindingTMxtoMaa,thatis,toMFncA(CtxVarc),andTwiththe con9text
zonthebAody
zofthefunction,Me,equal
ztoMcc,thatis, MFncC(CtxVarc).
 TheJsecondMFvalcompAonen9tmapstheabstractv|ralueMaofMx totheabstractv|ralueofMe.Thisiseasilydoneb9ycomputing MZTofMe,withMrhomoAdiedtobindMxtoMAbsVara. TheTMACasecaseisquiteeasy:MZ(tau,ACasesw[(cname1,(pars1,rhs1))...X0(cnamen,(parsn,rhsn))])frhof=AMeet[Zrhs1rho1...Zrhsnrhon] Thexaugmen9tedenvironmentsMrhoi(1<=i<=n)xareob- tained Rb9yextendingMrhotoprovidebindingsforMparsiin   15                                        ⍠?      viewofthev|ralueofMZswrho,SusingthemethoAdofsec-
  tionT3.5.3.
Finally:,PtheMAConstrcase..Althoughsections3.5.1and3.5.2completelyrdoAcumen9tabstractv|ralueandcontext
owsthroughconstructors,*w9easyethavenowayofcreatingabstractbv|raluesforconstructors.fStartingfromageneralconstructorTapplication\MCe1...enw9eTdesiretobuildMFval(\c1->f1(FncC^nc1))
  (\a1->Fval(\c2->f2(FncC^(n-1)c2))(\a2->...9TB...9TB...->Fval(\cn->fn(FncC^1cn))rJ(\an->aresultant)...))\where-MFncC^iemeansMFncC-appliedMitimestoMe.Observ9ethatjeac9huseofMFncCjhereisoftheformMFncC^icjwhereMi+j==n+1,Fandsoallthesetermssimplydenotethecon9text`ontheresultoftheconstructorapplication.WhatsectionP3.5.2pro9videsisawaytocomputetheMncontextmaps,Mf1...fn.-Section>3.5.1generatesatermoftheformM\a1...\an->aresultantand+bAet9weenthem,\that'sallthat'sneeded.
_Asthisisratherconfusing,here'sacoupleofexamples.F:orM(:)::Int->[Int]->[Int]:Fval(\c1->DropUU1(FncC(FncCc1)))(\a1->Fval(\c2->ZapWHNF(FncCc2))P0(\a2->ARec[ANonRec[]]))F:orTM(,)::Int->Int->(Int,Int):MFval(\c1->DropU1(FncC(FncCc1)))(\a1->Fval(\c2->DropU2(FncCc2))P0(\a2->ANonRec[ANonRec[], G&ANonRec[]]))3.6.2DenitionLofMCmPropagationTofacon9textontoaconstanthasnoeect:MCx(tau,ALitn)rhoalpha
f=bot(domain-of-x)TheTv|rariablecaseis:MCx(tau,AVarv)rhoalpha
f=ifXx==vthen	s,alphaelse	s,bot(domain-of-x)AsbAefore,9theapplicationandlam9bdacasesareabitmindbAending.MCx(tau,ALam[y]e)rhoalpha
f=Cxerho2(FncCalpha)where!Trho2=rho{y->FncAalpha}   Here,9OMalpha2isafunctioncon9textbAeingappliedtoM(\y.e).
   Assuming@thatMxandMyarenotthesamev|rariable(the lam9bAda-lifterassuresthis),IcontextonMxinM(\y.e)canbAe found	fromthecon9textonMxinMe.SinceMalphaisafunction con9text,MFncAalphak,isanabstractv|raluewhichMyisbAound to,TgeneratingMrho2.FncCalphaisthecon9textonMeitself.OMCx(tau,AApfe)rhoalphaf=CJoin[Cxfalpha_frho,ATBCxealpha_erho]where)Talpha_f=Fnc(Zerho)alpha)Talpha_e=CtxAp(FvalC(Zfrho))alpha_f T:odealwithapplications,ʆobserv9ethatMxmayoAccurinboth thefunctionandargumen9texpressions,soweneedtocol- lectupthecon9textsfromMfandMe,Uand\addthemtogether" usingMCJoin.pTheonlyproblemisguringoutwhatcon- textvpropagatestoMfandMe.@~Recallthatafunctioncon- textconsistsoftheabstractv|ralueoftheargumen9t,andthe con9textx1ontheresult.EHence,thecontextonMfmustbAe MFnc(Zerho)alpha.PThedcon9textonMeisequaltothe con9textlythatMfwouldpropagatetoitsargument,Bandwe kno9wthatthecontextonMfisMalpha_f.So,C4webuildthe abstractin9terpretationforMfwithMZfrho,extractthecon- textUmapusingMFvalC,andapplythattoMalpha_f.Alltold, that'sTMCtx(FvalC(Zfrho))alpha_f.
 DueWtotheheroiceortsofsection3.5.4,therathercompli- catedTMcaseclauseisstatedquitesuccinctly:MCx(tau,ACasesw[(cname1,(pars1,rhs1))...bg\(cnamen,(parsn,rhsn))])rhoalphaf=CJoin[Cxswrhoalpha_sw,ATBCMeet[Cxrhs1rho1alpha...g Cxrhsnrhonalpha]]7] Here,"Malpha_sw,isthecon9textonMsw,givenMalphacontext ontheMcaseexpressionitself,ascomputedb9ythemethoAdof sectionT3.5.4.
 AsbAefore,theMrhoi(1<=i<=n)areobtainedb9yextend- ingMrhotopro9videbindingsforMparsiinviewofthev|ralue ofTMZswrho,usingthemethoAdofsection3.5.3. V:ariableMxcanappAearinboththeswitc9hexpression,J[and an9y&ofthealternatives.
PT:odealwiththeformer,con- textonMswiscomputedaspAersection3.5.4,andthiscon- textb0propagatedin9toMsw.ContextforMxinalterativeMiis MCxrhsirhoialpha,pbutsincew9ecan'tsaywhichalter- ativ9e:willactuallybAeselected,wemusttakethegreatest lo9wer'bAoundo9ver'allalternativ9es.Finally:,theswitchand alterativ9econtextsareonceagain\added"usingMCJoin.IAs with5theMZ5clauseforMcaserhoisextendedtopro9videbind- ingsTforthev|rariablesassoAciatedwitheac9hconstructor. Finally:,DtheMAConstrcase.Alltheactualw9orkofdealing withcon9text
owthroughconstructorsisdoneinthecorre- spAonding?MZ?clause.Allw9eneeddohereisobservethatMxis nev9erTfreeinanyconstructor,andsoreturnzerocontext:OMCx(tau,AConstrc)rhoalphaf=bot(domain-of-x)   16                                        ⍠?      4TheLtermrewritingsystem4.1GIntroFfductionmF:or*eac9hCorefunction,o=theabstractinterpreterproAduces
  anEMAbsValterm.Recursiv9egroupsoftermsrequirexpAoint-ing,-jwhic9h(isdoneinastraightforwardmanner.V>Theinitialappro9ximationvforafunctionindomainMDvisMatop(D),sothehxpAoin9tingproducesthegreatestxpoin9t./Althoughitmigh9tseemalittleunusualtoseekthegreatestxedpAoint,bAearinmindthatthisapproac9hrepresentsstartingofroma)dangerousv|ralue,YMatop(D))anditeratingone'sw9ay)tosafet9y:.Inforw9ardanalysesinthestyleof[Sew91/],dangerisrep-resen9tedI:bytheleastpAointinthedomains,V3andxpAointingyields/theleastxedpAoin9t.Inanycase,ڦthisdiscussionisratherWacademic,h>sincew9ecanclaimtobAelookingforleastxpAoin9tsUheretoosimplyb9yturningallthedomainsupside-do9wnp{astheyarenite,completelattices,suc9hatrickisquiteTallo9wable.
The)termrewriterexistsbAecauseoftheneedtocompareap-pro9ximationsXduringxpAointing.}F:ornon-recursiveterms,thereis,strictlyspAeaking,noneedtousetherewriter.PNev-ertheless,bAecauseRwhatemergesfromtheabstractin9ter-preterfisusuallygrosslyredundan9t,alltermsaresub jecttoJBrewriting,}andtherecursiv9eonesaresubsequentlyx-pAoin9ted.WhattherewriterdoAesistotransformeac9hpossibletermin9to}anormalform,suchthatsemanticallyequiv|ralentformsmap9tothesamenormalform.EDetectionofxedpAoin9tsis;thenasimplematterofdetectingsyn9tacticequalityofthenormalforms.%F:orhigherorderterms,YLunfortunately,thisximpliesanabilit9ytosolvethehaltingproblem.DW:ethereforeVdealwithhigherorderfunctionsasdescribAedinsectionj5,andrestrictourselv9estogeneratinguniquenormalforms)fortheabstractin9terpretationsofrstorderfunctions,somethingTwhic9his,fortunately:,decidable.ThetermrewriterpropAerisanelaboratesystemwhic9hgen-eratesa,normalformsb9yapplyingmanyloAcaltransformationstovaterm.@bWhennomoretransformationscanbAeapplied,theMtermisdeemedtobAeinnormalform.!Eac9hkindofal-lo9wablejtransformationisencapsulatedinaso-calledrewriterule.Eac9h]#rulemustimplementasemanticallyinv|rarianttransformation.	Section3.2in9troAducedafewequalities,whic9h,Twhengivenadirectionality:,bAecomerewriterules:OMFncA(Fncac)===>,aFncC(Fncac)===>,cFvalA(Fvalca),===>aFvalC(Fvalca),===>cMost(rulesarecomplicatedb9ythepresenceofside-conditions:MFnc(FncAc1)(FncCc2),===>c1provided
fc1==c2These6yexamplesillustratetheproblemofwhethertosimplifyterms~startingfromthelea9ves~(innermost-rst)orfromtheroAotM(outermost-rst).ŷSince,inthesecondexample,theruleFonlyappliesifsubtermsMc1andMc2arepro9v|rablyequal,innermost-rst9rewritingseemsnecessary:.	/ButthesamestrategyJappliedtoMFvalC(Fvalca))Jcouldw9astealot   ofۯeortsimplifyingMa,onlytothro9witaway:,7sooutermost-
   rstTmigh9tgivebAetterperformance.
 Pro9vidingDtherulesarenitelycon
uentandterminating, bAoth:approac9hesstillgivethesamenormalforms.Observe ho9weverthatwhatev9erapproachisused,multiplepasses o9ver'thetreewill,Zingeneral,bAeneededtoarriv9eatnor- malform.)ThedecisioncanthereforebAebasedpurelyon whic9heverschemegivesbAetterperformance.HExperimen9ta- tion~"sho9wedthatoutermost-rstrewritingwasuptoten timesZDslo9werthaninnermost-rstforrealisticallysizedterms emitted?b9ytheabstractinterpreter.1AlthoughitwouldbAe foAolishBotoclaimthatthisisalw9aysBoso,ltheevidencesuggested anb innermost-rstsc9hemewouldusuallybAemuchquicker,so anTinnermost-rstsc9heme-=*Aa       cmr61?wasTadopted.5 4.2GPerformingLasinglesimplicationpassm BecausetheMAbsValandMContextt9ypAesaremutuallyre- cursiv9e,thetermrewriterpropAerconsistsoftwofunctions ofGt9ypAeMAbsVal->AbsValGandMContext->Context,each ofqwhic9hpAerformsmultipleinnermost-rstsimplication passesNwithanauxiliaryfunction.6Whenstabilit9yisreached, itgmeansnormalformhasbAeenac9hieved.OThisgsectiondis- cussesWho9wthoseauxiliaryfunctionswork.nxF:orsimplicity:, they!aretreatedasasinglefunction,calledMsimp,w9orking onTtheunionofMAbsValandMContext,calledMTerm. T:oimaximisepAerformance,)eac9hpassofMsimptriestodoas m9uchaspAossible,soastominimisethen9umberofpasses required.AMeasuremen9ts6showedthev|rastma jorityofterms reac9h#normalforminonepass,andnotermhasbAeenob- serv9edTtorequiremorethanthreepasses. TheL?individualrewriterulesareclassiedin9togroups(rep- resen9tedaslists)bytheroAotsymbAolofthetermwhichthey rewrite.TheJmec9hanismwhichdirectstheapplicationof rewriterulesensuresthateac9hruleisonlyappliedtoterms pAossessingxtherelev|ran9trootsym9bol.FEachxruleisimple- men9tedTasafunctionoftypAeMTerm->MaybeTerm,Twhere:OMdataMaybea=Nothing|Justa AsbAecomesclearshortly:,"w9eneedtoknowwhethertheap-
   plicationqofarewriterulehashadan9yeect.1VW:ecould mak9e6eachrulehavetypAeMTerm->Termandcomparethe term
bAeforeandafterapplication,butthisseemsabom- inably.inecien9t,tbAecausetheruleitself\knows"whenit has`madeac9hange.Therefore,cwe`encoAdethatkno9wledge inYthereturnv|ralueb9ypassingbackMNothingifthereisno c9hange.֎ObserveS^thatthereturnedMMaybeTermv|ralueisin- stan9tlydisassembledusingaHaskellcaseexpression,Stond outwhethertherulehassucceeded.Therefore,>aHask9ell implemen9tationwhichreturnsconstructorsinregisters,like Glasgo9wHaskell[PJ92L],:neveractuallybuildstheMNothing orTMJustclosureintheheap,apleasinglittleeciency:. Let9oMtdenoteaterm,uandMrulesfor(t)denotethelistof @   ff _
r}rZ       cmr51YOne 5ofthesharp7erwitsinthefunctionalprogrammingcommu-  nityZ,onreadinganearlydraft,commented:   How%couldyouletsuchawonderfulexampleofself- referenceAgobyunremarked?hIAthoughtitwasabsolutely marvelous:thatyoudecidedtouseaninnermost-rst schemeAinthetermrewriterwhichis,Xafterall,thewhole p7ointofAnna'sexistanceintheRealWZorldoutsideit- self !   17                                        Ƞ⍠?      rewriteМrulesrelev|ran9ttotheroAotsymbAolofMt.simp(t)is
  computedTasfollo9ws:OMsimp(t)
f=schedule(t_inner_simp)where!Tt_inner_simp/=twithsimpappliedtot'ssubtermsschedule(t)
f=rewrite_with(rulesfor(t),t)rewrite_with([],t)
f=trewrite_with((rule:rules),t)
f=case(rulet)of!TNothing->rewrite_with(rules,t)!TJustt2->schedule(t2)Firstly:,6$Mt'sasubtermsaresimplied,givingMt_inner_simp.This"ispassedtoin9termediaryMschedule,f[whichexaminestheroAotsym9boltodeterminetherelev|ran9tlistofrewriterules.)OMscheduleIpassestherulesanditsargumen9ttoMrewrite_with,whic9hzworksitswaythroughthelistofrules.If2itrunsoutofrules,`
itsimplyreturnstheterm.Butifthereisޠarule,itisappliedtotheterm.
4Thiseitherhasnoeect,inwhic9hcasethenextruleistried,/oritproAducesanewterm'eMt2.RNo9wMt2maywellhaveadierentroAotsymbAol,whic9hwouldinv|ralidatealltheremainingrules.SorewritingofTMt2iscon9tinuedTbypassingitbacktoMschedule.
ThemneteectofMschedule(t)isth9ustokeepapplyingrewriterulestotheroAotofMtun9tilnoapplicablerulescanbAe5found.
}ZThisprocessdealsproperlywithc9hangesintheroAotsym9bol.ObservethatthecalltoMschedulefromMrewrite_withHSisnotnecessaryforcorrectness.mW:ecouldsimply+returnMt2atthispAoin9t.ΐWhatthiswouldmeanisthatan9y8pAossiblerewritesofMt2wouldbAedelayeduntilthenextsimplication7pass,dratherthanbAeingdonestraigh9taway:.ҙSoomitting~there-sc9heduleimpliesmoresimplicationpassesandTaseriouslossofeciency:.54.3GDealingLwithlambFfdasandapplicationsmThepresenceofMAbsLam,^MAbsApandMAbsVartermsin9tro-duces?theneedtopAerformlam9bdacalculus-lik9esubsti-tution.*Whatfollo9wsappliesequallytothedualcon-structionsMCtxLam,MCtxApandMCtxVar.sInparticular,Msimp|UneedstobAeabletodealwithtermsoftheformM(AbsAp(AbsLamve)a).pNaturally:,w9ecanreachdi-rectlyBfortheblunderbusssolution:
wdeviseafunctionMsubst(e,v,a)XtoreplacefreeoAccurrencesofMvinMewithMa,andTemplo9yitintherewriterule:MAbsAp(AbsLamve)a,===>subst(e,v,a)Tw9oAdefectsareapparent.Firstly:,LsinceMsimpiscommittedto8doinginnermost-rstsimplication,dbAothfunctionandar-gumen9tBaresimpliedextensivelybAeforesubstitutionbegins.Ourhandsareno9wtied:wecannotmakethelambAda/applytermereductionan9ylazier.Ineciencyisthesecondcom-plain9t.0Thisq]schemedemandsacompletesubstitutionpasso9verTMeforev9eryargument.   AnRaltogethernicersolutionistoforgetabAoutMsubstandthe
   rewritedrule.Instead,w9eequipMsimpwithanenvironment Menv?owhic9hbindsMAbs-v|rariablestovalues.No9w,give?oMsimp acoupleofspAecialcases.Theseomittheusualsimplica- tionofsubterms,Oandb9ypassthegeneralrewritingmecha- nism.6InAthisw9ayAweregainprecisecontrolovertheorder ofrewrites,andnoseparatesubstitutionpassesareneeded. V:ariablesTaresimplyloAok9edup:OMsimpenv(AbsVarv)=envv Onencoun9teringM(AbsApfa),weneedtotryandturnMf
   in9to anM(AbsLamve).>The obviouswaytodothisisby applyingMsimptoMf,Sbutthisw9ouldbAeabigwasteoftimeif Mfisinthatformalready:.SothereisaspAecialc9heckforthis case.Themen9vironmentisthenaugmentedwithabinding forMv,Randsimplicationcon9tinueswithMe.Byc9hoAosingto bindMvtoMaorMsimpenva,w9ecanagainv|rarythestrictness ofy;thesc9heme.H$ThelatterchoicegivesbAetterperformance, soTthespAecialcaseforM(AbsApfa)Tis:OMsimpenv(AbsApfa)f=letsa=simpenva.msf=simpenvfincasefof)TAbsLamve7->simpenv{v:->sa}e)Tother7->casesfofT:AbsLamv2e2bg\->simpenv{v2:->sa}e2T:otherbg\->AbsApsfsa IfMfsimplyrefusestobAerewrittenin9toanMAbsLam,theterm has,itssubtermssimpliedandisthenreturnedas-is.cJThis isDzconsisten9twithhownormalcasesaredealtwith,Csince thereTarenomoreMAbsAprewriterules.
 An-MAbsVarconstructcanrefernotjusttov|rariablesbAound b9y=asurroundingMAbsLam,butalsototheabstractv|ralues of6/otherfunctions.T:odealwiththese,~fw9e\preload"the MAbs-en9vironmentFwithsuitablebindingsbAeforestartingsim- plication.}Finally:,note*thatthedualMCtx-constructions aredealtwithinthesamew9ay:,6soMsimpcarriest9woenvi- ronmen9ts,Hrather>thanjustone.Theonlydierenceisthat aMCtxVarcanonlyrefertoMCtxLambAoundv|rariables.nThese t9worenvironmentsarehenceforthreferredtoasMaenvand McenvTrespAectiv9ely:.5 4.4GAvoidingLinnitebranchingm 4.4.1ALnaiveapproach Section323.4in9troAducedtheMCaseU3*andMCaseUUconstructions
   asyoneofthefundamen9talmechanismsfordisassembling con9texts.uAserious8problemwhichbAecomesapparentas soAonUasonestartsxpoin9tingisthepoten9tialforinnite branc9hing.pFixpAointingTproducesexpressionslik9eMCaseUe(CaseUewx)(CaseUeyz) whic9hTisequiv|ralentto:   18                                        Ӧ⍠?      MCaseUewzOW:ecangetroundthisb9ydesigningthenormalformsothat
  foratermM(CaseUeab),
neithersubtermManorMbma9ydoafMCaseUfonMe.T:oac9hievefthisnormalisationrequiresusingpartialfkno9wledgeabAoutthev|ralueofMewhensimplifyingMaandTMb.
T:o@implemen9tthis,wecouldadoptthefollowingscheme.Giv9e^#Msimpyetanotherenvironment,VMselenv,which^#mapsswitc9hexpressionsseeninsurroundingMCaseUandMCaseUUstoN"partialinformationabAouttheirv|ralue.WhenanestedMCasesexpressionisencoun9tered,3loAokupitsswitchv|ralueinMselenv.`If,thereisacorrespAondingen9try:,1thisMCaseexpres-sionm9ustbAeexaminingacontextwhichhasalreadybAeenloAok9edat,vsotheMCaseexpressionisreplacedbywhicheverarm;thetableen9trysaysiscorrect.$F:orexample,4givenacallMsimpselenv(CaseUe(CaseUewx)(CaseUeyz))simplication,ofM(CaseUewx),˺isdonewithMselenvbindingMe/toMStop1,]zandsimplicationofM(CaseUeyz)/isdonewithMselenv`LbindingMetosomev|ralueoftheformMUp1[...].Thispartial_$informationabAoutMeimmediatelyallo9wsthesystemto(reducethet9wo(subtermstoMwandMzrespAectiv9ely:.qProp-agationofinformationabAoutMCaseUUselectorv|raluesisdoneanalogously:.
Mselenv(cisaugmen9tedeachtimeaMCaseU(^orMCaseUUis\gonepast".?A problemiswhathappAenswhenw9egopastaM(CtxLamve),Jsincethisw9ouldinv|ralidateanykeysinMselenv9con9tainingfreev|rariableMv." RemembAerthatthekeysarearbitraryexpressions,5ratherthanmerev|rariables.ІAnexpAensiv9eWsolutionistolteroutall(key:,$v|ralue)pairswhichrefertoMv,nbutthat'so9verkill.~HItisc9heapAertocompletelyempt9y{MselenvateveryMCtxLam.OThisdoAesn'tloseinforma-tionkbAecausetheabstractin9terpreterneverbuildscontextexpressionsewherew9eneedtomaintainselectorinformationacrossMCtxLambAoundaries.F:orexample,Sitnev9erbuildsany-thingTlik9e:MCaseUs1(\c1->...(CaseUs2....))&m(\c2->...(CaseUs2....))54.4.2GeneralisingLtheschememAlittlethough9tshowsoursolution,whilstpAerfectlywork-able,Dis@toAow9eak.iW:eneedamoregeneralwaytopropagateso-called\Mselenvinformation"around,!ascanbAeseenb9yconsidering:MCMeet[e,UpUp2[Stop1,Stop1]]Initially:,itUloAokslik9enothingmorecanbedonewiththis.Butif,ab9yloAokinginMselenv,w9ecanshowthatMehasanMUpUp2[...]Tv|ralue,then:ZMCMeet[e,UpUp2[Stop1,Stop1]]=UpUp2[Stop1,Stop1]What}tw9ereallyneedisageneralmechanismforpropagat-ingTMselenvinformation.VqT:obAefullygeneral,w9ewillhavetoWsearc9hMselenvforeachtermMsimpencounters.Thispro-cesscanbAerolledin9tothegeneralmechanismofMsimp,by   searc9hingMselenvafterMsimprunsoutofapplicablerewrite
   rules.5W:eexpAecttodisco9vernothingaboutthev|rastma- jorit9yXofterms,iinwhichcaseMsimpactsasbAefore.But,ifor aluc9kyfew,?MselenvtellsusalittleabAouttheterm:itis either>jMStop1,MStop2,MUp2,MUp1[...]orMUpUp2[...].In therstthreecases,·w9ecanobviouslyreplacethetermwith therelev|ran9tvalue,buttheothert9woareproblematic.'Ho9w canyw9eexploitpartialinformationlikethis?GConceptually:, w9e%needtoaddafoAotnotetothev|raluesaying,	forexample, \P:.S.)Thisv|ralueiskno9wntobAeMUpUp2[...]",.andmodify theTrewriterulestotak9eaccountofsuchfoAotnotes.
 ThisLHallsoundsratherclumsy:,Zbutthereisaneatsolution. Recall
qsection3.4in9troAducedMDefU
1andMDefUU.MDefsstand forg\denitely",andarein9tendedasawayofattachingsuch aTfoAotnotetoav|ralue.-Thein9tuitiveTreadingofM(DefUe)is \I'mnotsurewhattheexactv|ralueofMeis,butIdokno9wit's anzMUp1[...]v|ralue".MISono9w,YondiscoveringfromMselenv thatxatermMchasanMUp1[...]orMUpUp2[...]v|ralue,w9e merelyneedtowrapMcinMDefU~orMDefUUrespAectiv9ely:.All that/remainstodoismoAdifyrewriterulestotak9eaccountof MDefUBHandBTMDefUUasappropriate.pThismec9hanismsubsumes theTpreviousone.pConsideragain:썒Msimpselenv(CaseUe(CaseUewx)(CaseUeyz)) IgnoringpAossiblec9hangestoMw,Mx,MyandMz,Msimptranforms thisTto:MCaseUe(CaseUStop1wx)(CaseU(DefUe)yz) ApplicationToftherewriterulesMCaseUStop1Xab,===>aCaseU(DefUe)ab,===>b yieldsTthedesiredresult:MCaseUewz Recall&theotherexample,j,inwhic9hMselenvbindsMetoan MUpUp2[...]Tv|ralue:MCMeet[e,UpUp2[Stop1,Stop1]] After}wrappingMDefUUMaroundMe,thefollo9wingsequenceof rewritesTispAossible:
ZMCMeet[DefUUe,UpUp2[Stop1,Stop1]]=UpUp2[CMeet[SelUU1e,Stop1],3'CMeet[SelUU2e,Stop1]]=UpUp2[Stop1,Stop1] Again,the/desiredresultisobtained.5Allw9ehadtodois includeTarewriterulederiv9edfromthis:MCMeet[UpUp2[x1,x2],	s,UpUp2[y1,y2]]f===>,UpUp2[CMeet[x1,y1],X0CMeet[x2,y2]] By\moAdifyingtherulesothatoneoftheinitialtermsis M(DefUUe),HandbAearinginmindthemeaningsofMDefUU̲and MSelUUT(seesection3.4),onecaneasilysho9wthat:   19                                        s⍠?      MCMeet[DefUUe,	s,UpUp2[y1,y2]]
  
f===>,UpUp2[CMeet[SelUU1e,y1],P0CMeet[SelUU2e,y2]]OAllinall,aratherelegan9tsolutiontoatrickyproblem.ThereTisjustonenalca9veat.pConsider:Msimpselenv(CaseUeab)IfFw9ecannotndav|ralueforMeinMselenv,theMCaseU?expres-sion͗ma9ystillbAeremov|rablebythefollowingmeans.E:FindinMselenvak9eyMkforwhichwecanprovethatMkPvzgMe
3,and(forwhic9hMkisbAoundtosomeMUp1[...]v|ralue.SoMem9ust&alsobindtosomeMUp1[...]v|ralue,*CsowecanreplaceM(CaseUeab)b9yM(CaseU(DefUe)ab).'MCaseUUsare,asev9er,Wanalogous.SoJgwemightbAeabletodojustalittlebitbAetter	m9ytakingmonotonicityofkeysintoaccountwhensearc9hingTMselenv.54.5GAvoidingLanexpFfonentialexplosionmAlthough4w9ehaveavoidednon-terminationviainnitebranc9hing,anotherinsidiousproblemlurks:.termswhichexpand,expAonen9tiallyforawhile,"beforeshrinkingbac9ktoa#compactnormalform.Suc9hbAehaviourcausesthetermrewriterltorunoutofmemorysimplifyingseeminglyin-signican9texpressions.yTheproblemmanifestsitself,onceagain,nwith\MCaseU\andMCaseUUterms.Thenormalformre-quiresthattheswitc9hexpressioncannotitselfbAeaMCaseUorMCaseUU,Tgivingrisetosomerulesoftheform:MCaseUU(CaseUUabcd)efg===>CaseUUa(CaseUUbefg)&m(CaseUUcefg)&m(CaseUUdefg)ThezproblemoAccursbecauseofthew9ayzMrewrite_withat-tempts5toapplyrewriterulestotheroAottermun9tilnomorecanbAefound.IfMaisitselfaMCaseUUterm,DhMrewrite_withwillimmediatelyreapplytherule,Mtreblingtheexpres-sionsizeagain.1rItw9ouldbAebettertolooktoseeifw9ecandosomesimplicationsontheM(CaseUUbefg),M(CaseUUcefg)kandM(CaseUUdefg)ktermsRbeforekse-lectingFanotherrewriterulefortheroAotterm.There'sav9eryyZgoAodc9hancewecan,bAecauseitislikelythatwealreadykno9wenoughabAoutMb,McandMdtoeliminatetheirassociatedMCaseUUs.iIt/"ma9yalsoturnoutthatMaisthesameasMb,5McorMd,TandthisishelpfultoAo.
Implemen9tingothisisnotonlyeasy:,jbutessential.+WhenMrewrite_withI$detectsthatarewriterulehascreatedaMCaseUU3term,it4doAesnotimmediatelyseekoutanotherrewritearulefortheroAotterm.}Instead,$ittriestorewritethesubtermsasm9uchaspAossible,andonlythenlooksagainat3<theroAotterm.v'Thisminormodicationpro9ves3<verysuc-cessfulTata9voidingTexpAonentialexplosions.54.6GT,ypFfe-specicLMAbsValoptimisationmThe abstractv|ralues(MAbsVals)ofallnon-function-spaceob-jectsarepAoin9tsinaonepoin9tdomain.(Therefore, foranyMAbsVal
Xatall,ifw9ecandeterminethattheob ject'sdomainis+non-functional,w9ecanmanufactureanequiv|ralentv|ralue   from)@MARecandMANonRec.X3Thisisextremelyuseful.Thedef-
   inition/cofMAbsVal,5presen9tedinsection3.3,isaugmen9tedso w9e.canidentifythedomainforanyterm.Thisisdoneby tagging^eac9hMAbsValwithacontextdomainv|ralue,Jexceptfor theTMARecandMANonReccases,wherethedomainisob9vious.
 TheMsimpactionforMAbsValsno9wbAeginsbyextractingthe con9textdomain,¯andbuildingaliteralreplacementifappro- priate.pLetTMdomainof(a)bAethedomainofMa.7Msimpaf=leta_ctx_domain=domainof(a)inifXunitary_ctx_domain(a_ctx_domain)then	s,unit_value(a_ctx_domain)else	s,(...doasbefore...)unitary_ctx_domain(Lift	s,(D1x...xDn))f=unitary_ctx_domain(D1)&&...&&unitary_ctx_domain(Dn)unitary_ctx_domain(Lift2(D1x...xDn))f=unitary_ctx_domain(D1)&&...&&unitary_ctx_domain(Dn)unitary_ctx_domain(Ds->Dt)f=Falseunit_value(Lift	s,(D1x...xDn))f=ANonRec[unit_value(D1)...unit_value(Dn)]unit_value(Lift2(D1x...xDn))f=ARecX[unit_value(D1)...unit_value(Dn)] ThisTw9orksne,gbut,asTusual,weTcandoalittlebAetter. Presen9ted&withatermalreadycompAosedentirelyofMARec andMANonRecs,qthesc9hemereturnsacopyoftheterm,qgiving ak
pAoten9tiallossofsharing.Ajsmallmodicationdetects suc9hTtermsandreturnsthemas-is. 4.7GImprovingLtherepresentationofcontexts:fhMApplyETm F:or;tman9ytrivial-loAokingfunctions,Dtheabstractinterpreter emitswaremark|rablycum9bAersomeandunintuitive-loAoking term.ExaminationYJoftermsfromrstorderfunctionssho9ws asw9aytocutdowntheirsizes.
zSinceallabstractv|raluespAer- tainingtotheargumen9tsandresultofarstorderfunction areH
unitary:,TtheonlythingonecanaskabAoutitisho9wthe con9textontheresultpropagatestoeachargument.SuppAos- ingw9ehaveMf,arstorderfunctionofO5" 	   	   cmmi9Omarguments,andwe w9ant^tokno9wwhatcontextpropagatestotheOn'thargument ifatheresultisdemandedincon9textMalpha.Atpresent,twe getTalargetermoftheform:MCtxAp	s,(FvalC(AbsAp(GetA...(AbsAp(FvalAf)-~a1)zv...kڈai)$))$(Fncaj...(Fncamalpha)...) whereMi(=dOnbP 1andMj=dOnb+1.WhatthisdoAesittouse theM(AbsAp(GetA...))constructionOn6P 1timestosupply thewrstOnOP 1wabstractv|ralueargumen9ts,whichwexpAosesthe   20                                        	֠⍠?    iefg  ff̟͠)402  ff33MFsqDiff
  	=(Fval(\c1->(CJOIN^U(ApplyET#0F+(ApplyET#1F*(FncC(FncCc1))))^U(ApplyET#0F-(ApplyET#0F*(FncC(FncCc1))))))/y(\a1->(Fval(\c2->(CJOIN (ApplyET#1F+(ApplyET#1F*(FncCc2))) (ApplyET#1F-(ApplyET#0F*(FncCc2)))))q߭(\a2->(ANonRec[])))))33FsqDiff	=(Fval(\c1->(CJOIN^U{(FvalCF+)c(Fnc(ANonRec[])(Fnc(ANonRec[]){(FvalC{*(FvalAF*)(ANonRec[])*})(Fnc(ANonRec[])(FncC(FncCc1)))}))}^U{(FvalCF-)c(Fnc(ANonRec[])(Fnc(ANonRec[]){(FvalCF*)(Fnc(ANonRec[])(Fnc(ANonRec[])2(FncC(FncCc1))))}))}))/y(\a1->(Fval(\c2->(CJOIN {(FvalC{*(FvalAF+)(ANonRec[])*}) (Fnc(ANonRec[]){(FvalC{*(FvalAF*)(ANonRec[])*}) A(Fnc(ANonRec[])(FncCc2))})} {(FvalC{*(FvalAF-)(ANonRec[])*}) (Fnc(ANonRec[]){(FvalCF*) A(Fnc(ANonRec[])(Fnc(ANonRec[])(FncCc2)))})}))q߭(\a2->(ANonRec[])))))  ^rFigureT1:pAbstractin9terpretationofMsqDiff,withandwithoutusingMApplyETff02  ff*  ff̎XOn'thcon9textmap.xThisisthenappliedtoMalphawrappAed
  upNinac9hainofM(Fnc...)constructionswhichsupplytheremainingTOm8P OnP 1abstractv|ralueargumen9ts.
This^seemsanenormouslyw9astefulwaytosaywhatamountsto:MApplyETnfalphaThat##is,S\extracttheOn'thcon9textmapfromMfandapplyitto
  theMcon9textMalpha".ŁW:ell,[almost.InMfact,Mf'sOn'thcon9textmapHexpAectstobeappliednotdirectlytoMalpha,buttothetermM(Fncaj...(Fncamalpha)...).+ItloAoksatrstlik9e~weneedtoincludetheabstractv|raluesMajtoMamintheMApplyET=term.'F:ortunately,
that=isa9voidable:msince=theyare9vallunitary:,~w9eshouldneverneedtoknowwhattheyare.Instead,w9e<simplyrecordintheMApplyET<termhowman9y8Iofthese\trailing"argumentsthereare.OWhentheterm%rewriternallygetsholdofMf'sOn'thcon9textmap,ZitusesTthisn9umbAerTtobuildasuitable\dumm9yterm"M(FncError...(FncErroralpha)...)to~whic9hitappliestherelev|rantcontextmap.YhIneect,fwe
  a9voided9storingthosetrailingargumen9ts,andfakedtheminstead,F using<^MErrorterms,bAecausew9ecanguaranteetheywillnev9erbAeused.JF:romthisitfollowsthatitisanerrorforTMErrortoappAearinthenormalformofan9yterm.UseofMApplyETwshrinksman9ytermsdramatically:,%anden-hances thetimeandspacepAerformanceoftheanalyser.>AsanTexample,Figure1sho9wstheabstractinterpretationofMsqDiffxy=(x+y)*(x-y) withLandwithoutusingMApplyET.Ofcourse,Zwhenthede-
   nitionsofM(+),vM(-)andM(*)aresubstitutedin,bAothterms reduce'Ztothesamething.RNotethatM(CtxApe1e2)'Zand M(AbsApe1e2)oarewrittenasPfMe1e2PgandPfM*e1e2*Pgre- spAectiv9ely:.5 4.8GNormalLformsandterminationpropFfertiesm Sho9wingthatthetermrewritingsystemalwaysterminates, and\`proAducesnormalforms,^isimportan9t.F:orasystemwith asBman9yrewriterulesandcomplicationsasthis,NproAducing a	correctnessargumen9tisaformidabletask.rW:ehopAeto includeoneinalaterv9ersionofthispapAer.fAlsotobe includedEwillbAealistingoftherewriterules,
alongwith theirDassoAciatedproofsofcorrectness.Thereareatpresen9t inTtheregionofsixt9yrewriterules.- 5FirsticationLandmonomorphisation 5.1GIntroFfduction Althoughrstorderfunctionsareeasilyhandledb9yterm- rewriting basedxpAoin9ting,higherorderrecursivefunctions giv9eTtrouble,astypiedbyfoldr:OMfoldrfa[]Y=afoldrfa(x:xs)	s,=fx(foldrfaxs) Naiv9ely\xpAointingthisgivesanseriesofapproximations in whic9haterminvolvingfunctionalparameterMfisapplied ev9erJ(moretimestoaninitialterm.طThetermrewritercannot   21                                        %⍠?      sho9wսthattwoapproximationsarethesame,soaxpAoint
  is-apparen9tlyneverreached.eHWhat'sreallygoingonisthattheTxpAoin9tofMfoldrdependsonthexpoin9tofMf.
There lareonlyt9wo lwaysroundthis.=Therstistoiter-ateenoughtimestobAesurethatthexpoin9tiscertainlyreac9hed.ЂW:orkQZbyNielsonandNielson[NN92>]givessafelo9werbAoundsonthen9umberofiterationsneeded.>Unfor-tunately:,WtheexpAenseofdoingthismak9esitunattractive.NoteTalsothatthisapproac9hdemandsmonomorphisation.TheM9secondsolutionrequiresustosupplyav|ralueforMfbAe-fore%xpAoin9tingMfoldr,sothatweare,Yineect,nolongerdealingxwithahigher-orderfunction.Therearen9umerousw9aysTtodothis,dsomeratherobscureinthattheypartiallysubstituteg?infunctionalparametersaspartofthexpAoin9t-inghproAcess[N?s].Bycon9trast,Annaadoptsacompletelystraigh9tforwardpapproach:ӑtransformthesourceprogram.ProgramvtransformationisapAopularsub ject,(~andv|rariouspapAersdescribehigher-orderfunctionremo9v|ral(alsoknownasМrsticationorspAecialisation)[CD91]8[Nel
].Thesc9hemepresen9tedTbAelowisbasedonworkbyGeorgeNelan[Nel
].NotallfunctionalparameterscanbAeremo9ved.F:orexam-ple,recursiv9e functionswhichhaveaccumulatingfunctionalparametersIarenottransformable,atleastwiththesc9hemebAelo9w::Mfgx=ifXx==0!Tthen	s,g1!Telse	s,x*f(\y->gx+y)(x-1)W:e _justifythisdesigndecisiononthebasisthatthev|rastma jorit9yYoffunctionsthatpAeoplereallywritecanbersti-ed,TandGthev|rastma jorit9yoftherestcanbAehandledbyasecondary=mec9hanismoutlinedinsection6.4.jIndoingthisw9eYimplicitlyappAealtothemeasurement-leadapproachtodesignԼdiscussedinthein9troAduction.ZW:eonlyneedtore-mo9vePfunctionalparametersforrecursiv9efunctions,_but,asbAecomesfclear,thismeansrstifyingnon-recursiv9efunctionstoAo.5.2GFirsticationLbyexamplesmF:orcthemomen9t,xlet'suseMfoldrasarunningexample.Giv9enTauseofMfoldr,likeMsumxs=foldr(+)0xsw9ecanunfoldfunctionalparameterM(+)andidentityM0intoMfoldr,TgivinganewfunctionMfoldrSpec:Msumxs=foldrSpecxsfoldrSpec[]Y=0foldrSpec(x:xs)	s,=x+foldr(+)0xsAndno9w,E%foldingthebAodyofMfoldrSpecgiveswhatwereallyw9ant:Msumxs=foldrSpecxsfoldrSpec[]Y=0foldrSpec(x:xs)	s,=x+foldrSpecxsTheh5k9eytosuccesshereistheeasewithwhichthatlastfold4w9asdone.xIngeneral,;foldingisatrickybusiness,;with   no4`guaran9teeoftermination.yHowever,|"byrestrictingthe
   functionssw9edealwith, wecanguaranteetomakethefold stepterminating,andtrivialtocarryout. Therestriction isPthatthefunctionm9ustpassalongallparameterswhich w9ewanttospAecialiseinthesamepositioninrecursiv9ecalls asytheyappAearedintheargumen9ts.+F:orexample,inMfoldr, bAothTMaandMfsatisfythis.
 Infact,:w9eonlywanttosubstituteinfunctionalparameters. SoTthetransformationofMsumisreally:OMsumxs=foldrSpec0xsfoldrSpeca[]Y=afoldrSpeca(x:xs)	s,=x+foldrSpecaxs Alittleterminology:.ƨThefunctionorrecursiv9egroupoffunc- tions3-forexample,àMfoldr-forwhic9hfunctionalparameters areݷbAeingremo9vedݷiscalledtheNtargetLgroup.	Andafunc- tionTcon9tainingacalltoatargetgroupiscalledaNsource.
 TheOxrestrictiononv|ralidtargetsseemstobAethis:thefunc- tionm9ustpassalongallfunctionalparametersunchangedin all~recursiv9ecalls.Generalisingthistodealwithmutually recursiv9eRtargetsrequiresthenotionofaNconstanCtUargu- menCtset.Callinggarecursiv9egroupingeneralcausescalls within'thegroup,andaconstan9targumentsetgathersto- gether&margumen9tswhichareguaranteedtohavethesame v|ralueTforev9erysub-call.pF:orexample,givenMfxyz	s,=fyyz+gzxgabX=faba+gab alittlethough9tshowsMf'sthirdargumentandMg'srstargu- men9tsarealwaysthesame,{givingaconstantargumentset writtengM{f.3,g.1}.Afgroupcanha9vegmorethanoneset, asTthefollo9wingtrivialexampleshows:Mfxy	s,=gxygab	s,=fab Constan9tmargumentsetscanbAecomputedusingasimple abstract>in9terpretationdescribAedbelo9w.Whatisimportan9t here Iisthatforarecursiv9etargetgrouptobAespecialisable, allbfunctionalparametersinthegroupm9ustbAeconstantar- gumen9ts.Certainotherconstraintsalsoapply:.Wereturn toTtheselater.
 TheTfollo9wingexamplebreaksournicescheme:Mmapf[]Y=[]mapf(x:xs)	s,=fx:mapfxsaddNnxs=map(+n)xs F:oldingTandunfoldingasabAo9veTgivesMaddNnxs=mapSpecxsmapSpec[]Y=[]mapSpec(x:xs)	s,=(x+n):mapSpecxs whic9hۆisclearlywrongbAecauseMnisundenedinMmapSpec. What?jw9eneedtodoispassalongallfreelambAda-bound v|rariablesѸinthespAecialisingvalueM(+n)asnewparameters, inTast9ylereminiscentoflambAda-lifting:   22                                        8⍠?      MaddNnxs=mapSpecnxs
  mapSpecn[]Y=[]mapSpecn(x:xs)	s,=(x+n):mapSpecnxsNev9erthelessPthisstillallowsustogetourknickersinatwist.Ind%thefollo9wing(admittedlycontrived)example,wemayselectTeitherMincorMgasasourcetotransformrst:Mapplyfx	s,=fxgabY=applyabincyY=g(+1)yDoingTgrstgiv9es:MapplySpecx	s,=axgab%̰=applySpecbincy%̰=g(+1)yNo9wmweneedtointroAducefreev|rariablesofthespecialisingv|ralueTMaasanewparametertoMapplySpec:MapplySpecax	s,=axgab/?=applySpecabincy/?=g(+1)yWhereupAonuitshouldbeeminen9tlyclearthatwe'veachievedexactlynothing!Ourmistak9ewastoselectasourceforwhic9hthespAecialisingv|raluehadfunction-valuedfreevari-ables,
since}passingthemasnewparameterstoMapplySpecmeansMapplySpecisstillahigher-orderfunction.PThemoralisbTclear:qonlytransformsourcesforwhic9hthefreelambAda-bAoundrv|rariablesofthespecialisingv|raluearenothigher-order.Asecondob9viousconstraintonsourcecallsisthatthecallshouldbAesucien9tlyappliedforallfunction-v|raluedparametersTtobAevisible.
In5whatfollo9ws,bwe5assumethatnamingissuesaredealtwithcorrectly:.T=In'particular,,thefreev|rariablesinanspAecialisingv|ralueΐneedtobAerenamedbeforetheycanbesafelyinsertedasTnewparametersofthespAecialisedtarget.The4algorithmbAelo9wrequirestheprogramtobestratiedin9to minimalmutuallyrecursivegroups,;andtopAologicallysorted.%
W:e2adopttheusualcon9vention2thattheprogramisbIwrittentop-to-bAottom,uwithan9ygivenfunctionreferringonlyotoitso9wngroup,ifrecursive,andgroupsabAoveit.yTheroAotTexpressionisrigh9tatthebottom.SpAecialisation(oftargetgroupsma9yresultinsomegroupsbAecomingunreac9hablefromMmain.Thesegroupsshouldberemo9ved.4Amore@dicultproblemisho9wtoinsertanewgroup,resultingfromspAecialisationofanexistinggroup,in9totheprogramsoastomaintaindepAendancy:.7Itturnsout thatt9wo dierentbAehavioursarepAossible.?EIntheusualcase,Tthenewgroup\splits"a9wayTfromthesourcegroup:MletrecXmapf[]Y=[]+'mapf(x:xs)	s,=fx:mapfxsinlet+'squarexY=x*xinlet+'squareListxs=mapsquarexsin...   SinceLthespAecialisedtargetMmapSpecreferstoMsquare,w9e
   m9ustplaceitafterMsquare.sKT:akingthisargumenttoits conclusionEsho9wsweshouldplaceany\splitting"groupim- mediatelyTbAeforethesourcegroup:OMlet!squarex%̰=x*xinletrec3'mapSpec[]Y=[]3'mapSpec(x:xs)	s,=squarex:4mapSpecxsinlet3'squarelistxs,=mapSpecxsin... SourcesTgivingriseto\joining"spAecialisationsareun9usual:MletrecXmapf[]Y=[]3'mapf(x:xs)	s,=fx:mapfxsinletrec3'squareListxsATB=map(head.squareList.unit)xsin... Here,~theX8denitionsofM(.),MheadandMunitareunimpAortan9t. BecausethespAecialisingv|ralueM(head.squareList.unit) refersztothesourcegroupfromwhic9hitoriginates,there- sultingspAecialisationofMmapwillalsorefertoMsquareList, andKthatinturnmeansthespAecialisationshouldbemerged in9toTthesourcegroup:MletrecfsquareListxs,=mapSpecxsfmapSpec[]Y=[]fmapSpec(x:xs)	s,=(head.squareList.unit)x:g mapSpecxsin... Since{onlyrecursiv9esourcegroupscanrefertothemselves, spAecialisationsBcorrespondingtosourcesinnon-recursiv9e groupsTnev9erexhibitthis\joining"bAehaviour.5 5.3GAnLalgorithmm ThePproAcedurebelo9wisrepeatedun9tilnomorev|ralid(source, target)җpairscanbAefound.T9Assho9wnbyNelan[Nel
],the order)inwhic9hthesepairsareselectedmakesnodierence. Un9usedtargetsshouldbAedeleted,"butagainitdoesn'tmak9e an9yTdierencewhen.pAsarunningexample,wetake: .Mletrec
Zmap1fg(x:y:xys)	s,=fx:gy:map2gfxys
Zmap1fg_/?=[]
Zmap2gf(x:y:xys)	s,=gx:fy:map1fgxys
Zmap2gf_/?=[] .inlet
Zaddmulpqxs!=map1(+p)(*q)xsO 1.:Find&av|ralidtargetgroup,kandavalidsourcegroup:whic9hTreferstothetargetgroup.͍gMTargetgroup,={map1,map2}gSourcegroup,={addmul},referstomap1   23                                        R⍠?      2.:Ifdthetargetgroupisrecursiv9e,computeitsconstant
  :argumen9tsets(seesection5.4).Inreality:,thiscom-:putation$hastobAeperformedatstep(1).	7Ifnon-:recursiv9e,$manufactureia\fak9e"singletonsetlisting:allThigher-orderparametersasconstan9t._gMConstargsets	s,={{map1.1,map2.2},p\{map1.2,map2.1}}3.:In9ventAanewsetofnamesforthespAecialisedtarget:group.gMNewnames	s,={map1Spec,map2Spec}4.:Determine,fromltheconstan9targumentset,whichar-:gumen9tsYinthesourcecallsitearethespAecialisingv|ral-:ues.ExtractG8theirfreelam9bAda-boundG8v|rariablesand:rename.gMOriginal:!:specialisingvalues={(+p),(*q)}!:freevariablesY={p,q}gRenamed:!:specialisingvalues={(+pnew),(*qnew)}!:freevariablesY={pnew,qnew}5.:Rebuildthesourcecallb9ydeletingthespAecialisation:v|ralues,ninsertingtfreevariablesasnewparameters,nand:c9hanging+thecalledfunctiontoitsnewname,asde-:terminedTinstep(3).gMRebuiltsourcecall	s,=map1Specpqxs6.:Build2vthespAecialisedtargetgroup,_startingwithacop9y:of$theoriginaltargetgroup.JAF:oreac9hrecursivecall:insideTthegroup,dmoAdifythatcallinasimilarw9ayTto:ho9wTthesourcecallwasmoAdiedinstep(5).:MRebuilttargetgroup:gmap1Specpnewqnew(x:y:xys) f=(x+pnew):(y*qnew):gt0map2Specpnewqnewrestgmap1Specpnewqnew_ f=[]gmap2Specpnewqnew(x:y:xys) f=(x*qnew):(y+pnew):gt0map1Specpnewqnewrestgmap2Specpnewqnew_ f=[]7.:DetermineZgwhetherthespAecialisedtargetgroupshould:splitorjoin,b9yndingoutwhetherthespAecialisation:v|raluesfcon9tainedanyreferencetothesourcegroup.:Augmen9tTprogramappropriately:.gMSpecialisationvals{(+p),(*q)}don'tgreferto{addmul},sonewgroupsplits.⍑Aqv|ralidrnon-recursiv9etargetgroupmustconsistofasinglehigherHorderfunction.AHv|ralidrecursiv9etargetgroupsatis-esTallthefollo9wing:  P:Allږfunctionsinthegroupha9veږatleastonefunctional
  :parameter.8P:Eac9hlfunctionalparameterinthegroupisamembAer:ofsexactlyoneofthegroup'sconstan9targumentsets.:This|impliesthatallin9tra-groupcallsmustbAesu-:cien9tlyTappliedtoexpAoseallfunctionalarguments.P:Eac9hconstantargumentsetmustmentionexactlyone:argumen9tforeachfunctioninthegroup.Thisdisal-:lo9ws'certaincontrivedpathologicalcaseswhichwould:otherwiseTseriouslycomplicatethealgorithm.W ATv|ralidsourcecallsitesatisesthefollo9wing:P:TheTsiteisacalltoav|ralidtargetgroup.P:TheBpapplicationm9usthavesucientargumentstosup-
  :plyTallhigherorder(spAecialisable)argumen9ts.P:F:or7eac9hspAecialisableargument,noneofthefree:lam9bAda-bound&v|rariablesmaybAe,jNorcontain,jNafunc-:tionTspace.W Although/itloAokseasyonpaper,uqimplemen9tingthisalgo- rithms3istric9ky:.6Takings3intoaccountthemechanismsfor detectingbconstan9targumentsandmaintainingtypAeanno- tations,theHask9ellimplementationapproaches1500lines ofTcoAde.* 5.4GComputingLconstantargumentsetsm Asimpleabstractin9terpretationisused.Eachfunctioncall inkthegroupisabstractedtoexpAosetheparametersitpasses along:Mfxyz	s,=fyyz+gzxgabX=faba+gab PhrasedTabstractly:,thisbAecomes:Mf:callsf[#2,#2,#3]fcallsg[#3,#1]g:callsf[#1,#2,#1]fcallsg[#1,#2] No9w;weiteratetoaxedpAoint,@gatheringacompletesetof theopAossiblev|raluesofeac9hargument.$Thereisalistforeach function,andeac9hlistcontainsasetofpAossiblev|raluesfor eac9hTargument.pInitially:,eachargumentcanonlybAeitself:MF0=[{f.1},{f.2},{f.3}]G0=[{g.1},{g.2}] A9teachiteration,?newapproximationsarecomputedbyus- ingEtheabstractv9ersionsoffunctionstoloAokuppossible argumen9t\setsintheexistingapproximation.Also,mtheex- istingTappro9ximationismergedinwholesale:MF1=F0U[{f.2},{f.2},{f.3}])TU[{g.1},{g.2},{g.1}]f=[{f.1,f.2,g.1},{f.2,g.2},{f.3,g.1}]G1=G0U[{f.3},{f.1}]   24                                        i⍠?      !TMU[{g.1},{g.2}]
  
f=[{f.3,g.1},{f.1,g.2}]F2=F1U[{f.2,g.2},{f.2,g.2},{f.3,g.1}]+'[{f.3,g.1},{f.1,g.2},{f.3,g.1}]
f=[{f.1,f.2,f.3,g.1,g.2},{f.1,f.2,g.2},{f.3,g.1}]G2=G1U[{f.3,g.1},{f.1,f.2,g.1}]!TU[{f.3,g.1},{f.1,g.2}]
f=[{f.3,g.1},{f.1,f.2,g.1,g.2}]YEv9entuallyg<thisproAcessstabilises,{givingthefollo9wingpos-sibleTargumen9tv|ralues:Mf.1	s,couldhavevaluef.1,f.2,f.3,g.1,g.2f.2	s,couldhavevaluef.1,f.2,f.3,g.1,g.2f.3	s,couldhavevaluef.3,g.1g.1	s,couldhavevaluef.3,g.1g.2	s,couldhavevaluef.1,f.2,f.3,g.1,g.2SoE3w9ehavetwocandidateconstantargumentsets:M{f.1,f.2,f.3,g.1,g.2}andM{f.3,g.1}.d{W:erejectthe`rstbAecauseitdoesnotmen9tioneachfunctionexactlyonce.DeducingthatM{f.1,f.2,f.3,g.1,g.2}뀺isacon-stan9təargumentsetiscorrect,ؿbutonlyundertheconditionsthat,forXtheinitialcallin9tothegroup,Mf.1==f.2==f.3,if^UMfw9ascalled,porMg.1==g.2^UforaninitialcalltoMg.sThislea9vesM{f.3,g.1}asthesoleconstan9targumentsetforthisrecursiv9eTgroup.
A#glaring#
a9wistheinabilitytoabstractfunctioncallswhichdoan9ythingmorethanpassparametersunchanged.ZInthiscase,a5spAecialv|ralueMUnknownisusedtodenotethatw9ecan-notbAesurewhatthev|ralueofthisargumen9tis.F:orexampleMfxy=fx(y+1)+fyxabstractsTtoMf:callsf[#1,Unknown]
fcallsf[#2,#1]DuringxpAoin9ting,EMUnknownannihilatesanyotherv|raluesinaset.F:or;example,EfasetM{f.1,g.2,Unknown};ɺisequiv|ralen9tsimplytoM{Unknown}.MUnknownrepresen9tsanargumentofuncertain\origin,nsow9edisallowanyconstantargumentsetcon9tainingTit.5.5GPreservingLtypFfeannotationsmSincegAnnaw9orkswithtypAeannotatedCoreexpressions,w9eneedtogotoalittletroubletotransformtheannota-tions-gtoAo.dA9trstglance,3lthislookslik9easimplematterofmoAdifyingFhfunctiont9ypespertainingtospecialisedfunctions,b9yɚdeletingtypAesofspecialisedargumen9tsandinsertingthet9ypAesJoffreev|rariablesbeingpassedasextraparameters.This.isindeedcorrect,Mbutthere'smoretoit.	RecallthepreviousTdenitionofMfoldr.pThet9ypAecheckerTinfers:Mfoldr::(a->b->b)->b->[a]->bGiv9en[)LtheusualHask9ell!denitionofM(++)::[c]->[c]->[c],dw9ecandene  Mconcat=foldr(++)[]O whic9hTspAecialisesto:MfoldrSpeca[]Y=a
  foldrSpeca(x:xs)	s,=x++foldrSpecaxsconcat=foldrSpec[]O MerelyXaddinganddeletingargumen9ttypAesgivesMfoldrSpec ann`apparen9ttypAeMb->[a]->b,whichn`istoAogen- eral.!W:eneedtounifythet9ypAeofspecialisingv|ralue M(++),M[c]->[c]->[c]޽withthet9ypAeofthefunc- tionalparameteritreplaces,BMa->b->b,andapply theEresultingsubstitutionM{a->[c],b->[c]}Etothe annotationsonMfoldrSpec.0Thisgiv9esMfoldrSpec:: [c]->[[c]]->[c],Tasrequired.
 Suc9h+trickeryshouldnotcomeasacompletesurprise.Af- terall,\theMilner-Hindleyt9ypAerulesforanapplicationof Mf::(T1->T2)-!toMa::T3-!requireunicationofMT1with MT3.pThat'sTeectiv9elywhatisgoingonhere. The]needtopreserv9etypAeannotationsisama jornuisance fromtheimplemen9tationviewpAoint,5Gbecausemoretimeis spAen9tgqinxinguptypAesthandoingthetransformation propAer.W:orkatoimpro9veaeciencyisapriorit9y.Thesc9heme describAedhabo9veisarstimplementationinwhichcorrect- nessTw9asmoreimpAortantthaneciency:.5 5.6GMonomorphisationm Bycomparisonwithrstication,\monomorphisationissim- ple.;Monomorphisationisat9wo-phaseproAcess.Therst passJfconductswhatamoun9tstoadepth-rstsearchfrom Mmaindtodisco9verdallrequiredinstances.
nThesecondpass clonescoAde,,c9hangesfunctionnamesaccordinglyandre- storesTdepAendancyorder. 5.6.1CollectingLtheinstancesm Iam
indebtedtoMarkJonesforsuggestingthefollo9wing algorithm.GYW:excarryasetMinstancestoaccum9ulatethe ev9entualg|result,andastac9kMtoVisitrecordingplaceswe needLtovisit.Elemen9tsofMinstancesandMtoVisitarepairs ofz(functionname,Ct9ypAeexpression)specifyingaparticu- larCinstanceofafunction.8Thet9ypAeexpressionsarealways monomorphic.
 SinceB
Mmainma9ybAeofanytypAe,6wetriviallymonomor- phisezitb9ysubstitutinganytypAev|rariableswithMInt.This giv9esasingleinitialv|ralueforMtoVisit,! withMinstancesini- tiallyH	bAeingempt9y:.Thenalv|ralueofMinstancesisthen Msearch(instances,toVisit),Twhere:O Msearch(instances,toVisit)=ifX[toVisitisempty]
Zthen	s,instances
Zelse
Zlet,next=headtoVisit
ZinXifnext`elem`instancesF
[We'vealreadybeenhere]
Zthen	s,search(instances,tailtoVisit)
Zelse	s,[Getthefunctionspecifiedbynext..mFindoutwhatinstancesofother   25                                        ~ ⍠?      &mMfunctionsarecalled.	s,Addthese
  &minstancesto(tailtoVisit)giving&mtoVisitAug,andthendo]&msearch({next}Uinstances,toVisitAug)zF:orTexample,giv9enMidx	s,=x
  fx,=idxmain	s,=id42+ord(f'c')ztheTalgorithmrunsthroughthesestates:
fMinstancesY"toVisit
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{}z<[(main,Int)]{(main,Int)}F[(id,,Int->Int),v(f,XChar->Char)]{(main,Int),F[(f,XChar->Char)]tx(id,,Int->Int)}{(main,Int),F[(id,,Char->Char)]tx(id,,Int->Int),tx(f,XChar->Char)}{(main,Int),F[]tx(id,,Int->Int),tx(id,,Char->Char),tx(f,XChar->Char)}zThisgiv9estwoinstancesforMid.Becausetheabstractinter-pretationoft9ypAesmapsbothMIntandMChartothet9wopointdomain,only.oneofthoseinstancesisneededforanalysispurpAoses. In_9general,w9ecanexploitthefactthatmanydieren9t@RtypAesareassignedthesamedomaintoreducetheprogramexpansioncausedb9ymonomorphisation.F:aranda9waytheeasiestw9aytodothisistotransformthet9ypAean-notationsntodomainannotationsbAeforemonomorphisation,usingtheresultsofsection2.2.5.ST9ypAev|rariablesaresimplyreplacedTb9ydomainv|rariables.덍5.6.2CloningLcoFfdemThisisfairlytrivial.+Eac9hfunctionisduplicatedoncepAerinstance,ܶwithappropriatenewnames.ThefunctionbAod-ies#\ha9vetheircallsitesmoAdiedtorefertoappropriatelynamed_2instancesinpreviousgroups,qandthisone,ifrecur-siv9e.\ThenthebAodieshavethetypAev|rariablesintheiranno-tationssubstitutedappropriatelyforeac9hdierentinstancerequired.eTheen9tireprogramcanbAeprocessedinasingletop-to-bAottomTpass.
Theonlysligh9tlytrickyproblemisrebuildingrecursivegroups0soastomain9taindepAendancy:.For0non-recursiveclones,/thisÅiseasy:,butbAecauseoftheexistanceofcer-tain2con9trivedrecursivefunctions,: maintainingdepAendancyintherecursiv9ecasecanbAecomplicated.vW:eavoidtheseproblems"db9ylumpingalltheclonesarisingfromarecursivefunctiongroupin9toasingleMletrec,:andpassingthepro-gramTathirdtimethoughthedepAendancyanalyser.Despite8hthesecomplications,,themonomorphiserisex-tremelyaquic9kanddoAesnotproveasignicantlimitationonTpAerformance.   6Discussion Thissectiondra9wstogetherthedetailedtechnicalthreads
   expAoundedinthepreviousthreesections,b9ypresenting somekpAerformanceresults,1andlookingatrelatedandfur- therxw9ork.5ButwebAeginbyloAokingatsomeperformance issues.t 6.1GPuttingLitalltogetherm Thro9wingrealisticallysizedprogramsattheanalyserre- v9ealedpsomepAerformanceproblemswhichweretracedto nicetiesXinthein9terfacebAetweentheabstractinterpreterand theTtermrewriter.
 P9erformancerproblemsappAearwhenthetermrewritingsys- temu,isfedagigan9tictermtosimplify:.;Usually,"suchu,terms reduce-tosomethingquitetrivial.eHItisimpAortan9ttorealise that}0theabstractin9terpreterwillgenerateabsolutelyenor- mousUterms,3espAeciallyfromsourcetextwhic9hhasdeeply nestedBfunctioncallsordeeplynestedMcaseexpressions,lbAoth ofˁwhic9harequitecommon.>F:orexample,thebiggerpro- grams2men9tionedinsection6.2generatedtermswhich,_when prett9y-printed#inthest9yleusedinthispapAer,&coveredliter- allyTtensofA4pages. AnalysisofaprogramproAceedsasfollo9ws.First,thepro- gramLispassedinitsen9tiretyLthroughtheabstractin9ter- preter,0generatingīacorrespAondingcollectionofrecursiv9e equations\(orterms).TTheseequationsareh9ugelyredun- dan9t`andaresimpliedindividually:,withoutreferenceto eac9hnother.Finally:,thexpAointingsystemtravelsalong the_groupsofequations,accum9ulatinganenvironmentof \solv9ed"equations.Asolvedequationisself-contained:#_it doAes2notrefertotheabstractin9terpretationofanyother function.Solvinggnon-recursiv9eequationsisasimplematter of\substitutingintheabstractin9terpretationsofotherfunc- tions,7andsimplifying.,F:orrecursiv9efunctions,thisstageis follo9wedTbyxpAointing. WhatreallyruinspAerformanceisnotxpoin9ting,C.butthe initialsimplicationoftermswhic9hemergefromtheab- stractein9terpreter.Thisproblemwaslargelyalleviatedby givingwtheabstractin9terpreteralittlemoreintelligence,?in theTformof:tP:The#t9ypAe-specicMAbsValrewritesdescribedinsec-:tionT4.6.BFP:Akno9wledgeIofkeyMContextrewriterules.]PInpar-:ticular,~9the6rulesforMcasestatemen9tsgeneratelarge:expressionsxin9volvingMCMeet,"MCJoin,MStop1andMStop2.:Ahandfulyofrulesem9bAodyingysimplefactssuchas:MCMeet[...Stop2...]==Stop2Tw9ereadded.#:Bet9weenYthem,gthesizesoftermsgeneratedw9eresome-:timesقcutb9ytwoordersofmagnitude,JandpAerfor-:manceTw9asmuchimproved.u AmsecondmpAerformanceproblemw9astracedtotheinitialsim- plicationMoftermsemergingfromtheabstractin9terpreter. These=termsaresimpliedwithoutreferencetoeac9hother. ItturnsouttobAebettertosimplifyatermonlywhen w9exknowthesolvedv|raluesoftheothertermsitrefersto, bAecauseVkno9wingthesev|raluesmakesthenaltermmuch smaller.рIneect,pthisisac9hievedsimplyb9yomittingthis simplication?Wpassaltogether.zF:oratleastoneinput,Ianal- ysisTtimew9ascutbyafactorofve.   26                                        d⍠?    	dl΍⟴S4  ff̤͠ ٚ ٘  ff32Ќ͉  ffF  
    fffg 
    ff6 
    ffXG  
    fffg 
    ffz3F:orTacompleterunZw  
    fffg 
    ff IAnalysisTonlyV  
    fffg 
    ffW5CompilingTwithMghc-0.10}  
    fffg 
    fffhZG  ffr`  
    fffg 
    ff33ProgramH 
    ff>2Lines33  
    fffg 
    ffkg&Time33  
    ff  Claim33  
    ff |Space33  
    fffg 
    ff Time33  
    ff++SClaim33  
    fffg 
    ff[FwTime33  
    ff{%analysisTtimeas%33  
    fffg 
    ff  ffF  
    fffg 
    ff6 
    ffXG  
    fffg 
    ff   
    ff [  
    ff   
    fffg 
    ffs  
    ffH  
    fffg 
    ffuK  
    ffF  
    fffg 
    ff
    
    fffg 
    ff33concat0 
    ff? O<T1033  
    fffg 
    ffiL0.42Ts33  
    ff 1.485TM33  
    ff 447.2Tk33  
    fffg 
    ff w"0.18Ts33  
    ff"0.586TM33  
    fffg 
    ffY+0.92Ts33  
    ff19T%33  
    fffg 
    ff  
    fffg 
    ff33zip3 
 
    ff? O<T1033  
    fffg 
    ffiL0.52Ts33  
    ff 1.793TM33  
    ff 456.1Tk33  
    fffg 
    ff w"0.17Ts33  
    ff"0.570TM33  
    fffg 
    ffY+1.00Ts33  
    ff17T%33  
    fffg 
    ff  
    fffg 
    ff33w9angӡ 
    ffE38533  
    fffg 
    ffd23.62Ts33  
    ff 85.396TM33  
    ff Ĕ908.8Tk33  
    fffg 
    ff w"9.15Ts33  
    ff
15.861TM33  
    fffg 
    ffT43.61Ts33  
    ff21T%33  
    fffg 
    ff  
    fffg 
    ff33w9ave4main 
    ffE61933  
    fffg 
    ffd43.40Ts33  
    ff F116.207TM33  
    ff 2897.7Tk33  
    fffg 
    ff $21.62Ts33  
    ff
43.239TM33  
    fffg 
    ffO199.29Ts33  
    ff11T%33  
    fffg 
    ff  
    fffg 
    ff33ag2hs: 
    ff@104733  
    fffg 
    ff`208.95Ts33  
    ff F275.245TM33  
    ff 9653.8Tk33  
    fffg 
    ff 7&126.42Ts33  
    ffq135.335TM33  
    fffg 
    ffO100.68Ts33  
    ffh126T%33  
    fffg 
    ff  
    fffg 
    ff6 
    ffXG  
    fffg 
    ff   
    ff [  
    ff   
    fffg 
    ffs  
    ffH  
    fffg 
    ffuK  
    ffF  
    fffg 
    fffh  ffFE̍ /T:ableT2:pSomepAerformanceguresforNAnna
  ff ٘  ff @   ff̎Y%d6.2GAbsoluteLpFferformanceresultsmFiv9eWtestprogramswereused.xThersttwo,9Mconcatand
  Mzip3,Zareutterlytrivialandw9ereincludedascomparisonagainstgurespresen9tedin[Sew93/].p7MwangandMwave4mainareHtak9enfromPieterHartel'sbAenchmarksuite[HL92l].Thebiggestone,Mag2hs,ispreproAcessorforadialectofHask9ellaugmen9tedwithattributegrammar[Joh879]facilities,writ-tenb9yDavidRushall.	%TheanalyserwascompiledwithChalmersHask9ell-Bٻ0.999.4,with
agsM-fpbu-O,andrunusinganeigh9tmegabyteheapforallexceptMag2hs,whichrequired~asixteenmegab9yteheap.XYA~generationalgarbagecollectorWw9asemployed.T:estswererunonalightlyloadedSunSparc10/31,andeac9htestwaspAerformedatleastthreetimes.pTimesTareuserCPUseconds.
Simplymeasuringo9verallruntimesisnotparticularlyhelp-ful,mbAecause[w9ereallywanttoestablishhowexpAensivethisanalyserw9ouldbAeifemployedinaHaskellcompiler.|ZItseemsvreasonabletoconsiderthe\bAorder"bet9weenvthefron9tend andtheanalyseritselfasthepAoin9twherethetypAe-c9heckerproAducesat9ype-annotatedCoretree,since,atleastinqGlasgo9wHaskell,thecompilerproAducesthistreeany-w9ay:.Sowepresentguresnotonlyforacompleterun,butalsofortheanalysisphasepropAer.6Thelattercategoryco9v-ers_rstication,monomorphisation,abstractin9terpretationandxpAoin9ting,DallofwhicharelegitimateanalysisexpAenses.T:o assesswhetherornotw9eareapproachingtherightball-park,Cw9e;timedGlasgowHaskell0.10compilingtheprogramsin9to*C,andcomparedthosetimeswiththeanalysisphasetime^ofAnna.Thecompileroptionsw9ereM-O2-C.Compilersemispacesizesw9ere3megabytesforthesmalltwo,sand8megab9ytesforthebigthree:cthisturnedouttobAeplenty:.ThetimesrepAortedforGlasgo9wHaskellareforthecompilerpropAer,(thatis,thatpartofthecompilerwhic9hisitselfwrit-tenfinHask9ell,andwhichtranslatestheoutputoftheY:accparserTin9toC.T:able2presen9tsthegures.Themaximumresidencyg-uresw9ereobtainedusingacopyingcollectorwithheapsizessetonlyjustbigenough.Thisquan9tityisomittedfortheanalysis-onlyguresbAecauseofthedicultiesofdecidingon	ho9wtodividespaceexpAensesbet9ween	thefron9tendandtheTanalysisphase.F:or{thebigthree,timesare,v9eryroughly:,dividedequallybAet9weenthefron9tendandanalysisphases.Mag2hshasarel-ativ9ely؈largeanalysistimeincomparisontoitssize.f
Thisis4bAecauseitmak9esconsiderableuseoflazypatternmatch-ing,Fwhic9h	translatestoalargequantityofcomplexCore%d expressions.TheseR}inturngeneratesomelarge,complex
   sets(zofequationsforthexpAoin9tertosolve.UA(3technique men9tioned9insection6.4mighthelphere.9F:orthelarger problems,spacex4consumptionisofconcern.Muc9h,ifnotthe ma jorit9y:,@ofthespaceusedisrelatedtofront-endproAcess- ing,+andfitseemslik9elythattheanalysisitselfisrelatively c9heaponspace.F:urtherinvestigationwithaheapproler isTnecessary:.
 TheresultsofcomparinganalysistimewitharunofGlasgo9w Hask9ellUeonthesameprogramareintriguing.vThetestsareat leastfairinthesensethatbAothAnnaandtheHask9ellcom- pilerarewritteninHask9ell,
{soneitherhasanunfairadv|ran- tage.Justb9ythemselves,-itisalittleunusualthatMghccom- piledMag2hsinalmosthalfthetimeittoAokforMwave4main. It+ma9ybAethattheheavyuseofnumericoverloadinginMwang andMwave4mainhasslo9weddownMghcasitwillhavehad togenerateandoptimiselargequan9titiesofdictionaryhan- dlingbdcoAde.Mag2hs,.b9ycomparison,ismostlystringhandling: thereislittleo9verloadinginit.rAnnahasanaiv9eviewof theKHask9ellnumbAers{itonlyknowsabAoutMInt,soitwill not)ha9veseenanysuchnumericoverloading.ZQInorderto mak9eAnnaacceptthesetwoprograms,wehadtostripout theextensiv9etypAesignatureswhichhadbAeenplacedthere expresselyvxtoeliminaten9umericoverloading.?Thesefactors ma9y8wellhaveconspiredtogiveAnnaaremark|rablygoAodrel- ativ9e#showingforMwangandMwave4main,Walthoughitishard tobAeliev9etheyaccountforallthedierencebAetween11% (Mwave4main)Tand126%(Mag2hs). BecauseMwangandMwave4mainaremac9hine-generated Hask9ell,LJtheALexpressionsinthemarereasonablysimpleand small.By8comparison,Athedesugaredv9ersionofMag2hscon- tainedusomev9erylargeexpressionsandsomequitecompli- cated-structuredt9ypAes.eW:atching-thebeha9viourofAnna on޳thisexample,itisclearthatthema jorit9yoftheanalysis timeJisspAen9txpoin9tingasinglelargegroupofaboutt9wenty functionswhic9harosefromtheextensiveuseoflazypattern matc9hing.~It6seemsplausiblethatthisparticulargroupdid notcausean9ysimilardicultytoMghc,anditmayalsobAe pAossiblexthatMghc'sdesugarerdidabetterjobthanAnna's inqCtranslatingthepatternmatc9hing.0<Nevertheless,>theqCdis- parit9yinrelativeanalysis/compilecostsbAetweenMag2hsand theothert9wobigexamplesisaw9arningthatweshouldnot read\toAom9uch\intothesemeasurementsbAeyondthepAerhaps heartening]conclusionthatw9eareindeedapproachingthe righ9tTballparkforanalyserpAerformance.   27                                        ⍠?      6.3GRelatedLworkmMycroft'soriginalw9ork[Myc80|]onapplyingabstractinter-
  pretationtotheanalysisoffunctionalprogramsspark9edoin9tense[workonforwardanalyses.ޢA[forwardstrictnessanal-ysiskktellsusthedenednessofafunctionapplicationgiv9enthedenednessoftheargumen9ts.>LandmarkpapAersincludethe*Burn-Hankin-Abramskyw9ork[BHA85b]whichputhigherorderanalysisonarmtheoreticalfoAoting,TPandW:adler'spapAer[W:ad87]whic9hshowedhowonemightdealsensiblywith.sum-of-proAductst9ypes.Implementors.madem9uch.ofndingxpAoin9tsusingtheF:rontiersalgorithm,massagingitextensiv9elymtodealwithhigherorderfunctions[HH91>],esum-of-proAducts~#t9ypes[Sew91/]andpolymorphism[Sew93/].VDe-spiteѽthisandothertric9keryѽ[HH92>][Sew92/],Bfron9tiersfailedtodeliv9erusablepAerformanceforhigh-denitionstrictnessanalysispforan9ythingotherthantrivialinputs,andtherearegoAodtheoreticalreasonsforbAelievingthesituationcannotbAeTimpro9ved.
Starting{ataroundthesametime,anothersc9hoAolofthoughtw9asdevelopingbackwards,Qorpro jection,analyses.Abac9k-w9ardsanalysisshowshowthesemanticquantityinquestion-Jphere,Wdemandforev|raluation-propagatesfromafunctionapplication@totheindividualargumen9ts.\Hughes[Hug90']ar-guesthatbac9kwardsanalysesareinheren9tlymoreecientthanU[forw9ardones,e]bAecausethefunctionspaceswithwhichtheanalysesdealaresmallerinthebac9kwardscase.Pro jec-tionanalysisdealseasilywithsum-of-proAductst9ypes, GandcapturesZcertainpropAerties,Dsuc9hashead-strictness,thatseemtoeludeforw9ardanalyses.AgoAodreferenceforpro-jectionanalysisis[WH87].vLaterw9orkshowedhowtodomak9e+non-
atpro jectionanalysispAolymorphic[Hug+],qandasuccessfulnon-
at,WpAolymorphicpro jectionanalyserw9asbuiltTin9toGlasgowHaskell[KHL91(].Despitethesesuccesses,tpro jectionanalysesha9veafunda-men9tal	#inabilitytodealwithhigherorderfunctions.F:ol-lo9wing˜theleadofW:ray[W:ra85:C],.Hughesdenedamixedanalysis|whic9hwasforwardsforthehigherorderbitsandbac9kwardsSforev9erythingelse[Hug87'].Doingthisgivesananalysisr+whic9hdealswithhigher-ordernesswhilstretainingtheinheren9teciencyofbackwardanalysis.KRecently:,.otherw9orkersQhavebAeguntoexploretherelationshipbet9weenfor-w9ardandbackwardanalysis[Bur90][HL90l][DW90N].TTheanalysisdescribAedinthispaperisamodicationofHughes'originalTmixedanalysis.Mean9while,=pAeoplexhavebAeenlookingatotherw9aysofsolv-ingvrecursiv9edomainequations.ATherehasbAeenadiscern-ableJshiftto9wardsJtermorien9tedapproaches.F:ergusonandHughes#dev9elopAed\concretedatastructures"(CDSs)[N?s]based7onCurien'sw9orkonsequentialalgorithms[Cur86].CDSsdealwithhigher-ordernessb9yregardingahigheror-der#%functionascon9tainingaCDS#!interpreterforeachfunc-tional0parameter.Thisisreallyadisguisedw9ay0ofsubsti-tutinginfunctionalparametersbAeforexpoin9ting.WhetherornotCDSscandeliv9eraviablexpAointingmechanismre-mainstobAeseen.mEarlyimplemen9tationshintedatspaceproblems,butDthesema9ynowhavebAeensolved[Hug93'].CDSs/canalsobAeview9edasahigher-ordergeneralisationoftheminimalfunctiongraphsc9hemeoriginallydescribAedb9yENeilJones[JM86z].jMinimalfunctiongraphsareusedin=theSeman9tiqueanalyser[KHL91(]builtintoGlasgowHask9ellT[PHHP93#].ThetermrewritingbasedxpAoin9terdescribedherew9as,   inpart,inspiredb9yCharlesConsel'sstrictnessanalyserin
   theGY:aleHask9ellcompiler[Gro92P].Consel'spapAer[Con91], whic9hseemstohavepassedbyalmostunnoticed,describAed a7#successful,ifsimple,strictnessanalysersolvingxpAoin9t equationsYb9ytermrewriting.Inviewofhowwellthisand Consel's}systemw9ork,,itispAerhapsapitythatPeytonJones et;almadedisparagingremarksabAoutterm-basedxpoin9t- ingTintheirseminalfron9tierspapAer[PC879].5 6.4GFurtherLworkm Anna'sNpAerformanceisencouraging.ȭNev9ertheless,there's stillalongw9aytogobAeforeev|raluationtransformerinfor- mationBcanbAegeneratedautomaticallyinproductioncom- pilers.pThreeTa9venuesofdevelopmentneedtobAepersued.OP:NEnhancemenCtjeofapplicability.]Anna'smostw9orry-:ingalimitationisherinabilit9ytodealwithhigherorder:functionswhic9hcannotbAerstied.Apossiblepartial:solutionMistoiteratethese(or,؂moreprecisely:,justthe:nast9ywbits)asmanytimesasisnecessarytoguaran-:teeGaxpAoin9t.TheworkofNielsonandNielson[NN92>]:giv9es7ethemagicnumbAerofiterationsneeded.vF:ormany:common'forms,[thisn9umbAer'isreasonablylo9w,and:itZseemsreasonabletoexpAectthisapproac9htoyield:w9orthwhileTresults.
:Iteisalsonecessarytoremo9veesomeoftheexcessiv9ere-:strictionsJionuser-deneddatat9ypAesdiscussedinsec-:tion\2.2.6.QThisdoAesnotappeartobeparticularly:dicult.Kubiak\etal[KHL91(]managedthisquite:successfully:.34P:NEnhancemenCtgofpKerformance.ٺTherenemen9tsof:section=6.1ha9ve=donealottoimpro9ve=thesystem's:pAerformance.Nev9ertheless,someAprogramswetried:recen9tly-inexcessofathousandlines-runmore:slo9wlythanonewouldlike.InvestigationsarebAeing:made.:FixpAoin9tingLlargegroupsoffunctionscouldconciev-:ablybAeacceleratedb9yreducingthegrouptoa\mini-:malTform"rst.pF:orexample,giv9en͍gMa=...a...b...gb=...c...gc=...c...d...gd=...a...:w9e`canremoveMbandMdbysubstitutingthemintoMaand:McrespAectiv9ely:.ThishalvesthenumbAeroffunctionsin:the2groupbAeingxpoin9ted.OncethesolutionstoMa:andlMcha9velbAeengenerated,4w9eobtainv|raluesforMband:MdTb9ystraightforwardback-substitution.
:NoteGthatthistec9hniquemaybAeusedinanysitua-:tionin9volvingxpAointingmutuallyrecursivegroupsof:equations.Theideastemsfromananalogywiththe:Gauss-JordanmethoAdforsolvingsim9ultaneouslinear:equations.zIn4thiscase,<arecursiv9egroupcanonlybAe:reducedItothepAoin9twhereeveryequationinthegroup:refersdirectlytoitself{nofurther.HAfterthat,.x-:pAoin9tingx	isunavoidable.DWhetherornotthisrenders:aspAeedupdependsontherelativ9ecostsofsubstitution,:bac9kTsubstitutionandxpAointing.   28                                        Ѡ⍠?      P:NDealingwithmoKdules.	5MoAdulesZareanunmiti-
  :gatedn9uisanceformanykindsofhighpAoweredseman-:ticxManalysesandoptimisations.E\Inparticular,moAd-:ulescausebigdicultiesforan9ykindofwhatJohn:Y:oung(termed\collectingin9terpretations"[You89-].TA:collectingTin9terpretationisessentiallyaglobalanal-:ysis.	vMan9y,compiletimeoptimisationsarelimited:b9y$themoAdulestructure.IF:orexample,hMsomeofthe:moreirecen9tschemesforcompilingoverloadingef-:cien9tly[Jon939][Aug93']requireglobalanalysisfor:full=applicabilit9y:.	;,ThepAointofallthisisthatthe:monomorphisation+andrsticationtransformations:usedTinAnnaalsorequireaglobalview.k:There"isanurgen9tneedtodevisesophisticatedcom-:pilationwsystemswhic9hmaintainenoughintermoAdule:comm9unication?tomakeglobalanalysespAossible.?De-:v9elopmentfofsuc9haframeworkwouldbAenetnotonly:strictnessoanalysis,@butman9yaspAectsofcompiletime:optimisation.Suc9hacompilermightworkbydump-:ing^alotofinformationin9toamoAdule'sinterfacele,:enoughAtodowhatev9eranalysesweneed.Thiswould:reallyjustbAeanextensionofthesc9hemesusedal-:readya
intheChalmersandGlasgo9wcompilers,swhich:dump{functionarit9yandrudimentarystrictnessinfor-:mationin9tointerfaceles.Thequestionisnotre-:ally@ whetherw9ecouldconstructsuchasystem,but:whetherthequan9tityofinformationdumpAedin9toin-:terface3lescouldbAelimitedsucien9tlytorenderthe:sc9hemeTpractical.AcknowledgementsThanks9toBillMitc9hellforadviceonbuildingtermrewrit-ing
systems,andtoBarneyHilk9enforaninv|raluableinsightregardingseparatecompilationsystems. MarkJonespro-videdman9yinterestingcommentsabAoutmonomorphisationandOzrstication,^andoutlinedtheinstance-collectingalgo-rithm߯ofSection5.6.1.
GeoreyBurnandDenisHo9we߯weresucien9tly8bravetoexpAerimentwiththeimplementation,andTpro9videdusefulfeedback.
Denis۳Ho9wereadanearlydraftinminutedetail.	:Hisexten-siv9e|andsometimesamusing-=2#commentsprovedveryhelpfulinTmakingthepresen9tationclearer.References[Aug87]fL.|Augustsson.RCompilingJLazyFJunctionalLan-fguages,lPartfII.hPhD/thesis,6WChalmers/T:eknisk|rafH`ogsk9ola,TGotebAorg,Sw9eden,1987.֍[Aug93]fLennartAugustsson.bImplemen9tinghaskellover-floading.-InRProceedingsAEoftheFJunctionalPro-fgramming`LanguagesandComputerAÎrchitecturefConference,N<Copenhagen,Denmark,TJune1993.[Bar91]fG.Baraki.uAnoteonabstractin9terpretationfofQpAolymorphicfunctions.	}InR.J.M.Hughes,feditor,RProceedingsofthefthAÎCMconferencefon6FJunctionalLanguagesandComputerAÎrchi-ftecture,Fn9umbAer:523inLectureNotesinCom-fputer{Science,&pages367{378,Cam9bridge,Mas-fsac9husetts,T26{30August1991.Springer-V:erlag.â  ff _
r}r2YSeetheotherfo7otnote.   [BHA85]#fG.L.0Burn,ܧC.L.Hankin,andS.Abramsky:.
  #fThetheoryofstrictnessanalysisforhigher-order#ffunctions.MIn~QRProceedingsoftheWorkshopon#fProgramsasDataObjects,Fpages42{62,DIKU,#fCopAenhagen,Denmark,17{19October1985.#fSpringer-V:erlagTLNCS217.V [Bur87]#fG.L.Burn.RAÎbstract))InterpretationandthePar-#falxlelEvaluationofFJunctionalLanguages.VPhD#fthesis,ImpAerial7PCollege,Univ9ersityofLondon,#fMarc9hT1987. [Bur90]#fG.L.}Burn.QA}relationshipbAet9ween}abstractin-#fterpretationk{andpro jectionanalysis.InR17th)AÎn-#fnualFAÎCMFSymposiumonthePrinciplesofPro-#fgrammingkLanguages,lpages[,151{156,SanF:ran-#fcisco,T17{19Jan9uary1990.ACM. [Bur91]#fG.L.yoBurn.RLazyFJunctionalLanguages:bAÎbstract#fInterpretation<andCompilation.Researc9hIMono-#fgraphsinP9arallelandDistributedComputing.#fPitmaninassoAciationwithMITݺPress,1991.CT:o#fappAear. [CD91]#fW:ei-NganChinandJohnDarlington.Remo9ving#fhigher-orderPexpressionsb9yprogramtransforma-#ftion.Chin
zisatNUS,SingapAoreandDarlington#fat<|ImpAerial,FFLondon.P9ossiblypublished,F:ebru-#faryT1991. [Con91]#fCharlesConsel.F:aststrictnessanalysisvia#fsym9bAolicJUxpointJUiteration.Unpublished.Y:ale#fUniv9ersity:,9Department[ofComputerScience,#fSeptem9bAerT1991. [Cur86]#fP:.-L.ZCurien.8RCategoricalCombinators,Sequen-#ftialAÎlgorithmsAndFJunctionalProgramming.#fResearc9h\NotesinTheoreticalComputerSci-#fenceseries.PitmanPublishingLimited,London,#f1986. [D9W90]#fKeiUDa9visandPhilipW:adler.nStrictnessanalysis#fin4d._7InRInproceedingsofthe1990GlasgowAyr#fFPN<Workshop(??),T1990. [Gro92]#fTheJY:aleHask9ellGroup.WTheyalehaskellusers#fman9ual,Tversiony2.0-bAeta,August1992. [HH91]#fSebastianHun9tandChrisHankin.#FixedpAoints#fandfron9tiers:anewpAerspective.	/RJournalof#fFJunctional-Programming,01(1):91&{120,Jan9uary#f1991. [HH92]#fSebastian7Hun9tandChrisHankin.Approximate#fxedpAoin9tsinabstractinterpretation.XInRFJourth#fEuropeann{SymposiumonProgramming,vRennes,#fFJrance,T1992.LNCS582. [HL90]#fR.J.M.5HughesandJ.Launc9hbury:.zTo9wards5re-#flating߱forw9ardsandbackwardsanalyses.`InRPro-#fceedingsVoftheThirdAÎnnualGlasgowWorkshop#fonYFJunctionalProgramming,%(pages!145{155,Ul-#flapAool,TScotland,13{15August1990. [HL92]#fPieterWH.HartelandKoAenG.Langendoen.#fBenc9hmarkingimplementationsoflazyfunc-#ftionalzlanguages.GT:ec9hnicalrepAort,Department#fofFhComputerSystems,F:acult9yofMathematics#fandComputerScience,Univ9ersityofAmster-#fdam,TDecem9bAer1992.   29                                        ⍠?      [HP90]fJohnSL.HennessyandDa9vidA.Patterson.RCom-
  fputer}AÎrchitecture:A}QuantitativeApproach.fMorgan36KaufmannPublishers,:Inc.,San36Mateo,fCA,T1990.34[Hug]fJohn3hHughes.Pro jectionsforpAolymorphicstrict-fnessQ(analysis.InRIn7SpringerVJerlagLNCS)389.fY:earTandconferencenotestablished.[Hug87]fJohnHughes.Bac9kwardsanalysisoffunctionalfprograms.tT:ec9hnical>RepAortCSC/87/R3,SUni-fv9ersity\ofGlasgo9w,Department\ofComputingfScience,TMarc9h1987.[Hug90]fJohnHughes.	jCompile-timeanalysisoffunc-ftionalprograms.
InDa9vidA.T:urner,edi-ftor,KFRResearchf$TJopicsinFunctionalProgramming.fAddison-W:esleyAPublishingCompan9y,	#1990.fF:romЈthe1987YearofProgramming,KUniv9ersityfofTT:exas,Austin,Texas.[Hug93]fJohn7Hughes.kPriv|ratecomm9unicationregardingfcdss,T1993.[JM86]fNeilD.JonesandAlanMycroft.PData
o9wanal-fysisofapplicativ9eprogramsusingminimalfunc-ftiongraphs:Abridgedv9ersion.mInRUnknown,6)butfdenitelyN<inanAÎCMproceedings,T1986.[Joh85]fT.7Johnsson.ULam9bAdalifting:6T:ransform-fingNprogramstorecursiv9eequations.	'InJ.-P:.fJouannaud,8editor,RProceedings"oftheConfer-fenceonFJunctionalProgrammingLanguagesandfComputerAÎrchitecture,pages190{203,Nancy:,fF:rance,TSeptem9bAer1985.[Joh87]fT.Johnsson.	dA9ttributegrammarsasafunc-ftionalV#programmingparadigm.InG.Kahn,fVed-fitor,$RProceedings,oftheFJunctionalProgrammingfLanguagesӜandComputerAÎrchitectureConfer-fence,pages154{173.Springer-V:erlagLNCSq274,fSeptem9bAerT1987.[Jon93]fMark0Jones.fP9artialev|raluationfordictionary-ffree_o9verloading.Unpublisheddraft.Y:aleUni-fv9ersity:,gDepartmentVofComputerScience,Aprilf1993.[KHL91]fR.'Kubiak,W+J.Hughes,andJ.Launc9hbury:.VA'cpro-ftot9ypAe$implementationofpro jection-basedrst-forderpAolymorphicstrictnessanalysis.cInR.Hel-fdal,@editor,RDraftProceedingsofFJourthAÎnnualfGlasgow)WorkshoponFJunctionalProgramming,fpagesT322{343,Sky9e,August13{151991.[Min92]fSa9v|raMintchev.IA}parallelstg-machine.IMaster'sfthesis,6Departmen9t<ofComputerScience,Uni-fv9ersityTofManc9hester,UK,SeptembAer1992.[Myc80]fA.Mycroft.Theoryandpracticeoftransform-fing:
call-b9y-needintocall-by-v|ralue.4InR4thoInter-fnationalSymposiumonProgramming,Gpages269f{281,luP9aris,April'1980.Springer-V:erlagLNCSf83.[Nel]fGeorge+FC.Nelan.[4Firstication.Date+Funkno9wn,fbut`m9ustbAe1992orafter.BasedonNelan'sPhDfthesis.TArizonaStateUniv9ersity:.   [NN92]#fF.NielsonandH.R.Nielson.<Finitenesscondi-
  #ftionsFforxedpAoin9titeration.T:echnicalrepAort,#fComputerScienceDepartmen9t,̑AarhusUniver-#fsit9y:,TDenmark,February1992.34 [P9ar92]#fWillP9artain.ATheMnofibbAenchmarksuite#fofhask9ellprograms.DInRFifthAÎnnualGlas-#fgow{rWorkshoponFJunctionalProgramming,Ayr,#f1992. [PC87]#fSimon!P9eytonJonesandChrisClack.v&Finding#fxpAoin9ts/inabstractinterpretation.InS.Abram-#fskyandC.L.Hankin,Neditors,RAÎbstract4Interpre-#ftation8IofDeclarative8ILanguages,8Computersqand#fTheir'Applications,0c9hapter11,pages246{265.#fEllisTHorw9oAod,1987. [P9ey87]#fS.L.rDP9eytonJones.RTheeImplementationofFJunc-#ftionaldProgrammingLanguages.{wPren9tice-Hall$In-#fternational!SeriesinComputerScience.Pren9tice-#fHallTIn9ternational(UK)Ltd,London,1987. [PHHP93]#fS.L.EP9eytonJones,ïCordeliaV+Hall,KevinHam-#fmond,andaWillP9artain.Theglasgowhaskell#fcompiler:ښatec9hnicaloverview.C+InRProceedings<of#ftheDUK0JoinFJrameworkforInformationTechol-#fogy,N<Keele,T1993. [PJ92]#fS.L.P9eytonJones.2Implementinglazyfunctional#flanguagesconstoAc9khardware:
thespinelesstag-#flessJG-Mac9hine.kRJournalcofFJunctionalProgram-#fming,T2(2):127{202,April1992. [Sew91]#fJuliannSew9ard.GT:owardsastrictnessanalyserfor#fhask9ell:#Puttingԭtheoryintopractice.TMaster's#fthesis,#Univ9ersity ofManc9hester,Department of#fComputerScience,E1991.T
Av|railableasUniv9ersity#fofTManc9hesterT:echnicalRepAortUMCS-92-2-2. [Sew92]#fJulianSew9ard.ePolymorphic,higherorderstrict-#fness|ianalysisusingfron9tiers. UnpublishedpapAer,#f1992. [Sew93]#fJulianSew9ard.R#Polymorphicstrictnessanalysis#fusing؂fron9tiers.	ZRInRProceedingsoftheSympo-#fsiumonPartialEvaluationandSemanticsbased#fProgramtManipulation,PEPM93,Copenhagen,#fDenmark,TJune1993. [W:ad87]#fP:.L.dWadler.:Strictnessanalysisonnon-
atdo-#fmains(b9yabstractinterpretationovernitedo-#fmains).InUS.AbramskyandC.L.Hankin,edi-#ftors,-RAÎbstract`SInterpretationofDeclarativeLan-#fguages,zc9hapter12,pages266{275.EllisHor-#fw9oAodsLtd.,sChichester,W:estsSussex,England,#f1987. [W:ad92]#fPhilipcW:adler.-Theessenceoffunctionalpro-#fgramming.=;InxRProceedingsofthe19thAÎnnual#fSymposiumqonPrinciplesofProgrammingLan-#fguages,N<SantaFJe,NewMexico,T1992. [WH87]#fP:.")WadlerandR.J.M.Hughes.@Pro jectionsfor#fstrictness)@analysis.U,InG.Kahn,.;editor,RProceed-#fings=3oftheFJunctionalProgramming=3Languages#fandr~ComputerAÎrchitecturer~Conference,pages#f385{407.N`Springer-V:erlagLNCSNQ274,\Septem9bAer#f1987.   30                                        w⍠?      [W:ra85]fS.C.W:ra9y.~\Anewstrictnessdetectionalgorithm.
  fIn'RProceedings_RoftheWorkshoponImplementa-ftions~ofFJunctionalLanguages,jAspenas,Sweden.fAÎvailableN<asChalmersPMGreportN<17,T1985.34[Y:ou89]fJ.H.aY:oung.nRTheTheoryandPracticeofSeman-fticęProgramAÎnalysisforHigher-OrderFJunc-ftional%
ProgrammingLanguages.PhDwthesis,yDe-fpartmen9tTofComputerScience,djY:aleUniversity:,fMa9yT1989.   31 9.;      Rj 	   	   cmti9P 	   	   cmsy9O5" 	   	   cmmi9Nt: 	   	   cmbx9MߤN  	   	   cmtt97<x 
3 
   cmtt10*Aa       cmr6(K`y 
3 
   cmr10N ff    cmbx12XQ ff    cmr12o 	   	   cmr9kAH 	   
   cmssbx10
!", 
   
   cmsy100n       cmsy5ٓR       cmr7Z       cmr5 ;