/
TowardsapracticalprogramminglanguagebasedondependenttypetheoryUlfNorel TowardsapracticalprogramminglanguagebasedondependenttypetheoryUlfNorel

TowardsapracticalprogramminglanguagebasedondependenttypetheoryUlfNorel - PDF document

unita
unita . @unita
Follow
344 views
Uploaded On 2021-10-09

TowardsapracticalprogramminglanguagebasedondependenttypetheoryUlfNorel - PPT Presentation

4connectionisestablishedbyageneralmetatheoremFinallyweputourworkintopractiseintheimplementationofaprogramminglanguageAgdabasedontypetheoryAsanillustratingexampleweshowhowtoprogramasimplecerti12edprov ID: 898534

nat x0000 forinstance set x0000 nat set forinstance rst orderlogic prop sucn unify lista metavariables theagdalanguage seti prf lemma3

Share:

Link:

Embed:

Download Presentation from below link

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

1 Towardsapracticalprogramminglanguagebase
TowardsapracticalprogramminglanguagebasedondependenttypetheoryUlfNorellc UlfNorell,2007ISBN978-91-7291-996-9ISSN0346-718XDoktorsavhandlingarvidChalmerstekniskahogskola,NyserieNr2677.Technicalreport33DDepartmentofComputerScienceandEngineeringResearchgroup:ProgrammingLogicDepartmentofComputerScienceandEngineeringChalmersUniversityofTechnologyandGoteborgUniversitySE-41296GoteborgSwedenTelephone+46(0)31-7721000PrintedattheDepartmentofComputerScienceandEngineeringGoteborg,2007 4 connectionisestablishedbyageneralmetatheorem.Finallyweputourworkintopractiseintheimplementationofapro-gramminglanguage,Agda,basedontypetheory.Asanillustratingexample

2 weshowhowtoprogramasimplecerti edpro
weshowhowtoprogramasimplecerti edproverforequationsinacommu-tativemonoid,whichcanbeusedinternallyinAgda.Muchmoreimpressiveexampleshavebeendonebyothers,showingthattheideasdevelopedinthisthesisareviableinpractise. 6 8CONTENTS 3.3Thetypecheckingalgorithm................... 53 3.3.1Operationsonthesignature............... 54 3.3.2Thealgorithm....................... 55 3.4Examples............................. 60 3.5Proofofcorrectness........................ 62 3.5.1Soundnesswithoutconstraintsolving.......... 62 3.5.2Soundnessofconstraintsolving............. 65 3.5.3Relatinguserexpressionsandcheckedterms...... 68 3.5.4Mainresult...............

3 ......... 68 3.6Implicitarguments.......
......... 68 3.6Implicitarguments........................ 69 3.7Extendingtheunderlyingtheory................. 70 3.7.1Sigmatypesandtheunittype.............. 71 3.7.2Functiontypesasterms................. 72 3.7.3Universehierarchy.................... 72 3.7.4Patternmatching..................... 72 3.8Summary............................. 73 4ModuleSystem754.1Introduction............................ 75 4.2Description............................ 76 4.2.1Privatede nitions.................... 77 4.2.2Namemodi ers...................... 78 4.2.3Re-exportingnames.................... 79 4.2.4Parameterisedmodules.................. 79 4.2.5Split

4 tingaprogramovermultiple les........
tingaprogramovermultiple les......... 81 4.3Equipmentforrecordtypes................... 82 4.4Anexample............................ 83 4.4.1Anoteonrecordsubtyping............... 87 4.5Implementation.......................... 87 4.5.1Scopecheckingstate................... 88 4.5.2Lookingupandaddingnames.............. 89 4.5.3Pushingandpopping................... 89 4.5.4Scopemodi ers...................... 90 4.5.5Scopechecking...................... 91 4.5.6Typechecking....................... 93 4.6Summary............................. 95 5TheAgdaLanguage975.1Languagedescription....................... 97 5.1.1Names........................

5 ... 97 5.1.2Interactionpoints...........
... 97 5.1.2Interactionpoints..................... 98 10CONTENTS 12CHAPTER1.INTRODUCTION basedonadependenttypetheoryinwhichveryprecisestatementsofthepurposeofaprogramcanbemade.Themaincontributionsare:  Analgorithmfortypecheckingpatternmatchingequationsoverinduc-tivefamiliesofdatatypes,  atype-safetreatmentofmetavariables,enablingaformofimplicitsyn-tax,  asimplebutpowerfulmodulesystem,  awaytoconnectthetypecheckertoa rst-orderlogictheoremprovertoallowsimpleproofstobefoundautomatically,and  animplementationofaprogramminglanguage,Agda,provingthatpracticalprogrammingwithdependenttypesiswithinourreach.1.1Overviewofth

6 ethesisTherestofthischaptersetsthesceneb
ethesisTherestofthischaptersetsthescenebyintroducingadependenttypetheoryUTTandatypecheckingalgorithmforthistheory.Thefollowingthreechaptersdealwiththetaskofturningthisbasictheoryintoaprogramminglanguage,addingpatternmatching,metavariables,andamodulesystem.Chapter2discusseshowtoextendthetheorywithinductivefamiliesandfunctionsde nedbypatternmatchingoverelementsinthesefamilies.Wegiveatypecheckingalgorithmandanalgorithmforcheckingcoverageofpatternmatchde nitions.InChapter3wedescribeandprovesoundanalgorithmfortypecheckingatypetheoryextendedwithmetavariables.Thisallowsustoextendourlanguagewithanotionofimplicitarguments.Chapter4describ

7 esasimplebutpowerfulmodulesystemfordepen
esasimplebutpowerfulmodulesystemfordependentlytypedlanguages.Bykeepingthemodulesystemseparatefromthetypecheckerweobtainacleanmodulesystemwhichislargelyindependentoftheunderlyinglanguage.Theresultsfromthethesechaptersareputtogooduseintheimplemen-tationoftheAgdalanguage,whichisdescribedfromauser'sperspectiveinChapter5.AbiggerexampleofanAgdaprogramforprovingequationsinacommutativemonoidisgiven.Chapter6digressesfromthethemeofusingtypetheoryforprogram-ming,andshowshowa rst-orderlogictheoremprovercanbeconnectedtoadependenttypetheorytoprovideautomationofproofsof rst-ordertheorems. 14CHAPTER1.INTRODUCTION ideaisthatonewritesdependentlytyped

8 programsasiftheyweresimplytyped.Theproof
programsasiftheyweresimplytyped.TheproofobligationsarisingfromthedependenttypesarerecordedbyRussellandcanbeprovedseparatelyusingthetacticlanguageofCoq.Thisapproachisquiteappealinginthatitseparatestheprogramlogicfromtheproofsrequiredtoshowwell-typednessoftheprogram.Therehasalsobeenalotofworkfromtheotherdirection|addingdepen-denttypestoconventionalprogramminglanguages.DependentML[Xi98]extendsMLwithtypesdependentonintegers,andHaskellhasrecentlybeenextendedwithgeneralisedalgebraicdatatypes(GADT)[PVWW06],are-strictedformofinductivefamilies.Therehasalsobeensomenewlanguages,suchasAppliedTypeSystems[Xi04]andOmega[She05].Commonfortheselanguagesandex

9 tensionsisthattheyonlysupportalimitedfor
tensionsisthattheyonlysupportalimitedformoftypedependencies.Forinstance,thereisnowayofhavingatypedependingonthevalueofanotherdependenttype.1.3AbasicdependenttypetheoryWhatsetsdependenttypetheoryapartfromothertypetheoriesisthattypescandependonterms.Inanon-dependenttheorytypesandtermsliveinseparateworldsandtheyonlymeettodecidewhattermshavewhichtypes.Inadependenttheory,ontheotherhand,typescantalkabouttermsandsoitispossibletoexpressthingsliketheprecisecharacterisationofthesortingfunctionmentionedabove.Inthissectionwepresentadependenttypetheorywhichcanserveasbasisfortheextensionsdiscussedinlaterchapters.Theparticularchoiceoftypetheoryisnotcrucia

10 landthetheorywechooseisroughlyLuo'sUTT[L
landthetheorywechooseisroughlyLuo'sUTT[Luo94]extendedwith-typesand-laws.InthefollowingwewillrefertothistheoryasUTT.ThesyntaxofUTTispresentedinFigure1.1.Atelescope[dB91b]=(x1:A1):::(xn:An)isasequenceoftypeswherelatertypesmaydependonelementsofprevioustypes.Whenthereareconsecutiveoccurrencesofatypeinatelescopewemaycombinethemandwrite,forinstance,(xy:A)(z:B)for(x:A)(y:A)(z:B).DependenttypetheorygeneralisesthesimplefunctionspaceA!Btoadependentfunctionspace(x:A)!BwheretheresulttypeBcandependonthevalueoftheargument.Wesometimesrefertodependentfunctiontypesas-typesformathematicalreasons.IfBdoesnotdependonxweallowourselvestow

11 riteA!Bandifwehaveatelescope=(x1:A1)
riteA!Bandifwehaveatelescope=(x1:A1):::(xn:An)wewrite!Bfor(x1:A1)!:::!(xn:An)!B.Functionsareintroducedby-termsx:tandcomputesby -reduction.Toabstractoverasequenceofvariablesxwewritex:tor:tratherthanx1:::xn:t. 16CHAPTER1.INTRODUCTION Contexts: �`valid `valid�`valid�`A:Seti �;x:A`validTypesandterms: �`t:A �`valid �`Seti:Seti+1�`A:Seti�;x:A`B:Seti �`(x:A)B:Seti�`A:Seti�;x:A`B:Seti �`(x:A)!B:Seti�`valid �`1:Set0�`validx:A2� �`x:A�`s:A�`t:B[x:=s] �`hs;ti:(x:A)B�`t:(x:A)B �`1t:A�`t:(x:A)B �`2t

12 :B[x:=1t]�;x:A`t:B �`x:t
:B[x:=1t]�;x:A`t:B �`x:t:(x:A)!B�`s:(x:A)!B�`t:A �`st:B[x:=t]�`valid �`hi:1�`t:A�`A6B �`t:B Figure1.2:TypingrulesforUTT 18CHAPTER1.INTRODUCTION thatifthastypeAandAisasubtypeofBthenthastypeB.Thesub-typingrelationistheextensionofthefactthatSetiisasubtypeofSetjifi6j.Wehavechosenandtobeinvariantintheir rstargument,butitisalsoconceivabletomakethemcovariantandcontravariant,respectively.Theconversionrulesimplement -equalityonterms.Worthnotingisthat -equalityisrepresentedbyareductionrelation,whereas-equalityisjudge-mental.Thispresentationcorrespondstohowconversionisimplemente

13 dinthetypecheckingrulesinthenextsection.
dinthetypecheckingrulesinthenextsection.Inthecurrentpresentationwecannotwriteverymanyinterestingpro-gramssincetheonlybasetypewehaveisthesingletontype.Ratherthanaddingmoreinterestingbasetypes,however,weholdoutuntilChapter2whereweshowhowtoaddinductivelyde nedfamiliesoftypes[Dyb94].Fornowwemakedowiththeexamplesofthepolymorphicidentityfunctionandadependentfunctioncomposition.id:(A:Set)!A!Aid=Ax:xcomp:(AB:Set)(C:B!Set)!((x:B)!Cx)!(g:A!B)(x:A)!C(gx)comp=ABCfgx:f(gx)Thiscompositionoperatorisnotthemostgeneralpossible|wecouldalsomakegadependentfunction|butitissucientlygeneralformostcommonapplications.Italsohasthenicepropertythatth

14 etypeargumentsA,B,andC,canbeinferredauto
etypeargumentsA,B,andC,canbeinferredautomatically(seeChapter3).1.4TypecheckingWenowpresentatypecheckingalgorithmforUTT.Weuseabidirec-tionalalgorithmwithmutuallyde nedjudgementsforcheckinganexpres-sionagainstatypeandinferringthetypeofanexpression[Pau90,Coq96].Wealsoletthetypecheckerproduceawell-typedtermfromtheinputex-pressionratherthanjustcheckthatitiswell-typed,thusseparatingtheuserlanguagefromthecorelanguageofthetypechecker.Thesetwolanguageshavedistinctlydi erentpurposes|theuserlanguageshouldbefriendlytotheuser,whereasthecorelanguageshouldbefriendlytothetypechecker.Forinstance,theuserlanguagemightusenamedvariableswhereasforthe

15 corelanguagewemaywanttohandlenamesusingd
corelanguagewemaywanttohandlenamesusingdeBruijnindicesordeBruijnlevels,oracombinationofboth[MM04b].Furthermore,whenwe 20CHAPTER1.INTRODUCTION Typeinference: �`e#A;t x:A2� �`x#A;x �`hi#1;hi�`e1#A;sA!whnf(x:B)!C�`e2"B;t �`e1e2#C[x:=t];st�`e#A;tA!whnf(x:B)C �`1e#B;1t�`e#A;tA!whnf(x:B)C �`2e#C[x:=1t];2t�`e1#C1;A�;x:A`e1#C2;BC1!whnfSetiC2!whnfSetj �`(x:e1)!e2#Setitj;(x:A)!B�`e1#C1;A�;x:A`e1#C2;BC2!whnfSetiC1!whnfSetj �`(x:e1)e2#Setitj;(x:A)B �`1#Set0;1 �`Seti#Seti+1;Seti Figure1.5:Typeinferencerules. 22CHAPTER1.INTRODUCTION Conversion: �`s't"A s!

16 whnfs0t!whnft0A!whnfA0�`s0'0t0"A0 �
whnfs0t!whnft0A!whnfA0�`s0'0t0"A0 �`s't"AConversion(weakheadnormalforms): �`s'0t"A �`Seti'0Seti"Set �`A1'A2"Set �;x:A1`B1'B2"Set �`(x:A1)!B1'0(x:A2)!B2"Set �`A1'A2"Set �;x:A1`B1'B2"Set �`(x:A1)B1'0(x:A2)B2"Set �`s'0t"1�;x:A`sx'tx"B �`s'0t"(x:A)!B�`1s'1t"A�`2s'2t"B[x:=1s] �`s'0t"(x:A)Bs;tneutral�`st#A0 �`s'0t"A Figure1.7:Typedirectedconversionchecking 24CHAPTER1.INTRODUCTION 1.5ExtensionstothetheoryInthecomingchapterswewilldiscussvariousextensionstoUTT.Topreparethereaderweoutlinetheseextensionshere.1.5.1Inductive

17 de nitionsInChapter2wedescribeatypec
de nitionsInChapter2wedescribeatypecheckingalgorithmforde nitionsbypatternmatchingoverinductivelyde nedfamiliesofdatatypes.Adatatypefamilyisintroducedbyadatadeclaration:dataD:�!Setiwherec1:1!Dt1...cn:n!DtnThisdeclarationintroducesadatatypefamilyDindexedover�andparam-eterisedby,inductivelyde nedbytheconstructorsc1:::cnwiththegiventypes.Theparametersscopeoverthetypesoftheconstructorsandmustbeunchangedinthetargetsoftheconstructors,whereaseachconstructorcantargetadi erentindex.Forordinarynon-familydatatypes�willbeempty.Forinstance,thedatatypeofnaturalnumberscanbeintroducedbydata

18 Nat:Setwherezero:Natsuc:Nat!Natandthefam
Nat:Setwherezero:Natsuc:Nat!Natandthefamilyofn-element nitesetsisgivenbydataFin:Nat!Setwherefzero:(n:Nat)!Fin(sucn)fsuc:(n:Nat)!Finn!Fin(sucn)AnexampleofaparameteriseddatatypeisthetypeoflistsoverasetA.dataList(A:Set):Setwherenil:ListAcons:A!ListA!ListAIfweindexthelistsbytheirlengthwegetthefamilyofvectors:dataVec(A:Set):Nat!Setwherevnil:VecAzerovcons:(n:Nat)!A!VecAn!VecA(sucn) 26CHAPTER1.INTRODUCTION R=(x:A)(y:Bx)Cxyand eldprojectionfunctionscanbede nedusingthe-projections:x:R!Axr=1ry:(r:R)!B(xr)yr=1(2r)z:(r:R)!C(xr)(yr)zr=2(2r)Inpractise,however,itisagoodideatoleteachrecorddeclarationintroduc

19 eanewtype.Thismeansthattworecordtypesdec
eanewtype.Thismeansthattworecordtypesdeclaredtohavethesame eldswillbedi erent,buttheywillhavethesameelements.Oneadvantageofthisisthatitsigni cantlyimprovestheeciencyofcheckingequalitybetweenrecordtypes|insteadofcomparingthetypesofallthe elds,itisenoughtocomparethenames.Itisalsogoodprogrammingpractisetokeepintentionallydi erenttypesseparateinthetypesystem.1.5.4ImplicitargumentsInChapter3wegiveanalgorithmfortypecheckinginthepresenceofmetavariables.Thiswillallowustoextendourtheorywithimplicitar-guments.Weintroduceanewfunctionspacefx:Ag!B,semanticallyequivalentto(x:A)!Bbutwheretheargumentcanbeomitted.Forinstance,thepoly

20 morphicidentityfunctioncanbegiventhetype
morphicidentityfunctioncanbegiventhetypeid:fA:Setg!A!AToapplytheidentityfunctiontoanelementxofatypeA,onesimplywritesidx,omittingthe rstargument.Wewillnotimposeanyrestrictionsonwhereimplicitfunctionspacesareallowed,butratherreportanerroriftheimplicitargumentscannotbeinferredinaparticularinstance.Thereasonforthisisthatitisnotclearexactlywhatsuchrestrictionswouldlooklikeandtheywouldnecessarilyexcludemanyusefulcasesofimplicitarguments. 28CHAPTER2.PATTERNMATCHING transkmnkmmn=?Ifwedecidetopatternmatchontheproofofk6mtheproblemisre nedtotranszeromn(leqZerom)mn=?trans(suck)(sucm)n(leqSuckmkm)mn=?Wecanclosethe rstcasewithleqZeronandinthe

