4connectionisestablishedbyageneralmetatheoremFinallyweputourworkintopractiseintheimplementationofaprogramminglanguageAgdabasedontypetheoryAsanillustratingexampleweshowhowtoprogramasimplecerti12edprov ID: 898534
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.
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 weshowhowtoprogramasimplecertiedpro
weshowhowtoprogramasimplecertiedproverforequationsinacommu-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.1Privatedenitions.................... 77 4.2.2Namemodiers...................... 78 4.2.3Re-exportingnames.................... 79 4.2.4Parameterisedmodules.................. 79 4.2.5Split
4 tingaprogramovermultipleles........
tingaprogramovermultipleles......... 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.4Scopemodiers...................... 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, awaytoconnectthetypecheckertoarst-orderlogictheoremprovertoallowsimpleproofstobefoundautomatically,and animplementationofaprogramminglanguage,Agda,provingthatpracticalprogrammingwithdependenttypesiswithinourreach.1.1Overviewofth
6 ethesisTherestofthischaptersetsthesceneb
ethesisTherestofthischaptersetsthescenebyintroducingadependenttypetheoryUTTandatypecheckingalgorithmforthistheory.Thefollowingthreechaptersdealwiththetaskofturningthisbasictheoryintoaprogramminglanguage,addingpatternmatching,metavariables,andamodulesystem.Chapter2discusseshowtoextendthetheorywithinductivefamiliesandfunctionsdenedbypatternmatchingoverelementsinthesefamilies.Wegiveatypecheckingalgorithmandanalgorithmforcheckingcoverageofpatternmatchdenitions.InChapter3wedescribeandprovesoundanalgorithmfortypecheckingatypetheoryextendedwithmetavariables.Thisallowsustoextendourlanguagewithanotionofimplicitarguments.Chapter4describ
7 esasimplebutpowerfulmodulesystemfordepen
esasimplebutpowerfulmodulesystemfordependentlytypedlanguages.Bykeepingthemodulesystemseparatefromthetypecheckerweobtainacleanmodulesystemwhichislargelyindependentoftheunderlyinglanguage.Theresultsfromthethesechaptersareputtogooduseintheimplemen-tationoftheAgdalanguage,whichisdescribedfromauser'sperspectiveinChapter5.AbiggerexampleofanAgdaprogramforprovingequationsinacommutativemonoidisgiven.Chapter6digressesfromthethemeofusingtypetheoryforprogram-ming,andshowshowarst-orderlogictheoremprovercanbeconnectedtoadependenttypetheorytoprovideautomationofproofsofrst-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.Wehavechosenandtobeinvariantintheirrstargument,butitisalsoconceivabletomakethemcovariantandcontravariant,respectively.Theconversionrulesimplement-equalityonterms.Worthnotingisthat-equalityisrepresentedbyareductionrelation,whereas-equalityisjudge-mental.Thispresentationcorrespondstohowconversionisimplemente
13 dinthetypecheckingrulesinthenextsection.
dinthetypecheckingrulesinthenextsection.Inthecurrentpresentationwecannotwriteverymanyinterestingpro-gramssincetheonlybasetypewehaveisthesingletontype.Ratherthanaddingmoreinterestingbasetypes,however,weholdoutuntilChapter2whereweshowhowtoaddinductivelydenedfamiliesoftypes[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-tionalalgorithmwithmutuallydenedjudgementsforcheckinganexpres-sionagainstatypeandinferringthetypeofanexpression[Pau90,Coq96].Wealsoletthetypecheckerproduceawell-typedtermfromtheinputex-pressionratherthanjustcheckthatitiswell-typed,thusseparatingtheuserlanguagefromthecorelanguageofthetypechecker.Thesetwolanguageshavedistinctlydierentpurposes|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 denitionsInChapter2wedescribeatypec
denitionsInChapter2wedescribeatypecheckingalgorithmfordenitionsbypatternmatchingoverinductivelydenedfamiliesofdatatypes.Adatatypefamilyisintroducedbyadatadeclaration:dataD:!Setiwherec1:1!Dt1...cn:n!DtnThisdeclarationintroducesadatatypefamilyDindexedoverandparam-eterisedby,inductivelydenedbytheconstructorsc1:::cnwiththegiventypes.Theparametersscopeoverthetypesoftheconstructorsandmustbeunchangedinthetargetsoftheconstructors,whereaseachconstructorcantargetadierentindex.Forordinarynon-familydatatypeswillbeempty.Forinstance,thedatatypeofnaturalnumberscanbeintroducedbydata
18 Nat:Setwherezero:Natsuc:Nat!Natandthefam
Nat:Setwherezero:Natsuc:Nat!Natandthefamilyofn-elementnitesetsisgivenbydataFin: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)Cxyandeldprojectionfunctionscanbedenedusingthe-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.Thismeansthattworecordtypesdeclaredtohavethesameeldswillbedierent,buttheywillhavethesameelements.Oneadvantageofthisisthatitsignicantlyimprovestheeciencyofcheckingequalitybetweenrecordtypes|insteadofcomparingthetypesofalltheelds,itisenoughtocomparethenames.Itisalsogoodprogrammingpractisetokeepintentionallydierenttypesseparateinthetypesystem.1.5.4ImplicitargumentsInChapter3wegiveanalgorithmfortypecheckinginthepresenceofmetavariables.Thiswillallowustoextendourtheorywithimplicitar-guments.Weintroduceanewfunctionspacefx:Ag!B,semanticallyequivalentto(x:A)!Bbutwheretheargumentcanbeomitted.Forinstance,thepoly
20 morphicidentityfunctioncanbegiventhetype
morphicidentityfunctioncanbegiventhetypeid:fA:Setg!A!AToapplytheidentityfunctiontoanelementxofatypeA,onesimplywritesidx,omittingtherstargument.Wewillnotimposeanyrestrictionsonwhereimplicitfunctionspacesareallowed,butratherreportanerroriftheimplicitargumentscannotbeinferredinaparticularinstance.Thereasonforthisisthatitisnotclearexactlywhatsuchrestrictionswouldlooklikeandtheywouldnecessarilyexcludemanyusefulcasesofimplicitarguments. 28CHAPTER2.PATTERNMATCHING transkmnkmmn=?Ifwedecidetopatternmatchontheproofofk6mtheproblemisrenedtotranszeromn(leqZerom)mn=?trans(suck)(sucm)n(leqSuckmkm)mn=?WecanclosetherstcasewithleqZeronandinthe
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,thepatternsforthenaturalnumberargumentswererenedeventhoughweneverexplicitlypatternmatchedonthem.Thishastheeectthatthepatternsbecome(seem
22 ingly)non-linear.Inthelastcaseabovethere
ingly)non-linear.Inthelastcaseabovetherearemultipleoccurrencesofthevariablesk,m,andn.Itisimportanttopointout,however,thattherepeatedvariablesareexactlythosethatarenecessarytomakethelefthandsidewell-typed.Thenalthingtonoteisthatwehaveamorerenednotionofimpossiblepatternsthanyouhaveforsimpledatatypes.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].Thismeansthatallequationsmightnotholdasdenitionalequalities.Consider,forinstance,thedenition t :Nat!Nat!Natxtzero=xzeroty=ysucxtsucy=suc(xty)Here,thereisnowaywecouldgetboththersttwoequationstoholddenitionally.Thealgorithmworksbyrsttypecheckingeachequationindividually,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!isthelistofvariablesinwherexhasbeenreplacedbyp.Thecontextjx:=pisdenedbyppp`p:Ap;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.4UnicationUnicationisperformedrelativetoasetof exiblevariables,i.e.variablesthatareopenforunication.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.Uponsuccessfulunicationacontextmappingfromanewcontexttotheoriginalcontextisproduced.Wewrite;`Unify(u=v:A)=):!forthesuccessfulunicationofuandvoftypeAinthecontextwith exiblevariables,resultinginthecontextmappingfromthenewcontextto.Intuitivelywillbethecontextobtainedbyapplyingtheunierofuandvto.Asweshallseethismightrequirereorderingof.Afailedunicationiswritten;
28 0;`Unify(u=v:A)*Whenfacedwithaproblemwhi
0;`Unify(u=v:A)*Whenfacedwithaproblemwhichistoodicultunicationwillsimplygiveup.Werepresentthisbyastuckunicationproblem.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:Unication 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:Congurationrenementrules A!whnfDuv8cj2Constrs(D):cju:j!Duwpj=b1c;cbc;b2cj=fjgifSplit(pj;1(x:A)2)=)j:j!;ifSplit(pj;1(x:A)2)* Splitx(1(x:A)2)=)[jjIfthecontextcanbesplitalongxthensplittingreturnsthesetofcon-textmappingsobtainedbysplittingwithrespecttoeachconstructorinthedatatypeatx.WewillusethissplittinginSection2.2whenwediscussthereductionbehaviouroffunctionsdenedbypatternmatching.2.1.6TypecheckingalgorithmAsdescribedinSection2.1.2,thetypecheckingalgorit
31 hmbuildsawell-typedcontextmappingcorresp
hmbuildsawell-typedcontextmappingcorrespondingtothegivenuserpatternsbysuccessivelyreningcongurationsintheformhp;:!i,whereisthetypeoftheargumentstothefunctionbeingchecked,isthecontextmappingbuiltsofar,andparetheuserpatternscorrespondingtothevariablesin.Wewritehp;:!i=)hq;:!i 38CHAPTER2.PATTERNMATCHING `CheckInaccessible(p=:)denedby`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.WedeneCheckPats(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 Wecannowgivetherulesforcheckingaclauseinafunctiondenition.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]denitionshavebeenrestrictedtonon-overlappingpatternscorrespondingtoacoveringoftheargumentcontext.Inthisworkwehaverelaxedthisrequirementand,sofar,onlyrequiredthattheclausesofadenitioncanbeobtainedbyourrelaxedformofcontex
35 tsplitting.Thismeansthatweallowoverlappi
tsplitting.Thismeansthatweallowoverlappingclauses.Forinstance, t :Nat!Nat!Natxtzero=xzeroty=ysucxtsucy=suc(xty)wherethersttwoclausesoverlap,or == :Nat!Nat!Bool 4Theconcretesyntaxfor;inAgdais(). 42CHAPTER2.PATTERNMATCHING fnmx(neqbsucmc)=:::fbsuc(dblm)cbsuc(suc(dblm))c(even(sucm))eq=:::Inordertoobtainthesecondclauseitisnecessarytorstsplitonx,butsincetherstclauseonlysplitsonpthatiswhatouralgorithmwillstartwith.Intheeqcasewewillthenhavethecontext(n:Nat)(x:Even(sucn))wherewewouldliketosplitonx.Thisisnotpossiblesinceunicationgivesupondblm=sucn.Ratherthanreportanerrorinthiscase,whichiswhatwedo,onecouldimaginebacktrackingandtry
36 ingtosplitinadierentorder.Thedrawba
ingtosplitinadierentorder.Thedrawbackwiththisapproachisthatitwillbeveryhardfortheusertopredictwhattheresultingcoveringwillbe.Withourapproachthisismucheasier.AnotheroptionisofcoursetogiveuponoverlappingpatternsandusethealgorithmoutlinedbyCoquand[Coq92],butaswehaveseenoverlappingcasescanbequitehandyattimes.Anotherobservationisthatwiththisalgorithmitisnotpossibletorecre-ateallsplittings.Considerthefollowingversionofthemajorityfunction:majxfalsefalse=falsemajxtruefalse=xmajfalsextrue=xmajtruextrue=trueThisversioncorrespondsexactlytothecoveringobtainedbyrstsplittingonthethirdargumentandtheninthefalsecasesplittingonthesecondargumentandi
37 nthetruecaseontherstargument.Therei
nthetruecaseontherstargument.Thereis,however,nowayofreorderingtheclausestohaveouralgorithmstartbysplittingonthethirdargument.Ontheotherhand,itiseasytogetthisbehaviourbyintroducingtwohelperfunctions,sowehavenotlostanyexpressivity.2.2.1CoveragealgorithmIfMatch(p;v)?=)thenthereisanon-emptysequenceofneutraltermsinvwhicharebeingmatchedagainstconstructorpatterns,andhencecausethematchingtogetstuck.WedenotethesetermsbyBlockers(p;v).NowwedeneaclauseCforafunctionf:!Atobeacontext,acontextmapping:!,andarighthandside`rhs:A.Weleavethecontextimplicit,sinceitcanbededucedfrom.Giventhe
38 listofclausesprovidedbytheuser(whichhave
listofclausesprovidedbytheuser(whichhavebeendeemedproperclausesbythetypechecker)wecomputeanewsetofclausescorrespondingtoacoveringoftheargumentcontext.WewriteCovering(C;:!)=)C0where 44CHAPTER2.PATTERNMATCHING thesecondcasematchingagainsttherstclausefails,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].ToseewheretheKaxiomisusedletuswalkthroughthetypecheckingofitsdenitionbypatternmatching.RecalldataId(A:Set)(x:A):A!Setwherere :IdAxxTosimplifymattersweassume(A:Set)(x:A)(P:IdAxx!Set)anddeneK:(pr:Pre )(p:IdAxx)!PpKprre =prCheckingthelefthandsideofthisdeni
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=enandwecheckthatthisconstitutesavaliddenition.Itisimportanttocheckthattheabstractedtypeiswell-formed,sincethisisnotnecessarilythecase.Forinstance,abstractingovertherstprojectionofadependentpairmightnotbewell-typedwithoutalsoabstractingoverthesecondprojection,sincetherstprojectionoccursinthetypeofthesecondprojection.Toa
41 bstractmorethanoneexpressionatoncetheyar
bstractmorethanoneexpressionatoncetheyareseparatedbybars,likeso:many:(x:(n:Nat)(n6zero))!Natmanyxwith1xj2xmanyxjbzerocjleqZero=zero2.3.1ExamplesFilteringlistsAbstractingsyntacticoccurrencesoftheanalysedexpressioncomesinveryhandywhenreasoningaboutfunctionsdenedbywith.Considerthelterfunctionwhichremovesallelementsnotsatisfyingagivenpredicatefromalist.dataList(A:Set):Setwhere":ListA :: :A!ListA!ListAlter:fA:Setg!(A!Bool)!ListA!ListAlterp"="lterp(x::xs)withpxlterp(x::xs)jtrue=x::lterpxslterp(x::xs)jfalse=lterpxsSupposewewanttoprovethatthelteredlistisasublistoftheoriginallist,i.e.th
42 atallelementsofthelteredlistappears
atallelementsofthelteredlistappearsintheoriginallistinthesameorder.Wemightdenedata 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.WerstdeneaviewdatatypeParitywithoneconstructorforeachofourtwocases.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,denethefunctionhalfveryelegantly.half:Nat!Nathalfnwithparitynhalfb2kcjevenk=khalfb2k+1cjoddk=kTheconceptofviewsinthisformwasintroducedbyMcBrideandMc-Kinna[MM04a]andtheytakeitonestepfurther,allowingyoutoomitthepatternsfortheviewdatatype. 50CHAPTER3.METAVARIABLES theconstraintsintherightorder,andtofailassoonasanequalityisinvalid,sincewelltypednessofaconstrain
44 tmaydependonpreviousconstraintsbeingsati
tmaydependonpreviousconstraintsbeingsatised.Forrepresentingproofsearchintheseframeworksitisconvenienttoex-tendthenotionoftermswithmetavariablesthatstandsforyetundeterminedterms(proofs).Metavariablesarealsousefulforstructureediting,asplace-holdersforinformationtobelledinbytheuser.Inthispaperwewillhoweverfocusontypereconstructionwheremetavariablesareusedforrep-resentingomittedinformationthatcanberecoveredfromtypingconstraintsthroughunication.Whenaddingmetavariables,equalitycheckinggetsmorecomplicated,sincewecannotalwaysdecidethevalidityofanequality,andwemaybeforcedtokeepitasaconstraint.Thisiswell-knowninhigherorderunica-ti
45 on[Hue75]:theconstraint?0=0hastwosolutio
on[Hue75]:theconstraint?0=0hastwosolutions?=x:xand?=x:0.ThisappearsalsointypetheorywithconstraintsoftheformF?=BoolwhereFisdenedbycomputationrules.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.7wediscusstheissuesinvolvedinextendingthisworktoUTTanddenitionsbypatternmatching.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-recursivedenitions.JudgementsThetypesystemofMLFispresentedinsixmutuallyde-pendentjudgementforms.`isavalidsignature`validisavalidcontext`AtypeAisavalidtypein`M:AshastypeAin`A=BAandBareconvertibletypesin`M=N:AsandtareconvertibletermsoftypeAinThetypingrulesfollowsstandardpresentationsoftypetheory[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,containingpreviouslydenedconstants,metavariables,andguardedconstants.Inotherwords,wecanwritealljudge-mentsontheformhiJ=)h0i.TomaketheruleseasiertoreadwerstdeneasetofoperationsreadingandmodifyingthesignatureandwhenpresentingthealgorithmsimplywriteJforthejudgementabove.Inruleswithmultiplepremissesthesignatureisthreadedtop-down,left-to-right.Forinstance,P1P2P3 Jisshort-handforh1iP1=)h2ih2iP2=)h3ih3iP3
50 =)h4i h1iJ=)h4iWeintroducean
=)h4i h1iJ=)h4iWeintroduceanoperationLookup(c:A)tolookupthetypeofaconstantinthesignature.Tomanipulatemetavariablesweintroduce:AddMeta(:A)whichaddsanewmetavariableoftypeAtothesignature,and:=swhichinstantiatestos.ForguardedconstantsweaddtheoperationAddConst(p:A=swhenC)toaddanewguardedconstanttothesignature.InSection3.3.2weexplaintherulesforsolvingtheconstraintsofaguardedconstant.WealsointroduceanoperationInScope(s)tocheckthatsisinscopeatthedenitionsiteof(toensurethatcanbeinstantiatedtos).DetaileddenitionsoftheoperationscanbefoundinFigure3.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.Iftheheadsaredierentconstantsorvariablesconversioncheckingfails. 60CHAPTER3.METAVARIABLES ingcaseiswhencomparingtherstargumentsresultsinsomeunsolvedconstraints.Ifthevalue
54 oftherstargumentisusedinthetypesofl
oftherstargumentisusedinthetypesoflaterarguments(x2FV())wehavetostopandproduceaconstraintsincethetypesofsandtdier.Ifontheotherhandthetypesoflaterargumentsareindependentofthevalueoftherstargument,wecanproceedandcomparethemwithoutknowingwhethertherstargumentsareconvertible.ConstraintSolvingSofar,wehavenotlookedatwhenorhowtheguardsofaconstantaresim-pliedorsolved.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,andametavariableoftypeSet.Nowwewanttocomputessuchthat`id 0";sTodothisoneoftheconversionruleshastobeapplied,sothetypecheckerrstinfersthetypeofid 0.`id#(A:Set)!A!A;id` "Set;`0#Nat;0:=Nat `0";0 `id 0#;id0 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,resultingintheconstraints0=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=coerceqwhen0=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.Thisfollowsfromthesignaturerenementlemma(Lemma3.5.3)whichcanbeappliedifweprovethatif=1;:B0;2then`j1jx:s:B0. 66CHAPTER3.METAVARIABLES Remark3.5.9. IfCensuresJinand0extends&
61 #6;thenCensuresJin0.Notethatinthecas
#6;thenCensuresJin0.Notethatinthecasewhen0invalidatesCtheremarkisvacuous|afalseconstraintensuresanything. Denition3.5.10(Consistentsignature). Asignatureissaidtobecon-sistentifforanypwithequalto1;p:A=swhenC;2itisthecasethatCensures`s:Ain1.Inordertoprovethattypecheckingpreservesconsistency,werstneedtoknowthattheconstraintsweproducearesound. 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:=px]itholdsthat;x:A1`j0jB1=B2giventhat;x:A1`j0jB1=B2[x:=px]Since2solvesA1'A2ithasanemptyguardforp,sopxreducestoxandwearedone. InthecasewhereCisknown(forinstance,intheruleforblockedterms),wecanapplysoundnessofconversionchecking(Theorem3.5.5)
63 toget`j0jC. Lemma3.5.12. Reneme
toget`j0jC. Lemma3.5.12. Renementpreservesconsistentsignatures.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(renement)andreplacingatermbyaguardedconstantwithanappropriatecandidatevalue(approximation). Denition3.5.15(Approximation). Atermsapproximatess0ifscanbeobtainedbyreplacingsubtermstofs0byguardedconstantspxwhosecandi-datevaluesapproximatest. Denition3.5.16(Renement). Atermsisarenementofauserexpres-sioneifscanbeobtainedbyreplacingthe inebyconcreteterms. Lemma3.5.17. If`e"A;sthensapproximatesarene
65 mentofe.Thispropertyispreservedwhenunfol
mentofe.Thispropertyispreservedwhenunfoldinginstantiatedmetavariablesandguardedconstantsins. Proof. Byinductionoverthederivation. 3.5.4MainresultWenowprovethemainsoundnesstheoremstatingthatifallmetavariablesareinstantiatedandallguardssolved,thenthetermproducedbythetypechecker(extendedwithconstraintsolving)isvalidintheoriginalsignatureafterunfoldingthedenitionsofthemetavariablesandguardedconstantsintroducedduringtypechecking. Theorem3.5.18(Soundnessoftypechecking). Ifisawell-formedMLFsignatureandhi`e"A;s=)h0i,thenifallmetavariableshavebeeninstantiatedandallguardsareemptyin0,then`s:Awhereisthesubstit
66 utionunfoldingthemetavariablesandconstan
utionunfoldingthemetavariablesandconstantsin0.Moreover,sisarenementofe. 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.4PatternmatchingIfwehavedenitionsbypatternmatching,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)mappingmodulesimplementingaparticularinterfacetoamoduleimplementingadierentinterface.AlthoughthemodulesystemofCoqismuchmorepowerfulthanthemodulesystempresentedhere,itisalsosignicantlymorecomplex.HarperandPfenning[HP98]presentsamodulesystemforLFinthesamespiritasthemodulesystemofCoq,andCourant[Cou07]givesatheoreticalfoundationforthiskindofmodulesystemsinthecontextofPureTypeSystems[Bar92a].Whilew
72 earetryingourbesttodecouplemodulesfromre
earetryingourbesttodecouplemodulesfromrecordtypes,Pollacktakestheoppositeapproach[Pol00,CPT]andextendsrecordtypeswithmoremodulesystemlikefeatures,suchasmanifestelds.4.2DescriptionThesyntaxofthemodulesystemisgiveninFigure4.1.Weleavethesyntaxofdenitionsopen,sinceitisnotimportantforthemodulesystem.Theexamplesusesomesuitablemade-upsyntax,orinthecaseoftheexampleinSection4.4,Agdasyntax(seeChapter5).Firstletusintroducesometerminology.Adenitionisasyntacticcon-structiondeninganentitysuchasafunctionoradatatype.Anameisastringusedtoidentifydenitions.Thesamedenitioncanhavemanynamesandatdierentpointsintheprogramitwillha
73 vedierentnames.Itmayalsobethecaseth
vedierentnames.Itmayalsobethecasethattwodenitionshavethesamename.Inthiscasetherewillbeanerrorifthenameisused.Themainpurposeofthemodulesystemistostructurethewaynamesareusedinaprogram.Thisisdonebyorganisingtheprograminanhierarchicalstructureofmoduleswhereeachmodulecontainsanumberofdenitionsand 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.Thesametechniqueisusedfordenitionsthatonlyhaveambiguousnames.Ineectusingprivatedenitionsmeansthatfromtheuser'sperspectivewedonothavesubjectreduction.Thisisjustanillusion,however|thetypecheckerhasfullaccesstoalldenitions.4.2.2NamemodiersAnalternativetomakingdenitionsprivateistoexertnercontroloverwhatnamesareintroducedwhe
75 nopeningamodule.Thisisdonebyqualifyingan
nopeningamodule.Thisisdonebyqualifyinganopenstatementwithoneormoreofthemodiersusing,hiding,orrenaming.Youcancombinebothusingandhidingwithrenaming,butnotwitheachother.TheeectofopenAusing(x)renaming(ytoz)istointroducethenamesxandzwherexireferstothesamedenitionasA:xiandzireferstoA:yi.Notethatifxandyoverlaptherewillbetwonamesintroducedforthesamedenition.Wedonotpermitxandztooverlap.Theotherformsofopeningaredenedintermsofthisone.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)Asmentionedparametrisingamodulehastheeectofabstractingthepa-rametersoverthedenitionsinthemodule,sooutsidetheSortmodulewehaveSort:insert:(A:Set)( 6 :A!A!Bool)!A!ListA!ListASort:sort:(A:Set)( 6 :A!A!Bool)!ListA!ListAForfunctiondenitions,explicitmoduleparameterbecomeexplicitargu-mentstotheabstractedfunction,andimplicitparametersbecomeimplicitarguments.Forconstructors,however,theparametersarealwaysimplicitarguments.Thisisaconsequenceofthefactthatmoduleparametersareturnedintodatatypeparameter
77 s,andthedatatypeparametersareimplicitarg
s,andthedatatypeparametersareimplicitargumentstotheconstructors.Italsohappenstobethereasonablethingtodo.SomethingwhichyoucannotdoinCoqistoapplyasectiontoitsar-guments.Weallowthisthroughthemoduleapplicationstatement.Inourexample:moduleSortNat=SortNatleqNatThiswilldeneanewmoduleSortNatasfollowsmoduleSortNatwhereinsert:Nat!ListNat!ListNatinsert=Sort:insertNatleqNatsort:ListNat!ListNatsort=Sort:sortNatleqNatThenewmodulecanalsobeparameterised,andyoucanusenamemodi-erstocontrolwhatdenitionsfromtheoriginalmoduleareappliedand 82CHAPTER4.MODULESYSTEM importMopenMSometimesthenameofanimportedmoduleclasheswithalocalmodule.Inthiscaseitispo
78 ssibletoimportthemoduleunderadieren
ssibletoimportthemoduleunderadierentname.importMasM0Itisalsopossibletoattachmodierstoimportstatements,limitingorchang-ingwhatnamesarevisiblefrominsidethemodule.4.3EquipmentforrecordtypesArecordisessentiallyanested-type2,butinordertousethemconvenientlyweneedsomebasictools.Twothingsthatonemightwantaresuitablynamedprojectionfunctionsandsomewayofopeningarecordtobringtheeldsintoscope.Itturnsoutthatusingthemodulesystemwecangetboththingsforthepriceofone.ForarecordtyperecordR:Setwherex1:A1x2:A2[x1]...xn:An[x1:::xn1]wegenerateaparameterisedmoduleRmoduleRfg(r:R)wherex1:A1x1=1rx2:A2[x1]x2=1(2r)...xn:An
79 [x1:::xn1]xn=2(:::(2r))The
[x1:::xn1]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|Wecandenesomederivedfunctions :A!A!Setxy=y6x|andprovesomeauxiliarylemmas.Proofsomitted.6antisym:fxy:Ag!x6y!xy!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 ealsodenethedualpartialorderdualOrd
ealsodenethedualpartialorderdualOrder:PartialOrderAdualOrder=recordf == = == ; 6 = ;:::gAcommonidiomwhenre-exportingthecontentsofamoduleMappliedtosomeargumentstisprivateopenmoduleM0=MtpublicwhichisequivalenttoprivatemoduleM0=MtopenM0publicThatis,wedeclareaprivatemoduleM0astheapplicationofMtotandthenweexportthecontentsofthismodule.Itmakessensetomaketheintermediatemoduleprivate,sinceweexportitscontentsfromthecurrentmodule.GivenapartialorderoverAandanoperation u :A!A!Awecandenewhatitmeansforthistobeasemilattice.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(6re tore ;6transtotrans;6antisymtoantisym; u to t ;ulbLtotubL;ulbRtotubR;uglbtotlub;ucommutetotcommute;uassoctotassoc;uidemtotidem)dualLattice:LatticeAdualLattice=recordfsl=sl0; t = u ;prf=SemiLattice:prfLL:slgWecanplaythesametrickwedidwiththedualpartialorderforlattices.Forinstanceifweprovetheleftabsorptionlawxu(xty)==xwegettheduallawxt(xuy)==xsimplybyinstantiatingtheabsorptionlawtotheduallattice. 88CHAPTER4.MODULESYSTEM japplyM1=M2termsjdefnAsbeforeweleavethesyntaxofdenitionsabstract
83 .Theonlypartsofthemodulesystemwhichremai
.Theonlypartsofthemodulesystemwhichremainaretheparameterisedmodulesandthemoduleapplications.Thesecouldalsobetranslatedawaybyperformingthecor-respondingabstractionsandapplicationssyntactically.Thiswouldhowevermeanthattheabstractedtelescopes,themodulearguments,andthetypesofthedenitionwouldbetypecheckedonceforeachmoduleapplicationanddenitionintheappliedmodule,soforperformancereasonswechoosetoleavethemforthetypechecker.4.5.1ScopecheckingstateThescopecheckingalgorithmispresentedinamonadicstyle,workingonastateconsistingofastackofscopes,whereeachscopecorrespondstoamoduleenclosingthedeclarationsbeingscopechecked.Ascopehasanamewhichisthena
84 meofthecorrespondingmoduleandaprivateand
meofthecorrespondingmoduleandaprivateandapublicnamespace.Anamespacemapsnamesofdenitionsandmod-ulestouniquefullyqualiednames.Wedistinguishbetweenthenamestheuserhasfordenitionsandmodules(UDefName,UModuleName)andtheuniquequaliednamesusedinternallybytheimplementation(DefName,ModuleName).WeusexandyforUDefNames,MforUModuleNames,zforwhenbothUName=UDefName[UModuleName,qforDefNames,andQforModuleNames.FortheunionofName=DefName[ModuleNameweusew.WedeneS::="jSscopestack::=hM;nspub;nspriiscopesns::=hx;Minamespacesx2UDefName!SetDefNameM2UModuleName!SetModuleNameThesamenamemightatsomepointrefertos
85 everaldierentdenitionssoanames
everaldierentdenitionssoanamespacemapsnamestosetsofuniquenames.ThenameofascopeisnotfullyqualiedsotogetthefullyqualiednameofanentityzdenedinthestateSwedeneFullNamezSbyFullName:UName!State!NameFullNamez("hM1; ; i:::hMn; ; i)=M1:::::Mn:z 90CHAPTER4.MODULESYSTEM pop:State!Statepop(S2hM;nspub; i)=S(extend(qualifyMnspub)2)InanamespacequaliedbyMallnamesstartwithM.qualify:UModuleName!NameSpace!NameSpace(qualifyMns)(M:z)=ns(z)(qualifyMns)(z)=;;ifzisnotoftheformM:wTodeneanamespace,wespecifyhowtolookupnamesinit.Sincenamespacesareessentiallyfunctionsthisc
86 onstitutesavaliddenition.Toaddnames
onstitutesavaliddenition.Toaddnamespacenstoascopewewriteextendns.Dependingonthenamespaceisaddedtoeitherthepublicorprivatepartof.Toaddascopetoascopestackbothpartsofareaddedtothetopscopenamespaceindicatedbytheargument.extend:NameSpace!Scope!ScopeextendpubnshM;nspub;nsprii=hM;nspub[ns;nspriiextendprinshM;nspub;nsprii=hM;nspub;nspri[nsiextend:Scope!State!Stateextendh ;nspub;nsprii(S)=Sextend(nspub[nspri)Rememberthatthetop-levelisalwaysamodule,sothescopestackwillneverbeempty.4.5.4ScopemodiersWerstdenetheeectofthethreescopemodiersonanames
87 pacesepa-rately.Notethatmodifyingamodule
pacesepa-rately.Notethatmodifyingamodulenameaectsallnamesinthatmodule.(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,whichnowcontainsallthenamesdenedinthemodule,andaddittothenextscopeonthestack.Wealsohavetobindthenameofthedenedmodule.Theoutputisasection.Scopecheckingamoduleapplicationis
88 alittlemoreinvolved.Basicallytodene
alittlemoreinvolved.BasicallytodeneamoduleM1astheapplicationofM2weopenM2intoanewscopenamedM1.However,sincemoduleapplicationsintroducenewdenitionswehavetochangethequaliednamespointingintoM2sothattheypointtoM1instead.`ScopeCheck(moduleM1=M2termsmods)=Q1 FullNameM1Q2 Lookup(M2)0 `ScopeCheck()terms0 0`ScopeCheck(terms)pushM1OpenM2pubmodsRedirect(Q27!Q1)popbindM1Q1return(applyQ10=M2terms0)OpeningamoduleMisdonebyaddingallnamesM:ztothecurrentscopeasz,possiblyhidingorrenamingsomenames.OpenMmods(S)=Sextendnswherens=ApplyModsmods(MatchM(Smash(S)))whe
89 re(MatchMns)(x)=ns(M:x).Theredirectionof
re(MatchMns)(x)=ns(M:x).TheredirectionofthenamesfromtheappliedmoduleisdenedbyRedirect(Q27!Q1)(S)=Redirect(Q27!Q1)(Redirect(Q27!Q1))(z)=fQ1:qjQ2:q2(z)gForthistobecorrectitisimportantthatthepublicnamesinM2allrefertodenitionsinM2.Thatis,wehavetomakesurethateverytimeweaddanametothepublicnamespaceofamoduleitreferstoadenitionfromthatmodule.Inparticularwehavetotakecarewhenopeningmodulespublicly.IdeallywewouldliketodenethescopecheckingofanopenstatementsimplyasacalltoOpenbutasjustobservedthiswouldnotbecorrectinthecaseofapublicopen.Inthiscasewecreateadummymodulewhichwethenopen.`ScopeCheck(openMmods)= 9
90 4CHAPTER4.MODULESYSTEM M:id:(X:Set)!X!XM
4CHAPTER4.MODULESYSTEM M:id:(X:Set)!X!XM:idXx=xThejudgementformforcheckingdeclarationsisQ()`decl;0andtherulesformodulesanddenitionsareQ()`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=:tToeasethepresentationthedenitionruleisforasimpliedformofde-nitionQ:f:A=t.Theprincipleisthesameformoreadvancedformsofdenitions,however.Formoduleapplicationswegeneratenewdenitionsapplyingthedeni-tionsfromtheappliedmodule:applyM0=MNatturnsintoM0
91 :id:Nat!NatM0:id=M:idNatHerewearemakingt
:id:Nat!NatM0:id=M:idNatHerewearemakingthefurtherassumptionontheunderlyinglanguagethatitsupportsdenitionsoftheformx:A=t.TheruleisQ1(1)Q2(2)`ctx;0Q1:Q4(14)2Q1(1)Q2(2)0`e:4;tforeachQ1:Q4:fi:14!Ai2leti=Q1:Q2:Q3:fi:120!Ai[4:=t]=120:Q1:Q4:fi1t Q1(1)Q2(2)`applyQ1:Q2:Q3=Q1:Q4e;;Tobetterunderstandwhatisgoingoninthisruleithelpstolookatwhattheprogramlookslikeatthetimethisruleisapplied:moduleQ11wheremoduleQ44whereQ1:Q4:fi:AimoduleQ22whereapplyQ1: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.Aqualiednameisanon-emptysequenceofnamesseparatedby.(dot).Qualiednamesareusedtorefertoentitiesinothermodules.5.1.2InteractionpointsInteractionpointsareholesinaprogramwhereanexpressionshouldbelledin.Thesearewritten?or{!...!}.Inaninteractiveenvironmenttheusercaninteractwith
93 thetypecheckerthroughtheseinteractionpoi
thetypecheckerthroughtheseinteractionpoints,forinstance,askingforthetypeoftheexpressiontobelledinorthelocalcontext.Internallythetypecheckertreatsinteractionpointsasmetavariableswhichwillnotbesolvedautomatically.5.1.3ImplicitsyntaxItispossibletoomittermsthatthetypecheckercangureoutforitself,replacingthemby_.Ifthetypecheckercannotinferthevalueofan_itwillreportanerror.Forinstance,forthepolymorphicidentityfunctionid:(A:Set)!A!A,therstargumentcanbeinferredfromthetypeofthesecondargument,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.6DatatypesandfunctiondenitionsFunctionscanbeintroducedbygivingatypeandadenition.Forinstance,thepolymorphicidentityfunctioncanbedenedby id:{A:Set}-A-Aidx=xNotethattheimplicitargumenti
95 sleftoutinthelefthandside.Asinalambdaabs
sleftoutinthelefthandside.Asinalambdaabstractionitcanbegivenexplicitlybyenclosingitincurlybraces: id:{A:Set}-A-Aid{A}x=xDatatypesareintroducedbydatadeclarations.Forinstance,thenaturalnumberscanbedenedby dataNat:Setwherezero:Natsuc:Nat-NatToensurenormalisation,inductiveoccurrencesmustappearinstrictlyposi-tivepositions.Forinstance,thefollowingdatatypeisnotallowed: dataBad:Setwherebad:(Bad-Bad)-BadsincethereisanegativeoccurrenceofBadintheargumenttotheconstructor.Functionsoverelementsofadatatypecanbedenedusingpatternmatch-ingandstructuralrecursion.Theadditionfunctiononnaturalnumbersisdenedb
96 y _+_:Nat-Nat-Natzero+m=
y _+_:Nat-Nat-Natzero+m=msucn+m=suc(n+m)Theoperatorformcanbeusedbothinlefthandsidesandrighthandsidesasseenhere.Datatypescanbeparameterisedoveratelescopeofparameters.Thesearewrittenafterthenameofthedatatypeandscopeovertheconstructors. 102CHAPTER5.THEAGDALANGUAGE 5.1.7RecordsRecordtypesaredeclaredinmuchthesamewayasdatatypes,butinsteadofgivingthetypesoftheconstructorsyougivethetypesoftherecordelds.Forinstance,wecandenethetypeofevennumbersasarecordtypecontaininganumberandaproofthatitiseven. recordEven:Setwhereval:Natprf:IsEvenvalNotethatlatereldsmayrefertoearliereldvaluesbyname.Recordtypesarecomparedbyname,so
97 thisintroducesanewtypeEven,dierentf
thisintroducesanewtypeEven,dierentfromallotherrecordtypes.Tobuildanelementofarecordtypeyouwrite record{val=suc(suczero);prf=evenSS_evenZ}Theeldscanbegiveninanyorder.Foreachrecordtypeamoduleofthesamenameisdened,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.8LocaldenitionsEachclauseinafunctiondenitioncanhaveablockoflocaldeclarations.Thesecanbeanydeclarationsthatcanappearonthetop-level,includingmodules,datatypedeclarations,andrecursivefunctions.Forinstance,thereversefunctioncanbedenedusingalocalrecursivefunction: 104CHAPTER5.THEAGDALANGUAGE Rememberthattheextentofamoduleisdeterminedbyindentation.Tousethenamesfromamoduleavailablewithoutqualication,oneusesanopenstatement: openNumberstwo:Nattwo=suconeThefulldescriptionofthemodulesystemcanbefoundinChapter4,includingparameterisedmodules,andmorene-grainedcontroloveropenstatements.
99 5.1.10AdditionalfeaturesInadditiontothef
5.1.10AdditionalfeaturesInadditiontothefeaturesdescribedhere,Agdahasexperimentalsupportformutualinduction-recursivedenitions[DS06].Mutualdenitionsaregiveninsideamutualblock: mutualeven:Nat-Boolevenzero=trueeven(sucn)=oddnodd:Nat-Booloddzero=falseodd(sucn)=evennAdetaileddiscussionofmutualinductive-recursivedenitionsisbeyondthescopeofthisthesis.5.2AbiggerexampleDependenttypesnotonlygivesyouthepossibilitytoprovepropertiesaboutprograms,youcanalsowriteprogramstocomputeproofs.Toillustratethiswedevelopaninternalsolverforequationsinacommutativemonoid,suchasthenaturalnumberswithadditionandzero.Thebasicideaistomodelsuch
100 equationsbyadatatypeanddeneanormali
equationsbyadatatypeanddeneanormalisationfunctionforthisdatatype.Tocheckifanequationholdswecanthensimplycheckthatbothsidesreducestothesamenormalform.Weprovethisstrategysoundwhichenablesustousethesolvertoproveequationsinarbitrarycommutativemonoids.ThissectionconsistsofanumberofliterateAgdaleswhichcanbeprocessedbothbyLATEXandtheAgdatypechecker. 106CHAPTER5.THEAGDALANGUAGE Theidentityfunctionandfunctioncompositionarealwaysusefulsoletusdenethem. 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.Wedenethebooleanswiththeconstructorsfalse,andtrue. dataBool:Setwherefalse:Booltrue:Boolinfix5if_then_else_if_then_else_:{A:Set}-Bool-A-A-Aiftruethenxelsey=xiffalsethenxelsey=yThexityoftheif_then_else_dictateswhetherornotparenthesisareneededfortheelsebranch.Wewouldliketoavoidparenthesessowesetittoalowvalue.Ahighxitymeansthattheoperatorbindstightlyandalowxitythatitbindsloosely.Forinstance,given infixl20_+_infixl30_*_theexpressionx+y*zparsesasx+(y*z)ratherthan(x+y)*z.Naturalnumbersareden
102 edwithtwoconstructorszeroandsuc.TheBUILT
edwithtwoconstructorszeroandsuc.TheBUILTINpragmastellsthetypecheckeraboutourdenitionofnaturalnum-bersandallowsthemtoberepresentedmoreecientlyinternally.Italsoletsususenumericliteralstoconstructnaturalnumbers. dataNat:Setwherezero:Natsuc:Nat-Nat{-#BUILTINNATURALNat#-}{-#BUILTINZEROzero#-}{-#BUILTINSUCsuc#-} 108CHAPTER5.THEAGDALANGUAGE Thenaturalnumberargumentntotabulatecanbeinferredbythetypecheckerwhenweusethefunction,butdeningtabulateweneedtorecurseovern.RatherthanalsobindingAexplicitlyinthelefthandsidewerefertonbyname.Thenametobeusedistakenfromthetype.5.2.3EquivalencerelationsNextwedeneasmalllibraryforequivalenc
103 erelationsandgiveinstancesforlistsand
erelationsandgiveinstancesforlistsandnitesetswhicharetheonesweneedforoursolver. moduleEquivalencewhereopenimportLogicWesplitthedenitionofwhatanequivalencerelationisintotwoparts.Firstwedenewhatitmeansforarelationtobeanequivalenceandthenwedeneanequivalencerelationtobearelationandaproofthatitisanequivalence.Theadvantageofthisapproachasopposedtojusthavingasinglerecordisthatwecantalkaboutwhatitmeanstobeanequivalence.Thismakesdeningmorerenedequivalencerelations,suchasdecidableequivalencerelations,easier. recordIsEquivalence{A:Set}(_==_:A-A-Set):Setwhererefl:(x:A)-x==xsym:(xy:A)-x==y
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.ForthisreasonwedeneanewmoduleEquivalenceOpswhichsimplyre-exportstheprojectionfunctionsfromthetworecords. moduleEquivalenceOps{A:Set}(Eq:EquivalenceA)whereprivateopenmoduleEq=EquivalenceEqpublicprivateopenmoduleIsEq=IsEquivalenceisEquivpublicWenowdeneatypeofdecidableequivalencerelations.Thedenitionisthesameasthedenitionofequivalencerelat
105 ionexceptwehaveanextra 110CHAPTER5.THEAG
ionexceptwehaveanextra 110CHAPTER5.THEAGDALANGUAGE Intheproofsofsymmetryandtransitivitywecanseethepatternmatchingonidentityproofsinaction.Wedeneadecidableequivalencerelationonnitesetsbyprovingthattheidentityrelationisdecidable. 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=neqrefNotethatwhenweinstantiatetheEquivalenceOpsmoduletotheidentityrelationonnitesetsweabstractoverthesizeoftheset.Thiskeepstheoperationspolymorphicinthesize,whichweneedintheproof.Todismisstheo-diagonalcasesweusethesyntaxforpatternmatchingoncaselesstypes.GivenanequivalencerelationonatypeAwecandeneanequivalencerelationonlistsoverA,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.Fortunatelywecanusealittleimplicitargumentandinxoperatormagictosolvethisproblem.WedeneamoduleChainparameterisedoverare 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.Westarttheproblemspecicpartbydeningwhatacommutativemonoidis.ThisisdonerelativetoasetAequippedwithanequivalencerelation. openimportEquivalencemoduleMonoid{A:Set}(Eq:EquivalenceA)whereWewanttohaveaccesstotheoperationsonequivalencerelationssoweapplyandopentheEquivalenceOpsmodule. privateopenmoduleEq=EquivalenceOpsEqWeusethesametwostageapproachaswedidforequivalencerelationsandrstdenewhatitmeansforanelement;andanoperation_+_toformamonoid.Thedenitionofamonoidisthensimplya;,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;_+_Againwedeneanewmodulewiththeprojectionfunctionsfrombothrecordsaswellasacoupleofderivedones. 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::[]Wealsodeneafunctionreifytocomebackfromanormalformtoanexpression. reify:{n:Nat}-NFn-Exprnreify[]=|;|reify(i::nf)=vari|+|reifynfWeneeddecidableequalityonnormalforms,butsincenormalformsarejustslistsofelementsfromanitesetwehavealreadydenedit. 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.Wehavedenedafunctiontodecideequalityinacommutativemonoidby atteningandsortingtheexpressions.Whatcannotbedoneinasimplytypedsettingisconstructingtheactualproofthattheequationholdsinanycommutativemonoid.WedeneamoduleSemanticsparameterisedbyanarbitrarycommuta-tivemonoid. openimportEquivalenceo
114 penimportMonoidmoduleSemantics{A:Set}{Eq
penimportMonoidmoduleSemantics{A:Set}{Eq:EquivalenceA}(M:CommutativeMonoidEq)whereimportChainopenimportLogicopenimportBasicsopenimportExprprivateopenmoduleE=EquivalenceOpsEqopenmoduleM=CommutativeMonoidOpsEqMopenmoduleC=Chain_==_refltransFirst,wehavetodenethesemanticsofanexpression,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.Wedeneatype_^_!_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)xsNowwecandeneafunctionequationwh
x)xsNowwecandeneafunctionequationwhichgivenafunctionfromnexpres-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 propositionalorrst-orderprovers[BHdN02,ST95,MP04].But,inordertoarriveatproofdocument
119 swhicharestillreadable,onlytrivialproofs
swhicharestillreadable,onlytrivialproofstepsshouldbehandledbytheautomaticprover.Sincedierentreadersmighthavedierentnotionsoftrivial,theautomaticprovershouldnotbeablackbox.Withsomeeortbythehuman,theoutputoftheprovershouldbeunderstandable.Inthispaper,weareexploringconnectionsbetweenalogicalframeworkMLFPropbasedontypetheoryandresolution-basedtheoremprovers.Oneprobleminsuchaninteractionisthatresolutionproofsarehardtoreadandunderstandingeneral.Indeed,resolutionproofsystemsworkwithformulinclausenormalform,whereclausesare(theuniversalclosuresof)disjunc-tionsofliterals,aliteralbeinganatomoranegatedatom.Thesystemtranslatesthenega
120 tionofthestatementtobeprovedtoclauseform
tionofthestatementtobeprovedtoclauseform,usingskolemisationanddisjunctivenormalform.Itthengeneratesnewclausesusingresolutionandparamodulation,tryingtoderiveacontradiction.Ifsuccessful,thesystemdoespruningonthe(typicallyhighnumberof)gen-eratedclausesandoutputsonlytherelevantones.1Welosethestructureoftheinitialproblemwhendoingskolemisationandclausication.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 niversallyquantiedpropositionalform
niversallyquantiedpropositionalformul,inthefollowingcalledopenformul,thisproblemdoesnotarise.Furthermore,whenwerestricttothisfragment,wecanusetheideaofimplicittyping[Bee07,WM89].Inthisway,thetranslationfromframeworktypestoFOLformulisparticularlysimple.Technically,thisisre ectedbyageneralmetatheoremwhichensuresthatwecanliftarst-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=2foranyU.Similarly,a
Tpresupposesx:U=2foranyU.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!PrfPcorrespondstoauniversalrst-orderformula8x1:::8xnPwithquantier-freekernelP.Judgements.ThetypetheoryMLFPropispresen
124 tedviavejudgements,whichareallrelat
tedviavejudgements,whichareallrelativetoa(user-dened)signature.`isawell-formedcontext`TTisawell-formedtype`r:TrhastypeT`T=T0TandT0areequaltypes`r=r0:Trandr0areequaltermsoftypeTAllvejudgementsaredenedsimultaneously.Sincethesignatureremainsxedinalljudgementswewillomitit.Judgmentaltypeandtermequalityaregeneratedfromexpansionofsig-naturedenitionsaswellasfrom-,-,andlet-equality,thelatterofwhichisgivenby(letx:T=rins)=s[x:=r].TherulesforequalityaresimilartotheonesofMLF[AC05],andtype-checkingofnormaltermswithlocaldenitionsisdecidable.Figure6.1showsthety
125 pingrules.Therulesfun-fandfun-icarryasid
pingrules.Therulesfun-fandfun-icarryasidecondition()thatensuresthatnotypecandependonaproof,whichisneededfortheconservativitytheorem. 130CHAPTER6.FIRST-ORDERLOGIC Naturaldeduction.WeassumeasignaturendgiveninFigure6.2,whichassumestheinxlogicalconnectivesop::=^;_;),plusthedenedones,:and,.Furthermore,itcontainsasetPredSymofbasicpredicatesym-bolspoftype!Propwhereisa(possiblyempty)setcontext.Cur-rentlyweonlyassumetruth,absurdity?,andtypedequalityId,butuserdenedsignaturescanextendPredSymbytheirownsymbols.Foreachlogicalconstructs,thereareappropriateproofrules,e.g.,aconstantimpI:(P;Q:Prop)!(PrfP!PrfQ)!Prf(P)Q):
126 First-orderlogicassumesthateverysetisnon
First-orderlogicassumesthateverysetisnon-empty,andouruseofarst-orderproverisonlysoundunderthisassumption.Hence,weaddaspecialconstant:(D:Set)!ElDtondwhichenforcesthisfact.Noticethatthisimpliesthatallsetcontextsareinhabited2.Classicalreasoningcanbeperformedinthesignatureclass,whichwedeneastheextensionofndbyEM:(P:Prop)!Prf(P_:P);thelawoftheexcludedmiddle.Thefolrule.ThisarticleinvestigatesconditionsunderwhichtheadditionofthefollowingruleisconservativeoverMLFProp+ndandMLFProp+class,respectively.fol`T `():T`FOLTThesidecondition`FOLTexpressesthatTisaprooftypeandthattherst-orderprovercandeduce
127 thetruthofthecorrespondingrst-order
thetruthofthecorrespondingrst-orderfor-mulafromtheassumptionsin.ItensuresthatonlytautologieshaveproofsinMLFProp,butitisnotconsideredpartofthetypechecking.Metatheoreti-calpropertiesofMLFProplikedecidabilityofequalityandtype-checkingholdindependentlyofthissidecondition.Conservativityfailsifwehavetocompareproofobjectsduringtype-checking.Thisisbecausetherulefolproducesasingleproofobjectforall(true)propositions,whereasuponremovaloffoltheholehastobelledwithspecicproofobject.Hencetwoequalobjectswhicheachdependonaproofgeneratedbyfolcouldbecomeunequalafterreplacingfol.Toavoidthis,itissucienttorestrictfunctionspaces(x:T)!U:ifT
128 isaprooftype,thenalsoU.Whilethisrestrict
isaprooftype,thenalsoU.Whilethisrestrictionisclearlysucient,itisrathersever.Forinstance,itisnotpossibletodeneafunctioncomputinganelementofasetundersomepropositionalpreconditions.Whatwereallyneedhereisproofirrelevantpropositions.Intheremainderofthepaper,weuseLFasasynonymforMLFProp. 2Semantically,itmaybefruitfultothinkoftermsoftypeSetasinhabitedPartialEquivalenceRelations,whiletermsoftypeProparePERswithatmostoneinhabitant. 132CHAPTER6.FIRST-ORDERLOGIC 6.3TranslationfromMLFProptoFOLWeshalldeneapartialtranslationfromsomeLFtypestoFOLpropositions.Wetranslateonlytypesoftheform(x1:T1):::(xk:Tk)!Prf(P(x1;:::;xk));andthesearetranslated
129 toopenformul[P(x1;:::;xk)]ofrs
toopenformul[P(x1;:::;xk)]ofrst-orderlogic.Allthevariablesx1;:::;xkareconsidereduniversallyquantied.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,whichmeansthatalldenitionshaveb
130 eenunfoldedandallredexesreduced.Threecla
eenunfoldedandallredexesreduced.ThreeclassesofnormalMLFProp-expressionsareintroduced:(formal)rst-ordertermsand(formal)rst-orderformul,whicharequantierfreeformuloveratomspossiblycontainingfreetermvariables,andtranslatableformul,whicharerst-orderformulprexedbyquanticationoversetelements.t;u::=xjf~trst-ordertermsA;B::=p~tjIdSt1t2atomsW::=AjWopW0rst-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:xisnotarst-orderterm(y:ElD!ElD)!Prf(P(yx))yxisnotarst-ordertermWeshallalsousetheclassofgeometricalformul,givenbythefollowinggrammar:G::=HjH!GjG^GgeometricalformulaH::=AjH^HjH_HpositiveformulaTheaboveexampleWexisgeometrical.Aswewillshow,(classical)rst-orderproofsofgeometricalformulcanbemappedtointuitionisticproofsinthelogicalframeworkwithnd.6.3.2ResolutionCalculusItwillbeconvenienttousethefollowingnon-standardpresentationoftheresolutioncalculus[Rob65].AclauseCisano
132 penrst-orderformulaoftheformA1^
penrst-orderformulaoftheformA1^^An)B1__Bmwherewecanhaven=0orm=0andAiandBjareatomicformul.FollowingGentzen[Gen35],wewritesuchaclauseontheformA1;:::;An)B1;:::;Bm;thatis,X)Y,whereXandYarenitesetsofatomicformul.AnemptyXisinterpretedastruth,anemptyYasabsurdity.Resolutionisforwardreasoning.Figure6.3liststherulesforextendingthecurrentsetofderivedclauses:ifallclausesmentionedinthepremiseofarulearepresent,thisrulecanreandtheclauseoftheconclusionisaddedtotheclauseset.Inourformulation,allrulesareintuitionisticallyvalid3,andcanbejus-tiedinMLFProp+nd.Itcanbeshown,classically,thattheserulesarecomp
133 leteinthefollowingsense:ifaclauseisasema
leteinthefollowingsense:ifaclauseisasemanticalconsequenceofotherclausesthenitispossibletoderiveitusingtheresolutioncalculus.Hence,anyproofinFOLcanbeperformedwithresolution4.Itcanbepointedoutthatthesubruleisonlynecessaryattheveryend|anyresolutionproofcanbenormalizedtoaproofthatonlyusessubinthenalstep. 3Inthestandardformulation,theaxrulewouldread:A_A|theexcludedmiddle.4Todealwithexistentialquanticationwealsoneedskolemisation. 136CHAPTER6.FIRST-ORDERLOGIC Proof. Thelemmaisaconsequenceofthefollowingstrongerproposition:Ift1;:::;tnandu1;:::;unarelistsoftermsthattthesamecontextinandisthemostgeneralsubstitutionsuchthatti
134 =uifor16i6n,then`(x):
=uifor16i6n,then`(x):Aforall(x:A)2.Let`t:Aand0`u:B.Sincetanduarepropertermsanduniable,t=f(~t)andu=f(~u)forsomeconstantf:!C.Hence,~tand~utin0,whichisavalidcontextsinceand0aredisjoint.Nowthepropositionimpliesthatmgu(t;u)iswell-typed.Toprovethestrongerproposition,wefollowthestepsofasimpleuni-cationalgorithmandconsidertheunicationproblemt1=u1;:::;tn=unIfbotht1andu1areproperterms,theyareoftheformf(a1;:::;ak)andf(b1;:::;bk)andwegetasimplerunicationproblema1=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.Wethengetthesimplerunicationproblemin1;2[x:=u1]t2[x:=u1]=u2[x:=u1];:::;tn[x:=u1]=un[x:=u1]Weproceedinthiswayuntilwegetanemptylistinthecontextinwhichthemostgeneralunierofthetwotermsiswell-typed. Forinstance,addxzeroandadd(sucy)zareuniableandwell-typedandthemostgeneralunierfx7!sucy;z7!zerogiswell-typed.Usingthislemma,wecanliftanyFOLresolutionstepto
136 anLFresolutionstep.Thesameholdsforanyres
anLFresolutionstep.Thesameholdsforanyrestrictedparamodulationstep,whichjustiesthetranslationofIdStuashti=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,inductionandanadditionfunctiondenedbyrecursiononthesecondargument.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.Foreveryuseofxwerequirethattheinstantiationofcanbeinferredusingpatternunication[Mil92].NotethatwhenwehaveimplicitargumentswecanreplaceIdwithaninxoperator(==)(D:Set):ElD!ElD!PropWeconjecturethattheconservativityresultcanbeextendedtoallowtheomissionofimplicitargumentswhentranslatingtorst-orderlogicifthey 142CHAPTER6.FIRST-ORDERLOGIC shouldberesponsibleforcheckingthesidecondition`FOLPinthefolrule.Animportantobservationisthatdecidabilityoftypecheckingandequal-itydonotdependonthevalidityofthepropositionsbeingcheckedbytheFOLplug-in|nothi
141 ngwillbreakifthetypecheckerisledtobeliev
ngwillbreakifthetypecheckerisledtobelievethatthereisans:Prf?.Thisallowsustodelayallrst-orderreasoninguntilaftertypechecking.Therationalefordoingthisisthattypecheckingischeapandrst-orderprovingisexpensive.Anotherobservationisthatitisnotfeasibletopasstheentirecontexttotheprover.Typically,thecontextcontainsmanythingsthatarenotneededfortheproof,butwouldratheroverwhelmtheprover.Tosolvethisproblem,werequirethatanyaxiomsorlemmasneededtoproveaparticulargoalarepassedasargumentstotheplug-in.Thismightseemasevererequirement,butbearinmindthattheplug-inisintendedforsimplegoalswhereyoualreadyhaveanideaoftheproof.Moreformally,thetypingruleforcall
142 stotheFOLplug-inis``s1:
stotheFOLplug-inis``s1:1:::`sn:n `folplugin(s1;:::;sn):1;:::;n`FOL:Whenfacedwithacalltoaplug-inthetypecheckercallsthetypecheckingfunctionoftheplug-in.Inthiscase,thetypecheckingfunctionoftheFOLplug-inwillverifythatthegoalisatranslatableformulaandthatthear-gumentsarewell-typedproofsoftranslatableformul.Ifthisisthecaseitwillreportsuccesstothetypecheckerandstoreawaythesideconditioninitsinternalstate.AftertypecheckingthenalizationfunctionoftheFOLplug-iniscalled.Foreachconstraint1;:::;n`FOL,thisfunctionveriesthat[]isderivablefrom[1];:::;[n]intheres
143 olutioncalculusbytrans-latingtheformul
olutioncalculusbytrans-latingtheformultoclausenormalformandfeedingthemtoanexternalrst-orderprover(Gandalf,atthemoment).Iftheproverdoesnotmanagetondaproofwithinthegiventimelimit,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)ThetransitiveclosureisnowdenedasTCRxy=9n:R(n)xy.Tofor-malizethis,weaddexistentialquanticationanditsproofrules.Thenaltheoremdemostrateshowexistentialquanticationcanbehandledintheframework.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!existsInfolplugin(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.Forthisusethedatatypeextensionswhichallowsustodenerecursivefunctionsoverthenaturalnumbers.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.Westartbydeningwhatitmeanstobeanintegralring.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=folplugin(axR)rem2:(Zero+One)
nerem1=folplugin(axR)rem2:(Zero+One)x==Zerox+Onexrem2=folplugin(axR)rem3:Zerox+Onex==Onexrem3=folplugin(axR;rem1;rem2)infolplugin(rem3;lemCancel)lemOneZero:(x:R)!One==Zero=)isZeroxlemOneZerox=folplugin(axR;lemZero)Themainlemmaisprovedbyinductionexplicitlyattheframeworklevel.prop:R!Nat!Proppropxn=isZero(powernx)=)isZeroxlemMain:(x:R)!(n:Nat)!propxnlemMainx=letbase:propxzerobase=folplugin(lemOneZero)step:(n:Nat)!propxn=)propx(sucn)stepn=folplugin(axR;axI)inindNat(propx)basestepthm:(x:R)!isNilpotentx!isZeroxthmxh=existsE(n!isZero(powernx))h(isZerox)(lemMainx)6.6RelatedWorkSmithandTammet[
148 ST95]alsocombineMartin-Loftypetheoryand
ST95]alsocombineMartin-Loftypetheoryandrst-orderlogic,whichwastheoriginalmotivationforcreatingthesystemGan-dalf.Themaindierencetotheirworkisthatweuseimplicittypingandrestricttoquantier-freeformul.Anadvantageisthatwehaveasimpletranslation,andhencegetaquitedirectconnectiontoresolutiontheoremprovers.Hence,wecanhope,andthishasbeentestedpositivelyinsev-eralexamples,thattheprooftraceswegetfromtheproverarereadableassuchandthereforecanbeenusedasaproofcerticateorasfeedbackfortheuser.Forinstance,theusercanformulatenewlemmassuggestedbythis 150CHAPTER6.FIRST-ORDERLOGIC onhowtointegratetheresolutiontheoremproverVampireintothein
149 terac-tiveprooftoolIsabelle.Theirtransla
terac-tiveprooftoolIsabelle.Theirtranslationfromhigher-orderlogic(HOL)torst-orderlogickeepstypeinformation,sinceHOLsupportsoverloadingviaaxiomatictypeclassesanddiscardingtypeinformationforoverloadedsym-bolswouldleadtounsoundreasoning.Theyclaimtocutdownthesearchspaceviatypeinformation,butthisisalsoconnectedtooverloading.Theaimoftheirworkisdierenttoours:whiletheyuserst-orderproverstodoasmuchautomaticproofsandproofsearchaspossible,weemployautomationonlytoliberatetheuserfromseeminglytrivialproofsteps.InCoq,NuPrl,andIsabelle,theuserconstructsaproofviatactics.Weprovidetypetheoryasaprooflanguageinwhichtheuserwritesdownaproofskeleton
150 ,consistingoflemmas,scopedhypotheses,inv
,consistingoflemmas,scopedhypotheses,invocationofinduction,andmajorproofsteps.Therst-orderproverisinvokedtosolve(easy)subgoals.Thisway,wehopetoobtainhuman-readableproofdocuments(seeourexamples).6.7FutureWorkThelogicalframeworkusedinthischapterdoesnotsupport-types.How-ever,theextensionofthetranslationtoFOLisstraightforward,wesimplyaddanewbinaryfunctionsymbolsforrepresentingpairs.Amoresubstan-tialextensionistheadditionofdatatypesandfunctionsdenedbypatternmatching.Withthisextension,itispossibletorepresenteachconnectiveasaparameterizeddatatype.Eachintroductionruleisrepresentedbyaconstructor,andtheeliminationrulesarerepresentedbyfu
151 nctionsdenedbycases.Thisgivesacompu
nctionsdenedbycases.Thisgivesacomputationaljusticationofeachoftheaxiomsofthesignaturenat.TheextensionofthetranslationtoFOLisalsostraight-forward:eachdenedequationsforfunctionsbecomesaFOLequality.Oneneedsalsotoexpressthateachconstructorisone-to-oneandthattermswithdistinctconstructorsaredistinct.Anotherdirectionoffurtherworkistoextendtheconservativitytheoremtohandleimplicitarguments.Wealsothinkthatitispossibletoextendourclassoftranslatableformul,forinstance,toincludesomecasesofexistentialquantication.Onecouldthinkofaddingmoreplug-ins,withthesameprinciplethattheyarejustiedbyageneralmetatheorem.Forinstance,onec
152 ouldaddaplug-intoamodelchecker,oraplug-i
ouldaddaplug-intoamodelchecker,oraplug-intoasystemwithadecisionprocedureforPresburgerarithmetic.Adierentapproach,whichissomewaysismoreappealing,istoimple-mentcertiedproversinternallyinthelanguage,inthewaythatwasdonefor 152CHAPTER6.FIRST-ORDERLOGIC 154CHAPTER7.CONCLUSIONS Wehavegivenatypecheckingalgorithmforadependentlytypedlogicex-tendedwithmetavariables.Tomaintaintheimportantinvariantthattermsbeingevaluatedaretypecorrectweworkwithwell-typedapproximationsofterms,wherepotentiallyill-typedsubtermshavebeenreplacedbyconstants.Weshowedthattypecheckingisdecidableandthatthealgorithmissound.Wepresentedthetypecheckingalgorithmforasimpledep
153 endentlytypedlogicalframeworkMLF,butoutl
endentlytypedlogicalframeworkMLF,butoutlinedhowitcanbeextendedtomorefeature-richlogics.TheimplementationhandlesthefulllogicofAgda,andhasproventoworkwellwithexamplesofseveralthousandmetavariables.ModulesystemInlargerdevelopmentsitiscrucialtobeabletosplitaprogramintoseparateunits,andtomanagethescopeoftheseunitssothatdenitionsfromoneunitisnotautomaticallyvisibleinallothers.Forthispurpose,wehavepresentedareasonablesimpleandeasytoimplementmodulesystemwhichisstillexpressiveenoughtoallowlargeprogramstobestructuredinaniceway.Akeydesigndecisionwastokeepthemodulesystemandthetypesystemasseparateaspossible.Asaresultthemodulesystemislargelyindepend
154 entoftheunderlyinglanguage.AutomationWhe
entoftheunderlyinglanguage.AutomationWhenworkingwiththemoreprecisetypesthatadependentlytypedlanguageenables,itissometimesnecessaryordesirabletoprovepropertiesofyourprograms.Whilethesecanbeconstructeddirectlyinthetypetheory,thisissometimestediouswork.Toalleviateprovingsimplerst-orderproperties,wedescribedtheimplementationofalogicalframeworkwithproof-irrele-vantpropositionsanditsconnectiontotheautomaticrst-orderlogicproverGandalf.Soundnessandconservativityoftheconnectionwasestablishedbygeneralmetatheorems.Byrestrictingthesetofformulasunderconsiderationtothatofgeometricformulasweobtainedasimple,transparenttranslationbetweentheframewo
155 rkandrst-orderlogic.Moreovertheproo
rkandrst-orderlogic.Moreovertheproofsconstructedbytheproverareintuitionisticallyvalid.AgdaWehavecollectedthefeaturesdescribedinthisthesis1inalanguageAgda.Whileitisstillfarfrombeingafully edgedprogramminglanguage,it 1Withtheexceptionoftherst-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.Averiedstagedinterpreterisaveriedcompiler: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-orderunicationviaexplicitsubstitutions.InDexterKozen,editor,ProceedingsoftheTenthAnnualIEEESymp.onL
160 ogicinComputerScience,LICS1995,pages366{
ogicinComputerScience,LICS1995,pages366{374.IEEEComputerSocietyPress,June1995. [Dow01] GillesDowek.Higher-orderunicationandmatching.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-styleinterfacebetweenHOLandrst-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.Formalcerticationofacompilerback-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.Unicationofsimplytypedlambda-termsaslogicpro-gramming.InK.Furukawa,editor,LogicProgramming:Proc.oftheEighthInternationalConference,pages255{269.MITPress,Cambridge,MA,1991. [Mil92] DaleMiller.Unicationunderamixedprex.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.Unicationandanti-unicationintheCalculusofConstructions.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 typetheoryinrst-orderlogic.InStefan
typetheoryinrst-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.