/
paperaimsataddressingthisveryquestion.Althoughthisisstillworkinprogres paperaimsataddressingthisveryquestion.Althoughthisisstillworkinprogres

paperaimsataddressingthisveryquestion.Althoughthisisstillworkinprogres - PDF document

jane-oiler
jane-oiler . @jane-oiler
Follow
367 views
Uploaded On 2016-07-03

paperaimsataddressingthisveryquestion.Althoughthisisstillworkinprogres - PPT Presentation

1httpcristalinriafrremyornamentsandsimultaneouslyerasingtheheadeldHoweveragainfromasoftwareengineeringperspectiveourinterestliesinconverselybeingabletoliftafunctionoperatingonnaturalnu ID: 389352

1http://cristal.inria.fr/~remy/ornaments/andsimultaneouslyerasingtheheadeld.However again fromasoftwareengineeringperspective ourinterestliesin conversely beingabletoliftafunctionoperatingonnaturalnu

Share:

Link:

Embed:

Download Presentation from below link

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


Presentation Transcript

paperaimsataddressingthisveryquestion.Althoughthisisstillworkinprogressandwecannotyetdrawrmconclusionsatthisstage,ourpreliminaryinvestigationisratherencouraging.Ourcontributionsarefourfold:rst,wepresentaconcretesyn-taxfordescribingornamentsofdatatypesandspecifyingthelift-ingoffunctionsworkingonbaretypestoornamentedfunctionsoperatingonornamentedtypes(§2);second,wedescribetheal-gorithmthatgivensuchaliftingspecicationtransformsthedef-initionofafunctiononbaretypestoafunctionoperatingonor-namentedtypes(§2);third,wepresentafewtypicalusecasesofornamentswhereoursemi-automaticliftingperformsratherwellinsections§3and§4;nally,wehaveidentiedseveralinterestingissuesrelatedtotheimplementationofornamentsthatneedtobeinvestigatedinfutureworks(§5).Wehaveaverypreliminaryprototypeimplementationoforna-mentsthathasbeenusedtoprocesstheexamplespresentedbelow,butuptosomeminorsyntacticaldifferencesandomittingmanytypeannotationstomimicwhatcouldbedoneifwehadML-styletypeinference,whileourprototypestillrequiresannotationsonallfunctionparameters.ExamplesarethuspresentedinOCaml-likesyntax.Examplesinthesyntaxacceptedbyourprototypeareavail-ableonline1.2.OrnamentsbyexamplesInformally,ornamentsarerelating“similar”datatypes.Inthissec-tion,weaimatclarifyingwhatwemeanby“similar”andjustify-ingwhy,fromasoftwareengineeringstandpoint,onewouldbenetfromorganizingdatatypesbytheir“similarities”.Forexample,comparePeano'snaturalnumbersandlists:typenat=Z|Sofnattype list=Nil|Consof  listThetwodatatypedenitionshaveasimilarstructure,whichcanbeputinclosecorrespondenceifwemap listtonat,NiltoZ,andConstoS.Moreover,theconstructorConstakesarecursiveargu-ment(oftype list)thatcoincideswiththerecursiveargumentoftheconstructorSoftypenat.Theonlydifferenceisthatthecon-structorConstakesanextraargumentoftype .Indeed,ifwetakealist,erasetheelements,andchangethenameoftheconstructor,wegetbackanaturalnumberthatrepresentsthelengthofthelist,asillustratedbelow:Cons(1,Cons(2,Cons(3,Nil)))S(S(S(Z)))Thisanalysisalsoadmitsaconverseinterpretation,whichisper-hapsmoreenlighteningfromasoftwareevolutionperspective:listscanbeunderstoodasanextensionofnaturalnumbersthatisob-tainedbygraftingsomeinformationtotheSconstructor.Toem-phasizethisdynamic,wesaythatthetype listisanornamentofthetypenatwithanextraeldoftype ontheconstructorS.Oneisthennaturallyledtoaskwhetherfunctionsovernaturalnumberscanbeliftedtofunctionsoverlists(DagandandMcBride2014).Forinstance,theadditionofPeano-encodednaturalnum-bersletrecaddmn=matchmwith|Z!n|Sm'!S(addm'n)isstrikinglysimilartotheappendfunctionoverlists:letrecappendxsys=matchxswith|Nil!ys|Cons(x,xs')!Cons(x,appendxs'ys)Intuitively,additioncanberecoveredfromtheoperationonlistsbychangingtheconstructorstotheircounterpartonnaturalnumbers 1http://cristal.inria.fr/~remy/ornaments/andsimultaneouslyerasingtheheadeld.However,again,fromasoftwareengineeringperspective,ourinterestliesin,conversely,beingabletoliftafunctionoperatingonnaturalnumberstoafunctionoperatingoveritsornament.Theexampleofappendisnotafortunatecoincidence:severalfunctionsoperatingonlistsadmitacounterpartoperatingsolelyonintegers.Ratherthanduplicatingtheseprograms,wewouldliketotakeadvantageofthisinvarianttoliftthecodeoperatingonnumbersovertolists.Oneshouldhastentoaddthatnoteveryfunctionoverlistsadmitsacounterpartoverintegers:forexample,afunctionfilterthattakesapredicatepandalistlandreturnsthelistofalltheelementssatisfyingp,hasnocounterpartonintegers,asthelengthofthereturnedlistisnotdeterminedbythelengthofl.2.1AsyntaxforornamentsInformally,anornamentisanytransformationofadatatypethatpreservesitsunderlyingrecursivestructure.Readfromanopera-tionalstandpoint,thisamountstobeingabletodroptheextrainformationintroducedbytheornament,transformtheargumentsoftheornamentedtypedowntothebaretype,whileleavinguntouchedthestructureofbothdatatypes.Droppingtheextra-informationcanbeeasilydescribedbyatotalprojectionfunctionfromtheornamentedtypetothebaretype.Forthenat/listcase,theprojectionisthelengthfunction:letreclength=function|Nil!Z|Cons(x,xs)!S(lengthxs)Thisformsthebasisofoursyntaxforornaments,leavingasidethevericationofthestructuralequivalenceforthemoment.Hence,theornamentationofnaturalnumbersintolistsissimplyspeciedbythedeclarationletornamentlength:list!natsubjecttocertainconditionsthatwedescribenow.Theconditionbywhichanornament“preservestherecursivestructure”ofitsunderlyingdatatypeissomewhathardertocharac-terizesyntactically.Letusrstclarifywhatwemeanbyrecursivestructure.Forasingle,regularrecursivetype,theeldsofeachconstructorcanbedividedintotwosets:therecursiveones(forexample,thetailofalist,ortheleftandrightsubtreesofabi-narytree),andthenon-recursiveones(forexample,primitivetypesorparameters).Afunctionpreservestherecursivestructureofapairofdatatypes(itsdomainandcodomain)ifitbijectivelymapstherecursiveeldsofthedomaindatatype(theornament)ontothecodomaindatatype(itsbaretype).Fromthisdenition,binarytreescannotbeornamentsoflists,sincetreeshaveaconstructorwithtworecursiveelds,whilelistsonlyhaveaconstantconstructorandaconstructorwithasinglerecursiveeld;thusnofunctionfromtreestolistscanpreservetherecursivestructure.Whilewehaveagoodsemanticunderstandingofthesecon-ditions(DagandandMcBride2013),thispaperaimsatgivingasyntactictreatment.Wearethusfacedwiththechallengeoftrans-latingthesenotionstoMLdatatypes,whichsupports,forexample,mutually-recursivedatatypes.Fromthecategoricaldenitionofornaments,wecannonethe-lessextractafewsufcientsyntacticconditionsforaprojectiontodeneanornament.Forthesakeofpresentation,wewillassumethattheargumentsofdatatypesconstructorsarealwaysordered,non-recursiveeldscomingrst,followedbyrecursiveelds.Theprojectionhdeningtheornamentmustimmediatelypatternmatchonitsargument,andtheargumentmustnotbeusedelsewhere.The22014/5/28 constraintsareexpressedoneachclausep!eofthispatternmatching:1.ThepatternpmustbeoftheformCy(p1;:::;pm;x1;:::;xn)wherethepiarepatternsmatchingthenon-recursiveelds,andthexi'sarevariablesmatchingtherecursiveelds.2.TheexpressionemustbeoftheformC(e1;:::;eq;hy1;:::;hyn)wheretheei'sareexpressionsthatdonotusethexj's,andtheyj'sareapermutationofthexi's.Inparticular,aconstructorCyoftheornamentedtypewillbemappedtoaconstructorCofthebaretypewiththesamenumberofrecursiveelds.Thisrulesoutallthefollowingfunctionsinthedenitionofornaments:letreclength_div2=function|Nil!Z|Cons(_,Nil)!Z|Cons(x,Cons(y,xs))!S(length_div2xs)Thesecond(recursive)eldofConsisnotmatchedbyavari-able.letreclength2=function|Nil!Z|Cons(x,xs)!S(S(length2xs))TheargumentoftheouteroccurrenceofSisnotarecursiveapplicationoftheprojectionlength2.letrecspine=function|NLeaf!Nil|NNode(l,x,r)!Cons(x,spinel)letrecspan=function|Nil!NLeaf|Cons(x,xs)!NNode(spanxs,x,spanxs)Thefunctionspineisinvalidbecauseitdiscardstherecursiveeldr,andspanisinvalidbecauseitduplicatestherecursiveeldxs.Thesyntacticrestrictionsweputonthedescriptionofornamentmakeprojectionsincomplete,i.e..onemaycookupsomevalidornamentsthatcannotbedescribedthisway,e.g..usingarbitrarycomputationintheprojection.However,itseemsthatinterestingornamentscanusuallybeexpressedasvalidprojections.Asexpected,lengthsatisestheconditionsimposedonprojec-tionsandthusdenesanornamentfromnaturalnumberstolists.Perhapssurprisingly,bythisdenition,theunittypeisanorna-mentoflists(and,infact,ofanytype),witnessedbythefollowingfunction:letnil()=Nilletornamentnil:unit! listThisexampleactuallybelongstoalargerclassofornamentsthatremovesconstructorsfromtheirunderlyingdatatype(seemoreadvancedusesofsuchexamplesin§3.3.Fromatypetheoreticperspective,thisisunsurprising:removingaconstructorissimplyachievedbyinsertingaeldaskingforanelementoftheemptyset.Theconditionsontheornamentprojectioncanbegeneralizedtoworkwithmutuallyrecursive,non-regulardatatypes:theprojec-tionsbecomemutuallyrecursive,butalltheconditionsonrecursivecallsremainunchanged.2.2Liftingfunctions:syntaxandautomationUsingtheornamentprojection,wecanalsorelatealiftedfunc-tionoperatingonsomeornamentedtypeswiththecorrespondingfunctionoperatingontheirrespectivebaretypes.Intuitively,suchacoherencepropertystatesthattheresultsoftheornamentedfunc-tionarepartiallydeterminedbytheresultofthebarefunction(thefunctiononthebaretype).Togiveamoreprecisedenition,letusdeneasyntaxoffunctionalornaments,describinghowonefunctionisaliftingofanother,andthecoherencepropertythatitdenes.Supposewewanttoliftafunctionfoftype!tothetypey!yusingtheornaments.Moreprecisely,supposewewantthisliftingtousetheornamentsu:y!andu:y!.Wesaythatfyisacoherentliftingoffwiththeornamentsuanduifandonlyifitsatisestheequation:f(ux)=u(fyx)forallxoftypey.Thisdenitionreadilygeneralizestoanynumberofarguments.Forexample,liftingthefunctionaddwiththeornamentlengthfromnaturalnumberstolist,thepropertybecomes:length(fyxsys)=add(lengthxs)(lengthys)Andindeed,takingthefunctionappendforfysatisesthisprop-erty.Sowecansaythatappendisacoherentliftingofaddwiththeornamentlengthforthetwoargumentsandtheresult.Butisittheonlyone?Canwenditautomatically?Sofar,wehaveonlyspeciedwhenafunctionisacoherentliftingofanother.However,thewholepointofornamentsistoautomatethegenerationofthecodeoftheliftedfunction.Forinstance,wewouldliketowriteletornamentappendfromaddwith{length}!{length}!{length}where{length}!{length}!{length}speciestheorna-mentstobeusedfortheargumentsandtheresultandexpectthatthecompilerwouldderivethedenitionofappendforus.Inpractice,wewillnotexactlygetthedenitionofappend,butalmost.Toachievethisobjective,thecoherencepropertyappearstobeinsufcientlydiscriminating.Forinstance,thereisaplethoraofco-herentliftingsofaddwiththeornamentlengthbesideappend.Ratherthantryingtoenumerateallofthesecoherentliftings,wechoosetoignoreallsolutionswhosesyntacticformisnotcloseenoughtotheoriginalfunction.Ourprototypetakeshintsfromthesyntacticdenitionofthebarefunction,thussacricingcomplete-ness.Thesystemtriestoguesstheliftingbasedontheformoftheoriginalfunctionandeventuallyreliesontheprogrammertosupplycodethatcouldnotbeinferred.Letusunfoldthisprocessontheliftingofaddalonglength,asdescribedabovewhereaddisimplementedas:letrecaddmn=matchmwith|Z!n|Sm'!S(addm'n)Theornamentspecication{length}!{length}!{length}playsseveralroles.First,itsdescribeshowthetypeofaddshouldbetransformedtoobtainthetypeofappend.Indeed,knowingthatlengthhastype list!natandaddhastypenat!nat!nat,weknowthatappendmusthavetype list! list! list.Second,itdescribeshoweachargumentandtheresultshouldbelifted.Duringtheliftingprocess,theornamentsoftheargumentsandoftheresultplayverydifferentroles:liftinganargumentchangesthecontextandthusrequiresliftingpatternmatching,thusintroducingadditionalinformationinthecontext;bycontract,liftingthereturntyperequiresliftingexpressions,andrequiresad-ditionalinformationtobestoredontheornamentedconstructors,whichgeneralcannotbeinferredandwillbelefttotheuser.Onourexample,theliftingspecicationsaysthattheargumentsmandnofthefunctionaddareliftedintosomeargumentsmlandnlofthefunctionappendsuchthatlengthmlismandlengthnlisn.Thematchingonmcanbeautomaticallyupdatedtoworkonlistsinsteadofnumbers,bysimplycopyingthestructureoftheornamentdeclaration:theprojectionreturnsZonlywhengivenNil,whiletheconstructorS(-)isreturnedforeveryvaluematching32014/5/28 typekeyvalcompare:key!key!inttypeset=Empty|Nodeofkeysetsetletempty:set=Emptyletrecfind:key!set!bool=funk!function|Empty!false|Node(k',l,r)!ifcomparekk'=0thentrueelseifcomparekk'�0thenfindklelsefindkrOurgoalistoliftthetwooperationsemptyandndtoassocia-tivemaps.Inthisprocess,weshallchangethereturntypeofndto optiontobeabletoreturnthevalueassociatedtothekey.Thisispossiblebecause optioncanbeseenasanornamentofboolwhereanextraeldhasbeenaddedtotrue:type option=None|Someof letis_some=function|Some_!true|None!falseletornamentis_some: option!boolTheinterfaceofthemaplibraryshouldbe:type map=|MEmpty|MNodeofkey  map mapvalmempty: mapvalmfind:key! map! optionWedenethetype mapasanornamentofset:letreckeys=function|MEmpty!Empty|MNode(k,v,l,r)!Node(k,keysl,keysr)letornamentkeys: map!setWemaynowaskforaliftingofourtwooperations:letornamentmemptyfromemptywith{keys}letornamentmfindfromfindwith[key]!{keys}!{is_some}Inthespecicationofmfindtherstargumentshouldnotbelifted,whichisindicatedbygivingitstypekey(surroundedbysquarebrackets)insteadofitsprojection(surroundedbybraces),whichinthiscasewouldbetheidentityfunction.Thisinformationisexploitedbytheliftingprocesswhichcandomoreautomationbyknowingthattheargumentisnotlifted.Theliftingofmfindisonlypartial,andthesystemreplieswiththeliftedcodebelowthatcontainsaholeforthemissingpieceofinformation: letmempty=MEmpty letrecmfind=funk!function |MEmpty!None |MNode(k',v,l,r)! ifcomparekk'=0thenSome(? ) elseifcomparekk'�0thenmfindkl elsemfindkrThatis,theprogrammerisleftwithspecifyingwhichvalueshouldbeincludedinthemapforeverykey.Thesolutionisofcoursetolltheholewithv(whichherecouldbeinferredfromitstype,asvistheonlyvariableoftype inthecurrentcontext).LiftingOCaml'sSetlibrary:Asalarger-scaleexperiment,wetriedtoautomaticallyliftpartsofOCaml'sSetlibrarytoassocia-tivemaps.Afewfunctionscannotbeliftedintofunctionsofthedesiredtype:forexample,theliftofthefor_allfunctionthatcheckswhetherallelementsofasetverifyapredicatewouldtakeasar-gumentapredicatethatonlyexaminesthekeys,whereaswewouldliketobeabletoexaminethekey-valuepairs.Thisisbecauseourtheoryofornamentsdoesnothandlehigher-orderfunctions.Afewotherfunctionscanbeliftedbuttheircoherenceproper-tiesdonotcapturethedesiredbehaviorovermaps.Forexample,theliftoftheequalfunctiononsetsofkeystoanequalfunctiononmapswouldonlycheckforequalityofthekeys.Indeed,byco-herence,applyingtheliftedversiontotwomapsshouldbethesameasapplyingequaltothesetsofkeysofthetwomaps.Still,formanyfunctions,theliftingmakessenseand,asinthendexampleabove,theonlyholeswehavetollarethosecon-tainingthevaluesassociatedtokeys.Thisisastraightforwardpro-cess,atthecostofafewsmall,manualinterventionsfromthepro-grammer.Moreover,manyofthesecouldbeavoidedbyperformingsomelimitedformofcodeinferenceinapost-processingphase.Openquestion:In§5,weproposewritingpatchesinasmalllanguageextensionthatwouldallowustollintheholesleftbytheliftingprocess.Thislanguagewouldaimatdeclarativelyspecifyingtheseliftingoperations,allowingthemtobeprocessedinbatchwithoutrequiringanyuserinteraction.3.2RefactoringAnotherapplicationofornamentsisrelatedtocoderefactoring:uponreorganizingadatatypedenition,withoutaddingorremov-inganyinformation,wewouldliketoautomaticallyupdatethepro-gramsmanipulatingthatdatatype.Forinstance,considertheabstractsyntaxofasmallprogram-minglanguage:typeexpr=|Constofint|Addofexprexpr|Mulofexprexprletreceval=function|Const(i)!i|Add(u,v)!evalu+evalv|Mul(u,v)!evaluevalvAscodeevolvesandthelanguagegetsbigger,atypicalrefactoriza-tionistouseasingleconstructorforallbinaryoperationsandhaveaseparatedatatypeofoperations,asfollows:typebinop=Add'|Mul'typeexpr'=|Const'ofint|BinOp'ofbinopexpr'expr'Bydeningtheexpr'datatypeasanornamentofexpr,wegetaccesstotheliftingmachinerytotransportprogramsoperatingoverexprtoprogramsoperatingoverexpr'.Thisornamentisdenedasfollows:letrecconvert=function|Const'(i)!Const(i)|BinOp(op,u,v)!beginmatchopwith|Add'!Add(convertu,convertv)|Mul'!Mul(convertu,convertv)endletornamentconvert:expr'!exprWemaynowlifttheevalfunctiontothenewrepresentation:letornamenteval'fromevalwith{convert}![int]Inthiscase,theliftingistotalandreturnsthefollowingcode: letreceval'=function |Const'(i)!i |BinOp'(op,u,v)!beginmatchopwith |Add'!eval'u+eval'v |Mul'!eval'ueval'v endQuiteinterestingly,theliftingiscompletelydeterminedbythecoherencepropertyforstrictrefactoringapplicationsbecausethe52014/5/28 ornamentdenesabijectionbetweenthetwotypes(here,exprandexpr').Here,wehavehitasweetspotwheretheornamentissufcientlysimpletobereversibleoneachconstructor.Thisallowsoursystemtoliftthesourceprogramintotality.Openquestion:Inordertofullyautomatetherefactoringtasks,wecruciallyrelyonthegoodbehavioroftheornamentunderinversion.However,wecannothopetogiveacompletesyntacticcriterionforsuchaclassofornaments.Westillhavetodeviseasyntacticpresentationthatwoulddelineateasufcientlyexpressivesubclassofreversibleornamentswhilebeingintuitive.3.3RemovingconstructorsAnothersubclassofornamentsconsistsofthosethatremovesomeconstructorsfromanexistingtype.Perhapssurprisingly,therearesomeinterestingusesofthispattern:forexample,inacompiler,theabstractsyntaxmayhaveexplicitnodestorepresentsyntacticsugarsincetheearlypassesofthecompilermayneedtomaintainthedifferencebetweenthesugaredanddesugaredforms.However,onemaylaterwanttoattenoutthesedifferencesandreasoninthesubsetofthelanguagethatdoesnotincludethedesugaredforms—thusensuringthestrongerinvariantthatthesugaredformsdonotappearasinputsorouputs.Concretely,thelanguageofexpressionsdenedintheprevioussection(§3.2)couldhavebeendenedwithaletconstruct(denotedbylexpr).Thetypeexprisasubsetoflexpr:wehaveanornamentoflexprwhoseprojectionto_lexprinjectsexprintolexprintheobviousway:typelexpr=|LConstofint|LAddoflexprlexpr|LMuloflexprlexpr|Letofstringlexprlexpr|Varofstringletrecto_lexpr:expr!lexpr=function|Constn!LConstn|Add(e1,e2)!LAdd(to_lexpre1,to_lexpre2)|Mul(e1,e2)!LMul(to_lexpre1,to_lexpre2)letornamentto_lexpr:expr!lexprAswiththerefactoring,liftingafunctionfoperatingonlexprovertoexpriscompletelydeterminedbythecoherenceproperty.Stillfortheliftingtoexist,thefunctionfmustverifythecoher-enceproperty,namelythattheimagesoffwithoutsugaredinputsareexpressionswithoutsugaredoutputs,andtheliftingwillfailwheneverthesystemcannotverifythisproperty,eitherbecausethepropertyisfalseorbecauseoftheincompletenessoftheverica-tion.Forexample,thefollowingfunctionmul_to_addintroducesalet:letmul_to_add=function|LMul(LConst2,x)!letn=gen_name()inLet(n,x,Add(Varn,Varn))|y!yHence,itisrejected: letornamentmul_to_add'frommul_to_add with{expr_to_lexpr}!{expr_to_lexpr}4.GADTsasornamentsofADTsGADTsallowtoexpressmorepreciseinvariantsondatatypes.Inmostcases,aGADTisobtainedbyindexingthedenitionofanothertypewithadditionalinformation.Dependingontheinvariantsneededinthecode,multipleindexingsofthesamebaretypecancoexist.Butthisexpressivenesscomesatacost:foreachindexing,manyoperationsavailableoverthebaretypemustbereimplementedoverthenely-indexedtypes.Indeed,awell-typedfunctionbetweentwoGADTsdescribesnotonlyaprocessfortransformingthedata,butalsoaproofthattheinvariantsoftheresultfollowfromtheinvariantscarriedbytheinputarguments.Wewouldliketoautomaticallygeneratethesefunctionsinsteadofrstduplicatingthecodeandtheneditingthedifferences,whichistediousandhindersmaintainability.Thekeyideaisthatindexingatypeisanexampleofornament.Indeed,totransportavalueoftheindexedtypebacktothebaretype,itisonlynecessarytodroptheindicesandconstraintsem-beddedinvalues.Theprojectionwillthusmapeveryindexedcon-structorbacktoitsunindexedequivalent.Letusconsidertheexampleoflistsindexedbytheirlength(orvectors)mentionedintheintroduction:type list=Nil|Consof  listtypezero=Zero;;type_succ=Sutype(_, )vec=|INil:(zero, )vec|ICons: (n, )vec!(nsucc, )vecWemaydeneanornamentto_listreturningthelistoftheelementsofavector(atypesignatureisrequiredbecauseto_listusespolymorphicrecursionontheindexparameter).letrecto_list:typen.(n, )vec! list=function|INil!Nil|ICons(x,xs)!Cons(x,xs)letornamentto_list:('l, )vec! listInmostcasesofindexingornaments,theprojectionisinjective.Asforrefactoring,theliftingofafunctionisthusunique.FormorecomplexGADTs,theprojectionmayforgetsomeeldsthatonlyserveasarepresentationofaproof.Sinceproofsshouldnotinuencetheresultsoftheprogram,thisambiguityshouldnotcauseanyissue.Inpractice,liftingseemstoworkwellformanyfunctions.Takeforexamplethezipfunctiononlists:letreczipxsys=matchxs,yswith|Nil,Nil!Nil|Cons(x,xs),Cons(y,ys)!Cons((x,y),zipxsys)|_!failwith"differentlength"Whenspecifyingtheliftingofzip,wemustalsogivethetypesoftheornamentsusedinthespecicationbecausethesearenecessarytogenerateapolymorphictypeannotationonthevzipfunctionensuringthatbothargumentsandtheresultsarevectorsofthesamelength.letornamentvzipfromzipwithtypen.{to_list:(n, )vec! list}!{to_list:(n, )vec! list}!{to_list:(n,  )vec!(  )list}Thisliftingisfullyautomatic,thusgeneratingthefollowingcode: letrecvzip: typen.(n, )vec!(n, )vec!(n,  )vec =funxsys!matchxs,yswith |INil,INil!INil |ICons(x,xs),ICons(y,ys)! ICons((x,y),vzipxsys) |_!failwith"differentlength"Observethatthestructureoftheliftedfunctionisidenticaltotheoriginal.Indeed,thefunctiononvectorscouldhavebeenobtainedsimplybyaddingatypeannotationandreplacingeachconstructorbyitsvectorequivalent.Thelastcaseofthepatternmatchingisnowredundant,itcouldberemovedinasubsequentpass.Theautomaticliftingignorestheindices:theproofsoftheinvariantsenforcedbyindexingislefttothetypechecker.Inthecaseofvzip,thetypeannotationsprovideenoughinformationforOCaml'stypeinferencetoaccepttheprogram.However,thisisnotalwaysthecase.Takeforexamplethefunctionzipmthatbehaveslikezipbuttruncatesonelisttomatchthelengthoftheother:62014/5/28 letreczipmxsys=matchxs,yswith|Nil,_!Nil|_,Nil!Nil|Cons(x,xs),Cons(y,ys)!Cons((x,y),zipmxsys)Toliftittovectors,weneedtoencodethefactthatonetype-levelnaturalnumberistheminimumoftwoothers.Thisisencodedinthetypemin.type(_,_,_)min=|MinS:( , , )min!( su, su, su)min|MinZl:(ze, ,ze)min|MinZr:( ,ze,ze)minTheliftingofzipmneedstotakeanadditionalargumentthatcon-taintsawitnessoftypemin:thisisindicatedbyaddinga“+”signinfrontofthecorrespondingargumentintheliftingspecication.letornamentvzipmfromzipmwithtypen1n2nmin.+[(n1,n2,nmin)min]!{to_list:(n1, )vec! list}!{to_list:(n2, )vec! list}!{to_list:(nmin,  )vec!(  )list}Thisliftingispartial,andactuallyfails: letrecvzipm: typen1n2nmin.(n1,n2,nmin)min !(n1, )vec!(n2, )vec!(nmin,  )vec =funminxsys!matchxs,yswith |INil,INil!INil |ICons(x,xs),ICons(y,ys)! ICons((x,y),vzipm? xsys) |_,!failwith"differentlength"Eventhoughitbehavescorrectly,thisfunctiondoesnottypecheck,evenifweputacorrectwitnessinsidethehole:sometypeequal-itiesneedtobeextractedfromthewitnessmin.Thisamountstowritingthefollowingcode:letrecvzipm:typel1l2lm.(l1,l2,lm)min!( ,l1)vec!( ,l2)vec!(  ,lm)vec=funminxsys!matchxs,yswith|INil,_!(matchminwithMinZl!INil|MinZr!INil)|_,VNil!(matchminwithMinZr!INil|MinZl!INil)|ICons(x,xs),ICons(y,ys)!(matchminwith|MinSmin'!ICons((x,y),vzipmmin'xsys))Generatingsuchacodeisoutofreachofourcurrentprototype.Besides,itcontradictsoursimplicationhypothesisthatornamentsshouldnot(automatically)inspectargumentsmorethanintheoriginalcode.Insteadofattemptingtodirectlygeneratethiscode,apossibleextensiontoourworkwouldbetoautomaticallysearch,inapost-processingphase,foraproofoftherequiredequalitiestogeneratecodethattypechecks,i.e.togeneratetheabovecodefromtheouputofthelifting.5.Discussion5.1ImplementationOurpreliminaryimplementationofornamentsisbasedonasmall,explicitlytypedlanguage.Oncetypesareerased,itisastrictsubsetofOCaml:inparticular,itdoesnotfeaturemodules,objects,etc.,buttheseareorthogonaltoornaments.Theliftingofornamentsdoesnotdependontypeinference,butonlyontypeannotationsthatresultsfromtypeinference.Hence,itissufcienttoimplementornamentsonalanguagewithexplicittypes,eventouseitinalanguagewithtypeinference,suchasOCamlorHaskell,usingthehostlanguagetypeinferencertodec-oratetermswithexplicittypes,elaboratetheornaments,erasetypeinformation,andrerunthehostlanguagetypeinferencerontheliftedfunctions.Thus,itwouldnotbedifculttointegrateoursystemtoOCaml:elaborationofornamentscouldbeinsertedafterrunningtypein-ferencetoworkonthetypedabstractsyntaxtree,liftthefunctions,thenerasetheirtypestooutputtheresultingcode.Thetheoryofornamentsassumesnosideeffect.However,asourimplementationofliftingpreservesthestructureoffunctions,theornamentedcodeshouldlargelybehaveasthebarecodewithrespecttotheorderofcomputations.Still,wewouldhavetobemorecarefulnottoduplicateordeletecomputations,whichcouldbeobservedwhenfunctionscanbereceivedasarguments.Ofcourse,itwouldalsobesafertohavesomeeffecttypesystemtoguardtheprogrammeragainstindirectside-effectingperformedbyliftedfunctions—butthiswouldalreadybeveryusefulforbareprograms.5.2FutureworkWhentheliftingprocessispartial,itreturnscodewithholesthathavetobelledmanually.Onedirectionforimprovementistoaddapost-processingpasstollinsomeoftheholesbyusingcodeinferencetechniquessuchasimplicitparameters(ChambardandHenry2012;Scala),whichcouldreturnthreekindsofanswers:auniquesolution,adefaultsolution,i.e..lettingtheuserknowthatthesolutionisperhapsnotunique,orfailure.Infact,itseemsthataverysimpleformofcodeinferencemightbepertinentinmanycases.However,codeinferenceremainsanorthogonalissuethatshouldbestudiedonitsown.Apossibleextensiontoavoidmanualeditingafterliftingwouldbetoallowtheusertoprovidethecodetobelledintheholesinadvance,i.e.inthespecicationofthelifting.Thiscouldtaketheformofapatch,whichwouldbeautomaticallyappliedtotheoutputoftheliftingprocess.Anotherdirectionforimprovementistoalsoenablethede-nitionofnewornamentsbycombinationofexistingornamentsofthesametype.ThiswouldbeparticularlyusefulforGADTs:anindexedtypecouldthenbebuiltfromabaretypeandalibraryofusefulpropertiesexpressedasGADTs.Also,wearemissingatheoryofhigher-orderornaments.Thispreventsusfromgeneratingusefulliftingsforanumberoffunc-tionssuchasmapandfilterthatareverycommoninfunctionalprograms.6.ConclusionWehaveexploredanonintrusiveextensionofanML-likelanguagewithornaments.Thedescriptionofornamentsbytheirprojectionseemsquiteconvenientinmostcases.Althoughourliftingalgo-rithmissyntax-directedandthuslargelyincomplete,itseemstoberatherpredictiveandintuitive,anditalreadycoversafewinter-estingapplications.Infact,incompletenessimprovesautomation,whichseemsnecessarytomakeornamentspractical.Still,itwouldbeinterestingtohaveamoresemanticcharacterizationofourre-strictedformoflifting.Ourresultsarepromising,ifstillpreliminary.Thisinvitesustopursuetheexplorationofornamentsbothonthepracticalandtheoreticalsides,butmoreexperienceisreallyneededbeforewecandrawdeniteconclusions.Aquestionthatremainsuncleariswhatshouldbethestatusofornaments:shouldtheybecomearst-classconstructofprogram-minglanguages,remainameta-languagefeatureusedtopreprocessprogramsintothecorelanguage,oramerepartofanintegratedde-velopmentenvironment?72014/5/28

Related Contents


Next Show more