21 secondcaseweproceedwithpatternmatchingon
secondcaseweproceedwithpatternmatchingonmn.Now,sincemn:sucm6ntheonlypossiblecaseisleqSucandweendupwithtranszeromn(leqZerom)mn=leqZerontrans(suck)(sucm)(sucn)(leqSuckmkm)(leqSucmnmn)=?TheremainingcaseisclosedbyanappealtoleqSucandarecursivecall.transzeromn(leqZerom)mn=leqZerontrans(suck)(sucm)(sucn)(leqSuckmkm)(leqSucmnmn)=leqSuckn(transkmnkmmn)Thereareanumberofinterestingthingstonotehere.Firstofall,asmen-tionedpreviously,whenpatternmatchingonelementsofthe6familytheindicesareinstantiated.Inthiscase,thepatternsforthenaturalnumberargumentswerere nedeventhoughweneverexplicitlypatternmatchedonthem.Thishasthee ectthatthepatternsbecome(seem

22 ingly)non-linear.Inthelastcaseabovethere
ingly)non-linear.Inthelastcaseabovetherearemultipleoccurrencesofthevariablesk,m,andn.Itisimportanttopointout,however,thattherepeatedvariablesareexactlythosethatarenecessarytomakethelefthandsidewell-typed.The nalthingtonoteisthatwehaveamorere nednotionofimpossiblepatternsthanyouhaveforsimpledatatypes.AboveweconcludedthattheconstructorleqZerocouldnotbeusedtobuildanelementofsucm6n.ThisisexplainedindetailinSection2.1.8.Fornowletusturnourattentiontothenon-linearityofpatterns.Theimportantobservationisthatthenon-linearityarisesfromtheinstantiationofindices.Ingeneralwemightnotonlygetnon-linearpatternbutarbitrarytermsinpatterns.Considertheda

23 tatypeImfrepresentingthepropertyofbeingi
tatypeImfrepresentingthepropertyofbeingintheimageofafunctionf:A!B(assumingsomeA;B:Setandf:A!B):dataImf:B!Setwhereimf:(x:A)!Imf(fx) 30CHAPTER2.PATTERNMATCHING ratherthaninthetheoryitselfwhendescribingthetypecheckingalgorithmwhichmakesthingsabiteasier.OurworkisbasedonCoquand'salgorithm,butwherehedescribeshowtoincrementallyconstructawell-typedprogramwegiveadetailedalgorithmforprogramrecognition.2.1TypecheckingpatternmatchequationsInthissectionwepresentthetypecheckingalgorithmforsystemsofpatternmatchequations.Contrarytopreviouswork[Coq92,GMM06]weallowequa-tionstooverlapandprioritisetherulesfromtoptobottom.Operationally,however,wetranslatethesys

24 temofequationstoacasetree[Aug85].Thismea
temofequationstoacasetree[Aug85].Thismeansthatallequationsmightnotholdasde nitionalequalities.Consider,forinstance,thede nition t :Nat!Nat!Natxtzero=xzeroty=ysucxtsucy=suc(xty)Here,thereisnowaywecouldgetboththe rsttwoequationstoholdde nitionally.Thealgorithmworksby rsttypecheckingeachequationindividually,andthencheckingthatallcasesarecoveredbytranslatingthesystemintoonethatcanberepresentedbyacasetree.Weusethefollowingconventions:u;v;wstandforwell-typedterms,eforapotentiallyill-typedterm,p;qarepatterns,;; arecontextmappings(substitutions),andGreekcapitalletters(�,,..)arecontexts(telescopes).2.1.1Contextma

25 ppingsAcontextmapping:!�isal
ppingsAcontextmapping:!�isalistofpatternswith`:�whichislinearinthevariablesof.Thismeansthateachvariableinoccursexactlyonceinanaccessiblepositionin.Therearenorestrictionsontheinaccessibleoccurrencesofavariable,however.If�`v:A,thenwecansubstitutevandAby,obtaining`v:A.Theidentitymappingid:�!�isthelistofvariablesin�.Thesingletoncontextmapping[x:=p]:�jx:=p!�isthelistofvariablesin�wherexhasbeenreplacedbyp.Thecontext�jx:=pisde nedbypp�p`p:A�p;x:A`p (�;x:A;)jx:=p=�p(p[x:=p]) 32CHAPTER2.PATTERNMATCHING follows: Mat

26 ch(x;p)=)[x:=p] Match(buc;p)=)"Match(
ch(x;p)=)[x:=p] Match(buc;p)=)"Match(;p)=)q Match(c;cp)=)qc16=c2 Match(c1;c2p)* Match(";")=)"Match(p1;p2)=)q1Match(;p)=)q2 Match(p1;;p2;p)=)q1;q2Notethatanythingmatchesaninaccessiblepattern.Thisisreasonablesinceinaccessiblepatternsareguaranteedtomatchbythetypesystem.2.1.4Uni cationUni cationisperformedrelativetoasetof exiblevariables,i.e.variablesthatareopenforuni cation.Inourcasethe exiblevariablesarethosecorrespondingtoinaccessiblepatternsintheinputpattern,computedbyFlexible(p:)Flexible(":")=;Flexible(bec;p:(x:A))=fxg[Flexible(

27 2;p:)Flexible(p;p:(x:A))=Fl
2;p:)Flexible(p;p:(x:A))=Flexible(p:)Thereasonforkeepingtrackof exiblevariablesisthatweneedtomakesurethatthecontextmappinggeneratedbythealgorithmcorrespondstothepatternsgivenbytheuser.Uponsuccessfuluni cationacontextmappingfromanewcontexttotheoriginalcontextisproduced.Wewrite;�`Unify(u=v:A)=):!�forthesuccessfuluni cationofuandvoftypeAinthecontext�with exiblevariables,resultinginthecontextmappingfromthenewcontextto�.Intuitivelywillbethecontextobtainedbyapplyingtheuni erofuandvto�.Asweshallseethismightrequirereorderingof�.Afaileduni cationiswritten;&#

28 0;`Unify(u=v:A)*Whenfacedwithaproblemwhi
0;`Unify(u=v:A)*Whenfacedwithaproblemwhichistoodicultuni cationwillsimplygiveup.Werepresentthisbyastuckuni cationproblem.Forinstance,the 34CHAPTER2.PATTERNMATCHING x2x=2FV(v) ;�`Unify(x=v:A)=)[x:=bvc]:�jx:=v!�(U-Var)c16=c2 ;�`Unify(c1u=c2v:A)*(U-Fail)x2Acc(p) ;�`Unify(x=cp:A)*(U-Occ)c:!Dw;�`Unify(u=v:)=):�0!� ;�`Unify(cu=cv:A)=):�0!�(U-Con) ;�`Unify("=":")=)id:�!�(U-Empty);�`Unify(u=v:A)=)1:�1!�;�1`Unify(u[1]=v[1]:[x:=u][2])=)2:&#

29 0;2!�1 ;�`Unify(u;u=v;&#
0;2!�1 ;�`Unify(u;u=v;v:(x:A))=)21:�2!�(U-Tel)�`u'v"A ;�`Unify(u=v:A)=)id:�!�(U-Conv) Figure2.1:Uni cation 36CHAPTER2.PATTERNMATCHING A!whnfDuvDu:!Setcu:!Duw=Flexible(p1;q:1);1`Unify(v=w:)=):0!10="(x:A)[x:=c]:0!1(x:A) Split(p1;cq;p2;1(x:A)2)=)0"2:0(20)!1(x:A)2A!whnfDuvDu:!Setcu:!Duw=Flexible(p1;q:1);1`Unify(v=w

30 :)* Split(p1;cq;p2;&#
:)* Split(p1;cq;p2;1(x:A)2)* Figure2.2:Con gurationre nementrules A!whnfDuv8cj2Constrs(D):cju:j!Duwpj=b�1c;cbc;b�2cj=fjgifSplit(pj;�1(x:A)�2)=)j:�j!�;ifSplit(pj;�1(x:A)�2)* Splitx(�1(x:A)�2)=)[jjIfthecontextcanbesplitalongxthensplittingreturnsthesetofcon-textmappingsobtainedbysplittingwithrespecttoeachconstructorinthedatatypeatx.WewillusethissplittinginSection2.2whenwediscussthereductionbehaviouroffunctionsde nedbypatternmatching.2.1.6TypecheckingalgorithmAsdescribedinSection2.1.2,thetypecheckingalgorit

31 hmbuildsawell-typedcontextmappingcorresp
hmbuildsawell-typedcontextmappingcorrespondingtothegivenuserpatternsbysuccessivelyre ningcon gurationsintheformhp;:!�i,where�isthetypeoftheargumentstothefunctionbeingchecked,isthecontextmappingbuiltsofar,andparetheuserpatternscorrespondingtothevariablesin.Wewritehp;:!�i=)hq;:!�i 38CHAPTER2.PATTERNMATCHING `CheckInaccessible(p=:�)de nedby`e"A;u`u'v"A `CheckInaccessible(bec=bvc:A) `CheckInaccessible(x=x:A)c:!Dw`CheckInaccessible(p=q:) `CheckInaccessible(cp=cq:A)`CheckInaccessible(p=q:A)

32 `CheckInaccessible(p=q:
`CheckInaccessible(p=q:[x:=q]) `CheckInaccessible(p;p=q;q:(x:A)) `CheckInaccessible("=":")Notethatsincewehavecheckedtheaccessiblepartofthepatternsweknowthatpandagreesonconstructorsandvariablenames.Thisisallweneedtocheckalefthandside.Wede neCheckPats(p:�)=):!�`CheckInaccessible(p=:�) CheckLhs(p:�)=):!�2.1.8RefutingelementsofemptytypesInmanypreviouspresentations[Coq92,McB99,SP03]coveragecheckingisundecidable.Thisisduetothefactthatsplittingonacaselessdatatypedoesnotleaveanyevidenceintheprogram|itsimplymakesthewholebranchdisappear.Toso

33 lvethisproblemwefollowthesameapproachtak
lvethisproblemwefollowthesameapproachtakenbyGoguenetal.[GMM06]andrequireprogramstocontainexplicitdismissalofelementsinemptytypes.Firstwemakeadistinctionbetweenemptytypesandcaselesstypes.In-formallywesaythatanemptytypeisatypewithnoclosedinhabitants,whereasacaselessdatatypeisatypewithnoconstructorheadedopenin-habitants.Forinstance,?iscaseless,while?0isnot:data?:Setwheredata?0:Setwhere 40CHAPTER2.PATTERNMATCHING Wecannowgivetherulesforcheckingaclauseinafunctionde nition.WewriteCheckClause(fprhs:�!A)forthecheckingoffprhsagainstthetype�!A.CheckLhs(p:�)=):!�`e"A;v CheckClause(fp=e:�!A)Check

34 Lhs(p:�)=):!�8i:
Lhs(p:�)=):!�8i:`Caseless((xi)) CheckClause(fp\jx:�!A)Tosavetheuserfrominventingnamesforrefutedvariablesweextendthesyntaxofpatternswithaspecialpattern;,themeaningofwhichisananonymousvariablethatisimplicitlyrefutedintherighthandside4.Forinstance,f:(n:Nat)!sucn6zero!(A:Set)!Afn;Aistheusersyntaxforf:(n:Nat)!sucn6zero!(A:Set)!AfnxA\jx2.2CoveragecheckingInpreviouswork[Coq92,GMM06]de nitionshavebeenrestrictedtonon-overlappingpatternscorrespondingtoacoveringoftheargumentcontext.Inthisworkwehaverelaxedthisrequirementand,sofar,onlyrequiredthattheclausesofade nitioncanbeobtainedbyourrelaxedformofcontex

35 tsplitting.Thismeansthatweallowoverlappi
tsplitting.Thismeansthatweallowoverlappingclauses.Forinstance, t :Nat!Nat!Natxtzero=xzeroty=ysucxtsucy=suc(xty)wherethe rsttwoclausesoverlap,or == :Nat!Nat!Bool 4Theconcretesyntaxfor;inAgdais(). 42CHAPTER2.PATTERNMATCHING fnmx(neqbsucmc)=:::fbsuc(dblm)cbsuc(suc(dblm))c(even(sucm))eq=:::Inordertoobtainthesecondclauseitisnecessaryto rstsplitonx,butsincethe rstclauseonlysplitsonpthatiswhatouralgorithmwillstartwith.Intheeqcasewewillthenhavethecontext(n:Nat)(x:Even(sucn))wherewewouldliketosplitonx.Thisisnotpossiblesinceuni cationgivesupondblm=sucn.Ratherthanreportanerrorinthiscase,whichiswhatwedo,onecouldimaginebacktrackingandtry

36 ingtosplitinadi erentorder.Thedrawba
ingtosplitinadi erentorder.Thedrawbackwiththisapproachisthatitwillbeveryhardfortheusertopredictwhattheresultingcoveringwillbe.Withourapproachthisismucheasier.AnotheroptionisofcoursetogiveuponoverlappingpatternsandusethealgorithmoutlinedbyCoquand[Coq92],butaswehaveseenoverlappingcasescanbequitehandyattimes.Anotherobservationisthatwiththisalgorithmitisnotpossibletorecre-ateallsplittings.Considerthefollowingversionofthemajorityfunction:majxfalsefalse=falsemajxtruefalse=xmajfalsextrue=xmajtruextrue=trueThisversioncorrespondsexactlytothecoveringobtainedby rstsplittingonthethirdargumentandtheninthefalsecasesplittingonthesecondargumentandi

37 nthetruecaseonthe rstargument.Therei
nthetruecaseonthe rstargument.Thereis,however,nowayofreorderingtheclausestohaveouralgorithmstartbysplittingonthethirdargument.Ontheotherhand,itiseasytogetthisbehaviourbyintroducingtwohelperfunctions,sowehavenotlostanyexpressivity.2.2.1CoveragealgorithmIfMatch(p;v)?=)thenthereisanon-emptysequenceofneutraltermsinvwhicharebeingmatchedagainstconstructorpatterns,andhencecausethematchingtogetstuck.WedenotethesetermsbyBlockers(p;v).Nowwede neaclauseCforafunctionf:�!Atobeacontext,acontextmapping:!�,andarighthandside`rhs:A.Weleavethecontextimplicit,sinceitcanbededucedfrom.Giventhe

38 listofclausesprovidedbytheuser(whichhave
listofclausesprovidedbytheuser(whichhavebeendeemedproperclausesbythetypechecker)wecomputeanewsetofclausescorrespondingtoacoveringoftheargumentcontext.WewriteCovering(C;:!�)=)C0where 44CHAPTER2.PATTERNMATCHING thesecondcasematchingagainstthe rstclausefails,butmatchingagainsttheothertwoclausesisinconclusive.Henceweapplythe(Split)rulesplit-tingalongxobtainingtheneighbourhoods(aftercompositionwith2)3=zero;(sucy):(y:Nat)!(xy:Nat)4=(sucx);(sucy):(xy:Nat)!(xy:Nat)Now3matchesthesecondclausewiththesubstitution[y:=sucy]and4matchesthethirdclausewiththeidentitysubstitutionsoweproducetheclauseshzero(suc

39 y);sucyiandh(sucx)(sucy);sucyi.Theresult
y);sucyiandh(sucx)(sucy);sucyi.Theresultisthefollowingcovering:xtzero=xzerotsucy=sucysucxtsucy=suc(xty)2.2.2UniquenessofidentityproofsAsmentionedinSection1.5.2thepatternmatchingpresentedinthissectioncanbereducedtoeliminationrulesprovidedwehaveuniquenessofidentityproofs(theKaxiom[HS94]).ThiswasshownbyMcBride[McB99,MM04a,GMM06]andthisishowpatternmatchingistreatedinEpigram[McB07].ToseewheretheKaxiomisusedletuswalkthroughthetypecheckingofitsde nitionbypatternmatching.RecalldataId(A:Set)(x:A):A!Setwherere :IdAxxTosimplifymattersweassume(A:Set)(x:A)(P:IdAxx!Set)andde neK:(pr:Pre )(p:IdAxx)!PpKprre =prCheckingthelefthandsideofthisde ni

40 tionwillinvolveasinglesplittingofthecont
tionwillinvolveasinglesplittingofthecontext(pr:Pre )(p:IdAxx)alongpwiththeexpectedconstructorre .ThederivationisIdAx:A!Setre A;x:IdAxx;;(pr:Pre )`Unify(x=x:A)=)id:(pr:Pre )!(pr:Pre ) Split(pr;re ;(pr:Pre )(p:IdAxx))=)[p:=re ]:(pr:Pre )!(pr:Pre )(p:IdAxx) 46CHAPTER2.PATTERNMATCHING f0p01q1=e1:::f0p0nqn=enandwecheckthatthisconstitutesavalidde nition.Itisimportanttocheckthattheabstractedtypeiswell-formed,sincethisisnotnecessarilythecase.Forinstance,abstractingoverthe rstprojectionofadependentpairmightnotbewell-typedwithoutalsoabstractingoverthesecondprojection,sincethe rstprojectionoccursinthetypeofthesecondprojection.Toa

41 bstractmorethanoneexpressionatoncetheyar
bstractmorethanoneexpressionatoncetheyareseparatedbybars,likeso:many:(x:(n:Nat)(n6zero))!Natmanyxwith1xj2xmanyxjbzerocjleqZero=zero2.3.1ExamplesFilteringlistsAbstractingsyntacticoccurrencesoftheanalysedexpressioncomesinveryhandywhenreasoningaboutfunctionsde nedbywith.Considerthe lterfunctionwhichremovesallelementsnotsatisfyingagivenpredicatefromalist.dataList(A:Set):Setwhere":ListA :: :A!ListA!ListA lter:fA:Setg!(A!Bool)!ListA!ListA lterp"=" lterp(x::xs)withpx lterp(x::xs)jtrue=x:: lterpxs lterp(x::xs)jfalse= lterpxsSupposewewanttoprovethatthe lteredlistisasublistoftheoriginallist,i.e.th

42 atallelementsofthe lteredlistappears
atallelementsofthe lteredlistappearsintheoriginallistinthesameorder.Wemightde nedata  fA:Setg:ListA!ListA!Setwherestop:""keep:fx:Agfxsys:ListAg!xsys!(x::xs)(x::ys)skip:fy:Agfxsys:ListAg!xsys!xs(y::ys)sublist:fA:Setg(p:A!Bool)(xs:ListA)! lterpxsxssublistp"=stop 48CHAPTER2.PATTERNMATCHING TheparityofanaturalnumberWementionedabovethatthewithconstructcanbeusedtoemulatenon-standardpatternmatching.Hereisanexamplewhichletsyoumatchonanaturalnumberbeingeither2kor2k+1forsomek.We rstde neaviewdatatypeParitywithoneconstructorforeachofourtwocases.dataParity:Nat!Setwhereeven:(k:Nat)!Parity(2&

43 #3;k)odd:(k:Nat)!Parity(2k+1)Thenext
#3;k)odd:(k:Nat)!Parity(2k+1)ThenextstepistoshowthatanynumbersupportstheParityview.Notehowweusetheviewintherecursivecase.parity:(n:Nat)!Paritynparityzero=evenzeroparity(sucn)withparitynparity(sucb2kc)jevenk=oddkparity(sucb2k+1c)joddk=even(k+1)Nowwecan,forinstance,de nethefunctionhalfveryelegantly.half:Nat!Nathalfnwithparitynhalfb2kcjevenk=khalfb2k+1cjoddk=kTheconceptofviewsinthisformwasintroducedbyMcBrideandMc-Kinna[MM04a]andtheytakeitonestepfurther,allowingyoutoomitthepatternsfortheviewdatatype. 50CHAPTER3.METAVARIABLES theconstraintsintherightorder,andtofailassoonasanequalityisinvalid,sincewelltypednessofaconstrain

44 tmaydependonpreviousconstraintsbeingsati
tmaydependonpreviousconstraintsbeingsatis ed.Forrepresentingproofsearchintheseframeworksitisconvenienttoex-tendthenotionoftermswithmetavariablesthatstandsforyetundeterminedterms(proofs).Metavariablesarealsousefulforstructureediting,asplace-holdersforinformationtobe lledinbytheuser.Inthispaperwewillhoweverfocusontypereconstructionwheremetavariablesareusedforrep-resentingomittedinformationthatcanberecoveredfromtypingconstraintsthroughuni cation.Whenaddingmetavariables,equalitycheckinggetsmorecomplicated,sincewecannotalwaysdecidethevalidityofanequality,andwemaybeforcedtokeepitasaconstraint.Thisiswell-knowninhigherorderuni ca-ti

45 on[Hue75]:theconstraint?0=0hastwosolutio
on[Hue75]:theconstraint?0=0hastwosolutions?=x:xand?=x:0.ThisappearsalsointypetheorywithconstraintsoftheformF?=BoolwhereFisde nedbycomputationrules.Thefactthatwetypecheckmoduloyetunsolvedconstraintscanleadtoill-typedterms.Forinstance,considerthetype-checkingproblemg:g0:((x:F?)!F(:x))!Natwhere?:Bool0:NatF:Bool!SetFfalse=NatFtrue=BoolFirstwecheckthat((x:F?)!F(:x))!Natisawell-formedtype,whichgeneratestheconstraintF?=Bool,sincetheterm:xforcesxtobeoftypeBool.Checkingg:g0:((x:F?)!F(:x))!NatthengeneratestheconstraintsF?=NatF(:0)=Natwhichcontainsanill-typedterm.Thisproblemhassomenegativeconsequenceforthetypecheckingal-gorithm

46 .Withdependenttypes,verifyingconvertibil
.Withdependenttypes,verifyingconvertibilitybetweentwotermsreliesonnormalisingtheseterms,whichisonlysafeifthesetermsarewell-typed.But,aswehaveseen,inpresenceofmetavariables,wemaynotbesurethatthesetermsarewelltyped,andthus,thetypecheckermayloop.Itisstillthecasehoweverthatifallconstraintscanbesolvedwehaveacor-rectsolution;sowehavesomeformofpartialcorrectnessandthisisindeed 52CHAPTER3.METAVARIABLES logic.InSection3.7wediscusstheissuesinvolvedinextendingthisworktoUTTandde nitionsbypatternmatching.SyntaxThesyntaxofMLFisgivenbythefollowinggrammar.A;B::=Setjsj(x:A)!Atypess;t::=xjcjstjx:Mterms�;::="j�;x:Acontexts::="j;

47 c:Aj;c:A=ssignaturesWeadoptthesamesy
c:Aj;c:A=ssignaturesWeadoptthesamesyntacticconventionsasforUTT(seeSection1.3).Thesignaturecontainsaxiomsandnon-recursivede nitions.JudgementsThetypesystemofMLFispresentedinsixmutuallyde-pendentjudgementforms.`isavalidsignature�`valid�isavalidcontext�`AtypeAisavalidtypein��`M:AshastypeAin��`A=BAandBareconvertibletypesin��`M=N:AsandtareconvertibletermsoftypeAin�Thetypingrulesfollowsstandardpresentationsoftypetheory[NPS00]andcanbeobtainedbysuitablyrestrictingthetypingrulesforUTTfromSection1.3.PropertiesWhenprovingthepropertiesofthetypecheckingalgorithminSection3.3wetaket

48 hefollowingpropertiesofMLFforgranted. Le
hefollowingpropertiesofMLFforgranted. Lemma3.2.1(Uniquenessoftypes). �`cs:A�`cs:B �`A=B Lemma3.2.2(Constructorinversion). �`c:!B�`cs:B0 �`s: 54CHAPTER3.METAVARIABLES hiLookup(c:A)=)hiifc:A2hiAddMeta( :A)=)h; :Aiif =2hi :=s=)h1; :A=s;2iif=1; :A;2hiAddConst(p:A=swhenC)=)h;p:A=swhenCiifp=2hiInScope (s)=)hiif=1; :A;2andc2simpliesc21 Figure3.1:Operationsonthesignature writep:A=swhenCforaguardedconstantpoftypeA,withcandidatevalues,andguardC.WehavethecomputationrulethatpcomputestoswhenCis

49 theemptyset.Weusethenamingconventionthat
theemptyset.Weusethenamingconventionthatlowercasegreekletters ; ;:::standforconstantsrepresentingmetavariablesandpandqforguardedconstants.3.3.1OperationsonthesignatureAllrulesworkonasignature,containingpreviouslyde nedconstants,metavariables,andguardedconstants.Inotherwords,wecanwritealljudge-mentsontheformhiJ=)h0i.Tomaketheruleseasiertoreadwe rstde neasetofoperationsreadingandmodifyingthesignatureandwhenpresentingthealgorithmsimplywriteJforthejudgementabove.Inruleswithmultiplepremissesthesignatureisthreadedtop-down,left-to-right.Forinstance,P1P2P3 Jisshort-handforh1iP1=)h2ih2iP2=)h3ih3iP3

50 =)h4i h1iJ=)h4iWeintroducean
=)h4i h1iJ=)h4iWeintroduceanoperationLookup(c:A)tolookupthetypeofaconstantinthesignature.Tomanipulatemetavariablesweintroduce:AddMeta( :A)whichaddsanewmetavariable oftypeAtothesignature,and :=swhichinstantiates tos.ForguardedconstantsweaddtheoperationAddConst(p:A=swhenC)toaddanewguardedconstanttothesignature.InSection3.3.2weexplaintherulesforsolvingtheconstraintsofaguardedconstant.WealsointroduceanoperationInScope (s)tocheckthatsisinscopeatthede nitionsiteof (toensurethat canbeinstantiatedtos).Detailedde nitionsoftheoperationscanbefoundinFigure3.1. 56CHAPTER3.METAVARIABLES �`etype;A �`Se

51 ttype;Set�`e1type;A�;x:A`e2type;B
ttype;Set�`e1type;A�;x:A`e2type;B �`(x:e1)!e2type;(x:A)!B�`e"Set;s �`etype;s Figure3.2:Checkingforwell-formedtypes �`e#A;s x:A2� �`x#A;xLookup(c:A) �`c#A;c�`e1#(x:A)!B;s�`e2"A;t �`e1e2#B[x:=N];st Figure3.3:Typeinferencerules �`e"A;s �;x:A`e"B;s �`x:e"(x:A)!B;x:MAddMeta( :�!A) �` "A; ��`e#B;s�`A'B;; �`e"A;s�`e#B;s�`A'B;C6=;AddConst(p:�!A=�:swhenC) �`e"A;p� Figure3.4:Typecheckingrules 58CHAPTER3.METAVARIABLES �`s't"A;C �;x:A`sx'tx"B;C �`s't"(x:A)!B;Cs!whnfs0t!whnft0�`s0'0t0"A;C �`s't"A;C Figure3.6:Termconversionrules �`s'0

52 t"A;C h:!A�`s't";C
t"A;C h:!A�`s't";C �`hs'0ht"A[:=s];C �`ps'0t"A;f�`ps=t:Agxdistincts!nfs0FV(s0)xInScope (x:s0) :=x:s0 �` x'0s"A;; Figure3.7:Conversionrulesforweakheadnormalforms. TermconversionrulesCheckingconversionoftermsisdoneonweakheadnormalforms.Theonlyrulethatisappliedbeforeweakheadnormalisationisthe-ruleshowninFigure3.6.InMLFfunctiontypesarenottermssoametavariablecanneverbeinstantiatedtoafunctiontype.WhenextendingthealgorithmtoUTT,wherethisisthecase,wehavetocheckifthetypeisametavariable,andifsopostponetheconstraint,sincewedonotkn

53 owwhetherornotthe-ruleshouldbeappli
owwhetherornotthe-ruleshouldbeapplied(seeSection3.7.2).TheconversionrulesforweakheadnormalformsareshowninFigure3.7.Theweakheadnormalformswecomparewillbeofatomictypeandsotheyareoftheformhswheretheheadhisavariable,constant,metavariable,orguardedconstant.Ifbothtermshavethesamevariableorconstantheadh:!Awecomparetheargumentsin.NotethatitisnotnecessarytocheckthatthegiventypeisindeedA[:=s]|thisisguaranteedbythefactthattheconstraintiswell-typed.Iftheheadsaredi erentconstantsorvariablesconversioncheckingfails. 60CHAPTER3.METAVARIABLES ingcaseiswhencomparingthe rstargumentsresultsinsomeunsolvedconstraints.Ifthevalue

54 ofthe rstargumentisusedinthetypesofl
ofthe rstargumentisusedinthetypesoflaterarguments(x2FV())wehavetostopandproduceaconstraintsincethetypesofsandtdi er.Ifontheotherhandthetypesoflaterargumentsareindependentofthevalueofthe rstargument,wecanproceedandcomparethemwithoutknowingwhetherthe rstargumentsareconvertible.ConstraintSolvingSofar,wehavenotlookedatwhenorhowtheguardsofaconstantaresim-pli edorsolved.Inprinciplethiscanbedoneatanytime,forinstanceasaseparatephaseaftertypechecking.Inpractice,however,itmightbeabet-terideatointerleaveconstraintsolvingandtypechecking.InSection3.5weprovethatthiscanbedonesafely.Constraintsolvingamountstorecheckingtheg

55 uardofaconstantandreplacingitbytheresult
uardofaconstantandreplacingitbytheresultingconstraints.3.4ExamplesInthissectionwelookatafewexampleswhichillustratetheworkingsofthetypechecker.AsimpleexampleFirstletuslookataverysimpleexample.ConsiderthesignaturegivenbyNat:Set0:Natid:(A:Set)!A!A=Ax:x :SetcontainingasetNatwithanelement0,apolymorphicidentityfunctionid,andametavariable oftypeSet.Nowwewanttocomputessuchthat`id 0" ;sTodothisoneoftheconversionruleshastobeapplied,sothetypechecker rstinfersthetypeofid 0.`id#(A:Set)!A!A;id` "Set; `0#Nat;0 :=Nat `0" ;0 `id 0# ;id 0 62CHAPTER3.METAVARIABLES Whatcouldgowrong?Sofarwehaveonlylookedattypecorrect

56 examples,wherenothingbadwouldhavehappene
examples,wherenothingbadwouldhavehappenedifwehadnotintroducedguardedconstantswhenwedid.Thefollowingexampleshowshowthingscangowrong.TakethesignatureNat:Set;0:Nat.Nowaddtheperfectlywell-typedidentityfunctioncoerce:coerce:(F:Nat!Set)!F0!F0=Fx:xForanywell-typedtermt:BandtypeA,coerce twillsuccessfullycheckagainstA,resultingintheconstraints 0=BandA= 0,noneofwhichcanbesolved.Ifwedidnotintroduceguardedconstantscoerce twouldreducetotandhencewecouldusecoercetogiveanarbitrarytypetoaterm.Forinstancewecantype2!:(Nat!Nat)!Nat=x:x(coerce x) :Nat=!(coerce !)where,withoutguardedconstants, wouldreducetothenon-normalising-term(x:xx

57 )(x:xx).Withouralgorithmnewguardedc
)(x:xx).Withouralgorithmnewguardedconstantsareintroducedforfortheargumenttocoerceandfortheapplicationofcoerce.Sothetypecorrectapproximationof wouldbe!pwherep=coerce qwhen 0=Nat!Natq=!when(Nat!Nat)!Nat= 03.5ProofofcorrectnessThecorrectnessofthealgorithmreliesonthefactthatweonlycomputewithwell-typedterms.Thisguaranteestheexistenceofnormalformsandhenceensurestheterminationofthetypecheckingalgorithm.Theproofwillbedoneintwostages: rstweprovesoundnessintheabsenceofconstraintsolving,andthenweprovethatconstraintsolvingissound.3.5.1SoundnesswithoutconstraintsolvingThereareanumberofthingsweneedtoprove:thattypecheckingpreserveswel

58 l-formedsignatures,thatitproduceswell-ty
l-formedsignatures,thatitproduceswell-typedterms,thatconversioncheckingissound,andthatnewsignaturesrespecttheoldsignatures.Un-fortunatelythesepropertiesareallinterdependent,sowecannotprovethemseparately. 2Thisonlytypechecksifweallowmetavariablestobeinstantiatedtofunctiontypes,whichisnotthecaseinMLF.SeeSection3.7.2foradiscussiononhowtoextendthealgorithmtohandlethis 64CHAPTER3.METAVARIABLES producewell-formedextensionsofthesignature.Moreprecisely,thefollowingrulesareadmissible:hi�`etype;A=)h0i�`jjvalid 0extends^�`j0jAtypehi�`e"A;s=)h0i�`jjAtype 0extends^�`j0js:Ahi�`e#A;s

59 =)h0i�`jjvalid 0extends&#
=)h0i�`jjvalid 0extends^�`j0js:Ahi�`A'B;C=)h0i�`jjAtype�`jjBtype 0extends^`j0jCok^(C=;=)�`j0jA=B)hi�`s't"A;C=)h0i�`jjs:A�`jjt:A 0extends^`j0jCok^(C=;=)�`j0js=t:A)Thestatementsforweakheadnormalformconversion(�`s'0t"A;C)andtermsequenceconversion(�`s't";C)areequivalenttothatoftermconversion. Proof. Byinductiononthederivation.Someinterestingcases:  Inthetypeconversioncaseforfunctionspaceswherethedomainspro-duceconstraints,wehavetousethesubstitutionlemma(Lemma3.2.3)andstrengthening(Lemma3.2.5).  Intheter

60 mconversioncasewherethetermsareweakheadn
mconversioncasewherethetermsareweakheadnormalisedweneedsubjectreductionforweakheadnormalisation(Lemma3.2.4).  Whencheckingconversionoftermswiththesameheadweneedaninversionprincipleforapplication(Lemma3.2.2).  Themostinterestingcaseisthemetavariableinstantiationcase,soletusspellthatoutinmoredetail.Theinstantiationruledoesnotproduceanyconstraints,sotheonlythingwehavetoproveisthatitconstructsavalidextensionofthesig-nature.Thisfollowsfromthesignaturere nementlemma(Lemma3.5.3)whichcanbeappliedifweprovethatif=1; :B0;2then`j1jx:s:B0. 66CHAPTER3.METAVARIABLES Remark3.5.9. IfCensuresJinand0extends&

61 #6;thenCensuresJin0.Notethatinthecas
#6;thenCensuresJin0.Notethatinthecasewhen0invalidatesCtheremarkisvacuous|afalseconstraintensuresanything. De nition3.5.10(Consistentsignature). Asignatureissaidtobecon-sistentifforanypwithequalto1;p:A=swhenC;2itisthecasethatCensures`s:Ain1.Inordertoprovethattypecheckingpreservesconsistency,we rstneedtoknowthattheconstraintsweproducearesound. Lemma3.5.11(Soundnessofgeneratedconstraints). Theconstraintsgen-eratedduringconversioncheckingensuresthatthecheckedtermsarecon-vertible.Forinstance,if�`A'B;C,thensolvingCguaranteesthat�`A=BinMLF.Moreprecisely,  �`Atype^�`Btype^hi�`A'B;C

62 =)h0i=)Censures�`A=Bin0 
=)h0i=)Censures�`A=Bin0  �`s:A^�`t:A^hi�`s't"A;C=)h0i=)Censures�`s=t:Ain0 Proof. Againwehighlightsomeinterestingcases.  Theonlynon-trivialcaseisthecaseofconversionforfunctiontypeswhereanewconstantpisintroduced.Thereweneedtoprovethatforasignature0whichsolvestheconstraintsgeneratedbycomparingA1withA2andB1withB2[x:=p�x]itholdsthat�;x:A1`j0jB1=B2giventhat�;x:A1`j0jB1=B2[x:=p�x]Since2solvesA1'A2ithasanemptyguardforp,sop�xreducestoxandwearedone.  InthecasewhereCisknown(forinstance,intheruleforblockedterms),wecanapplysoundnessofconversionchecking(Theorem3.5.5)

63 toget`j0jC. Lemma3.5.12. Re neme
toget`j0jC. Lemma3.5.12. Re nementpreservesconsistentsignatures.Moreprecisely,if  `1s:A 68CHAPTER3.METAVARIABLES Lemma3.5.14(Constraintsolvingissound). Ifisconsistentandsolvingtheconstraintsyieldsasignature0,then0isconsistentand0extends. Proof. FollowsfromTheorem3.5.5,Lemma3.5.11,andLemma3.5.13. Fromthisfollowsthatwecanmixtypecheckingandconstraintsolvingfreely,sowecanaddaconstraintsolvingruletothetypecheckingalgorithm.Inordertoobtainoptimalapproximationswehavetosolveconstraintsea-gerly,i.e.assoonasametavariablehasbeeninstantiated.3.5.3RelatinguserexpressionsandcheckedtermsAnimportantpropertyofthetypechec

64 kingalgorithmisthatthetypecorrecttermspr
kingalgorithmisthatthetypecorrecttermsproducedcorrespondtotheexpressionsbeingtypechecked.Thecor-respondenceisexpressedbystatingthattheonlyoperationsthetypecheckerisallowedwhenconstructingatermisreplacingan byaterm(re nement)andreplacingatermbyaguardedconstantwithanappropriatecandidatevalue(approximation). De nition3.5.15(Approximation). Atermsapproximatess0ifscanbeobtainedbyreplacingsubtermstofs0byguardedconstantspxwhosecandi-datevaluesapproximatest. De nition3.5.16(Re nement). Atermsisare nementofauserexpres-sioneifscanbeobtainedbyreplacingthe inebyconcreteterms. Lemma3.5.17. If�`e"A;sthensapproximatesare ne

65 mentofe.Thispropertyispreservedwhenunfol
mentofe.Thispropertyispreservedwhenunfoldinginstantiatedmetavariablesandguardedconstantsins. Proof. Byinductionoverthederivation. 3.5.4MainresultWenowprovethemainsoundnesstheoremstatingthatifallmetavariablesareinstantiatedandallguardssolved,thenthetermproducedbythetypechecker(extendedwithconstraintsolving)isvalidintheoriginalsignatureafterunfoldingthede nitionsofthemetavariablesandguardedconstantsintroducedduringtypechecking. Theorem3.5.18(Soundnessoftypechecking). Ifisawell-formedMLFsignatureandhi�`e"A;s=)h0i,thenifallmetavariableshavebeeninstantiatedandallguardsareemptyin0,then�`s:Awhereisthesubstit

66 utionunfoldingthemetavariablesandconstan
utionunfoldingthemetavariablesandconstantsin0.Moreover,sisare nementofe. 70CHAPTER3.METAVARIABLES Thenewtypecheckingandinferencerulesarethefollowing.�;x:A`e"B;s �`fxg:e"fx:Ag!B;fxg:s�;x:A`e"B;s �`e"fx:Ag!B;fxg:se6=fxg:e0x:A2��`A@e#B;s �`xe#B;xsLookup(x:A)�`A@e#B;s �`ce#B;csAscanbeseen,whencheckinganexpressionagainstanimplicitfunctiontypeanimplicitlambdaisinsertedifneeded.Tocheckafunctionapplicationweintroduceanewjudgementform�`A@e#B;swiththemeaningthatafunctionoftypeAcanbeappliedtotheargumentseresultinginatermoftypeB.Theterm

67 ssarethetypecorrectapproximationsof
ssarethetypecorrectapproximationsofthearguments.Therulesbasicallyinsertsmetavariablesintoewhenevernec-essary,andotherwisechecksthattheexpressionshavetheexpectedtypes.Onethingtonoteisthatisthereareimplicitfunctionspacesleftoverattheendtheyareinstantiatedwithmetavariables.Therulesare �`A@e#B;s �`e"A;s�`B[x:=s]@e#B0;s �`(x:A)!B@e;e#B0;s;s�`e"A;s�`B[x:=s]@e#B0;s �`fx:Ag!B@feg;e#B0;s;s�`fx:Ag!B@f g;e;e#B0;s �`fx:Ag!B@e;e#B0;s�`fx:Ag!B@f g#B0;s �`fx:Ag!B@"#B0;s �`A@"#A;"A6=fx:A1g!A23.7ExtendingtheunderlyingtheoryThealgorit

68 hmpresentedinthischapterworksonthelogica
hmpresentedinthischapterworksonthelogicalframeworkMLFextendedwithmetavariables.Thisframeworklacksanumberoffeatures 72CHAPTER3.METAVARIABLES 3.7.2FunctiontypesastermsAllowingfunctiontypesastermsposesabiggerchallenge.Thismeansthatmetavariablescanbeinstantiatedwithfunctiontypes,andsoeverytimeweexpectafunctiontypewehavetoconsiderthepossibilitythatweencounterametavariable.Thishappenswhentypecheckingaandinferringthetypeofanapplication.Inthesecasesweknowthatthetypehastobeafunctiontype,soitissafetoinstantiatethemetavariablethusly.Incasethemetavariableisnotappliedtodistinctvariablesthetypecheckingproblemhastobepostponed,awaitinganinstantiationo

69 fthemetavariable.Thismeansthatwehavetoex
fthemetavariable.Thismeansthatwehavetoextendthesignaturewithconstantsthatarewaitingtobetypechecked.Wealsohavetotakeintoaccountthatmetavariabletypesmightappearwhenconversioncheckingterms.Inthiscaseconversioncheckinghastobepostponed,sincewedonotknowwhat-rulestoapply.3.7.3UniversehierarchyInthepresenceofauniversehierarchythelogichastobeextendedbylevelmetavariables.Thisisbecausewhenweinstantiateametavariablewithafunctiontypeasdescribedabove,wedonotknowwhatlevelsthenewmetavariablesshouldliveat.Itisunclearatthispointhowtohandlethein-teractionbetweenuniversesubtypingandlevelmetavariables,sincethiswillintroduceinequalityconstraintsbetweentheva

70 riables,ratherthanequal-ityconstraints.T
riables,ratherthanequal-ityconstraints.Thecurrentimplementationturnsunsolvedinequalitiesintoequalityconstraints,whichwillnecessarilyexcludevalidsolutions.Theal-ternativeofkeepingtheinequalityconstraintsandattemptingtosolvethemgloballyaftertypecheckingispotentiallyverycostly.3.7.4PatternmatchingIfwehavede nitionsbypatternmatching,reductiontoweakheadnormalformmightbeblockedbyanuninstantiatedmetavariable.Forinstance: cannotbereducedtoweakheadnormalfor::Bool!Bool:true=false:false=trueSinceconversioncheckingisdoneonweakheadnormalformswegenerateaconstraintwhenencounteringablockedterm. 74CHAPTER3.METAVARIABLES 76CHAPTER4.MODULESYSTEM decl:

71 :=[private]moduleMwheredeclsj[privat
:=[private]moduleMwheredeclsj[private]moduleM1=M2termsmodsjopenM[public]modsjimportM1[asM2]modsj[private]defnmod::=using(atom;:::)jhiding(atom;:::)jrenaming(atomtoname;:::)atom::=namejmodulename Figure4.1:Modulesystemsyntax (functors)mappingmodulesimplementingaparticularinterfacetoamoduleimplementingadi erentinterface.AlthoughthemodulesystemofCoqismuchmorepowerfulthanthemodulesystempresentedhere,itisalsosigni cantlymorecomplex.HarperandPfenning[HP98]presentsamodulesystemforLFinthesamespiritasthemodulesystemofCoq,andCourant[Cou07]givesatheoreticalfoundationforthiskindofmodulesystemsinthecontextofPureTypeSystems[Bar92a].Whilew

72 earetryingourbesttodecouplemodulesfromre
earetryingourbesttodecouplemodulesfromrecordtypes,Pollacktakestheoppositeapproach[Pol00,CPT]andextendsrecordtypeswithmoremodulesystemlikefeatures,suchasmanifest elds.4.2DescriptionThesyntaxofthemodulesystemisgiveninFigure4.1.Weleavethesyntaxofde nitionsopen,sinceitisnotimportantforthemodulesystem.Theexamplesusesomesuitablemade-upsyntax,orinthecaseoftheexampleinSection4.4,Agdasyntax(seeChapter5).Firstletusintroducesometerminology.Ade nitionisasyntacticcon-structionde ninganentitysuchasafunctionoradatatype.Anameisastringusedtoidentifyde nitions.Thesamede nitioncanhavemanynamesandatdi erentpointsintheprogramitwillha

73 vedi erentnames.Itmayalsobethecaseth
vedi erentnames.Itmayalsobethecasethattwode nitionshavethesamename.Inthiscasetherewillbeanerrorifthenameisused.Themainpurposeofthemodulesystemistostructurethewaynamesareusedinaprogram.Thisisdonebyorganisingtheprograminanhierarchicalstructureofmoduleswhereeachmodulecontainsanumberofde nitionsand 78CHAPTER4.MODULESYSTEM mightshowupingoalsanderrormessages.Considerthefollowing(con-trived)examplemoduleMainwheremoduleAwhereprivateIsZero0:Nat!SetIsZero0zero=�IsZero0(sucn)=?IsZero:Nat!SetIsZeron=IsZero0nopenAprf:(n:Nat)!IsZeronprfn=?0Thetypeofthegoal?0isIsZeronwhichnormalisestoIsZero0n.Theques-tionishowtodisplaythisnormalformtoth

74 euser.Atthepointof?0thereisnonameforIsZe
euser.Atthepointof?0thereisnonameforIsZero0.OneoptioncouldbetrytofoldthetermandprintIsZeron.Thisisaveryhardproblemingeneral,soratherthantryingtodothiswemakeitcleartotheuserthatIsZero0issomethingthatisnotinscopeandprintthegoalas:Main:A:IsZero0n.Theleadingdotindicatesthattheentityisnotinscope.Thesametechniqueisusedforde nitionsthatonlyhaveambiguousnames.Ine ectusingprivatede nitionsmeansthatfromtheuser'sperspectivewedonothavesubjectreduction.Thisisjustanillusion,however|thetypecheckerhasfullaccesstoallde nitions.4.2.2Namemodi ersAnalternativetomakingde nitionsprivateistoexert nercontroloverwhatnamesareintroducedwhe

75 nopeningamodule.Thisisdonebyqualifyingan
nopeningamodule.Thisisdonebyqualifyinganopenstatementwithoneormoreofthemodi ersusing,hiding,orrenaming.Youcancombinebothusingandhidingwithrenaming,butnotwitheachother.Thee ectofopenAusing(x)renaming(ytoz)istointroducethenamesxandzwherexireferstothesamede nitionasA:xiandzireferstoA:yi.Notethatifxandyoverlaptherewillbetwonamesintroducedforthesamede nition.Wedonotpermitxandztooverlap.Theotherformsofopeningarede nedintermsofthisone.LetAdenoteallthe(public)namesinA.ThenopenArenaming(ytoz) 80CHAPTER4.MODULESYSTEM moduleSort(A:Set)( 6 :A!A!Bool)whereinsert:A!ListA!ListAinse

76 rtx"=x::"insertx(y::ys)withx6yinsertx(y:
rtx"=x::"insertx(y::ys)withx6yinsertx(y::ys)jtrue=x::y::ysinsertx(y::ys)jfalse=y::insertxyssort:ListA!ListAsort"="sort(x::xs)=insertx(sortxs)Asmentionedparametrisingamodulehasthee ectofabstractingthepa-rametersoverthede nitionsinthemodule,sooutsidetheSortmodulewehaveSort:insert:(A:Set)( 6 :A!A!Bool)!A!ListA!ListASort:sort:(A:Set)( 6 :A!A!Bool)!ListA!ListAForfunctionde nitions,explicitmoduleparameterbecomeexplicitargu-mentstotheabstractedfunction,andimplicitparametersbecomeimplicitarguments.Forconstructors,however,theparametersarealwaysimplicitarguments.Thisisaconsequenceofthefactthatmoduleparametersareturnedintodatatypeparameter

77 s,andthedatatypeparametersareimplicitarg
s,andthedatatypeparametersareimplicitargumentstotheconstructors.Italsohappenstobethereasonablethingtodo.SomethingwhichyoucannotdoinCoqistoapplyasectiontoitsar-guments.Weallowthisthroughthemoduleapplicationstatement.Inourexample:moduleSortNat=SortNatleqNatThiswillde neanewmoduleSortNatasfollowsmoduleSortNatwhereinsert:Nat!ListNat!ListNatinsert=Sort:insertNatleqNatsort:ListNat!ListNatsort=Sort:sortNatleqNatThenewmodulecanalsobeparameterised,andyoucanusenamemodi- erstocontrolwhatde nitionsfromtheoriginalmoduleareappliedand 82CHAPTER4.MODULESYSTEM importMopenMSometimesthenameofanimportedmoduleclasheswithalocalmodule.Inthiscaseitispo

78 ssibletoimportthemoduleunderadi eren
ssibletoimportthemoduleunderadi erentname.importMasM0Itisalsopossibletoattachmodi erstoimportstatements,limitingorchang-ingwhatnamesarevisiblefrominsidethemodule.4.3EquipmentforrecordtypesArecordisessentiallyanested-type2,butinordertousethemconvenientlyweneedsomebasictools.Twothingsthatonemightwantaresuitablynamedprojectionfunctionsandsomewayofopeningarecordtobringthe eldsintoscope.Itturnsoutthatusingthemodulesystemwecangetboththingsforthepriceofone.ForarecordtyperecordR:Setwherex1:A1x2:A2[x1]...xn:An[x1:::xn�1]wegenerateaparameterisedmoduleRmoduleRfg(r:R)wherex1:A1x1=1rx2:A2[x1]x2=1(2r)...xn:An

79 [x1:::xn�1]xn=2(:::(2r))The
[x1:::xn�1]xn=2(:::(2r))ThefunctionsinRareexactlytheprojectionfunctionsfortherecordtypeR.Forinstance,wehaveR:x2:fg(r:R)!A2[R:x1r]3.Hereitisclearthatwewanttheparameterstotherecordtobeimplicitregardlessof 2Butwithnameequality.3So,whatinsomelanguagesiswrittenr:x2forr:R,wewriteasR:x2r. 84CHAPTER4.MODULESYSTEM |WewanttheprojectionfunctionstobepartofthismoduleprivateopenmodulePO=PartialOrderpopublic|Wecande nesomederivedfunctions � :A!A!Setx�y=y6x|andprovesomeauxiliarylemmas.Proofsomitted.6�antisym:fxy:Ag!x6y!x�y!x==y==�re :fx:Ag!x==x==�sym:fxy:Ag!x==y!y==x==�trans:fxyz:Ag!x==y!y==z!x==z|W

80 ealsode nethedualpartialorderdualOrd
ealsode nethedualpartialorderdualOrder:PartialOrderAdualOrder=recordf == = == ; 6 = � ;:::gAcommonidiomwhenre-exportingthecontentsofamoduleMappliedtosomeargumentstisprivateopenmoduleM0=MtpublicwhichisequivalenttoprivatemoduleM0=MtopenM0publicThatis,wedeclareaprivatemoduleM0astheapplicationofMtotandthenweexportthecontentsofthismodule.Itmakessensetomaketheintermediatemoduleprivate,sinceweexportitscontentsfromthecurrentmodule.GivenapartialorderoverAandanoperation u :A!A!Awecande newhatitmeansforthistobeasemilattice.Sinceyoucannot,inthecurrentpresentation,applyoropenmodulesinsidethedeclarationofarecordtypewepu

81 tthedeclarationinaparameterisedmodule.Th
tthedeclarationinaparameterisedmodule.ThisallowsustoapplythePartialOrderOpsmoduletoourpartialorderpoandthuswritex6yratherthanPartialOrderOps: 6 poxy.private 86CHAPTER4.MODULESYSTEM openSemiLatticeOpsusing(dualOrder)recordLattice(A:Set):Set1wheresl:SemiLatticeA t :A!A!Aprf:IsSemiLattice(dualOrdersl) t AlatticeoverAisasemilatticeoverAtogetherwithajoinoperationwhichformsasemilatticewiththedualpartialorder.Togetthelawsforjoinwecansimplyrenamethesemilatticelaws:moduleLatticeOpsfA:Setg(L:LatticeA)whereprivatemoduleLL=LatticeLopenmoduleSLL=SemiLatticeOpsLL:slpublichiding(dualOrder)sl0:SemiLatticeAsl0=recordfpo=dualOrderLL:sl; u =LL: t ;prf=LL:prfg

82 openmoduleSLL0=SemiLatticeOpssl0publicus
openmoduleSLL0=SemiLatticeOpssl0publicusing()renaming(6�re to��re ;6�transto��trans;6�antisymto��antisym; u to t ;u�lbLtot�ubL;u�lbRtot�ubR;u�glbtot�lub;u�commutetot�commute;u�assoctot�assoc;u�idemtot�idem)dualLattice:LatticeAdualLattice=recordfsl=sl0; t = u ;prf=SemiLattice:prfLL:slgWecanplaythesametrickwedidwiththedualpartialorderforlattices.Forinstanceifweprovetheleftabsorptionlawxu(xty)==xwegettheduallawxt(xuy)==xsimplybyinstantiatingtheabsorptionlawtotheduallattice. 88CHAPTER4.MODULESYSTEM japplyM1=M2termsjdefnAsbeforeweleavethesyntaxofde nitionsabstract

83 .Theonlypartsofthemodulesystemwhichremai
.Theonlypartsofthemodulesystemwhichremainaretheparameterisedmodulesandthemoduleapplications.Thesecouldalsobetranslatedawaybyperformingthecor-respondingabstractionsandapplicationssyntactically.Thiswouldhowevermeanthattheabstractedtelescopes,themodulearguments,andthetypesofthede nitionwouldbetypecheckedonceforeachmoduleapplicationandde nitionintheappliedmodule,soforperformancereasonswechoosetoleavethemforthetypechecker.4.5.1ScopecheckingstateThescopecheckingalgorithmispresentedinamonadicstyle,workingonastateconsistingofastackofscopes,whereeachscopecorrespondstoamoduleenclosingthedeclarationsbeingscopechecked.Ascopehasanamewhichisthena

84 meofthecorrespondingmoduleandaprivateand
meofthecorrespondingmoduleandaprivateandapublicnamespace.Anamespacemapsnamesofde nitionsandmod-ulestouniquefullyquali ednames.Wedistinguishbetweenthenamestheuserhasforde nitionsandmodules(UDefName,UModuleName)andtheuniquequali ednamesusedinternallybytheimplementation(DefName,ModuleName).WeusexandyforUDefNames,MforUModuleNames,zforwhenbothUName=UDefName[UModuleName,qforDefNames,andQforModuleNames.FortheunionofName=DefName[ModuleNameweusew.Wede neS::="jSscopestack::=hM;nspub;nspriiscopesns::=hx;Minamespacesx2UDefName!SetDefNameM2UModuleName!SetModuleNameThesamenamemightatsomepointrefertos

85 everaldi erentde nitionssoanames
everaldi erentde nitionssoanamespacemapsnamestosetsofuniquenames.Thenameofascopeisnotfullyquali edsotogetthefullyquali ednameofanentityzde nedinthestateSwede neFullNamezSbyFullName:UName!State!NameFullNamez("hM1; ; i:::hMn; ; i)=M1:::::Mn:z 90CHAPTER4.MODULESYSTEM pop :State!Statepop (S2hM;nspub; i)=S(extend (qualifyMnspub)2)Inanamespacequali edbyMallnamesstartwithM.qualify�:UModuleName!NameSpace!NameSpace(qualifyMns)(M:z)=ns(z)(qualifyMns)(z)=;;ifzisnotoftheformM:wTode neanamespace,wespecifyhowtolookupnamesinit.Sincenamespacesareessentiallyfunctionsthisc

86 onstitutesavalidde nition.Toaddnames
onstitutesavalidde nition.Toaddnamespacenstoascopewewriteextend ns.Dependingon thenamespaceisaddedtoeitherthepublicorprivatepartof.Toaddascopetoascopestackbothpartsofareaddedtothetopscopenamespaceindicatedbytheargument .extend :NameSpace!Scope!ScopeextendpubnshM;nspub;nsprii=hM;nspub[ns;nspriiextendprinshM;nspub;nsprii=hM;nspub;nspri[nsiextend :Scope!State!Stateextend h ;nspub;nsprii(S)=Sextend (nspub[nspri)Rememberthatthetop-levelisalwaysamodule,sothescopestackwillneverbeempty.4.5.4Scopemodi ersWe rstde nethee ectofthethreescopemodi ersonanames

87 pacesepa-rately.Notethatmodifyingamodule
pacesepa-rately.Notethatmodifyingamodulenamea ectsallnamesinthatmodule.(Usingxns)(z)=ns(z);ifz2x(Usingxns)(M:z)=ns(M:z);ifmoduleM2x(Usingxns)(z)=;;otherwise(Hidingxns)(z)=ns(z);ifz=2x(Hidingxns)(M:z)=ns(M:z);ifmoduleM=2x(Hidingxns)(z)=;;otherwise(Renaming(xtoy)ns)(yi)=ns(xi)(Renaming(xtoy)ns)(yi:z)=ns(M:z);ifxi=moduleM(Renaming(xtoy)ns)(z)=;;otherwise 92CHAPTER4.MODULESYSTEM scope,whichnowcontainsallthenamesde nedinthemodule,andaddittothenextscopeonthestack.Wealsohavetobindthenameofthede nedmodule.Theoutputisasection.Scopecheckingamoduleapplicationis

88 alittlemoreinvolved.Basicallytode ne
alittlemoreinvolved.Basicallytode neamoduleM1astheapplicationofM2weopenM2intoanewscopenamedM1.However,sincemoduleapplicationsintroducenewde nitionswehavetochangethequali ednamespointingintoM2sothattheypointtoM1instead.�`ScopeCheck( moduleM1=M2termsmods)=Q1 FullNameM1Q2 Lookup(M2)0 �`ScopeCheck()terms0 �0`ScopeCheck(terms)pushM1OpenM2pubmodsRedirect(Q27!Q1)pop bind M1Q1return(applyQ10=M2terms0)OpeningamoduleMisdonebyaddingallnamesM:ztothecurrentscopeasz,possiblyhidingorrenamingsomenames.OpenM mods(S)=Sextend nswherens=ApplyModsmods(MatchM(Smash(S)))whe

89 re(MatchMns)(x)=ns(M:x).Theredirectionof
re(MatchMns)(x)=ns(M:x).Theredirectionofthenamesfromtheappliedmoduleisde nedbyRedirect(Q27!Q1)(S)=Redirect(Q27!Q1)(Redirect(Q27!Q1))(z)=fQ1:qjQ2:q2(z)gForthistobecorrectitisimportantthatthepublicnamesinM2allrefertode nitionsinM2.Thatis,wehavetomakesurethateverytimeweaddanametothepublicnamespaceofamoduleitreferstoade nitionfromthatmodule.Inparticularwehavetotakecarewhenopeningmodulespublicly.Ideallywewouldliketode nethescopecheckingofanopenstatementsimplyasacalltoOpenbutasjustobservedthiswouldnotbecorrectinthecaseofapublicopen.Inthiscasewecreateadummymodulewhichwethenopen.�`ScopeCheck(openMmods)= 9

90 4CHAPTER4.MODULESYSTEM M:id:(X:Set)!X!XM
4CHAPTER4.MODULESYSTEM M:id:(X:Set)!X!XM:idXx=xThejudgementformforcheckingdeclarationsisQ(�)`decl;0andtherulesformodulesandde nitionsareQ(�)`ctx;0Q(�)M(0)`decls;0 Q(�)`sectionQ:Mwheredecls;0;Q:M(�0)Q(�)`e1#Seti;A0=;Q:f:�!AQ(�)`0e2"A;t Q(�)`Q:f:e1=e2;;Q:x:�!A=�:tToeasethepresentationthede nitionruleisforasimpli edformofde -nitionQ:f:A=t.Theprincipleisthesameformoreadvancedformsofde nitions,however.Formoduleapplicationswegeneratenewde nitionsapplyingthede ni-tionsfromtheappliedmodule:applyM0=MNatturnsintoM0

91 :id:Nat!NatM0:id=M:idNatHerewearemakingt
:id:Nat!NatM0:id=M:idNatHerewearemakingthefurtherassumptionontheunderlyinglanguagethatitsupportsde nitionsoftheformx:A=t.TheruleisQ1(�1)Q2(�2)`ctx;0Q1:Q4(�1�4)2Q1(�1)Q2(�2)0`e:�4;tforeachQ1:Q4:fi:�1�4!Ai2leti=Q1:Q2:Q3:fi:�1�20!Ai[�4:=t]=�1�20:Q1:Q4:fi�1t Q1(�1)Q2(�2)`applyQ1:Q2:Q3=Q1:Q4e;;Tobetterunderstandwhatisgoingoninthisruleithelpstolookatwhattheprogramlookslikeatthetimethisruleisapplied:moduleQ1�1wheremoduleQ4�4whereQ1:Q4:fi:AimoduleQ2�2whereapplyQ1:Q2:Q3=Q1:Q4e 96CHAPTER

92 4.MODULESYSTEM 98CHAPTER5.THEAGDALANGUAG
4.MODULESYSTEM 98CHAPTER5.THEAGDALANGUAGE [0-9]+�-:=?\|PropSet[0-9]abstractdataforallhidingimportininfixinfixlinfixrletmodulemutualopenpostulateprimitiveprivatepublicrecordrenamingusingwherewith Figure5.1:Reservedwords thenameif_then_else_toargumentsx,y,andzcanbewritteneitherasanormalapplicationif_then_else_xyzorasanoperatorapplicationifxthenyelsez.Aquali ednameisanon-emptysequenceofnamesseparatedby.(dot).Quali ednamesareusedtorefertoentitiesinothermodules.5.1.2InteractionpointsInteractionpointsareholesinaprogramwhereanexpressionshouldbe lledin.Thesearewritten?or{!...!}.Inaninteractiveenvironmenttheusercaninteractwith

93 thetypecheckerthroughtheseinteractionpoi
thetypecheckerthroughtheseinteractionpoints,forinstance,askingforthetypeoftheexpressiontobe lledinorthelocalcontext.Internallythetypecheckertreatsinteractionpointsasmetavariableswhichwillnotbesolvedautomatically.5.1.3ImplicitsyntaxItispossibletoomittermsthatthetypecheckercan gureoutforitself,replacingthemby_.Ifthetypecheckercannotinferthevalueofan_itwillreportanerror.Forinstance,forthepolymorphicidentityfunctionid:(A:Set)!A!A,the rstargumentcanbeinferredfromthetypeofthesecondargument,sowemightwriteid_zerofortheapplicationoftheidentityfunctiontozero.TheimplicitsyntaxisimplementedusingthemetavariablesdescribedinChapter3.5.1.4Funct

94 ionsFunctiontypesarewritten(x:A)-�
ionsFunctiontypesarewritten(x:A)-�BorA�-Bfornon-dependentfunc-tions.Functiontypescanrangeoverarbitrarytelescopes,forinstance,the 100CHAPTER5.THEAGDALANGUAGE Thereasonforthisliberalapproachtoimplicitargumentsisthatlimitingtheuseofimplicitargumenttothecaseswhereweguaranteethattheyaresolvedrulesoutmanyusefulcasesinpractice.SeeSection3.6forthedetailsonhowmetavariablesareinsertedforim-plicitargumentsduringtypechecking.5.1.6Datatypesandfunctionde nitionsFunctionscanbeintroducedbygivingatypeandade nition.Forinstance,thepolymorphicidentityfunctioncanbede nedby id:{A:Set}-�A-�Aidx=xNotethattheimplicitargumenti

95 sleftoutinthelefthandside.Asinalambdaabs
sleftoutinthelefthandside.Asinalambdaabstractionitcanbegivenexplicitlybyenclosingitincurlybraces: id:{A:Set}-�A-�Aid{A}x=xDatatypesareintroducedbydatadeclarations.Forinstance,thenaturalnumberscanbede nedby dataNat:Setwherezero:Natsuc:Nat�-NatToensurenormalisation,inductiveoccurrencesmustappearinstrictlyposi-tivepositions.Forinstance,thefollowingdatatypeisnotallowed: dataBad:Setwherebad:(Bad�-Bad)�-BadsincethereisanegativeoccurrenceofBadintheargumenttotheconstructor.Functionsoverelementsofadatatypecanbede nedusingpatternmatch-ingandstructuralrecursion.Theadditionfunctiononnaturalnumbersisde nedb

96 y _+_:Nat-�Nat-�Natzero+m=
y _+_:Nat-�Nat-�Natzero+m=msucn+m=suc(n+m)Theoperatorformcanbeusedbothinlefthandsidesandrighthandsidesasseenhere.Datatypescanbeparameterisedoveratelescopeofparameters.Thesearewrittenafterthenameofthedatatypeandscopeovertheconstructors. 102CHAPTER5.THEAGDALANGUAGE 5.1.7RecordsRecordtypesaredeclaredinmuchthesamewayasdatatypes,butinsteadofgivingthetypesoftheconstructorsyougivethetypesoftherecord elds.Forinstance,wecande nethetypeofevennumbersasarecordtypecontaininganumberandaproofthatitiseven. recordEven:Setwhereval:Natprf:IsEvenvalNotethatlater eldsmayrefertoearlier eldvaluesbyname.Recordtypesarecomparedbyname,so

97 thisintroducesanewtypeEven,di erentf
thisintroducesanewtypeEven,di erentfromallotherrecordtypes.Tobuildanelementofarecordtypeyouwrite record{val=suc(suczero);prf=evenSS_evenZ}The eldscanbegiveninanyorder.Foreachrecordtypeamoduleofthesamenameisde ned,containingprojectionfunctions.InthecaseofEvenwehave Even.val:Even�-NatEven.prf:(e:Even)-�IsEven(Even.vale)ThemoduleEvencontainingtheprojectionfunctionsisparameterisedovertherecordandsoitcanbeappliedandopened(seeSection4.3forthedetails).Incasetherecordisparameterisedthegeneratedmodulehavetherecordparametersasimplicitparameters.Forinstance, recordStep(A:Set):Setwherenext:A�-Awillintroduceamodule modul

98 eStep{A:Set}(s:StepA)wherenext:A�
eStep{A:Set}(s:StepA)wherenext:A�-A5.1.8Localde nitionsEachclauseinafunctionde nitioncanhaveablockoflocaldeclarations.Thesecanbeanydeclarationsthatcanappearonthetop-level,includingmodules,datatypedeclarations,andrecursivefunctions.Forinstance,thereversefunctioncanbede nedusingalocalrecursivefunction: 104CHAPTER5.THEAGDALANGUAGE Rememberthattheextentofamoduleisdeterminedbyindentation.Tousethenamesfromamoduleavailablewithoutquali cation,oneusesanopenstatement: openNumberstwo:Nattwo=suconeThefulldescriptionofthemodulesystemcanbefoundinChapter4,includingparameterisedmodules,andmore ne-grainedcontroloveropenstatements.

99 5.1.10AdditionalfeaturesInadditiontothef
5.1.10AdditionalfeaturesInadditiontothefeaturesdescribedhere,Agdahasexperimentalsupportformutualinduction-recursivede nitions[DS06].Mutualde nitionsaregiveninsideamutualblock: mutualeven:Nat�-Boolevenzero=trueeven(sucn)=oddnodd:Nat-�Booloddzero=falseodd(sucn)=evennAdetaileddiscussionofmutualinductive-recursivede nitionsisbeyondthescopeofthisthesis.5.2AbiggerexampleDependenttypesnotonlygivesyouthepossibilitytoprovepropertiesaboutprograms,youcanalsowriteprogramstocomputeproofs.Toillustratethiswedevelopaninternalsolverforequationsinacommutativemonoid,suchasthenaturalnumberswithadditionandzero.Thebasicideaistomodelsuch

100 equationsbyadatatypeandde neanormali
equationsbyadatatypeandde neanormalisationfunctionforthisdatatype.Tocheckifanequationholdswecanthensimplycheckthatbothsidesreducestothesamenormalform.Weprovethisstrategysoundwhichenablesustousethesolvertoproveequationsinarbitrarycommutativemonoids.ThissectionconsistsofanumberofliterateAgda leswhichcanbeprocessedbothbyLATEXandtheAgdatypechecker. 106CHAPTER5.THEAGDALANGUAGE Theidentityfunctionandfunctioncompositionarealwaysusefulsoletusde nethem. id:{A:Set}�-A�-Aidx=x__:{AB:Set}{C:B�-Set}�-((x:B)�-Cx)�-(g:A�-B)(x:A)�-C(gx)(fg)x=f(gx)Thegivengeneralisationofthenon-de

101 pendentcompositionfunctionissome-timesus
pendentcompositionfunctionissome-timesuseful,andenjoysthepropertythatwecanstillinferthetypeargu-ments.Wede nethebooleanswiththeconstructorsfalse,andtrue. dataBool:Setwherefalse:Booltrue:Boolinfix5if_then_else_if_then_else_:{A:Set}�-Bool�-A�-A�-Aiftruethenxelsey=xiffalsethenxelsey=yThe xityoftheif_then_else_dictateswhetherornotparenthesisareneededfortheelsebranch.Wewouldliketoavoidparenthesessowesetittoalowvalue.Ahigh xitymeansthattheoperatorbindstightlyandalow xitythatitbindsloosely.Forinstance,given infixl20_+_infixl30_*_theexpressionx+y*zparsesasx+(y*z)ratherthan(x+y)*z.Naturalnumbersarede n

102 edwithtwoconstructorszeroandsuc.TheBUILT
edwithtwoconstructorszeroandsuc.TheBUILTINpragmastellsthetypecheckeraboutourde nitionofnaturalnum-bersandallowsthemtoberepresentedmoreecientlyinternally.Italsoletsususenumericliteralstoconstructnaturalnumbers. dataNat:Setwherezero:Natsuc:Nat�-Nat{-#BUILTINNATURALNat#-}{-#BUILTINZEROzero#-}{-#BUILTINSUCsuc#-} 108CHAPTER5.THEAGDALANGUAGE Thenaturalnumberargumentntotabulatecanbeinferredbythetypecheckerwhenweusethefunction,butde ningtabulateweneedtorecurseovern.RatherthanalsobindingAexplicitlyinthelefthandsidewerefertonbyname.Thenametobeusedistakenfromthetype.5.2.3EquivalencerelationsNextwede neasmalllibraryforequivalenc

103 erelationsandgiveinstancesforlistsand
erelationsandgiveinstancesforlistsand nitesetswhicharetheonesweneedforoursolver. moduleEquivalencewhereopenimportLogicWesplitthede nitionofwhatanequivalencerelationisintotwoparts.Firstwede newhatitmeansforarelationtobeanequivalenceandthenwede neanequivalencerelationtobearelationandaproofthatitisanequivalence.Theadvantageofthisapproachasopposedtojusthavingasinglerecordisthatwecantalkaboutwhatitmeanstobeanequivalence.Thismakesde ningmorere nedequivalencerelations,suchasdecidableequivalencerelations,easier. recordIsEquivalence{A:Set}(_==_:A�-A�-Set):Setwhererefl:(x:A)�-x==xsym:(xy:A)�-x==y&#x

104 0000;-y==xtrans:(xyz:A)�-x==y�
0000;-y==xtrans:(xyz:A)�-x==y�-y==z�-x==zrecordEquivalence(A:Set):Set1where_==_:A�-A�-SetisEquiv:IsEquivalence_==_Nowthedisadvantageofthetwostageapproachisthatthemodulegeneratedfortheequivalencerecorddoesnotcontainprojectionsfortheaxiomsrefl,sym,andtrans.Forthisreasonwede neanewmoduleEquivalenceOpswhichsimplyre-exportstheprojectionfunctionsfromthetworecords. moduleEquivalenceOps{A:Set}(Eq:EquivalenceA)whereprivateopenmoduleEq=EquivalenceEqpublicprivateopenmoduleIsEq=IsEquivalenceisEquivpublicWenowde neatypeofdecidableequivalencerelations.Thede nitionisthesameasthede nitionofequivalencerelat

105 ionexceptwehaveanextra 110CHAPTER5.THEAG
ionexceptwehaveanextra 110CHAPTER5.THEAGDALANGUAGE Intheproofsofsymmetryandtransitivitywecanseethepatternmatchingonidentityproofsinaction.Wede neadecidableequivalencerelationon nitesetsbyprovingthattheidentityrelationisdecidable. finDecEquivalence:{n:Nat}�-DecidableEquivalence(Finn)finDecEquivalence{n}=record{_==_=_==_;isEquiv=isEquiv;decide=decide}whereopenmoduleE{n:Nat}=EquivalenceOps(identityEquivalence(Finn))decide:{n:Nat}(ij:Finn)�-(i==j)_:(i==j)decidefzerofzero=inlrefdecidefzero(fsucj)=inrdismisswheredismiss:fzero==fsucj�-Falsedismiss()decide(fsuci)fzero=inrdismisswheredismiss:fsuci==fzero�-Falsedis

106 miss()decide(fsuci)(fsucj)withdecideijde
miss()decide(fsuci)(fsucj)withdecideijdecide(fsuci)(fsuc.i)|inlref=inlrefdecide(fsuci)(fsucj)|inrneq=inr(dismissijneq)wheredismiss:(ij:Fin_)�-:(i==j)�-:(fsuci==fsucj)dismissi.ineqref=neqrefNotethatwhenweinstantiatetheEquivalenceOpsmoduletotheidentityrelationon nitesetsweabstractoverthesizeoftheset.Thiskeepstheoperationspolymorphicinthesize,whichweneedintheproof.Todismisstheo -diagonalcasesweusethesyntaxforpatternmatchingoncaselesstypes.GivenanequivalencerelationonatypeAwecande neanequivalencerelationonlistsoverA,relatinglistsofequallengthwhentheelementsarepointwiserelated.Theproofsaresimplebutsomewhattedious. listE

107 quivalence:{A:Set}�-EquivalenceA&
quivalence:{A:Set}�-EquivalenceA�-Equivalence(ListA) 112CHAPTER5.THEAGDALANGUAGE ;isEquiv=isEquiv;decide=decide}wheremoduleDEqA=DecidableEquivalenceOpsdeqAopenmoduleEqList=EquivalenceOps(listEquivalenceDEqA.Eq)decide:(xsys:ListA)�-(xs==ys)_:(xs==ys)decide[][]=inl_decide[](y::ys)=inr\w�-wdecide(x::xs)[]=inr\w�-wdecide(x::xs)(y::ys)withDEqA.decidexy|decidexsysdecide(x::xs)(y::ys)|inlxy|inlxsys=inl(xy,xsys)decide(x::xs)(y::ys)|inrnxy|_=inrdismisswheredismiss:(x::xs)==(y::ys)�-Falsedismiss(xy,_)=nxyxydecide(x::xs)(y::ys)|_|inrnxsys=inrdismisswheredismiss:(x::xs)==(y::ys)�-Falsedismiss(_,xsys)=nxs

108 ysxsysInthecasewherebothlistsarenon-empt
ysxsysInthecasewherebothlistsarenon-emptyweuseawithclausetopatternmatchontheresultsofcomparingtheheadsandthetails.5.2.4ChainreasoningConstructingequivalenceproofsusingtransitivitydirectlyresultsinveryunreadableproofs.Fortunatelywecanusealittleimplicitargumentandin xoperatormagictosolvethisproblem.Wede neamoduleChainparameterisedoverare exiveandtransitiverelation. moduleChain{A:Set}(_==_:A�-A�-Set)(refl:(x:A)�-x==x)(trans:(xyz:A)�-x==y�-y==z�-x==z)where 114CHAPTER5.THEAGDALANGUAGE 5.2.5MonoidsSofarwehavemostlybeendevelopinggenerallibrarieswithnoapparentconnectiontotheproblemwearetryingtosolve

109 |thatofautomaticallyprovingequationsinac
|thatofautomaticallyprovingequationsinacommutativemonoid.Westarttheproblemspeci cpartbyde ningwhatacommutativemonoidis.ThisisdonerelativetoasetAequippedwithanequivalencerelation. openimportEquivalencemoduleMonoid{A:Set}(Eq:EquivalenceA)whereWewanttohaveaccesstotheoperationsonequivalencerelationssoweapplyandopentheEquivalenceOpsmodule. privateopenmoduleEq=EquivalenceOpsEqWeusethesametwostageapproachaswedidforequivalencerelationsand rstde newhatitmeansforanelement;andanoperation_+_toformamonoid.Thede nitionofamonoidisthensimplya;,a_+_,andaproofthattheyformamonoid. recordIsMonoid(;:A)(_+_:A�-A�-A):SetwhereidL:

110 (x:A)�-(;+x)==xidR:(x:A)�-
(x:A)�-(;+x)==xidR:(x:A)�-(x+;)==xassoc:(xyz:A)�-(x+(y+z))==((x+y)+z)cong:(x1x2y1y2:A)�-x1==x2�-y1==y2�-(x1+y1)==(x2+y2)recordMonoid:Setwhere;:A_+_:A�-A�-AisMonoid:IsMonoid;_+_Againwede neanewmodulewiththeprojectionfunctionsfrombothrecordsaswellasacoupleofderivedones. moduleMonoidOps(M:Monoid)whereprivateopenmoduleM=MonoidMpublicprivateopenmoduleIsM=IsMonoidisMonoidpubliccongL:(xy1y2:A)�-y1==y2�-(x+y1)==(x+y2)congL___eq=cong____(refl_)eqcongR:(x1x2y:A)�-x1==x2�-(x1+y)==(x2+y)congR___eq=cong____eq(refl_) 116CHAPTER5.THEAGDALANGUAGE dataEquation(n:Nat):Set

111 where_:=_:Exprn�-Exprn�-Eq
where_:=_:Exprn�-Exprn�-EquationnInordertodecidewhetherornotanequationholdswewillnormalisebothsidesandcomparethenormalforms.Wechosenormalformstobeorderedlistsofvariables.Wedonotenforcethatthelistsareordered.Thisisnotnecessaryforsoundness,butifweweretoprovecompletenessitmightsimplifymatters. NF:Nat�-SetNFn=List(Finn)Analternative,perhapsnicer,representationofnormalformswouldbeasavectorofvariablecounts:NFn=VecNatn.Theemptylististhezeroofthenormalformsandtheadditionisthemergefunctionoftwoorderedlists: __:{n:Nat}�-NFn�-NFn�-NFn[]ys=ys(x::xs)[]=x::xs(x::xs)(y::ys)=ifx6Fin6ythenx::(xs(

112 y::ys))elsey::((x::xs)ys)Tonormalise
y::ys))elsey::((x::xs)ys)Tonormaliseanexpressionwesimplyreplace|;|withtheemptylistand_|+|_with__.Variablesbecomesingletonlists. normalise:{n:Nat}�-Exprn�-NFnnormalise|;|=[]normalise(e1|+|e2)=normalisee1normalisee2normalise(vari)=i::[]Wealsode neafunctionreifytocomebackfromanormalformtoanexpression. reify:{n:Nat}�-NFn�-Exprnreify[]=|;|reify(i::nf)=vari|+|reifynfWeneeddecidableequalityonnormalforms,butsincenormalformsarejustslistsofelementsfroma nitesetwehavealreadyde nedit. nfDecEquiv:{n:Nat}�-DecidableEquivalence(NFn)nfDecEquiv=listDecEquivalencefinDecEquivalence 118CHAPTER5.THEAGDA

113 LANGUAGE provable:{n:Nat}(thm:Equationn)
LANGUAGE provable:{n:Nat}(thm:Equationn)�-IsProvablethmprovable(e1:=e2)withdecideExprEqe1e2provable(e1:=e2)|inlp=can-provepprovable(e1:=e2)|inrp=can't-provepNotethatwehavenotyetprovedthatournotionofprovabilityiscorrect.Thatisthetopicofthenextmodule.5.2.7SemanticsUpuntilnowwehavenotreallydoneanythingthatcouldnotbedoneinasimplytypedlanguage.Wehavede nedafunctiontodecideequalityinacommutativemonoidby atteningandsortingtheexpressions.Whatcannotbedoneinasimplytypedsettingisconstructingtheactualproofthattheequationholdsinanycommutativemonoid.Wede neamoduleSemanticsparameterisedbyanarbitrarycommuta-tivemonoid. openimportEquivalenceo

114 penimportMonoidmoduleSemantics{A:Set}{Eq
penimportMonoidmoduleSemantics{A:Set}{Eq:EquivalenceA}(M:CommutativeMonoidEq)whereimportChainopenimportLogicopenimportBasicsopenimportExprprivateopenmoduleE=EquivalenceOpsEqopenmoduleM=CommutativeMonoidOpsEqMopenmoduleC=Chain_==_refltransFirst,wehavetode nethesemanticsofanexpression,i.e.howtotrans-lateitintoanelementofthemonoid.Todothisweneedanenvironmentcontainingvaluesforthefreevariablesoftheexpression. Env:Nat�-SetEnvn=VecAn 120CHAPTER5.THEAGDALANGUAGE -sound(x::xs)(y::ys)withx6Fin6y-sound(x::xs)(y::ys)|true=�chainnf[x::xs]+nf[y::ys]===(!x+[xs])+(!y+[ys])byrefl_===!x+([xs]+(

115 6;!y+[ys]))bysym__(assoc___)===!x+n
6;!y+[ys]))bysym__(assoc___)===!x+nf[xs(y::ys)]bycongL___(-soundxs(y::ys))===nf[x::(xs(y::ys))]byrefl_qedwhere[xs]=nf[xs][ys]=nf[ys]-sound(x::xs)(y::ys)|false=�chainnf[x::xs]+nf[y::ys]===(!x+[xs])+(!y+[ys])byrefl_===(!y+[ys])+(!x+[xs])bycommute__===!y+([ys]+(!x+[xs]))bysym__(assoc___)===!y+((!x+[xs])+[ys])bycongL___(commute__)===!y+nf[(x::xs)ys]bycongL___(-sound(x::xs)ys)===nf[y::((x::xs)ys)]byrefl_qedwhere[xs]=nf[xs][ys]=nf[ys]Itisworthpointingoutthatwhenwepatternmatchonx6Fin6ythisexpressioni

116 sabstractedfromthegoaltype,whichmakesthe
sabstractedfromthegoaltype,whichmakestheif_then_else_from__reduce.Nowprovingthatnormalisationissoundiseasy.Inthevariablecaseweaddanextra;sowehavetousetheaxiomthatx+;=x.The|;|caseistrivialandinthe_|+|_caseweusethefactthat__issound. normalise-sound:{n:Nat}(e:Exprn)(:Envn)�-expr[e]==nf[normalisee]normalise-sound(vari)=sym__(idR_) 122CHAPTER5.THEAGDALANGUAGE curry:{A:Set}{n:Nat}{P:VecAn�-Set}�-((xs:VecAn)�-Pxs)�-CurriednPcurry{n=zero}f=f"curry{n=sucn}f=\x�-curry(\xs�-f(xxs))Forinstance,givenP:VecA3!Setandf:(xs:VecA3)!PxswehaveCurried3P=(xyz:A)!P(xyz

117 ")curryf=xyz!f(xyz")
")curryf=xyz!f(xyz")Anotherthingwhichistediouswiththecurrentpresentationistowritedowntheequationtobeproven.Sincethereisnowaytore ectagoaltypeintoanexpressioninourrepresentationtheequationhastobegivenexplicitly.Inordertosaveusthetediumofwritingdownthenamesofthefreevariablesofanexpressionwecandoasimilartrick,onlybackwards.Wede neatype_^_!_ofcurriedfunctionsoftheformA!:::!A!B: _^_!_:Set�-Nat�-Set�-SetA^zero!B=BA^sucn!B=A�-A^n!BTheuncurryfunctionturnsacurriedfunctionintoanuncurriedfunction. uncurry:{AB:Set}{n:Nat}�-(A^n!B)�-(VecAn�-B)uncurryf"=funcurryf(xxs)=uncurry(f

118 x)xsNowwecande neafunctionequationwh
x)xsNowwecande neafunctionequationwhichgivenafunctionfromnexpres-sionstoanequationovernvariablesappliesthefunctiontothesevariables.TogetavectorofallfreevariableswesimplytabulatethevarfunctionwhosetypeisFinn!Exprn. equation:(n:Nat)�-(Exprn^n!Equationn)�-Equationnequationneq=uncurry{n=n}eq(tabulatevar)Finallywearereadytoputourprovertothetest.Asanexampleweprovepartofthesecondcaseinthe-soundproof.Weusecurrytogettheresultintotherightform,andequationtomakestatingtheequationeasier. 124CHAPTER5.THEAGDALANGUAGE 126CHAPTER6.FIRST-ORDERLOGIC propositionalor rst-orderprovers[BHdN02,ST95,MP04].But,inordertoarriveatproofdocument

119 swhicharestillreadable,onlytrivialproofs
swhicharestillreadable,onlytrivialproofstepsshouldbehandledbytheautomaticprover.Sincedi erentreadersmighthavedi erentnotionsoftrivial,theautomaticprovershouldnotbeablackbox.Withsomee ortbythehuman,theoutputoftheprovershouldbeunderstandable.Inthispaper,weareexploringconnectionsbetweenalogicalframeworkMLFPropbasedontypetheoryandresolution-basedtheoremprovers.Oneprobleminsuchaninteractionisthatresolutionproofsarehardtoreadandunderstandingeneral.Indeed,resolutionproofsystemsworkwithformulinclausenormalform,whereclausesare(theuniversalclosuresof)disjunc-tionsofliterals,aliteralbeinganatomoranegatedatom.Thesystemtranslatesthenega

120 tionofthestatementtobeprovedtoclauseform
tionofthestatementtobeprovedtoclauseform,usingskolemisationanddisjunctivenormalform.Itthengeneratesnewclausesusingresolutionandparamodulation,tryingtoderiveacontradiction.Ifsuccessful,thesystemdoespruningonthe(typicallyhighnumberof)gen-eratedclausesandoutputsonlytherelevantones.1Welosethestructureoftheinitialproblemwhendoingskolemisationandclausi cation.Typically,aproblemsuchas8x:9y:8z:R(x;y))R(x;z)(1)isnegatedandtranslatedintothetwocontradictoryunitclauses8y:R(a;y);8y::R(a;f(y));(2)buttheconnectionbetweenthestatement(1)andtherefutationof(2)isnotsointuitive.Wedonotsolvethisproblemhere,butwepointoutthat,ifwerestrictourselvestoimplicitlyu

121 niversallyquanti edpropositionalform
niversallyquanti edpropositionalformul,inthefollowingcalledopenformul,thisproblemdoesnotarise.Furthermore,whenwerestricttothisfragment,wecanusetheideaofimplicittyping[Bee07,WM89].Inthisway,thetranslationfromframeworktypestoFOLformulisparticularlysimple.Technically,thisisre ectedbyageneralmetatheoremwhichensuresthatwecanlifta rst-orderresolutionprooftoaframeworkderivation.Ifwerestricttheclassofformulfurthertoso-calledgeometricalopenformul[CLR01,BC03],thenthetranslationtoclausalformistransparent.Indeed,anyresolutionproofforthisfragmentisintuitionisticallyvalidandcanbeinterpretedasitisintypetheory.This 1Ifthese

122 archisnotsuccessful,itisquitehardtogetan
archisnotsuccessful,itisquitehardtogetanyrelevantinformationfromtheclausesthataregenerated.Wehavenotyetanalyzedtheproblemofgettingusefulfeedbackinthiscase. 128CHAPTER6.FIRST-ORDERLOGIC betweentermsandtypes.ThesyntacticentitiesofMLFProparegivenbythefollowinggrammar.x;y;zvariablesc;f;pconstants^c::=FunjEljSetj()jPrfjPropbuilt-inconstantsr;s;P;Q::=^cjcjxjx:rjrsjletx:T=rinsexpressionsT;U::=SetjElsjPropjPrfPjFunT(x:U)types�::=j�;x:Ttypingcontexts::=j;c:Tj;c:T=rsignaturesWeidentifytermsandtypesupto -conversionandadopttheconventionthatincontexts�,allvariablesmustbedistinct;hence,thecontextextension�;x:

123 Tpresupposesx:U=2�foranyU.Similarly,a
Tpresupposesx:U=2�foranyU.Similarly,aconstantcmaynotbedeclaredinasignaturetwice.WeusethesamesyntacticconventionsforUTT(seeSection1.3)andwrite(x:T)!UforFunT(x:U).TheinhabitantsofSetaretypecodes;Elmapstypecodestotypes.E.g.,(a:Set)!Ela!Elaisthetypeofthepolymorphicidentitya:x:x.SimilarlyPropcontainsformalpropositionsPandPrfPproofsofP.Typesoftheshape�!PrfParecalledprooftypes.Acontext�=(x1:T1):::(xn:Tn)isasetcontextifandonlyifallTiareoftheform!ElS.Inparticular,ifP:Prop,thentheprooftype�!PrfPcorrespondstoauniversal rst-orderformula8x1:::8xnPwithquanti er-freekernelP.Judgements.ThetypetheoryMLFPropispresen

124 tedvia vejudgements,whichareallrelat
tedvia vejudgements,whichareallrelativetoa(user-de ned)signature.�`�isawell-formedcontext�`TTisawell-formedtype�`r:TrhastypeT�`T=T0TandT0areequaltypes�`r=r0:Trandr0areequaltermsoftypeTAll vejudgementsarede nedsimultaneously.Sincethesignatureremains xedinalljudgementswewillomitit.Judgmentaltypeandtermequalityaregeneratedfromexpansionofsig-naturede nitionsaswellasfrom -,-,andlet-equality,thelatterofwhichisgivenby(letx:T=rins)=s[x:=r].TherulesforequalityaresimilartotheonesofMLF[AC05],andtype-checkingofnormaltermswithlocalde nitionsisdecidable.Figure6.1showsthety

125 pingrules.Therulesfun-fandfun-icarryasid
pingrules.Therulesfun-fandfun-icarryasidecondition()thatensuresthatnotypecandependonaproof,whichisneededfortheconservativitytheorem. 130CHAPTER6.FIRST-ORDERLOGIC Naturaldeduction.WeassumeasignaturendgiveninFigure6.2,whichassumesthein xlogicalconnectivesop::=^;_;),plusthede nedones,:and,.Furthermore,itcontainsasetPredSymofbasicpredicatesym-bolspoftype�!Propwhere�isa(possiblyempty)setcontext.Cur-rentlyweonlyassumetruth�,absurdity?,andtypedequalityId,butuserde nedsignaturescanextendPredSymbytheirownsymbols.Foreachlogicalconstructs,thereareappropriateproofrules,e.g.,aconstantimpI:(P;Q:Prop)!(PrfP!PrfQ)!Prf(P)Q):

126 First-orderlogicassumesthateverysetisnon
First-orderlogicassumesthateverysetisnon-empty,andouruseofa rst-orderproverisonlysoundunderthisassumption.Hence,weaddaspecialconstant:(D:Set)!ElDtondwhichenforcesthisfact.Noticethatthisimpliesthatallsetcontextsareinhabited2.Classicalreasoningcanbeperformedinthesignatureclass,whichwede neastheextensionofndbyEM:(P:Prop)!Prf(P_:P);thelawoftheexcludedmiddle.Thefolrule.ThisarticleinvestigatesconditionsunderwhichtheadditionofthefollowingruleisconservativeoverMLFProp+ndandMLFProp+class,respectively.fol�`T �`():T�`FOLTThesidecondition�`FOLTexpressesthatTisaprooftypeandthatthe rst-orderprovercandeduce

127 thetruthofthecorresponding rst-order
thetruthofthecorresponding rst-orderfor-mulafromtheassumptionsin�.ItensuresthatonlytautologieshaveproofsinMLFProp,butitisnotconsideredpartofthetypechecking.Metatheoreti-calpropertiesofMLFProplikedecidabilityofequalityandtype-checkingholdindependentlyofthissidecondition.Conservativityfailsifwehavetocompareproofobjectsduringtype-checking.Thisisbecausetherulefolproducesasingleproofobjectforall(true)propositions,whereasuponremovaloffoltheholehastobe lledwithspeci cproofobject.Hencetwoequalobjectswhicheachdependonaproofgeneratedbyfolcouldbecomeunequalafterreplacingfol.Toavoidthis,itissucienttorestrictfunctionspaces(x:T)!U:ifT

128 isaprooftype,thenalsoU.Whilethisrestrict
isaprooftype,thenalsoU.Whilethisrestrictionisclearlysucient,itisrathersever.Forinstance,itisnotpossibletode neafunctioncomputinganelementofasetundersomepropositionalpreconditions.Whatwereallyneedhereisproofirrelevantpropositions.Intheremainderofthepaper,weuseLFasasynonymforMLFProp. 2Semantically,itmaybefruitfultothinkoftermsoftypeSetasinhabitedPartialEquivalenceRelations,whiletermsoftypeProparePERswithatmostoneinhabitant. 132CHAPTER6.FIRST-ORDERLOGIC 6.3TranslationfromMLFProptoFOLWeshallde neapartialtranslationfromsomeLFtypestoFOLpropositions.Wetranslateonlytypesoftheform(x1:T1):::(xk:Tk)!Prf(P(x1;:::;xk));andthesearetranslated

129 toopenformul[P(x1;:::;xk)]of rs
toopenformul[P(x1;:::;xk)]of rst-orderlogic.Allthevariablesx1;:::;xkareconsidereduniversallyquanti ed.Forin-stance,(x:ElNat)!Prf(IdNatxx^IdNatx(addzerox))willbetranslatedtox=x^x=addzerox:Ifwehaveatheoryoflattices,thatis,wehaveaddedD:Setsup:ElD!ElD!ElD6:ElD!ElD!Proptothecurrentsignature,then(x;y:ElD)!Prf(supxy6x,y6x)wouldbetranslatedtosupxy6y,y6x.Thetranslationisdoneatasyntacticallevel,withoutusingtypes.WedemonstratethatwecanliftaresolutionproofofatranslatedformulatoanLFderivationinthesignatureclass(orinnd,insomecases).6.3.1FormalDescriptionoftheTranslationWetranslatenormalexpressions,whichmeansthatallde nitionshaveb

130 eenunfoldedandallredexesreduced.Threecla
eenunfoldedandallredexesreduced.ThreeclassesofnormalMLFProp-expressionsareintroduced:(formal) rst-ordertermsand(formal) rst-orderformul,whicharequanti erfreeformuloveratomspossiblycontainingfreetermvariables,andtranslatableformul,whichare rst-orderformulpre xedbyquanti cationoversetelements.t;u::=xjf~t rst-ordertermsA;B::=p~tjIdSt1t2atomsW::=AjWopW0 rst-orderformul::=!PrfWtranslatableformul(setcontext)Propertermsarethosewhicharenotjustvariables.Fortheconservativityresultthefollowingfactaboutpropertermswillbeimportant:Inawell-typedproperterm,thetypesofitsvariablesareu

131 niquelydetermined.For 134CHAPTER6.FIRST-
niquelydetermined.For 134CHAPTER6.FIRST-ORDERLOGIC Examplesoftypesthatcannotbetranslatedare(x:Prop)!Prfx(x:Prop)isnotasetcontextPrf(F(x:x))x:xisnota rst-orderterm(y:ElD!ElD)!Prf(P(yx))yxisnota rst-ordertermWeshallalsousetheclassofgeometricalformul,givenbythefollowinggrammar:G::=HjH!GjG^GgeometricalformulaH::=AjH^HjH_HpositiveformulaTheaboveexampleWexisgeometrical.Aswewillshow,(classical) rst-orderproofsofgeometricalformulcanbemappedtointuitionisticproofsinthelogicalframeworkwithnd.6.3.2ResolutionCalculusItwillbeconvenienttousethefollowingnon-standardpresentationoftheresolutioncalculus[Rob65].AclauseCisano

132 pen rst-orderformulaoftheformA1^
pen rst-orderformulaoftheformA1^^An)B1__Bmwherewecanhaven=0orm=0andAiandBjareatomicformul.FollowingGentzen[Gen35],wewritesuchaclauseontheformA1;:::;An)B1;:::;Bm;thatis,X)Y,whereXandYare nitesetsofatomicformul.AnemptyXisinterpretedastruth,anemptyYasabsurdity.Resolutionisforwardreasoning.Figure6.3liststherulesforextendingthecurrentsetofderivedclauses:ifallclausesmentionedinthepremiseofarulearepresent,thisrulecan reandtheclauseoftheconclusionisaddedtotheclauseset.Inourformulation,allrulesareintuitionisticallyvalid3,andcanbejus-ti edinMLFProp+nd.Itcanbeshown,classically,thattheserulesarecomp

133 leteinthefollowingsense:ifaclauseisasema
leteinthefollowingsense:ifaclauseisasemanticalconsequenceofotherclausesthenitispossibletoderiveitusingtheresolutioncalculus.Hence,anyproofinFOLcanbeperformedwithresolution4.Itcanbepointedoutthatthesubruleisonlynecessaryattheveryend|anyresolutionproofcanbenormalizedtoaproofthatonlyusessubinthe nalstep. 3Inthestandardformulation,theaxrulewouldread:A_A|theexcludedmiddle.4Todealwithexistentialquanti cationwealsoneedskolemisation. 136CHAPTER6.FIRST-ORDERLOGIC Proof. Thelemmaisaconsequenceofthefollowingstrongerproposition:Ift1;:::;tnandu1;:::;unarelistsoftermsthat tthesamecontextin�andisthemostgeneralsubstitutionsuchthatti

134 =uifor16i6n,then�`(x):
=uifor16i6n,then�`(x):Aforall(x:A)2�.Let�`t:Aand�0`u:B.Sincetanduarepropertermsanduni able,t=f(~t)andu=f(~u)forsomeconstantf:!C.Hence,~tand~u tin��0,whichisavalidcontextsince�and�0aredisjoint.Nowthepropositionimpliesthatmgu(t;u)iswell-typed.Toprovethestrongerproposition,wefollowthestepsofasimpleuni -cationalgorithmandconsidertheuni cationproblemt1=u1;:::;tn=unIfbotht1andu1areproperterms,theyareoftheformf(a1;:::;ak)andf(b1;:::;bk)andwegetasimpleruni cationproblema1=b1;:::;ak=bk;t2=u2;:::;tn=unIf,forinstance,t1isavariablex,andxdoesnotappearinu1,weclaimthatallvariablesinu1havea

135 typewhichisindependentofx.Thisholdsifu1i
typewhichisindependentofx.Thisholdsifu1isavariable,sincethetypeofu1isthesameastheoneofx,butitalsoholdsifu1isaproperterm,sincethetypeofthevariablesinu1arethendeterminedbyu1alone,andxdoesnotappearinu1.Wecanhenceassumethatallthesevariablesappearbeforexin�=�1;x:T;�2.Wethengetthesimpleruni cationproblemin�1;�2[x:=u1]t2[x:=u1]=u2[x:=u1];:::;tn[x:=u1]=un[x:=u1]Weproceedinthiswayuntilwegetanemptylistinthecontextinwhichthemostgeneraluni erofthetwotermsiswell-typed. Forinstance,addxzeroandadd(sucy)zareuni ableandwell-typedandthemostgeneraluni erfx7!sucy;z7!zerogiswell-typed.Usingthislemma,wecanliftanyFOLresolutionstepto

136 anLFresolutionstep.Thesameholdsforanyres
anLFresolutionstep.Thesameholdsforanyrestrictedparamodulationstep,whichjusti esthetranslationofIdStuashti=huiinFOL,Indeed,intheparamodulationstepbetweenX1)t=u;Y1andX2[t0])Y2[t0]weunifytandt0andforLemma6.3.1tobeapplicablebothtandt0havetobeproperterms.SimilarargumentshavebeenputforthbyBeeson[Bee07]andWickandMcCune[WM89].Aclausaltypeisaformulawhichtranslatestoaclause. 138CHAPTER6.FIRST-ORDERLOGIC thetypeofhbecomesx=zeroinFOLandfromthiswecouldderive,byparamodulationfromthevariablex,a=zerowhichisnotwell-typed.Thisproblemisalsodiscussedin[Bee07,WM89]andthesolutionissimplytoforbidtheFOLprovertouseparamodulationfromavariable5.Wecannowstatetheco

137 nservativitytheorem. Theorem6.3.5. Ifaty
nservativitytheorem. Theorem6.3.5. IfatypeisinhabitedinthesystemMLFProp+fol+classthenitisinhabitedinMLFProp+class. Proof. Byinductiononthetypingderivation,usingTheorem6.3.3forfolderivations. 6.3.4SimpleExamplesFigure6.4showsanextensionofndbynaturalnumbers,inductionandanadditionfunctionde nedbyrecursiononthesecondargument.Now Nat:Setnaturalnumberszero:ElNatzerosuc:ElNat!ElNatsuccessorindNat:(P:ElNat!Prop)!Pzero!((x:ElNat)!Px)P(sucx))!(n:ElNat)!Pninductionadd:ElNat!ElNat!ElNatadditionaddZero:(x:ElNat)!IdNat(addxzero)xaxiom1ofaddaddSuc:(x;y:ElNat)!IdNat(addx(sucy))(suc(addxy))axiom2ofadd Figure6.4:Asignatureofnaturalnumbersanda

138 ddition. considerthegoal(x:ElNat)!IdNat(
ddition. considerthegoal(x:ElNat)!IdNat(addzerox)x:Usingtheinduction 5ThisispossibleinOtter.InGandalf,thiscouldbecheckedfromthetrace.Paramodu-lationfromavariableishighlynon-deterministic.Foreciencyreasons,itwasnotpresentinsomeversionofGandalf,butitwasaddedlaterforcompleteness.Intheexampleswehavetried,thisrestrictionisnotaproblem. 140CHAPTER6.FIRST-ORDERLOGIC 6.4.1ImplicitArgumentsAproblemwithLFaspresentedhereisitsratherheavynotation.Forin-stance,tostatethatfunctioncompositionisassociativeonewouldgivethesignatureinFigure6.5.Thisisveryclosetobeingcompletelyillegible comp:(ABC:Set)!(ElB!ElC)!(ElA!ElB)!(ElA!ElC)compABCfg=x:f(gx)assoc:

139 (ABCD:Set)!(f:ElC!ElD;g:ElB!ElC;h:ElA!El
(ABCD:Set)!(f:ElC!ElD;g:ElB!ElC;h:ElA!ElB)!Prf(Id(ElA!ElD)(compACDf(compABCgh))(compABD(compBCDfg)h)) Figure6.5:AssociativitywithoutImplicitArguments. duetothefactthatwehavetobeexplicitaboutthetypeargumentstothecompositionfunction.Tosolvetheproblem,wehaveimplementedamech-anismforimplicitargumentswhichallowstheomissionofargumentsthatcanbeinferredautomatically(seeChapter3).Usingthismechanismtheassociativityexamplecanbewrittenasfollows:()(ABC:Set):(ElB!ElC)!(ElA!ElB)!(ElA!ElC)fg=x:f(gx)assoc(ABCD:Set):(f:ElC!ElD;g:ElB!ElC;h:ElA!ElB)!Prf(f(gh)==(fg)h)Ingeneral,wewritex:Ttosaythatxhastype!Twithimpli

140 cit.Notethatthisisamorerestrictedformofi
cit.NotethatthisisamorerestrictedformofimplicitargumentsthantheonepresentedinSection3.6.Foreveryuseofxwerequirethattheinstantiationofcanbeinferredusingpatternuni cation[Mil92].NotethatwhenwehaveimplicitargumentswecanreplaceIdwithanin xoperator(==)(D:Set):ElD!ElD!PropWeconjecturethattheconservativityresultcanbeextendedtoallowtheomissionofimplicitargumentswhentranslatingto rst-orderlogicifthey 142CHAPTER6.FIRST-ORDERLOGIC shouldberesponsibleforcheckingthesidecondition�`FOLPinthefolrule.Animportantobservationisthatdecidabilityoftypecheckingandequal-itydonotdependonthevalidityofthepropositionsbeingcheckedbytheFOLplug-in|nothi

141 ngwillbreakifthetypecheckerisledtobeliev
ngwillbreakifthetypecheckerisledtobelievethatthereisans:Prf?.Thisallowsustodelayall rst-orderreasoninguntilaftertypechecking.Therationalefordoingthisisthattypecheckingischeapand rst-orderprovingisexpensive.Anotherobservationisthatitisnotfeasibletopasstheentirecontexttotheprover.Typically,thecontextcontainsmanythingsthatarenotneededfortheproof,butwouldratheroverwhelmtheprover.Tosolvethisproblem,werequirethatanyaxiomsorlemmasneededtoproveaparticulargoalarepassedasargumentstotheplug-in.Thismightseemasevererequirement,butbearinmindthattheplug-inisintendedforsimplegoalswhereyoualreadyhaveanideaoftheproof.Moreformally,thetypingruleforcall

142 stotheFOLplug-inis�`�`s1:
stotheFOLplug-inis�`�`s1:1:::�`sn:n �`fol�plugin(s1;:::;sn):1;:::;n`FOL:Whenfacedwithacalltoaplug-inthetypecheckercallsthetypecheckingfunctionoftheplug-in.Inthiscase,thetypecheckingfunctionoftheFOLplug-inwillverifythatthegoalisatranslatableformulaandthatthear-gumentsarewell-typedproofsoftranslatableformul.Ifthisisthecaseitwillreportsuccesstothetypecheckerandstoreawaythesideconditioninitsinternalstate.Aftertypecheckingthe nalizationfunctionoftheFOLplug-iniscalled.Foreachconstraint1;:::;n`FOL,thisfunctionveri esthat[]isderivablefrom[1];:::;[n]intheres

143 olutioncalculusbytrans-latingtheformul&#
olutioncalculusbytrans-latingtheformultoclausenormalformandfeedingthemtoanexternal rst-orderprover(Gandalf,atthemoment).Iftheproverdoesnotmanageto ndaproofwithinthegiventimelimit,theplug-inreportsanerror.6.5ExamplesThecodeinthissectionhasbeentypecheckedsuccessfullybyourprototypetypechecker.Infact,thetypesetversionisautomaticallygeneratedfromtheactualcode.ThetypecheckercaninferwhichtypesareSetsandwhichareProps,soweomitElandPrfinthetypes. 144CHAPTER6.FIRST-ORDERLOGIC thestepcase:(1)8xy:(R(n)R(n))xy=)(R(n)R(n))yx(2)8mxy:R(sucm)xy=)(R(m)R(m))xy_R(m)xy(3)8mxy:(R(m)R(m))xy=)R(sucm)xy(4)8mxy:R(m)xy=)R(sucm)xy(5)8xy

144 :R(n)xy=)R(n)yx(6)R(sucn)ab(7)R(sucn)ba=
:R(n)xy=)R(n)yx(6)R(sucn)ab(7)R(sucn)ba=)?(8)(R(n)R(n))ab_R(n)ab(2);(6)(9)(R(n)R(n))ba_R(n)ab(1);(8)(10)R(n)ab(3);(7);(9)(11)R(n)ba(5);(10)(12)?(4);(7);(11)Thetransitiveclosureisnowde nedasTCRxy=9n:R(n)xy.Tofor-malizethis,weaddexistentialquanti cationanditsproofrules.The naltheoremdemostrateshowexistentialquanti cationcanbehandledintheframework.Exists(X:Set):(X!Prop)!PropexistsI(X:Set)(P:X!Prop):(x:X)!Px!ExistsPexistsE(X:Set)(P:X!Prop)(C:Prop):ExistsP!((x:X)!Px!C)!CTC:(A!A!Prop)!A!A!PropTCRxy=Exists(n!(R^n)xy)thm:(R:A!A!Prop)!symR!sym(TCR)thmRhxy=impI(p!existsEp(nq!existsInfol�plugin(q;mainRhn)))6

145 .5.2CategoryTheoryOneapplicationoftheFOL
.5.2CategoryTheoryOneapplicationoftheFOLplug-inistocategorytheory.Typically,proofsincategorytheorycontainafairamountofsymbolicmanipulation,somethingwhichwecanleavetotheplug-in.Toreasonaboutcategorytheoryweintroducetheappropriateconstantstogetherwiththeiraxioms.Obj:Set 146CHAPTER6.FIRST-ORDERLOGIC Exists(A:Set):(A!Prop)!PropexistsI(A:Set):(P:A!Prop)!(x:A)!Px!ExistsPexistsE(A:Set):(P:A!Prop)!ExistsP!(C:Prop)!((x:A)!Px=)C)!CWealsoneednaturalnumbers.Forthisusethedatatypeextensionswhichallowsustode nerecursivefunctionsoverthenaturalnumbers.Forinstance,wecanwritearecursiveproofoftheinductionprinciple.dataNat:Setwherezero:Natsuc:Nat!NatindNat:

146 (P:Nat!Prop)!Pzero!((n:Nat)!Pn=)P(sucn))
(P:Nat!Prop)!Pzero!((n:Nat)!Pn=)P(sucn))!(x:Nat)!PxindNatPagzero=aindNatPag(sucn)=impE(gn)(indNatPagn)Thegoaloftheexampleistoprovethatinanintegralring,theonlynilpotentelementiszero.Westartbyde ningwhatitmeanstobeanintegralring.isRing:(R:Set)!(R!R!R)!(R!R!R)!(R!R)!R!R!PropisRingR(+)()minusZeroOne=(x:R)!(y:R)!(z:R)!((x+y)==(y+x)^(x+Zero)==x^(x+(minusx))==Zero^(x+(y+z))==((x+y)+z)^(x(y+z))==((xy)+(xz))^((y+z)x)==((yx)+(zx))^(xOne)==x^(Onex)==x^(x(yz))==((xy)z))isIntegral:(R:Set)!(R!R!R)!R!PropisIntegralR()Zero=(x:R)!(y:R)!xy==Zero=) 148CHAPTER6.FIRST-ORDERLOGIC letrem1:Zero+One==O

147 nerem1=fol�plugin(axR)rem2:(Zero+One)
nerem1=fol�plugin(axR)rem2:(Zero+One)x==Zerox+Onexrem2=fol�plugin(axR)rem3:Zerox+Onex==Onexrem3=fol�plugin(axR;rem1;rem2)infol�plugin(rem3;lemCancel)lemOneZero:(x:R)!One==Zero=)isZeroxlemOneZerox=fol�plugin(axR;lemZero)Themainlemmaisprovedbyinductionexplicitlyattheframeworklevel.prop:R!Nat!Proppropxn=isZero(powernx)=)isZeroxlemMain:(x:R)!(n:Nat)!propxnlemMainx=letbase:propxzerobase=fol�plugin(lemOneZero)step:(n:Nat)!propxn=)propx(sucn)stepn=fol�plugin(axR;axI)inindNat(propx)basestepthm:(x:R)!isNilpotentx!isZeroxthmxh=existsE(n!isZero(powernx))h(isZerox)(lemMainx)6.6RelatedWorkSmithandTammet[

148 ST95]alsocombineMartin-Loftypetheoryand
ST95]alsocombineMartin-Loftypetheoryand rst-orderlogic,whichwastheoriginalmotivationforcreatingthesystemGan-dalf.Themaindi erencetotheirworkisthatweuseimplicittypingandrestricttoquanti er-freeformul.Anadvantageisthatwehaveasimpletranslation,andhencegetaquitedirectconnectiontoresolutiontheoremprovers.Hence,wecanhope,andthishasbeentestedpositivelyinsev-eralexamples,thattheprooftraceswegetfromtheproverarereadableassuchandthereforecanbeenusedasaproofcerti cateorasfeedbackfortheuser.Forinstance,theusercanformulatenewlemmassuggestedbythis 150CHAPTER6.FIRST-ORDERLOGIC onhowtointegratetheresolutiontheoremproverVampireintothein

149 terac-tiveprooftoolIsabelle.Theirtransla
terac-tiveprooftoolIsabelle.Theirtranslationfromhigher-orderlogic(HOL)to rst-orderlogickeepstypeinformation,sinceHOLsupportsoverloadingviaaxiomatictypeclassesanddiscardingtypeinformationforoverloadedsym-bolswouldleadtounsoundreasoning.Theyclaimtocutdownthesearchspaceviatypeinformation,butthisisalsoconnectedtooverloading.Theaimoftheirworkisdi erenttoours:whiletheyuse rst-orderproverstodoasmuchautomaticproofsandproofsearchaspossible,weemployautomationonlytoliberatetheuserfromseeminglytrivialproofsteps.InCoq,NuPrl,andIsabelle,theuserconstructsaproofviatactics.Weprovidetypetheoryasaprooflanguageinwhichtheuserwritesdownaproofskeleton

150 ,consistingoflemmas,scopedhypotheses,inv
,consistingoflemmas,scopedhypotheses,invocationofinduction,andmajorproofsteps.The rst-orderproverisinvokedtosolve(easy)subgoals.Thisway,wehopetoobtainhuman-readableproofdocuments(seeourexamples).6.7FutureWorkThelogicalframeworkusedinthischapterdoesnotsupport-types.How-ever,theextensionofthetranslationtoFOLisstraightforward,wesimplyaddanewbinaryfunctionsymbolsforrepresentingpairs.Amoresubstan-tialextensionistheadditionofdatatypesandfunctionsde nedbypatternmatching.Withthisextension,itispossibletorepresenteachconnectiveasaparameterizeddatatype.Eachintroductionruleisrepresentedbyaconstructor,andtheeliminationrulesarerepresentedbyfu

151 nctionsde nedbycases.Thisgivesacompu
nctionsde nedbycases.Thisgivesacomputationaljusti cationofeachoftheaxiomsofthesignaturenat.TheextensionofthetranslationtoFOLisalsostraight-forward:eachde nedequationsforfunctionsbecomesaFOLequality.Oneneedsalsotoexpressthateachconstructorisone-to-oneandthattermswithdistinctconstructorsaredistinct.Anotherdirectionoffurtherworkistoextendtheconservativitytheoremtohandleimplicitarguments.Wealsothinkthatitispossibletoextendourclassoftranslatableformul,forinstance,toincludesomecasesofexistentialquanti cation.Onecouldthinkofaddingmoreplug-ins,withthesameprinciplethattheyarejusti edbyageneralmetatheorem.Forinstance,onec

152 ouldaddaplug-intoamodelchecker,oraplug-i
ouldaddaplug-intoamodelchecker,oraplug-intoasystemwithadecisionprocedureforPresburgerarithmetic.Adi erentapproach,whichissomewaysismoreappealing,istoimple-mentcerti edproversinternallyinthelanguage,inthewaythatwasdonefor 152CHAPTER6.FIRST-ORDERLOGIC 154CHAPTER7.CONCLUSIONS Wehavegivenatypecheckingalgorithmforadependentlytypedlogicex-tendedwithmetavariables.Tomaintaintheimportantinvariantthattermsbeingevaluatedaretypecorrectweworkwithwell-typedapproximationsofterms,wherepotentiallyill-typedsubtermshavebeenreplacedbyconstants.Weshowedthattypecheckingisdecidableandthatthealgorithmissound.Wepresentedthetypecheckingalgorithmforasimpledep

153 endentlytypedlogicalframeworkMLF,butoutl
endentlytypedlogicalframeworkMLF,butoutlinedhowitcanbeextendedtomorefeature-richlogics.TheimplementationhandlesthefulllogicofAgda,andhasproventoworkwellwithexamplesofseveralthousandmetavariables.ModulesystemInlargerdevelopmentsitiscrucialtobeabletosplitaprogramintoseparateunits,andtomanagethescopeoftheseunitssothatde nitionsfromoneunitisnotautomaticallyvisibleinallothers.Forthispurpose,wehavepresentedareasonablesimpleandeasytoimplementmodulesystemwhichisstillexpressiveenoughtoallowlargeprogramstobestructuredinaniceway.Akeydesigndecisionwastokeepthemodulesystemandthetypesystemasseparateaspossible.Asaresultthemodulesystemislargelyindepend

154 entoftheunderlyinglanguage.AutomationWhe
entoftheunderlyinglanguage.AutomationWhenworkingwiththemoreprecisetypesthatadependentlytypedlanguageenables,itissometimesnecessaryordesirabletoprovepropertiesofyourprograms.Whilethesecanbeconstructeddirectlyinthetypetheory,thisissometimestediouswork.Toalleviateprovingsimple rst-orderproperties,wedescribedtheimplementationofalogicalframeworkwithproof-irrele-vantpropositionsanditsconnectiontotheautomatic rst-orderlogicproverGandalf.Soundnessandconservativityoftheconnectionwasestablishedbygeneralmetatheorems.Byrestrictingthesetofformulasunderconsiderationtothatofgeometricformulasweobtainedasimple,transparenttranslationbetweentheframewo

155 rkand rst-orderlogic.Moreovertheproo
rkand rst-orderlogic.Moreovertheproofsconstructedbytheproverareintuitionisticallyvalid.AgdaWehavecollectedthefeaturesdescribedinthisthesis1inalanguageAgda.Whileitisstillfarfrombeingafully edgedprogramminglanguage,it 1Withtheexceptionofthe rst-orderlogicconnection,whichhasbeenimplementedintheAgdaLightlanguage[Nor06] 156CHAPTER7.CONCLUSIONS 158BIBLIOGRAPHY [Bar92a] H.P.Barendregt.Typedlambdacalculi.InS.Abramskyetal.,editor,HandbookofLogicinComputerScience,pages117{309.OxfordUniversityPress,1992. [Bar92b] HenkBarendregt.Lambdacalculiwithtypes.InHandbookofLogicinComputerScience,Volumes1(Background:Mathemat-icalStructures)and2(Background

156 :ComputationalStructures),Abramsky&Gabba
:ComputationalStructures),Abramsky&Gabbay&Maibaum(Eds.),Clarendon,volume2.1992. [BC03] M.BezemandT.Coquand.Newman'slemma|acasestudyinproofautomationandgeometriclogic.Bull.Eur.Assoc.Theor.Comput.Sci.EATCSNo.79,pages86{100,2003. [BC04] YvesBertotandPierreCasteran.InteractiveTheoremProvingandProgramDevelopment.Coq'Art:TheCalculusofInductiveConstructions.TextsinTheoreticalComputerScience.SpringerVerlag,2004. [BD07] AlexandreBuisseandPeterDybjer.Towardsformalizingcate-goricalmodelsoftypetheoryintypetheory.InBrigitePientkaandCarstenSchurmann,editors,SecondInternationalWork-shoponLogicalFrameworksandMetalanguages:TheoryandPractice(LFMTP'07),E

157 lectronicNotesinTheoreticalCom-puterScie
lectronicNotesinTheoreticalCom-puterScience,pages72{85.Elsevier,2007. [Bee07] MichaelBeeson.Otter-homepage,2007.http://michaelbeeson.com/research/otter-lambda. [BH06] EdwinBradyandKevinHammond.Averi edstagedinterpreterisaveri edcompiler:Multi-stageprogrammingwithdependenttypes.InProc.Conf.GenerativeProgrammingandComponentEngineering(GPCE'06),Portland,Oregon,LectureNotesinComputerScience.Springer,2006.Toappear. [BHdN02] MarcBezem,DimitriHendriks,andHansdeNivelle.Automatedproofconstructionintypetheoryusingresolution.JAR,29(3{4):253{275,2002.SpecialIssueMechanizingandAutomatingMathematics:InhonourofN.G.deBruijn. [Bra05] EdwinBrady

158 .PracticalImplementationofaDependentlyTy
.PracticalImplementationofaDependentlyTypedFunctionalProgrammingLanguage.PhDthesis,DurhamUni-versity,2005. 160BIBLIOGRAPHY [Coq96] T.Coquand.Analgorithmfortype-checkingdependenttypes.Comput.Programming26,pages167{177,January1996. [Cou07] JudicaelCourant.MC2AmodulecalculusforPureTypeSys-tems.JournalofFunctionalProgramming,17:287{352,2007. [CPT] T.Coquand,R.Pollack,andM.Takeyama.Alogicalframeworkwithdependentlytypedrecords.InTypedlambdacalculiandapplications(2003),LectureNotesinComput.Sci.,2701,pages22{28. [Dan06] NilsAndersDanielsson.Aformalisationofadependentlytypedlanguageasaninductive-recursivefamily.InTYPES2006.Springer-Verlag,2006. [Da

159 n07] NilsAndersDanielsson.Lightweightsem
n07] NilsAndersDanielsson.Lightweightsemiformaltimecomplex-ityanalysisforpurelyfunctionaldatastructures.Draft,2007. [dB80] NiklasG.deBruijn.AsurveyoftheprojectAutomath.InJ.P.SeldinandJ.R.Hindley,editors,ToH.B.Curry:Essaysincombinatorylogic,lambdacalculusandformalism,pages579{606,London-NewYork,1980.AcademicPress. [dB91a] N.G.deBruijn.Apleaforweakerframeworks.pages40{67,1991. [dB91b] N.G.deBruijn.Telescopicmappingsintypedlambdacalculus.InformationandComputation,91(2):189{204,1991. [DHK95] GillesDowek,ThereseHardin,andClaudeKirchner.Higher-orderuni cationviaexplicitsubstitutions.InDexterKozen,editor,ProceedingsoftheTenthAnnualIEEESymp.onL

160 ogicinComputerScience,LICS1995,pages366{
ogicinComputerScience,LICS1995,pages366{374.IEEEComputerSocietyPress,June1995. [Dow01] GillesDowek.Higher-orderuni cationandmatching.Handbookofautomatedreasoning,pages1009{1062,2001. [DS06] PeterDybjerandAntonSetzer.Indexedinduction-recursion.TheJournalofLogicandAlgebraicProgramming,66(1):1{49,January2006. [Dyb94] P.Dybjer.Inductivefamilies.FormalAspectsofComputing,pages440{465,1994. 162BIBLIOGRAPHY [Hur02] JoeHurd.AnLCF-styleinterfacebetweenHOLand rst-orderlogic.InAndreiVoronkov,editor,CADE'02,volume2392ofLNAI,pages134{138.Springer,2002. [Hur03] JoeHurd.First-orderprooftacticsinhigher-orderlogictheoremprovers.InMylaArcher,BenDiVito

161 ,andCesarMu~noz,edi-tors,STRATA'03,
,andCesarMu~noz,edi-tors,STRATA'03,numberCP-2003-212448inNASATechnicalReports,pages56{68,September2003. [Joh85] ThomasJohnsson.Lambdalifting:Transformingprogramstorecursiveequations.InFPCA,pages190{203,1985. [Lam93] LeslieLamport.Howtowriteaproof.InGlobalAnalysisinModernMathematics,pages311{321.PublishorPerish,Hous-ton,Texas,U.S.A.,February1993.AlsoappearedasSRCRe-searchReport94. [Ler06] XavierLeroy.Formalcerti cationofacompilerback-end,or:programmingacompilerwithaproofassistant.In33rdsympo-siumPrinciplesofProgrammingLanguages,pages42{54.ACMPress,2006. [Luo94] ZhaohuiLuo.Computationandreasoning:atypetheoryforcomputerscience.OxfordU

162 niversityPress,Inc.,NewYork,NY,USA,1994.
niversityPress,Inc.,NewYork,NY,USA,1994. [McB99] ConorMcBride.DependentlyTypedFunctionalProgramsandtheirProofs.PhDthesis,UniversityofEdinburgh,1999. [McB06] ConorMcBride,2006.Personalcommunication. [McB07] ConorMcBride.Epigram,2007.http://www.e-pig.org. [Mil91] D.Miller.Uni cationofsimplytypedlambda-termsaslogicpro-gramming.InK.Furukawa,editor,LogicProgramming:Proc.oftheEighthInternationalConference,pages255{269.MITPress,Cambridge,MA,1991. [Mil92] DaleMiller.Uni cationunderamixedpre x.J.Symb.Com-put.,14(4):321{358,1992. [Miq01] AlexandreMiquel.Theimplicitcalculusofconstructions:Ex-tendingpuretypesystemswithanintersectiontypebind

163 erandsubtyping.InS.Abramsky,editor,Proc.
erandsubtyping.InS.Abramsky,editor,Proc.of5thInt.Conf. 164BIBLIOGRAPHY [NL98] G.NeculaandP.Lee.Ecientrepresentationandvalidationofproofs.InLICS'98,pages93{104.IEEE,June1998. [Nor06] UlfNorell.Agdalight,2006.http://www.cs.chalmers.se/~ulfn/agdaLight. [Nor07] UlfNorell.Agda2,2007.http://www.cs.chalmers.se/~ulfn/Agda. [NPP07] AleksandarNanevski,FrankPfenning,andBrigittePientka.Contextualmodaltypetheory.TransactionsonComputationalLogic,2007.Toappear. [NPS90] B.Nordstrom,K.Petersson,andJ.M.Smith.ProgramminginMartin-Lof'sTypeTheory.AnIntroduction.OxfordUniversityPress,1990. [NPS00] BengtNordstrom,KentPetersson,andJanSmith.Martin-Lof'styp

164 etheory.InHandbookofLogicinComputerScien
etheory.InHandbookofLogicinComputerScience,vol-ume5.OUP,October2000. [Pau90] L.C.Paulson.Isabelle:Thenext700theoremprovers.InP.Odifreddi,editor,LogicandComputerScience,pages361{386.AcademicPress,1990. [Pfe91] FrankPfenning.Uni cationandanti-uni cationintheCalculusofConstructions.InSixthAnnualIEEESymposiumonLogicinComputerScience,pages74{85,Amsterdam,TheNetherlands,1991. [PHe+99] S.PeytonJones,J.Hughes,(editors),L.Augustsson,D.Barton,B.Boutel,W.Burton,J.Fasel,K.Hammond,R.Hinze,P.Hu-dak,T.Johnsson,M.Jones,J.Launchbury,E.Meijer,J.Pe-terson,A.Reid,C.Runciman,andP.Wadler.ReportontheProgrammingLanguageHaskell98,aNon-strict,PurelyFunc-tion

165 alLanguage.Availablefromhttp://haskell.o
alLanguage.Availablefromhttp://haskell.org,Febru-ary1999. [Pol90] R.Pollack.Implicitsyntax.InthepreliminaryProceedingsofthe1stWorkshoponLogicalFrameworks,1990. [Pol94] R.Pollack.TheTheoryofLEGO:AProofCheckerfortheExtendedCalculusofConstructions.PhDthesis,UniversityofEdinburgh,1994. 166BIBLIOGRAPHY [Soz07] MatthieuSozeau.SubsetcoercionsinCoq.InTYPES'06,vol-ume4502ofLectureNotesinComputerScience,pages237{252.Springer,2007. [SP03] C.SchurmannandF.Pfenning.Acoveragecheckingalgorithmforlf.InProceedingsofthe16thInternationalConferenceonTheoremProvinginHigherOrderLogics,TPHOLs,2003. [ST95] JanM.SmithandTanelTammet.Optimizedencodingsoffrag-mentsof

166 typetheoryin rst-orderlogic.InStefan
typetheoryin rst-orderlogic.InStefanoBerardiandMarioCoppo,editors,TYPES'95,volume1158ofLNCS,pages265{287.Springer,1995. [Str93] ThomasStreicher.Investigationsintointensionaltypetheory.HabilitationThesis,LudwigMaximilianUniversitat,1993. [Tam97] TanelTammet.Gandalf.JAR,18(2):199{204,1997. [WM89] C.A.WickandW.McCune.Automatedreasoningaboutele-mentarypoint-settopology.JournalofAutomatedReasoning,5(2):239{255,1989. [Xi98] HongweiXi.DependentTypesinPracticalProgramming.PhDthesis,CarnegieMellonUniversity,1998. [Xi04] HongweiXi.AppliedTypeSystem(extendedabstract).Inpost-workshopProceedingsofTYPES2003,pages394{408.Springer-VerlagLNCS3085,2004.

Related Contents


Next Show more