cpdt - Certied Programming with Dependent Types Adam...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Certied Programming with Dependent Types Adam Chlipala February 3, 2010 gopyright ed—m ghlip—l— PHHVEPHHWF „his work is li™ensed under — gre—tive gommons ettri˜utionExon™ommer™i—lExo heriv—tive ‡orks QFH …nported vi™enseF „he li™ense text is —v—il—˜le —tX http://creativecommons.org/licenses/by-nc-nd/3.0/ Contents 1 Introduction IFI IFP IFQ IFR IFS IFT IFU ‡hen™e „his fookc F F F F F F F F F F F F F F F F F F F F F F F F F F ‡hy goqc F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F IFPFI f—sed on — righerEyrder pun™tion—l €rogr—mming v—ngu—ge IFPFP hependent „ypes F F F F F F F F F F F F F F F F F F F F F F F F IFPFQ en i—syEtoEghe™k uernel €roof v—ngu—ge F F F F F F F F F F IFPFR gonvenient €rogr—mm—˜le €roof eutom—tion F F F F F F F F IFPFS €roof ˜y ‚e)e™tion F F F F F F F F F F F F F F F F F F F F F F F ‡hy xot — hi'erent hependentlyE„yped v—ngu—gec F F F F F F F F ingineering with — €roof essist—nt F F F F F F F F F F F F F F F F F F €rerequisites F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F …sing „his fook F F F F F F F F F F F F F F F F F F F F F F F F F F F F gh—pter ƒour™e piles F F F F F F F F F F F F F F F F F F F F F F F F F F 2 Some Quick Examples PFI PFP erithmeti™ ixpressions yver x—tur—l xum˜ers PFIFI ƒour™e v—ngu—ge F F F F F F F F F F F F PFIFP „—rget v—ngu—ge F F F F F F F F F F F F PFIFQ „r—nsl—tion F F F F F F F F F F F F F F F PFIFR „r—nsl—tion gorre™tness F F F F F F F F „yped ixpressions F F F F F F F F F F F F F F F PFPFI ƒour™e v—ngu—ge F F F F F F F F F F F F PFPFP „—rget v—ngu—ge F F F F F F F F F F F F PFPFQ „r—nsl—tion F F F F F F F F F F F F F F F PFPFR „r—nsl—tion gorre™tness F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F 7 U V V V W W W IH II II IP IQ 14 IS IS IU IW IW PT PT QH QP QR I Basic Programming and Proving 36 3 Introducing Inductive Types 37 QFI QFP QFQ inumer—tions F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F ƒimple ‚e™ursive „ypes F F F F F F F F F F F F F F F F F F F F F F F F F F F F F €—r—meterized „ypes F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F P QU RH RR QFR QFS QFT QFU QFV QFW wutu—lly sndu™tive „ypes F F F F F ‚e)exive „ypes F F F F F F F F F F F en snterlude on €roof „erms F F F F xested sndu™tive „ypes F F F F F F F w—nu—l €roofs e˜out gonstru™tors ixer™ises F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F 4 Inductive Predicates RFI RFP RFQ RFR RFS RFT €roposition—l vogi™ F F F F F F F F F F F F ‡h—t hoes st we—n to fe gonstru™tivec pirstEyrder vogi™ F F F F F F F F F F F F F €redi™—tes with smpli™it iqu—lity F F F F ‚e™ursive €redi™—tes F F F F F F F F F F F ixer™ises F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F 5 Innite Data and Proofs SFI SFP SFQ SFR gomputing with sn(nite h—t— F F F F F F F F F F sn(nite €roofs F F F F F F F F F F F F F F F F F F F ƒimple wodeling of xonE„ermin—ting €rogr—ms ixer™ises F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F RT RV SH SR SW TH 62 TQ TV TW UH UP UV 82 VQ VT WH WP II Programming with Dependent Types 93 6 Subset Types and Variations 94 TFI TFP TFQ TFR TFS TFT sntrodu™ing ƒu˜set „ypes F he™id—˜le €roposition „ypes €—rti—l ƒu˜set „ypes F F F F won—di™ xot—tions F F F F F e „ypeEghe™king ix—mple F ixer™ises F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F vengthEsndexed vists F F F F F F F F F F F e „—gless snterpreter F F F F F F F F F F F hependentlyE„yped ‚edEfl—™k „rees F F e gerti(ed ‚egul—r ixpression w—t™her ixer™ises F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F 7 More Dependent Types UFI UFP UFQ UFR UFS 8 Dependent Data Structures VFI VFP VFQ wore vengthEsndexed vists reterogeneous vists F F F F VFPFI e v—m˜d— g—l™ulus ‚e™ursive „ype he(nitions FFFFFFF FFFFFFF snterpreter FFFFFFF Q F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F WR IHH IHP IHQ IHR IHV 110 IIH IIQ IIW IPV IQQ 135 IQS IQV IRH IRP VFR F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F IHFI ‚e)e™ting h—t—type he(nitions F F F F F F F F IHFP ‚e™ursive he(nitions F F F F F F F F F F F F F F IHFPFI €rettyE€rinting F F F F F F F F F F F F F IHFPFP w—pping F F F F F F F F F F F F F F F F F IHFQ €roving „heorems —˜out ‚e™ursive he(nitions F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F VFS VFT h—t— ƒtru™tures —s sndex pun™tions F VFRFI enother snterpreter ix—mple ghoosing fetween ‚epresent—tions F ixer™ises F F F F F F F F F F F F F F F F 9 Reasoning About Equality Proofs WFI WFP WFQ WFR WFS WFT WFU „he he(nition—l iqu—lity F F F F F reterogeneous vists ‚evisited F F F „ypeEg—sts in „heorem ƒt—tements reterogeneous iqu—lity F F F F F F F iquiv—len™e of iqu—lity exioms F F iqu—lity of pun™tions F F F F F F F F ixer™ises F F F F F F F F F F F F F F F F F F F F F F 10 Generic Programming 11 Universes and Axioms IIFI „he Type rier—r™hy F F F F F F F F IIFIFI sndu™tive he(nitions F F F IIFP „he Prop …niverse F F F F F F F F IIFQ exioms F F F F F F F F F F F F F F F IIFQFI „he f—si™s F F F F F F F F F IIFQFP exioms of ghoi™e F F F F F IIFQFQ exioms —nd gomput—tion F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F IRS IRV ISQ ISQ 155 ISS ISU ITP ITU ITW IUI IUP 175 IUS IUU IVH IVP IVR 191 IWI IWR IWV PHI PHP PHT PHV III Proof Engineering 210 12 Proof Search in Ltac 211 IPFI IPFP IPFQ IPFR IPFS IPFT ƒome fuiltEsn eutom—tion „—™ti™s rint h—t—˜—ses F F F F F F F F F F F vt—™ €rogr—mming f—si™s F F F F F pun™tion—l €rogr—mming in vt—™ F ‚e™ursive €roof ƒe—r™h F F F F F F F gre—ting …ni(™—tion †—ri—˜les F F F F F F F F F R F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F PII PIP PIS PPP PPR PQH 13 Proof by Reection IQFI IQFP IQFQ IQFR IQFS €roving ivenness F F F F F F F F F F F F F F F F F F F F F ‚e)e™ting the ƒynt—x of — „rivi—l „—utology v—ngu—ge e wonoid ixpression ƒimpli(er F F F F F F F F F F F F F e ƒm—rter „—utology ƒolver F F F F F F F F F F F F F F F ixer™ises F F F F F F F F F F F F F F F F F F F F F F F F F F 14 Proving in the Large IRFI IRFP IRFQ IRFR vt—™ entiE€—tterns F F F F F F F F F F F F he˜ugging —nd w—int—ining eutom—tion wodules F F F F F F F F F F F F F F F F F F fuild €ro™esses F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F 237 PQU PRH PRP PRR PSH 253 PSQ PSW PTU PUH IV Formalizing Programming Languages and Compilers 273 15 First-Order Abstract Syntax 274 16 Dependent De Bruijn Indices 298 17 Higher-Order Abstract Syntax 309 ISFI gon™rete finding F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F PUR ISFP he fruijn sndi™es F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F PVI ISFQ vo™—lly x—meless ƒynt—x F F F F F F F F F F F F F F F F F F F F F F F F F F F F F PVT ITFI he(ning ƒynt—x —nd sts esso™i—ted yper—tions F F F F F F F F F F F F F F F F F PWV ITFP gustom „—™ti™s F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QHI ITFQ „heorems F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QHR IUFI IUFP IUFQ IUFR gl—ssi™ ryeƒ F F F F F F €—r—metri™ ryeƒ F F F F e „ype ƒoundness €roof figEƒtep ƒem—nti™s F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QHW QIP QIV QPI 18 Type-Theoretic Interpreters 326 19 Extensional Transformations 336 20 Intensional Transformations 346 IVFI ƒimplyE„yped v—m˜d— g—l™ulus F F F F F F F F F F F F F F F F F F F F F F F F F QPT IVFP edding €rodu™ts —nd ƒums F F F F F F F F F F F F F F F F F F F F F F F F F F F QQH IWFI g€ƒ gonversion for ƒimplyE„yped v—m˜d— g—l™ulus F F F F F F F F F F F F F QQT IWFP ixer™ises F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QRS PHFI prom he fruijn to €ryeƒ F F F F F F F F F F F F F F F F F F F F F F F F F F F QRU PHFP prom €ryeƒ to he fruijn F F F F F F F F F F F F F F F F F F F F F F F F F F F QRW PHFPFI gonne™ting xotions of ‡ellEpormedness F F F F F F F F F F F F F F F F QRW S PHFPFP „he „r—nsl—tion F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QSI 21 Higher-Order Operational Semantics 354 PIFI glosure re—ps F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QSS PIFP v—ngu—ges —nd „r—nsl—tion F F F F F F F F F F F F F F F F F F F F F F F F F F F F QSU PIFQ gorre™tness €roof F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F QTI T Chapter 1 Introduction 1.1 Whence This Book? ‡e would —ll like to h—ve progr—ms ™he™k th—t our progr—ms —re ™orre™tF hue in no sm—ll p—rt to some ˜old ˜ut unful(lled promises in the history of ™omputer s™ien™eD tody most people who write softw—reD pr—™titioners —nd —™—demi™s —likeD —ssume th—t the ™osts of form—l progr—m veri(™—tion outweigh the ˜ene(tsF „he purpose of this ˜ook is to ™onvin™e you th—t the te™hnology of progr—m veri(™—tion is m—ture enough tod—y th—t it m—kes sense to use it in — support role in m—ny kinds of rese—r™h proje™ts in ™omputer s™ien™eF feyond the ™onvin™ingD s —lso w—nt to provide — h—nd˜ook on pr—™ti™—l engineering of ™erti(ed progr—ms with the goq proof —ssist—ntF „here —re — good num˜er of @though de(nitely not 4m—ny4A tools th—t —re in wide use tod—y for ˜uilding m—™hineE™he™ked m—them—ti™—l proofs —nd m—™hineE™erti(ed progr—msF „his is my —ttempt —t —n exh—ustive list of inter—™tive 4proof —ssist—nts4 s—tisfying — few ™riteri—F pirstD the —uthors of e—™h tool must intend for it to ˜e put to use for softw—reE rel—ted —ppli™—tionsF ƒe™ondD there must h—ve ˜een enough engineering e'ort put into the tool th—t someone not doing rese—r™h on the tool itself would feel his time w—s well spent using itF e third ™riterion is more of —n empiri™—l v—lid—tion of the se™ondX the tool must h—ve — signi(™—nt user ™ommunity outside of its own development te—mF ACL2 Coq Isabelle/HOL PVS Twelf http://www.cs.utexas.edu/users/moore/acl2/ http://coq.inria.fr/ http://isabelle.in.tum.de/ http://pvs.csl.sri.com/ http://www.twelf.org/ ss—˜elleGryvD implemented with the 4proof —ssist—nt development fr—mework4 ss—˜elleD is the most popul—r proof —ssist—nt for the ryv logi™F „he other implement—tions of ryv ™—n ˜e ™onsidered equiv—lent for purposes of the dis™ussion hereF U 1.2 Why Coq? „his ˜ook is going to ˜e —˜out ™erti(ed progr—mming using goqD —nd s —m ™onvin™ed th—t it is the ˜est tool for the jo˜F goq h—s — num˜er of very —ttr—™tive propertiesD whi™h s will summ—rize hereD mentioning whi™h of the other ™—ndid—te tools l—™k e—™h propertyF 1.2.1 Based on a Higher-Order Functional Programming Language „here is no re—son to give up the f—mili—r ™omforts of fun™tion—l progr—mming when you st—rt writing ™erti(ed progr—msF ell of the tools s listed —re ˜—sed on fun™tion—l progr—mming l—ngu—gesD whi™h me—ns you ™—n use them without their proofErel—ted —spe™ts to write —nd run regul—r progr—msF egvP is not—˜le in this (eld for h—ving only — rst-order l—ngu—ge —t its found—tionF „h—t isD you ™—nnot work with fun™tions over fun™tions —nd —ll those other tre—ts of fun™tion—l progr—mmingF fy giving up this f—™ilityD egvP ™—n m—ke ˜ro—der —ssumptions —˜out how well its proof —utom—tion will workD ˜ut we ™—n gener—lly re™over the s—me —dv—nt—ges in other proof —ssist—nts when we h—ppen to ˜e progr—mming in (rstEorder fr—gmentsF 1.2.2 Dependent Types e l—ngu—ge of dependent types m—y in™lude referen™es to progr—ms inside of typesF por inst—n™eD the type of —n —rr—y might in™lude — progr—m expression giving the size of the —rr—yD m—king it possi˜le to verify —˜sen™e of outEofE˜ounds —™™esses st—ti™—llyF hependent types ™—n go even further th—n thisD e'e™tively ™—pturing —ny ™orre™tness property in — typeF por inst—n™eD l—ter in this ˜ookD we will see how to give — winiEwv ™ompiler — type th—t gu—r—ntees th—t it m—ps wellEtyped sour™e progr—ms to wellEtyped t—rget progr—msF egvP —nd ryv l—™k dependent types outrightF €†ƒ —nd „welf e—™h supports — di'erent stri™t su˜set of goq9s dependent type l—ngu—geF „welf9s type l—ngu—ge is restri™ted to — ˜—reE ˜onesD monomorphi™ l—m˜d— ™—l™ulusD whi™h pl—™es serious restri™tions on how ™ompli™—ted computations inside types ™—n ˜eF „his restri™tion is import—nt for the soundness —rgument ˜ehind „welf9s —ppro—™h to representing —nd ™he™king proofsF sn ™ontr—stD €†ƒ9s dependent types —re mu™h more gener—lD ˜ut they —re squeezed inside the single me™h—nism of subset typesD where — norm—l type is re(ned ˜y —tt—™hing — predi™—te over its elementsF i—™h mem˜er of the su˜set type is —n element of the ˜—se type th—t s—tis(es the predi™—teF hependent types —re not just useful ˜e™—use they help you express ™orre™tness properties in typesF hependent types —lso often let you write ™erti(ed progr—ms without writing anything that looks like a proofF iven with su˜set typesD whi™h for m—ny ™ontexts ™—n ˜e used to express —ny relev—nt property with enough —™ro˜—ti™sD the hum—n driving the proof —ssist—nt usu—lly h—s to ˜uild some proofs expli™itlyF ‡riting form—l proofs is h—rdD so we w—nt to —void it —s f—r —s possi˜leD so dependent types —re inv—lu—˜leF V 1.2.3 An Easy-to-Check Kernel Proof Language ƒ™ores of —utom—ted de™ision pro™edures —re useful in pr—™ti™—l theorem provingD ˜ut it is unfortun—te to h—ve to trust in the ™orre™t implement—tion of e—™h pro™edureF €roof —ssist—nts s—tisfying the 4de fruijn ™riterion4 m—y use ™ompli™—ted —nd extensi˜le pro™edures to seek out proofsD ˜ut in the end they produ™e proof terms in kernel l—ngu—gesF „hese ™ore l—ngu—ges h—ve fe—ture ™omplexity on p—r with wh—t you (nd in propos—ls for form—l found—tions for m—them—ti™sF „o ˜elieve — proofD we ™—n ignore the possi˜ility of ˜ugs during search —nd just rely on — @rel—tively sm—llA proofE™he™king kernel th—t we —pply to the result of the se—r™hF egvP —nd €†ƒ do not meet the de fruijn ™riterionD employing f—n™y de™ision pro™edures th—t produ™e no 4eviden™e tr—ils4 justifying their resultsF 1.2.4 Convenient Programmable Proof Automation e ™ommitment to — kernel proof l—ngu—ge opens up wide possi˜ilities for user extension of proof —utom—tion systemsD without —llowing user mist—kes to tri™k the over—ll system into —™™epting inv—lid proofsF elmost —ny interesting veri(™—tion pro˜lem is unde™id—˜leD so it is import—nt to help users ˜uild their own pro™edures for solving the restri™ted pro˜lems th—t they en™ounter in p—rti™ul—r implement—tionsF „welf fe—tures no proof —utom—tion m—rked —s — ˜on—(de p—rt of the l—test rele—seY there is some —utom—tion ™ode in™luded for testing purposesF „he „welf style is ˜—sed on writing out —ll proofs in full det—ilF fe™—use „welf is spe™i—lized to the dom—in of synt—™ti™ met—theory proofs —˜out progr—mming l—ngu—ges —nd logi™sD it is fe—si˜le to use it to write those kinds of proofs m—nu—llyF yutside th—t dom—inD the l—™k of —utom—tion ™—n ˜e — serious o˜st—™le to produ™tivityF wost kinds of progr—m veri(™—tion f—ll outside „welf9s forteF yf the rem—ining toolsD —ll ™—n support user extension with new de™ision pro™edures ˜y h—™king dire™tly in the tool9s implement—tion l—ngu—ge @su™h —s yg—ml for goqAF ƒin™e egvP —nd €†ƒ do not s—tisfy the de fruijn ™riterionD over—ll ™orre™tness is —t the mer™y of the —uthors of new pro™eduresF ss—˜elleGryv —nd goq ˜oth support ™oding new proof m—nipul—tions in wv in w—ys th—t ™—nnot le—d to the —™™ept—n™e of inv—lid proofsF eddition—llyD goq in™ludes — dom—inEspe™i(™ l—ngu—ge for ™oding de™ision pro™edures in norm—l goq sour™e ™odeD with no need to ˜re—k out into wvF „his l—ngu—ge is ™—lled vt—™D —nd s think of it —s the unsung hero of the proof —ssist—nt worldF xot only does vt—™ prevent you from m—king f—t—l mist—kesD it —lso in™ludes — num˜er of novel progr—mming ™onstru™ts whi™h ™om˜ine to m—ke — 4proof ˜y de™ision pro™edure4 style very ple—s—ntF ‡e will meet these fe—tures in the ™h—pters to ™omeF 1.2.5 Proof by Reection e surprising we—lth of ˜ene(ts follow from ™hoosing — proof l—ngu—ge th—t integr—tes — ri™h notion of ™omput—tionF goq in™ludes progr—ms —nd proof terms in the s—me synt—™ti™ ™l—ssF „his m—kes it e—sy to write progr—ms th—t ™ompute proofsF ‡ith ri™h enough dependent W typesD su™h progr—ms —re certied decision proceduresF sn su™h ™—sesD these ™erti(ed pro™eE dures ™—n ˜e put to good use without ever running them 3 „heir types gu—r—ntee th—tD if we did ˜other to run themD we would re™eive proper 4ground4 proofsF „he ™riti™—l ingredient for this te™hniqueD m—ny of whose inst—n™es —re referred to —s proof by reectionD is — w—y of indu™ing nonEtrivi—l ™omput—tion inside of logi™—l propositions during proof ™he™kingF purtherD most of these inst—n™es require dependent types to m—ke it possi˜le to st—te the —ppropri—te theoremsF yf the proof —ssist—nts s listedD only goq re—lly provides this supportF 1.3 Why Not a Dierent Dependently-Typed Language? „he logi™ —nd progr—mming l—ngu—ge ˜ehind goq ˜elongs to — typeEtheory e™osystem with — good num˜er of other thriving mem˜ersF egd—1 —nd ipigr—m2 —re the most developed tools —mong the —ltern—tives to goqD —nd there —re others th—t —re e—rlier in their life™y™lesF ell of the l—ngu—ges in this f—mily feel sort of like di'erent histori™—l o'shoots of v—tinF „he h—rdest ™on™eptu—l epiph—nies —reD for the most p—rtD port—˜le —mong —ll the l—ngu—gesF qiven thisD why ™hoose goq for ™erti(ed progr—mmingc s think the —nswer is simpleF xone of the ™ompetition h—s wellEdeveloped systems for t—™ti™E˜—sed theorem provingF egd— —nd ipigr—m —re designed —nd m—rketed more —s proE gr—mming l—ngu—ges th—n proof —ssist—ntsF hependent types —re gre—tD ˜e™—use they often help you prove deep theorems without doing —nything th—t feels like provingF xonetheE lessD —lmost —ny interesting ™erti(ed progr—mming proje™t will ˜ene(t from some —™tivity th—t deserves to ˜e ™—lled provingD —nd m—ny interesting proje™ts —˜solutely require semiE —utom—ted provingD if the s—nity of the progr—mmer is to ˜e s—fegu—rdedF snform—llyD proving is un—void—˜le when —ny ™orre™tness proof for — progr—m h—s — stru™ture th—t does not mirror the stru™ture of the progr—m itselfF en ex—mple is — ™ompiler ™orre™tness proofD whi™h pro˜E —˜ly pro™eeds ˜y indu™tion on progr—m exe™ution tr—™esD whi™h h—ve no simple rel—tionship with the stru™ture of the ™ompiler or the stru™ture of the progr—ms it ™ompilesF sn ˜uilding su™h proofsD — m—ture system for s™ripted proof —utom—tion is inv—lu—˜leF yn the other h—ndD egd—D ipigr—mD —nd simil—r tools h—ve less implement—tion ˜—gg—ge —sso™i—ted with themD —nd so they tend to ˜e the def—ult (rst homes of innov—tions in pr—™ti™—l type theoryF ƒome signi(™—nt kinds of dependentlyEtyped progr—ms —re mu™h e—sier to write in egd— —nd ipigr—m th—n in goqF „he former tools m—y very well ˜e superior ™hoi™es for proje™ts th—t do not involve —ny 4provingF4 ene™dot—llyD s h—ve gotten the impression th—t m—nu—l proving is orders of m—gnitudes more ™ostly th—n m—nu—l ™oping with goq9s l—™k of progr—mming ˜ells —nd whistlesF sn this ˜ookD s will devote signi(™—nt time to p—tterns for progr—mming with dependent types in goq —s it is tod—yF ‡e ™—n hope th—t the type theory ™ommunity is tending tow—rds ™onvergen™e on the right set of fe—tures for pr—™ti™—l progr—mming with dependent typesD —nd th—t we will eventu—lly h—ve — single tool em˜odying 1 http://appserv.cs.chalmers.se/users/ulfn/wiki/agda.php 2 http://www.e-pig.org/ IH those fe—turesF 1.4 Engineering with a Proof Assistant sn ™omp—risons with its ™ompetitorsD goq is often derided for promoting unre—d—˜le proofsF st is very e—sy to write proof s™ripts th—t m—nipul—te proof go—ls imper—tivelyD with no stru™ture to —id re—dersF ƒu™h developments —re nightm—res to m—int—inD —nd they ™ert—inly do not m—n—ge to ™onvey 4why the theorem is true4 to —nyone ˜ut the origin—l —uthorF yne —ddition—l @—nd not insigni(™—ntA purpose of this ˜ook is to show why it is unf—ir —nd unprodu™tive to dismiss goq ˜—sed on the existen™e of su™h developmentsF s will go out on — lim˜ —nd guess th—t the re—der is — dedi™—ted f—n of some fun™tion—l progr—mming l—ngu—ge or —notherD —nd th—t he m—y even h—ve ˜een involved in te—™hing th—t l—ngu—ge to undergr—du—tesF s w—nt to propose —n —n—logy ˜etween two —ttitudesX ™oming to — neg—tive ™on™lusion —˜out goq —fter re—ding ™ommon goq developments in the wildD —nd ™oming to — neg—tive ™on™lusion —˜out ‰our p—vorite v—ngu—ge —fter looking —t the progr—ms undergr—du—tes write in it in the (rst week of ™l—ssF „he pr—gm—ti™s of me™h—nized proving —nd progr—m veri(™—tion h—ve ˜een under serious study for mu™h less time th—n the pr—gm—ti™s of progr—mming h—ve ˜eenF „he ™omputer theorem proving ™ommunity is still developing the key insights th—t ™orrespond to those th—t fun™tion—l progr—mming texts —nd instru™tors imp—rt to their studentsD to help those students get over th—t ™riti™—l hump where using the l—ngu—ge stops ˜eing more trou˜le th—n it is worthF wost of the insights for goq —re ˜—rely even dissemin—ted —mong the expertsD let —lone set down in — tutori—l formF s hope to use this ˜ook to go — long w—y tow—rds remedying th—tF sf s do th—t jo˜ wellD then this ˜ook should ˜e of interest even to people who h—ve p—rti™ip—ted in ™l—sses or tutori—ls spe™i(™—lly —˜out goqF „he ˜ook should even ˜e useful to people who h—ve ˜een using goq for ye—rs ˜ut who —re mysti(ed when their goq developments prove impenetr—˜le ˜y ™olle—guesF „he ™ru™i—l —ngle in this ˜ook is th—t there —re 4design p—tterns4 for reli—˜ly —voiding the re—lly grungy p—rts of theorem provingD —nd ™onsistent use of these p—tterns ™—n get you over the hump to the point where it is worth your while to use goq to prove your theorems —nd ™ertify your progr—msD even if form—l veri(™—tion is not your m—in ™on™ern in — proje™tF ‡e will follow this theme ˜y pursuing two m—in methods for repl—™ing m—nu—l proofs with more underst—nd—˜le —rtif—™tsX dependentlyEtyped fun™tions —nd ™ustom vt—™ de™ision pro™eduresF 1.5 Prerequisites s try to keep the required ˜—™kground knowledge to — minimum in this ˜ookF s will —ssume f—mili—rity with the m—teri—l from usu—l dis™rete m—th —nd logi™ ™ourses t—ken ˜y —ll underE gr—du—te ™omputer s™ien™e m—jorsD —nd s will —ssume th—t re—ders h—ve signi(™—nt experien™e progr—mming in one of the wv di—le™tsD in r—skellD or in some otherD ™loselyErel—ted l—ngu—geF II ixperien™e with only dyn—mi™—llyEtyped fun™tion—l l—ngu—ges might le—d to ˜efuddlement in some pl—™esD ˜ut — re—der who h—s ™ome to grok ƒ™heme deeply will pro˜—˜ly ˜e (neF e good portion of the ˜ook is —˜out how to form—lize progr—mming l—ngu—gesD ™ompilE ersD —nd proofs —˜out themF „o underst—nd those p—rtsD it will ˜e helpful to h—ve — ˜—si™ knowledge of form—l type systemsD oper—tion—l sem—nti™sD —nd the theorems usu—lly proved —˜out su™h systemsF es — referen™e on these topi™sD s re™ommend Types and Programming LanguagesD ˜y fenj—min gF €ier™eF 1.6 Using This Book „his ˜ook is gener—ted —utom—ti™—lly from goq sour™e (les using the wonderful ™oqdo™ progr—mF „he l—test €hp version is —v—il—˜le —tX http://adam.chlipala.net/cpdt/cpdt.pdf „here is —lso —n online r„wv version —v—il—˜leD with — hyperlink from e—™h use of —n identi(er to th—t identi(er9s de(nitionX http://adam.chlipala.net/cpdt/html/toc.html „he sour™e ™ode to the ˜ook is —lso freely —v—il—˜le —tX http://adam.chlipala.net/cpdt/cpdt.tgz „hereD you ™—n (nd —ll of the ™ode —ppe—ring in this ˜ookD with prose interspersed in ™ommentsD in ex—™tly the order th—t you (nd in this do™umentF ‰ou ™—n step through the ™ode inter—™tively with your ™hosen gr—phi™—l goq interf—™eF „he ™ode —lso h—s spe™i—l ™omments indi™—ting whi™h p—rts of the ™h—pters m—ke suit—˜le st—rting points for inter—™tive ™l—ss sessionsD where the ™l—ss works together to ™onstru™t the progr—ms —nd proofsF „he in™luded w—ke(le h—s — t—rget templates for ˜uilding — fresh set of ™l—ss templ—te (les —utom—ti™—lly from the ˜ook sour™eF s ˜elieve th—t — good gr—phi™—l interf—™e to goq is ™ru™i—l for using it produ™tivelyF s use the €roof qener—l3 mode for im—™sD whi™h supports — num˜er of other proof —ssist—nts ˜esides goqF „here is —lso the st—nd—lone goqshi progr—m developed ˜y the goq te—mF s like ˜eing —˜le to ™om˜ine ™erti(ed progr—mming —nd proving with other kinds of work inside the s—me fullEfe—tured editorD —nd goqshi h—s h—d — good num˜er of ™r—shes —nd other —nnoying ˜ugs in re™ent historyD though s he—r th—t it is improvingF sn the initi—l p—rt of this ˜ookD s will referen™e €roof qener—l pro™edures expli™itlyD in introdu™ing how to use goqD ˜ut most of the ˜ook will ˜e interf—™eE—gnosti™D so feel free to use goqshi if you prefer itF 3 http://proofgeneral.inf.ed.ac.uk/ IP 1.7 Chapter Source Files Chapter Source ƒome ui™k ix—mples sntrodu™ing sndu™tive „ypes sndu™tive €redi™—tes sn(nite h—t— —nd €roofs ƒu˜set „ypes —nd †—ri—tions wore hependent „ypes hependent h—t— ƒtru™tures ‚e—soning e˜out iqu—lity €roofs qeneri™ €rogr—mming …niverses —nd exioms €roof ƒe—r™h in vt—™ €roof ˜y ‚e)e™tion €roving in the v—rge pirstEyrder e˜str—™t ƒynt—x hependent he fruijn sndi™es righerEyrder e˜str—™t ƒynt—x „ypeE„heoreti™ snterpreters ixtension—l „r—nsform—tions sntension—l „r—nsform—tions righerEyrder yper—tion—l ƒem—nti™s IQ StackMachine.v InductiveTypes.v Predicates.v Coinductive.v Subset.v MoreDep.v DataStruct.v Equality.v Generic.v Universes.v Match.v Reflection.v Large.v Firstorder.v DeBruijn.v Hoas.v Interps.v Extensional.v Intensional.v OpSem.v Chapter 2 Some Quick Examples s will st—rt o' ˜y jumping right in to — fullyEworked set of ex—mplesD ˜uilding ™erti(ed ™ompilers from in™re—singly ™ompli™—ted sour™e l—ngu—ges to st—™k m—™hinesF ‡e will meet — few useful t—™ti™s —nd see how they ™—n ˜e used in m—nu—l proofsD —nd we will —lso see how e—sily these proofs ™—n ˜e —utom—ted inste—dF s —ssume th—t you h—ve inst—lled goq —nd €roof qener—lF „he ™ode in this ˜ook is tested with goq version VFPplID though p—rts m—y work with other versionsF es —lw—ysD you ™—n step through the sour™e (le StackMachine.v for this ™h—pter inter—™E tively in €roof qener—lF eltern—tivelyD to get — feel for the whole life™y™le of ™re—ting — goq developmentD you ™—n enter the pie™es of sour™e ™ode in this ™h—pter in — new .v (le in —n im—™s ˜u'erF sf you do the l—tterD in™lude two lines Require Import List TacticsF —nd Set Implicit ArgumentsF —t the st—rt of the (leD to m—t™h some ™ode hidden in this rendering of the ™h—pter sour™eD —nd ˜e sure to run the goq ˜in—ry coqtop with the ™omm—ndEline —rgument -I SRCD where SRC is the p—th to — dire™tory ™ont—ining the sour™e for this ˜ookF sn either ™—seD you will need to run make in the root dire™tory of the sour™e distri˜ution for the ˜ook ˜efore getting st—rtedF sf you h—ve inst—lled €roof qener—l properlyD it should st—rt —utom—ti™—lly when you visit — .v ˜u'er in im—™sF „here —re some minor he—d—™hes —sso™i—ted with getting €roof qener—l to p—ss the proper ™omm—nd line —rguments to the coqtop progr—mF „he ˜est w—y to —dd settings th—t will ˜e sh—red ˜y m—ny sour™e (les is to —dd — ™ustom v—ri—˜le setting to your .emacs (leD like thisX (custom-set-variables ... '(coq-prog-args '("-I" "/path/to/cpdt/src")) ... ) „he extr— —rguments demonstr—ted here —re the proper ™hoi™es for working with the ™ode for this ˜ookF „he ellipses st—nd for other im—™s ™ustomiz—tion settings you m—y —lre—dy h—veF st ™—n ˜e helpful to s—ve sever—l —ltern—te sets of )—gs in your .emacs (leD with —ll ˜ut one ™ommented out within the custom-set-variables ˜lo™k —t —ny given timeF IR ‡ith €roof qener—lD the portion of — ˜u'er th—t goq h—s pro™essed is highlighted in some w—yD like ˜eing given — ˜lue ˜—™kgroundF ‰ou step through goq sour™e (les ˜y positioning the point —t the position you w—nt goq to run to —nd pressing gEg gE‚i„F „his ™—n ˜e used ˜oth for norm—l stepE˜yEstep ™odingD ˜y pl—™ing the point inside some ™omm—nd p—st the end of the highlighted regionY —nd for undoingD ˜y pl—™ing the point inside the highlighted regionF 2.1 Arithmetic Expressions Over Natural Numbers ‡e will ˜egin with th—t st—ple of ™ompiler text˜ooksD —rithmeti™ expressions over — single type of num˜ersF 2.1.1 Source Language ‡e ˜egin with the synt—x of the sour™e l—ngu—geF Inductive binop X Set Xa Plus | TimesF yur (rst line of goq ™ode should ˜e unsurprising to wv —nd r—skell progr—mmersF ‡e de(ne —n —lge˜r—i™ d—t—type binop to st—nd for the ˜in—ry oper—tors of our sour™e l—nE gu—geF „here —re just two wrinkles ™omp—red to wv —nd r—skellF pirstD we use the keyword InductiveD in pl—™e of dataD datatypeD or typeF „his is not just — trivi—l surf—™e synt—x di'eren™eY indu™tive types in goq —re mu™h more expressive th—n g—rden v—riety —lge˜r—i™ d—t—typesD essenti—lly en—˜ling us to en™ode —ll of m—them—ti™sD though we ˜egin hum˜ly in this ™h—pterF ƒe™ondD there is the X Set fr—gmentD whi™h de™l—res th—t we —re de(ning — d—t—type th—t should ˜e thought of —s — ™onstituent of progr—msF v—terD we will see other options for de(ning d—t—types in the universe of proofs or in —n in(nite hier—r™hy of universesD en™omp—ssing ˜oth progr—ms —nd proofsD th—t is useful in higherEorder ™onstru™tionsF Inductive exp X Set Xa | Const X nat → exp | Binop X binop → exp → exp → expF xow we de(ne the type of —rithmeti™ expressionsF ‡e write th—t — ™onst—nt m—y ˜e ˜uilt from one —rgumentD — n—tur—l num˜erY —nd — ˜in—ry oper—tion m—y ˜e ˜uilt from — ™hoi™e of oper—tor —nd two oper—nd expressionsF e note for re—ders following —long in the €hp versionX ™oqdo™ supports prettyEprinting of tokens in v—„eˆ or r„wvF ‡here you see — right —rrow ™h—r—™terD the sour™e ™ont—ins the eƒgss text ->F yther ex—mples of this su˜stitution —ppe—ring in this ™h—pter —re — dou˜le right —rrow for => —nd the inverted 9e9 sym˜ol for forallF ‡hen in dou˜t —˜out the eƒgss version of — sym˜olD you ™—n ™onsult the ™h—pter sour™e ™odeF xow we —re re—dy to s—y wh—t these progr—ms me—nF ‡e will do this ˜y writing —n interpreter th—t ™—n ˜e thought of —s — trivi—l oper—tion—l or denot—tion—l sem—nti™sF @sf you IS —re not f—mili—r with these sem—nti™ te™hniquesD no need to worryY we will sti™k to 4™ommon sense4 ™onstru™tionsFA Definition binopDenote @b X binopA X nat → nat → nat Xa match b with | Plus ⇒ plus | Times ⇒ mult endF „he me—ning of — ˜in—ry oper—tor is — ˜in—ry fun™tion over n—tur—lsD de(ned with p—tternE m—t™hing not—tion —n—logous to the case —nd match of wv —nd r—skellD —nd referring to the fun™tions plus —nd mult from the goq st—nd—rd li˜r—ryF „he keyword Definition is goq9s —llEpurpose not—tion for ˜inding — term of the progr—mming l—ngu—ge to — n—meD with some —sso™i—ted synt—™ti™ sug—rD like the not—tion we see here for de(ning — fun™tionF „h—t sug—r ™ould ˜e exp—nded to yield this de(nitionX Definition binopDenote X binop → nat → nat → nat Xa fun @b X binopA ⇒ match b with | Plus ⇒ plus | Times ⇒ mult endF sn this ex—mpleD we ™ould —lso omit —ll of the type —nnot—tionsD —rriving —tX Definition binopDenote Xa fun match b with | Plus ⇒ plus | Times ⇒ mult endF b ⇒ v—nguges like r—skell —nd wv h—ve — ™onvenient principal typing propertyD whi™h gives us strong gu—r—ntees —˜out how e'e™tive type inferen™e will ˜eF …nfortun—telyD goq9s type system is so expressive th—t —ny kind of 4™omplete4 type inferen™e is impossi˜leD —nd the t—sk even seems to ˜e h—rd heuristi™—lly in pr—™ti™eF xonethelessD goq in™ludes some very helpful heuristi™sD m—ny of them ™opying the workings of r—skell —nd wv typeE™he™kers for progr—ms th—t f—ll in simple fr—gments of goq9s l—ngu—geF „his is —s good — time —s —ny to mention the preponder—n™e of di'erent l—ngu—ges —sso™iE —ted with goqF „he theoreti™—l found—tion of goq is — form—l system ™—lled the Calculus of Inductive Constructions (CIC)D whi™h is —n extension of the older Calculus of Constructions (CoC)F gsg is quite — sp—rt—n found—tionD whi™h is helpful for proving met—theory ˜ut not so helpful for re—l developmentF ƒtillD it is ni™e to know th—t it h—s ˜een proved th—t gsg enjoys properties like strong normalizationD me—ning th—t every progr—m @—ndD more import—ntlyD every proof termA termin—tesY —nd relative consistency with systems like versions of ermelo pr—enkel set theoryD whi™h roughly me—ns th—t you ™—n ˜elieve th—t goq proofs me—n th—t IT the ™orresponding propositions —re 4re—lly trueD4 if you ˜elieve in set theoryF goq is —™tu—lly ˜—sed on —n extension of gsg ™—lled GallinaF „he text —fter the Xa —nd ˜efore the period in the l—st ™ode ex—mple is — term of q—llin—F q—llin— —dds m—ny useful fe—tures th—t —re not ™ompiled intern—lly to more primitive gsg fe—turesF „he import—nt met—theorems —˜out gsg h—ve not ˜een extended to the full ˜re—dth of these fe—turesD ˜ut most goq users do not seem to lose mu™h sleep over this omissionF gomm—nds like Inductive —nd Definition —re p—rt of the vernacularD whi™h in™ludes —ll sorts of useful queries —nd requests to the goq systemF pin—llyD there is LtacD goq9s dom—inEspe™i(™ l—ngu—ge for writing proofs —nd de™ision pro™eduresF ‡e will see some ˜—si™ ex—mples of vt—™ l—ter in this ™h—pterD —nd mu™h of this ˜ook is devoted to more involved vt—™ ex—mplesF ‡e ™—n give — simple de(nition of the me—ning of —n expressionX Fixpoint expDenote @e X expA X nat Xa match e with | Const n ⇒ n | Binop b e1 e2 ⇒ @binopDenote b A @expDenote endF e1 A @expDenote e2 A ‡e de™l—re expli™itly th—t this is — re™ursive de(nitionD using the keyword FixpointF „he rest should ˜e old h—t for fun™tion—l progr—mmersF st is ™onvenient to ˜e —˜le to test de(nitions ˜efore st—rting to prove things —˜out themF ‡e ™—n verify th—t our sem—nti™s is sensi˜le ˜y ev—lu—ting some s—mple usesF Eval simpl in a RP X nat Eval simpl in a R X nat Eval simpl in a PV X nat expDenote @Const RPAF expDenote @Binop Plus expDenote @Binop Times @Const PA @Const PAAF @Binop Plus @Const PA @Const PAA @Const UAAF 2.1.2 Target Language ‡e will ™ompile our sour™e progr—ms onto — simple st—™k m—™hineD whose synt—x isX Inductive instr X Set Xa | IConst X nat → instr | IBinop X binop → instrF Definition Definition Xa list instrF stack Xa list natF prog en instru™tion either pushes — ™onst—nt onto the st—™k or pops two —rgumentsD —pplies — ˜in—ry oper—tor to themD —nd pushes the result onto the st—™kF e progr—m is — list of instru™tionsD —nd — st—™k is — list of n—tur—l num˜ersF IU ‡e ™—n give instru™tions me—nings —s fun™tions from st—™ks to option—l st—™ksD where running —n instru™tion results in None in ™—se of — st—™k under)ow —nd results in Some s' when the result of exe™ution is the new st—™k s'F XX is the 4list ™ons4 oper—tor from the goq st—nd—rd li˜r—ryF Definition instrDenote @i X instrA @s X stackA X option stack Xa match i with | IConst n ⇒ Some @n XX s A | IBinop b ⇒ match s with | arg1 XX arg2 XX s' ⇒ Some @@binopDenote b A arg1 arg2 XX | ⇒ None end endF ‡ith instrDenote de(nedD it is e—sy to de(ne — fun™tion ™—tion of instrDenote through — whole progr—mF s' A progDenoteD Fixpoint progDenote @p X progA @s X stackA {struct p } X option match p with | nil ⇒ Some s | i XX p' ⇒ match instrDenote i s with | None ⇒ None | Some s' ⇒ progDenote p' s' end endF stack whi™h iter—tes —ppliE Xa „here is one interesting di'eren™e ™omp—red to our previous ex—mple of — FixpointF „his re™ursive fun™tion t—kes two —rgumentsD p —nd s F st is ™riti™—l for the soundness of goq th—t every progr—m termin—teD so — sh—llow synt—™ti™ termin—tion ™he™k is imposed on every re™ursive fun™tion de(nitionF yne of the fun™tion p—r—meters must ˜e design—ted to de™re—se monotoni™—lly —™ross re™ursive ™—llsF „h—t isD every re™ursive ™—ll must use — version of th—t —rgument th—t h—s ˜een pulled out of the ™urrent —rgument ˜y some num˜er of match expressionsF expDenote h—s only one —rgumentD so we did not need to spe™ify whi™h of its —rguments de™re—sesF por progDenoteD we resolve the —m˜iguity ˜y writing {struct p } to indi™—te th—t —rgument p de™re—ses stru™tur—llyF ‚e™ent versions of goq will —lso infer — termin—tion —rgumentD so th—t we m—y write simplyX Fixpoint progDenote @p X progA @s X match p with | nil ⇒ Some s | i XX p' ⇒ match instrDenote i s with stackA X option stack Xa IV endF | None ⇒ None | Some s' ⇒ progDenote end p' s' 2.1.3 Translation yur ™ompiler itself is now unsurprisingF CC is the list ™on™—ten—tion oper—tor from the goq st—nd—rd li˜r—ryF Fixpoint compile @e X expA X prog Xa match e with | Const n ⇒ IConst n XX nil | Binop b e1 e2 ⇒ compile e2 CC endF compile e1 CC IBinop b XX nil fefore we set —˜out proving th—t this ™ompiler is ™orre™tD we ™—n try — few test runsD using our s—mple progr—ms from e—rlierF Eval simpl in compile @Const RPAF a IConst RP XX nil X prog Eval simpl in compile @Binop Plus @Const PA @Const PAAF a IConst P XX IConst P XX IBinop Plus XX nil X prog Eval simpl in compile @Binop Times @Binop Plus @Const PA @Const PAA @Const UAAF a IConst U XX IConst P XX IConst P XX IBinop Plus XX IBinop Times XX nil X prog ‡e ™—n —lso run our ™ompiled progr—ms —nd ™he™k th—t they give the right resultsF Eval simpl in progDenote @compile @Const RPAA a Some @RP XX nilA X option stack nilF Eval simpl in progDenote @compile @Binop a Some @R XX nilA X option stack @Const PA @Const PAAA Plus Eval simpl in progDenote @compile @Binop UAAA nilF a Some @PV XX nilA X option stack Times @Binop Plus nilF @Const PA @Const PAA @Const 2.1.4 Translation Correctness ‡e —re re—dy to prove th—t our ™ompiler is implemented ™orre™tlyF ‡e ™—n use — new vern—™ul—r ™omm—nd Theorem to st—rt — ™orre™tness proofD in terms of the sem—nti™s we de(ned e—rlierX Theorem compile correct X ∀ eD progDenote @compile e A nil a Some @expDenote e XX nilAF „hough — pen™ilE—ndEp—per proof might ™lo™k out —t this pointD writing 4˜y — routine indu™tion on eD4 it turns out not to m—ke sense to —tt—™k this proof dire™tlyF ‡e need to IW use the st—nd—rd tri™k of —uxili—ry lemm—X Lemma compile correct' progDenote @compile strengthening the induction hypothesisF X ∀ e p sD CC p A s a e progDenote p @expDenote efter the period in the Lemma ™omm—ndD we —re in the (nd ourselves st—ring —t this ominous s™reen of textX e ‡e do th—t ˜y proving —n XX s AF interactive proof-editing modeF ‡e I subgoal aaaaaaaaaaaaaaaaaaaaaaaaaaaa ∀ @e X expA @p X list instrA @s X stackAD progDenote @compile e CC p A s a progDenote p @expDenote e XX s A goq seems to ˜e rest—ting the lemm— for usF ‡h—t we —re seeing is — limited ™—se of — more gener—l proto™ol for des™ri˜ing where we —re in — proofF ‡e —re told th—t we h—ve — single su˜go—lF sn gener—lD during — proofD we ™—n h—ve m—ny pending su˜go—lsD e—™h of whi™h is — logi™—l proposition to proveF ƒu˜go—ls ™—n ˜e proved in —ny orderD ˜ut it usu—lly works ˜est to prove them in the order th—t goq ™hoosesF xext in the outputD we see our single su˜go—l des™ri˜ed in full det—ilF „here is — dou˜leE d—shed lineD —˜ove whi™h would ˜e our free v—ri—˜les —nd hypothesesD if we h—d —nyF felow the line is the ™on™lusionD whi™hD in gener—lD is to ˜e proved from the hypothesesF ‡e m—nipul—te the proof st—te ˜y running ™omm—nds ™—lled tacticsF vet us st—rt out ˜y running one of the most import—nt t—™ti™sX induction eF ‡e de™l—re th—t this proof will pro™eed ˜y indu™tion on the stru™ture of the expression eF „his sw—ps out our initi—l su˜go—l for two new su˜go—lsD one for e—™h ™—se of the indu™tive proofX P subgoals X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa ∀ @s X stackA @p X list instrAD progDenote @compile @Const n A CC p A s a progDenote p @expDenote @Const n A XX s A n subgoal P is X ∀ @s X stackA @p X list instrAD progDenote @compile @Binop b e1 e2 A CC p A s a progDenote p @expDenote @Binop b e1 e2 A XX s A PH „he (rst —nd ™urrent su˜go—l is displ—yed with the dou˜leEd—shed line ˜elow free v—ri—˜les —nd hypothesesD while l—ter su˜go—ls —re only summ—rized with their ™on™lusionsF ‡e see —n ex—mple of — free v—ri—˜le in the (rst su˜go—lY n is — free v—ri—˜le of type natF „he ™on™lusion is the origin—l theorem st—tement where e h—s ˜een repl—™ed ˜y Const nF sn — simil—r m—nnerD the se™ond ™—se h—s e repl—™ed ˜y — gener—lized invo™—tion of the Binop expression ™onstru™torF ‡e ™—n see th—t proving ˜oth ™—ses ™orresponds to — st—nd—rd proof ˜y stru™tur—l indu™tionF ‡e ˜egin the (rst ™—se with —nother very ™ommon t—™ti™F introsF „he ™urrent su˜go—l ™h—nges toX X nat X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote @compile @Const n A CC p A s a progDenote p @expDenote @Const n A XX s A n s ‡e see th—t intros ™h—nges ∀E˜ound v—ri—˜les —t the ˜eginning of — go—l into free v—riE —˜lesF „o progress furtherD we need to use the de(nitions of some of the fun™tions —ppe—ring in the go—lF „he unfold t—™ti™ repl—™es —n identi(er with its de(nitionF unfold compileF X nat X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote @@IConst n XX nilA CC p A s a progDenote p @expDenote @Const n A XX s A n s unfold expDenoteF X nat s X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote @@IConst n XX nilA CC p A s a progDenote n ‡e only need to unfold the (rst o™™urren™e of unfold progDenote at IF PI p @n XX s A progDenote to prove the go—lX X nat X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa @x progDenote @p0 X progA @s0 X stackA {struct option stack Xa n s p0 } X match p0 with | nil ⇒ Some s0 | i XX p' ⇒ match instrDenote i s0 with | Some s' ⇒ progDenote p' s' | None ⇒ None @AXast—™kA end endA @@IConst n XX nilA CC p A s a progDenote p @n XX s A „his l—st unfold h—s left us with —n —nonymous (xpoint version of progDenoteD whi™h will gener—lly h—ppen when unfolding re™ursive de(nitionsF portun—telyD in this ™—seD we ™—n elimin—te su™h ™ompli™—tions right —w—yD sin™e the stru™ture of the —rgument @IConst n XX nilA CC p is knownD —llowing us to simplify the intern—l p—ttern m—t™h with the simpl t—™ti™X simplF X nat s X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa @x progDenote @p0 X progA @s0 X stackA {struct p0 } X option stack Xa n match p0 with | nil ⇒ Some s0 | i XX p' ⇒ match instrDenote i s0 with | Some s' ⇒ progDenote p' s' | None ⇒ None @AXast—™kA end endA p @n XX s A a progDenote p @n XX s A xow we ™—n unexp—nd the de(nition of progDenoteX fold progDenoteF PP X nat s X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote p @n XX s A a progDenote p @n XX s A n st looks like we —re —t the end of this ™—seD sin™e we h—ve — trivi—l equ—lityF sndeedD — single t—™ti™ (nishes us o'X reflexivityF yn to the se™ond indu™tive ™—seX b X e1 binop X IHe1 exp X ∀ @s X progDenote e2 X @p X list instrAD @compile e1 CC p A stackA s a progDenote p e1 XX s A @expDenote e2 XX s A exp @p X list instrAD progDenote @compile e2 CC p A s a progDenote aaaaaaaaaaaaaaaaaaaaaaaaaaaa ∀ @s X stackA @p X list instrAD progDenote @compile @Binop b e1 e2 A CC p A s a progDenote p @expDenote @Binop b e1 e2 A XX s A IHe2 @expDenote X ∀ @s X stackA p ‡e see our (rst ex—mple of hypotheses —˜ove the dou˜leEd—shed lineF „hey —re the indu™tive hypotheses IHe1 —nd IHe2 ™orresponding to the su˜terms e1 —nd e2D respe™tivelyF ‡e st—rt out the s—me w—y —s ˜eforeD introdu™ing new free v—ri—˜les —nd unfolding —nd folding the —ppropri—te de(nitionsF „he seemingly frivolous unfoldGfold p—irs —re —™tu—lly —™™omplishing useful workD ˜e™—use unfold will sometimes perform e—sy simpli(™—tionsF introsF unfold compileF fold compileF unfold expDenoteF fold expDenoteF xow we —rrive —t — point where the t—™ti™s we h—ve seen so f—r —re insu0™ientF xo further de(nition unfoldings get us —nywhereD so we will need to try something di'erentF b X e1 binop X IHe1 exp X ∀ @s X @p X list instrAD @compile e1 CC p A stackA progDenote s a progDenote p PQ @expDenote e1 XX s A e2 X exp IHe2 X ∀ @s X @p X list instrAD @compile e2 CC p A stackA progDenote s a progDenote p @expDenote e2 XX s A X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote @@compile e2 CC compile e1 CC IBinop b XX nilA CC p A s a progDenote p @binopDenote b @expDenote e1 A @expDenote e2 A XX s A s ‡h—t we need is the —sso™i—tive l—w of list ™on™—ten—tionD —v—il—˜le —s — theorem in the st—nd—rd li˜r—ryF Check app ass app assF app ass X ∀ @A X TypeA @l m n X list AAD @l CC m A CC n a l CC m CC n ‡e use it to perform — rewriteX rewrite app assF ™h—nging the ™on™lusion toX progDenote progDenote @compile e2 CC @compile e1 CC IBinop b XX nilA CC p A p @binopDenote b @expDenote e1 A @expDenote e2 A XX s A s a xow we ™—n noti™e th—t the lefth—nd side of the equ—lity m—t™hes the lefth—nd side of the se™ond indu™tive hypothesisD so we ™—n rewrite with th—t hypothesisD tooX rewrite IHe2F progDenote @@compile e1 CC IBinop b XX nilA CC p A @expDenote e2 XX s A a @binopDenote b @expDenote e1 A @expDenote e2 A XX s A progDenote p „he s—me pro™ess lets us —pply the rem—ining hypothesisF rewrite rewrite app assF IHe1F progDenote progDenote @@IBinop b XX nilA CC p A @expDenote e1 XX expDenote e2 XX s A a p @binopDenote b @expDenote e1 A @expDenote e2 A XX s A xow we ™—n —pply — simil—r sequen™e of t—™ti™s to th—t th—t ended the proof of the (rst ™—seF unfold simplF progDenote at IF PR fold progDenoteF reflexivityF end the proof is ™ompletedD —s indi™—ted ˜y the mess—geX Proof completedF end there lies our (rst proofF elre—dyD even for simple theorems like thisD the (n—l proof s™ript is unstru™tured —nd not very enlightening to re—dersF sf we extend this —ppro—™h to more serious theoremsD we —rrive —t the unre—d—˜le proof s™ripts th—t —re the f—vorite ™ompl—ints of opponents of t—™ti™E˜—sed provingF portun—telyD goq h—s ri™h support for s™ripted —utom—tionD —nd we ™—n t—ke —dv—nt—ge of su™h — s™ripted t—™ti™ @de(ned elsewhereA to m—ke short work of this lemm—F ‡e —˜ort the old proof —ttempt —nd st—rt —g—inF AbortF Lemma compile correct' progDenote p induction e Y QedF X∀ e s pD progDenote @expDenote crushF e XX s AF @compile e CC p A s a ‡e need only to st—te the ˜—si™ indu™tive proof s™heme —nd ™—ll — t—™ti™ th—t —utom—tes the tedious re—soning in ˜etweenF sn ™ontr—st to the period t—™ti™ termin—tor from our l—st proofD the semi™olon t—™ti™ sep—r—tor supports stru™turedD ™omposition—l proofsF „he t—™ti™ t1Y t2 h—s the e'e™t of running t1 —nd then running t2 on e—™h rem—ining su˜go—lF „he semi™olon is one of the most fund—ment—l ˜uilding ˜lo™ks of e'e™tive proof —utom—tionF „he period termin—tor is very useful for explor—tory provingD where you need to see intermeE di—te proof st—tesD ˜ut (n—l proofs of —ny serious ™omplexity should h—ve just one periodD termin—ting — single ™ompound t—™ti™ th—t pro˜—˜ly uses semi™olonsF „he crush t—™ti™ ™omes from the li˜r—ry —sso™i—ted with this ˜ook —nd is not p—rt of the goq st—nd—rd li˜r—ryF „he ˜ook9s li˜r—ry ™ont—ins — num˜er of other t—™ti™s th—t —re espe™i—lly helpful in highlyE—utom—ted proofsF „he proof of our m—in theorem is now e—syF ‡e prove it with four periodEtermin—ted t—™ti™sD though sep—r—ting them with semi™olons would work —s wellY the version here is e—sier to step throughF Theorem compile introsF correct X ∀ eD progDenote @compile e A X exp aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote @compile eA nil a Some @expDenote e XX nil a Some @expDenote e XX nilAF e nilA et this pointD we w—nt to m—ss—ge the lefth—nd side to m—t™h the st—tement of e theorem from the st—nd—rd li˜r—ry is usefulX pile correct'F Check app nil endF PS com- app nil end X ∀ @A X TypeA @l X rewrite @app nil end list AAD l a l CC nil @compile e AAF „his timeD we expli™itly spe™ify the v—lue of the v—ri—˜le l from the theorem st—tementD sin™e multiple expressions of list type —ppe—r in the ™on™lusionF rewrite might ™hoose the wrong pl—™e to rewrite if we did not spe™ify whi™h we w—ntF X exp aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote @compile e CC nilA nil a Some @expDenote e e XX nilA xow we ™—n —pply the lemm—F rewrite compile correct'F X exp aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote nil @expDenote e XX nilA a Some @expDenote e e XX nilA ‡e —re —lmost doneF „he lefth—nd —nd righth—nd sides ™—n ˜e seen to m—t™h ˜y simple sym˜oli™ ev—lu—tionF „h—t me—ns we —re in lu™kD ˜e™—use goq identi(es —ny p—ir of terms —s equ—l whenever they norm—lize to the s—me result ˜y sym˜oli™ ev—lu—tionF fy the de(nition of progDenoteD th—t is the ™—se hereD ˜ut we do not need to worry —˜out su™h det—ilsF e simple invo™—tion of reflexivity does the norm—liz—tion —nd ™he™ks th—t the two results —re synt—™ti™—lly equ—lF reflexivityF QedF 2.2 Typed Expressions sn this se™tionD we will ˜uild on the initi—l ex—mple ˜y —dding —ddition—l expression forms th—t depend on st—ti™ typing of terms for s—fetyF 2.2.1 Source Language ‡e de(ne — trivi—l l—ngu—ge of types to ™l—ssify our expressionsX Inductive type X Set Xa Nat | BoolF xow we de(ne —n exp—nded set of ˜in—ry oper—torsF Inductive tbinop X type → type → type → Set Xa PT tbinop Nat Nat Nat TTimes X tbinop Nat Nat Nat TEq X ∀ tD tbinop t t Bool TLt X tbinop Nat Nat BoolF „he de(nition of tbinop is di'erent from binop in —n import—nt w—yF ‡here we de™l—red th—t binop h—s type SetD here we de™l—re th—t tbinop h—s type type → type → type → SetF ‡e de(ne tbinop —s —n indexed type familyF sndexed indu™tive types —re —t the he—rt | | | | TPlus X of goq9s expressive powerY —lmost everything else of interest is de(ned in terms of themF wv —nd r—skell h—ve indexed —lge˜r—i™ d—t—typesF por inst—n™eD their list types —re indexed ˜y the type of d—t— th—t the list ™—rriesF roweverD ™omp—red to goqD wv —nd r—skell WV pl—™e two import—nt restri™tions on d—t—type de(nitionsF pirstD the indi™es of the r—nge of e—™h d—t— ™onstru™tor must ˜e type v—ri—˜les ˜ound —t the top level of the d—t—type de(nitionF „here is no w—y to do wh—t we did hereD where weD for inst—n™eD s—y th—t TPlus is — ™onstru™tor ˜uilding — tbinop whose indi™es —re —ll (xed —t NatF Generalized algebraic datatypes (GADTs) —re — popul—r fe—ture in qrg r—skell —nd other l—ngu—ges th—t removes this (rst restri™tionF „he se™ond restri™tion is not lifted ˜y qeh„sF sn wv —nd r—skellD indi™es of types must ˜e types —nd m—y not ˜e expressionsF sn goqD types m—y ˜e indexed ˜y —r˜itr—ry q—llin— termsF „ype indi™es ™—n live in the s—me universe —s progr—msD —nd we ™—n ™ompute with them just like regul—r progr—msF r—skell supports — ho˜˜led form of ™omput—tion in type indi™es ˜—sed on multiEp—r—meter type ™l—ssesD —nd re™ent extensions like type fun™tions ˜ring r—skell progr—mming even ™loser to 4re—l4 fun™tion—l progr—mming with typesD ˜utD without dependent typingD there must —lw—ys ˜e — g—p ˜etween how one progr—ms with types —nd how one progr—ms norm—llyF ‡e ™—n de(ne — simil—r type f—mily for typed expressionsF Inductive texp X type → Set Xa | TNConst X nat → texp Nat | TBConst X bool → texp Bool | TBinop X ∀ arg1 arg2 resD tbinop texp arg1 → texp arg2 → texp resF „h—nks to our use of dependent typesD every wellEtyped texp represents — wellEtyped arg1 arg2 res → sour™e expressionD ˜y ™onstru™tionF „his turns out to ˜e very ™onvenient for m—ny things we might w—nt to do with expressionsF por inst—n™eD it is e—sy to —d—pt our interpreter —ppro—™h to de(ning sem—nti™sF ‡e st—rt ˜y de(ning — fun™tion m—pping the types of our l—ngu—ges into goq typesX Definition typeDenote @t X typeA X Set Xa match t with | Nat ⇒ nat | Bool ⇒ bool endF st ™—n t—ke — few moments to ™ome to terms with the f—™t th—t SetD the type of types of progr—msD is itself — (rstE™l—ss typeD —nd th—t we ™—n write fun™tions th—t return SetsF €—st PU th—t wrinkleD the de(nition of typeDenote is trivi—lD relying on the nat —nd bool types from the goq st—nd—rd li˜r—ryF ‡e need to de(ne — few —uxili—ry fun™tionsD implementing our ˜oole—n ˜in—ry oper—tors th—t do not —ppe—r with the right types in the st—nd—rd li˜r—ryF „hey —re entirely st—nd—rd —nd wvElikeD with the one ™—ve—t ˜eing th—t the goq nat type uses — un—ry represent—tionD where O is zero —nd S n is the su™™essor of nF Definition eq bool @b1 match b1D b2 with | trueD true ⇒ true | falseD false ⇒ true | D ⇒ false endF b2 X boolA X bool Xa Fixpoint eq nat @n1 n2 X natA X bool Xa match n1D n2 with | OD O ⇒ true | S n1'D S n2' ⇒ eq nat n1' n2' | D ⇒ false endF Fixpoint lt @n1 n2 X natA X bool Xa match n1D n2 with | OD S ⇒ true | S n1'D S n2' ⇒ lt n1' n2' | D ⇒ false endF xow we ™—n interpret ˜in—ry oper—torsX Definition tbinopDenote arg1 arg2 res @b X tbinop arg1 arg2 res A X typeDenote arg1 → typeDenote arg2 → typeDenote res Xa match b in @tbinop arg1 arg2 res A return @typeDenote arg1 → typeDenote arg2 → typeDenote res A with | TPlus ⇒ plus | TTimes ⇒ mult | TEq Nat ⇒ eq nat | TEq Bool ⇒ eq bool | TLt ⇒ lt endF „his fun™tion h—s just — few di'eren™es from the denot—tion fun™tions we s—w e—rlierF pirstD tbinop is —n indexed typeD so its indi™es ˜e™ome —ddition—l —rguments to tbinopDenoteF ƒe™ondD we need to perform — genuine dependent pattern match to ™ome up with — de(nition of this fun™tion th—t typeE™he™ksF sn e—™h ˜r—n™h of the matchD we need to use ˜r—n™hEspe™i(™ inform—tion —˜out the indi™es to tbinopF qener—l type inferen™e th—t t—kes su™h inform—tion into —™™ount is unde™id—˜leD so it is often ne™ess—ry to write —nnot—tionsD like we see —˜ove PV on the line with matchF „he in —nnot—tion rest—tes the type of the term ˜eing ™—seE—n—lyzedF „hough we use the s—me n—mes for the indi™es —s we use in the type of the origin—l —rgument ˜inderD these —re —™tu—lly fresh v—ri—˜lesD —nd they —re binding occurrencesF „heir s™ope is the return ™l—useF „h—t isD arg1D arg2D —nd arg3 —re new ˜ound v—ri—˜les ˜ound only within the return ™l—use typeDenote arg1 → typeDenote arg2 → typeDenote resF fy ˜eing expli™it —˜out the fun™tion—l rel—tionship ˜etween the type indi™es —nd the m—t™h resultD we reg—in de™id—˜le type inferen™eF sn f—™tD re™ent goq versions use some heuristi™s th—t ™—n s—ve us the trou˜le of writing match —nnot—tionsD —nd those heuristi™s get the jo˜ done in this ™—seF ‡e ™—n get —w—y with writing justX Definition tbinopDenote arg1 arg2 res @b X tbinop arg1 arg2 X typeDenote arg1 → typeDenote arg2 → typeDenote res Xa match b with | TPlus ⇒ plus | TTimes ⇒ mult | TEq Nat ⇒ eq nat | TEq Bool ⇒ eq bool | TLt ⇒ lt endF res A „he s—me tri™ks su0™e to de(ne —n expression denot—tion fun™tion in —n unsurprising w—yX Fixpoint texpDenote t @e X texp t A X typeDenote t Xa match e with | TNConst n ⇒ n | TBConst b ⇒ b b e1 e2 ⇒ @tbinopDenote b A @texpDenote | TBinop endF e1 A @texpDenote e2 A ‡e ™—n ev—lu—te — few ex—mple progr—ms to ™onvin™e ourselves th—t this sem—nti™s is ™orre™tF Eval simpl in texpDenote @TNConst RPAF a RP X typeDenote Nat Eval simpl in texpDenote @TBConst a true X typeDenote Bool trueAF Eval simpl in texpDenote @TBinop TTimes @TBinop TPlus @TNConst PA @TNConst PAA @TNConst UAAF a PV X typeDenote Nat Eval simpl in texpDenote @TBinop @TEq @TNConst UAAF a false X typeDenote Bool NatA PW @TBinop TPlus @TNConst PA @TNConst PAA Eval simpl in texpDenote @TBinop TLt @TBinop TPlus @TNConst PA @TNConst PAA @TNConst UAAF a true X typeDenote Bool 2.2.2 Target Language xow we w—nt to de(ne — suit—˜le st—™k m—™hine t—rget for ™ompil—tionF sn the ex—mple of the untyped l—ngu—geD st—™k m—™hine progr—ms ™ould en™ounter st—™k under)ows —nd 4get stu™kF4 „his w—s unfortun—teD sin™e we h—d to de—l with this ™ompli™—tion even though we proved th—t our ™ompiler never produ™ed under)owing progr—msF ‡e ™ould h—ve used dependent types to for™e —ll st—™k m—™hine progr—ms to ˜e under)owEfreeF por our new l—ngu—gesD ˜esides under)owD we —lso h—ve the pro˜lem of st—™k slots with n—tur—ls inste—d of ˜ools or vi™e vers—F „his timeD we will use indexed typed f—milies to —void the need to re—son —˜out potenti—l f—iluresF ‡e st—rt ˜y de(ning st—™k typesD whi™h ™l—ssify sets of possi˜le st—™ksF Definition tstack Xa list typeF eny st—™k ™l—ssi(ed ˜y — tstack must h—ve ex—™tly —s m—ny elementsD —nd e—™h st—™k element must h—ve the type found in the s—me position of the st—™k typeF ‡e ™—n de(ne instru™tions in terms of st—™k typesD where every instru™tion9s type tells us wh—t initi—l st—™k type it expe™ts —nd wh—t (n—l st—™k type it will produ™eF Inductive tinstr X tstack → tstack → Set Xa | TINConst X ∀ sD nat → tinstr s @Nat XX s A | TIBConst X ∀ sD bool → tinstr s @Bool XX s A | TIBinop X ∀ arg1 arg2 res sD tbinop arg1 arg2 → tinstr @arg1 XX res arg2 XX s A @res XX s AF ƒt—™k m—™hine progr—ms must ˜e — simil—r indu™tive f—milyD sin™eD if we —g—in used the list type f—milyD we would not ˜e —˜le to gu—r—ntee th—t intermedi—te st—™k types m—t™h within — progr—mF Inductive tprog X tstack → | TNil X ∀ sD tprog s s | TCons X ∀ s1 s2 s3D tinstr s1 s2 → tprog s2 → tprog s1 tstack → Set Xa s3 s3F xowD to de(ne the sem—nti™s of our new t—rget l—ngu—geD we need — represent—tion for st—™ks —t runtimeF ‡e will —g—in t—ke —dv—nt—ge of type inform—tion to de(ne types of v—lue st—™ks th—tD ˜y ™onstru™tionD ™ont—in the right num˜er —nd types of elementsF Fixpoint vstack @ts X match ts with tstackA X Set Xa QH | nil ⇒ unit | t XX ts' ⇒ typeDenote end7typeF t × vstack ts' „his is —nother SetEv—lued fun™tionF „his time it is re™ursiveD whi™h is perfe™tly v—lidD sin™e Set is not tre—ted spe™i—lly in determining whi™h fun™tions m—y ˜e writtenF ‡e s—y th—t the v—lue st—™k of —n empty st—™k type is —ny v—lue of type unitD whi™h h—s just — single v—lueD ttF e nonempty st—™k type le—ds to — v—lue st—™k th—t is — p—irD whose (rst element h—s the proper type —nd whose se™ond element follows the represent—tion for the rem—inder of the st—™k typeF ‡e write 7type so th—t goq knows to interpret × —s g—rtesi—n produ™t r—ther th—n multipli™—tionF „his ide— of progr—mming with types ™—n t—ke — while to intern—lizeD ˜ut it en—˜les — very simple de(nition of instru™tion denot—tionF yur de(nition is like wh—t you might expe™t from — vispElike version of wv th—t ignored type inform—tionF xonethelessD the f—™t th—t tinstrDenote p—sses the typeE™he™ker gu—r—ntees th—t our st—™k m—™hine progr—ms ™—n never go wrongF Definition tinstrDenote ts ts' @i X tinstr ts ts' A X vstack ts → match i with | TINConst n ⇒ fun s ⇒ @nD s A | TIBConst b ⇒ fun s ⇒ @bD s A b ⇒ fun s ⇒ | TIBinop match s with @arg1D @arg2D s' AA ⇒ @@tbinopDenote b A arg1 arg2D s' A end endF vstack ts' Xa ‡hy do we ™hoose to use —n —nonymous fun™tion to ˜ind the initi—l st—™k in every ™—se of the matchc gonsider this wellEintentioned ˜ut inv—lid —ltern—tive versionX Definition tinstrDenote ts ts' @i X tinstr ts ts' A @s X match i with | TINConst n ⇒ @nD s A | TIBConst b ⇒ @bD s A | TIBinop b⇒ match s with @arg1D @arg2D s' AA ⇒ @@tbinopDenote b A arg1 end endF vstack ts A arg2D s' A „he goq typeE™he™ker ™ompl—ins th—tX The term 4@nD sA4 has type 4@n—t × vst—™k tsA7type4 type 4vst—™k cIIW4F while it is expected to have QI X vstack ts' Xa „he text cIIW st—nds for — uni(™—tion v—ri—˜leF ‡e ™—n try to help goq (gure out the v—lue of this v—ri—˜le with —n expli™it —nnot—tion on our match expressionF Definition tinstrDenote ts ts' @i X tinstr ts ts' A @s X match i in tinstr ts ts' return vstack ts' with | TINConst n ⇒ @nD s A | TIBConst b ⇒ @bD s A | TIBinop b⇒ match s with @arg1D @arg2D s' AA ⇒ @@tbinopDenote b A arg1 end endF vstack ts A X vstack ts' Xa arg2D s' A xow the error mess—ge ™h—ngesF The term 4@nD sA4 has type 4@n—t × vst—™k tsA7type4 type 4vst—™k @x—t XX tA4F while it is expected to have ‚e™—ll from our e—rlier dis™ussion of match —nnot—tions th—t we write the —nnot—tions to express to the typeE™he™ker the rel—tionship ˜etween the type indi™es of the ™—se o˜je™t —nd the result type of the matchF goq ™hooses to —ssign to the wild™—rd —fter TINConst the n—me t D —nd the type error is telling us th—t the type ™he™ker ™—nnot prove th—t t is the s—me —s tsF fy moving s out of the matchD we lose the —˜ility to expressD with in —nd return ™l—usesD the rel—tionship ˜etween the sh—red index ts of s —nd iF „here are re—son—˜ly gener—l w—ys of getting —round this pro˜lem without pushing ˜inders inside matchesF roweverD the —ltern—tives —re signi(™—ntly more involvedD —nd the te™hnique we use here is —lmost ™ert—inly the ˜est ™hoi™eD whenever it —ppliesF ‡e (nish the sem—nti™s with — str—ightforw—rd de(nition of progr—m denot—tionF Fixpoint tprogDenote ts ts' @p X tprog ts ts' A X vstack ts → vstack ts' Xa match p with | TNil ⇒ fun s ⇒ s i p' ⇒ fun s ⇒ tprogDenote p' @tinstrDenote i s A | TCons endF 2.2.3 Translation „o de(ne our ™ompil—tionD it is useful to h—ve —n —uxili—ry fun™tion for ™on™—ten—ting two st—™k m—™hine progr—msF Fixpoint tconcat ts ts' ts @p X tprog ts ts' A X tprog ts' ts → tprog match p with | TNil ⇒ fun p' ⇒ p' | TCons i p1 ⇒ fun p' ⇒ TCons i @tconcat p1 p' A QP ts ts Xa endF ‡ith th—t fun™tion in pl—™eD the ™ompil—tion is de(ned very simil—rly to how it w—s ˜eforeD modulo the use of dependent typingF Fixpoint tcompile t @e X texp t A @ts X tstackA X tprog ts @t XX ts A Xa match e with | TNConst n ⇒ TCons @TINConst n A @TNil A | TBConst b ⇒ TCons @TIBConst b A @TNil A | TBinop b e1 e2 ⇒ tconcat @tcompile e2 A @tconcat @tcompile e1 A @TCons @TIBinop b A @TNil AAA endF yne interesting fe—ture of the de(nition is the unders™ores —ppe—ring to the right of ⇒ —rrowsF r—skell —nd wv progr—mmers —re quite f—mili—r with ™ompilers th—t infer type p—r—meters to polymorphi™ v—luesF sn goqD it is possi˜le to go even further —nd —sk the system to infer —r˜itr—ry termsD ˜y writing unders™ores in pl—™e of spe™i(™ v—luesF ‰ou m—y h—ve noti™ed th—t we h—ve ˜een ™—lling fun™tions without spe™ifying —ll of their —rgumentsF por inst—n™eD the re™ursive ™—lls here to tcompile omit the t —rgumentF goq9s implicit argument me™h—nism —utom—ti™—lly inserts unders™ores for —rguments th—t it will pro˜—˜ly ˜e —˜le to inferF snferen™e of su™h v—lues is f—r from ™ompleteD thoughY gener—llyD it only works in ™—ses simil—r to those en™ountered with polymorphi™ type inst—nti—tion in r—skell —nd wvF „he unders™ores here —re ˜eing (lled in with st—™k typesF „h—t isD the goq type inferen™er isD in — senseD inferring something —˜out the )ow of ™ontrol in the tr—nsl—ted progr—msF ‡e ™—n t—ke — look —t ex—™tly whi™h v—lues —re (lled inX Print tcompileF tcompile a @t X typeA @e X texp t A @ts X tstackA {struct e} X tprog ts @t XX ts A Xa match e in @texp t0 A return @tprog ts @t0 XX ts AA with x tcompile ⇒ TCons @TINConst ts nA @TNil @Nat XX ts AA ⇒ TCons @TIBConst ts b A @TNil @Bool XX ts AA TBinop arg1 arg2 res b e1 e2 ⇒ tconcat @tcompile arg2 e2 ts A @tconcat @tcompile arg1 e1 @arg2 XX ts AA @TCons @TIBinop ts b A @TNil @res XX ts AAAA end X ∀ t X typeD texp t → ∀ ts X tstackD tprog ts @t XX ts A | | | TNConst n TBConst b ‡e ™—n ™he™k th—t the ™ompiler gener—tes progr—ms th—t ˜eh—ve —ppropri—tely on our s—mple progr—ms from —˜oveX Eval simpl in a @RPD ttA X vstack Eval simpl in tprogDenote @tcompile @TNConst RPA @Nat XX nilA tprogDenote @tcompile @TBConst QQ nilA ttF trueA nilA ttF a @trueD ttA X vstack @Bool XX nilA Eval simpl in tprogDenote @tcompile @TBinop TTimes @TBinop TPlus @TNConst PA @TNConst PAA @TNConst UAA nilA ttF a @PVD ttA X vstack @Nat XX nilA Eval simpl in tprogDenote @tcompile @TBinop @TEq NatA @TBinop TPlus @TNConst PA @TNConst PAA @TNConst UAA nilA ttF a @falseD ttA X vstack @Bool XX nilA Eval simpl in tprogDenote @tcompile @TBinop TLt @TBinop TPlus @TNConst PA @TNConst PAA @TNConst UAA nilA ttF a @trueD ttA X vstack @Bool XX nilA 2.2.4 Translation Correctness ‡e ™—n st—te — ™orre™tness theorem simil—r to the l—st oneF Theorem tcompile correct tprogDenote @tcompile X∀ t @e X texp t AD a @texpDenote eD e nilA tt ttAF eg—inD we need to strengthen the theorem st—tement so th—t the indu™tion will go throughF „his timeD s will develop —n —ltern—tive —ppro—™h to this kind of proofD st—ting the key lemm— —sX Lemma tcompile correct' tprogDenote @tcompile X∀ t @e X texp t A ts @s X vstack a @texpDenote eD s AF e ts A s ts AD ‡hile lemm— compile correct' qu—nti(ed over — progr—m th—t is the 4™ontinu—tion4 for the expression we —re ™onsideringD here we —void dr—wing in —ny extr— synt—™ti™ elementsF sn —ddition to the sour™e expression —nd its typeD we —lso qu—ntify over —n initi—l st—™k type —nd — st—™k ™omp—ti˜le with itF ‚unning the ™ompil—tion of the progr—m st—rting from th—t st—™kD we should —rrive —t — st—™k th—t di'ers only in h—ving the progr—m9s denot—tion pushed onto itF vet us try to prove this theorem in the s—me w—y th—t we settled on in the l—st se™tionF induction e Y crushF ‡e —re left with this unproved ™on™lusionX tprogDenote @tconcat @tcompile e2 ts A @tconcat @tcompile e1 @arg2 XX ts AA @TCons @TIBinop ts t A @TNil @res XX ts AAAAA s a @tbinopDenote t @texpDenote e1 A @texpDenote e2 AD s A ‡e need —n —n—logue to the app ass theorem th—t we used to rewrite the go—l in the l—st se™tionF ‡e ™—n —˜ort this proof —nd prove su™h — lemm— —˜out tconcatF AbortF QR Lemma tconcat correct X ∀ ts ts' ts @p X tprog @s X vstack ts AD tprogDenote @tconcat p p' A s a tprogDenote p' @tprogDenote p s AF induction p Y crushF QedF ts ts' A @p' X tprog ts' „his one goes through ™ompletely —utom—ti™—llyF ƒome ™ode ˜ehind the s™enes registers app ass for use ˜y cat correct simil—rly to get the s—me e'e™tX Hint Rewrite tconcat correct X crushF ts A ‡e must register tcon- cpdtF ‡e —sk th—t the lemm— ˜e used for leftEtoEright rewritingD —nd we —sk for the hint to ˜e —dded to the hint d—t—˜—se ™—lled cpdtD whi™h is the d—t—˜—se used ˜y crushF xow we —re re—dy to return to tcompile correct'D proving it —utom—ti™—lly this timeF Lemma tcompile correct' @tcompile induction e Y crushF QedF tprogDenote @e X texp t A ts @s X vstack ts A s a @texpDenote eD s AF X∀ e t ts AD ‡e ™—n register this m—in lemm— —s —nother hintD —llowing us to prove the (n—l theorem trivi—llyF Hint Rewrite tcompile correct' Theorem tcompile correct tprogDenote crushF @tcompile e X cpdtF @e X texp t AD nilA tt a @texpDenote eD X∀ t QedF QS ttAF Part I Basic Programming and Proving QT Chapter 3 Introducing Inductive Types sn — senseD gsg is ˜uilt from just two rel—tively str—ightforw—rd fe—turesX fun™tion types —nd indu™tive typesF prom this modest found—tionD we ™—n prove e'e™tively —ll of the theorems of m—th —nd ™—rry out e'e™tively —ll progr—m veri(™—tionsD with enough e'ort expendedF „his ™h—pter introdu™es indu™tion —nd re™ursion for fun™tion—l progr—mming in goqF 3.1 Enumerations goq indu™tive types gener—lize the —lge˜r—i™ d—t—types found in r—skell —nd wvF gonfusingly enoughD indu™tive types —lso gener—lize gener—lized —lge˜r—i™ d—t—types @qeh„sAD ˜y —dding the possi˜ility for type dependen™yF iven soD it is worth ˜—™king up from the ex—mples of the l—st ™h—pter —nd going over ˜—si™D —lge˜r—i™ d—t—type uses of indu™tive d—t—typesD ˜e™—use the ™h—n™e to prove things —˜out the v—lues of these types —dds new wrinkles ˜eyond usu—l pr—™ti™e in r—skell —nd wvF „he singleton type unit is —n indu™tive typeX Inductive unit X Set Xa | ttF „his vern—™ul—r ™omm—nd de(nes — new indu™tive type we ™—n see ˜y ™he™king the types of the two identi(ersX unit whose only v—lue is ttD —s Check unitF unit X Set Check ttF tt X unit unit is — genuine singleton typeF singleton X ∀ x X unitD x a ttF ‡e ™—n prove th—t Theorem unit „he import—nt thing —˜out —n indu™tive type isD unsurprisinglyD th—t you ™—n do indu™tion over its v—luesD —nd indu™tion is the key to proving this theoremF ‡e —sk to pro™eed ˜y indu™tion on the v—ri—˜le x F QU induction xF „he go—l ™h—nges toX tt a tt FFFwhi™h we ™—n dis™h—rge trivi—llyF reflexivityF QedF st seems kind of odd to write — proof ˜y indu™tion with no indu™tive hypothesesF ‡e ™ould h—ve —rrived —t the s—me result ˜y ˜eginning the proof withX destruct x F FFFwhi™h ™orresponds to 4proof ˜y ™—se —n—lysis4 in ™l—ssi™—l m—thF por nonEre™ursive indu™tive typesD the two t—™ti™s will —lw—ys h—ve identi™—l ˜eh—viorF yften ™—se —n—lysis is su0™ientD even in proofs —˜out re™ursive typesD —nd it is ni™e to —void introdu™ing unneeded indu™tion hypothesesF ‡h—t ex—™tly is the indu™tion prin™iple for unitc ‡e ™—n —sk goqX Check unit indF unit ind X∀ P X unit → PropD P tt →∀ u X unitD P u ivery Inductive ™omm—nd de(ning — type T —lso de(nes —n indu™tion prin™iple n—med T indF goq follows the gurryErow—rd ™orresponden™e —nd in™ludes the ingredients of proE gr—mming —nd proving in the s—me single synt—™ti™ ™l—ssF „husD our typeD oper—tions over itD —nd prin™iples for re—soning —˜out it —ll live in the s—me l—ngu—ge —nd —re des™ri˜ed ˜y the s—me type systemF „he key to telling wh—t is — progr—m —nd wh—t is — proof lies in the distin™tion ˜etween the type PropD whi™h —ppe—rs in our indu™tion prin™ipleY —nd the type SetD whi™h we h—ve seen — few times —lre—dyF „he ™onvention goes like thisX Set is the type of norm—l typesD —nd the v—lues of su™h types —re progr—msF Prop is the type of logi™—l propositionsD —nd the v—lues of su™h types —re proofsF „husD —n indu™tion prin™iple h—s — type th—t shows us th—t it is — fun™tion for ˜uilding proofsF ƒpe™i(™—llyD unit ind qu—nti(es over — predi™—te P over unit v—luesF sf we ™—n present — proof th—t P holds of ttD then we —re rew—rded with — proof th—t P holds for —ny v—lue u of type unitF sn our l—st proofD the predi™—te w—s @fun u X unit ⇒ u a ttAF ‡e ™—n de(ne —n indu™tive type even simpler th—n unitX Inductive Empty set X Set Xa F Empty set h—s no elementsF ‡e ™—n prove fun theorems —˜out itX Theorem the sky is falling X ∀ x X Empty setD P C P a SF destruct IF QedF fe™—use Empty set h—s no elementsD the f—™t of h—ving —n element of this type implies —nythingF ‡e use destruct I inste—d of destruct x in the proof ˜e™—use unused qu—nti(ed QV v—ri—˜les —re releg—ted to ˜eing referred to ˜y num˜erF @„here is — good re—son for thisD rel—ted to the unity of qu—nti(ers —nd impli™—tionF en impli™—tion is just — qu—nti(™—tion over — proofD where the qu—nti(ed v—ri—˜le is never usedF st gener—lly m—kes more sense to refer to impli™—tion hypotheses ˜y num˜er th—n ˜y n—meD —nd goq tre—ts our qu—nti(er over —n unused v—ri—˜le —s —n impli™—tion in determining the proper ˜eh—viorFA ‡e ™—n see the indu™tion prin™iple th—t m—de this proof so e—syX Check Empty set indF Empty set ind X ∀ @P X Empty set → PropA @e X Empty setAD P e sn other wordsD —ny predi™—te over v—lues from the empty set holds v—™uously of every su™h elementF sn the l—st proofD we ™hose the predi™—te @fun X Empty set ⇒ P C P a SAF ‡e ™—n —lso —pply this getEoutEofEj—ilEfree ™—rd progr—mm—ti™—llyF rere is — l—zy w—y of ™onverting v—lues of Empty set to v—lues of unitX Definition e2u @e X Empty setA X unit Xa match e with endF ‡e employ match p—ttern m—t™hing —s in the l—st ™h—pterF ƒin™e we m—t™h on — v—lue whose type h—s no ™onstru™torsD there is no need to provide —ny ˜r—n™hesF woving up the l—dder of ™omplexityD we ™—n de(ne the ˜oole—nsX Inductive bool X Set Xa | true | falseF ‡e ™—n use less v—™uous p—ttern m—t™hing to de(ne ˜oole—n neg—tionF Definition not @b X boolA X bool Xa match b with | true ⇒ false | false ⇒ true endF en —ltern—tive de(nition desug—rs to the —˜oveX Definition not' @b X boolA X bool Xa if b then false else trueF ‡e might w—nt to prove th—t Theorem not inverse X ∀ destruct bF b X not is its own inverse oper—tionF boolD not @not b A a bF efter we ™—seE—n—lyze on bD we —re left with one su˜go—l for e—™h ™onstru™tor of P subgoals aaaaaaaaaaaaaaaaaaaaaaaaaaaa not @not trueA a true subgoal P is X QW boolF not @not falseA a false „he (rst su˜go—l follows ˜y goq9s rules of ™omput—tionD so we ™—n disp—t™h it e—silyX reflexivityF vikewise for the se™ond su˜go—lD so we ™—n rest—rt the proof —nd give — very ™omp—™t justi(™—tionF RestartF destruct b Y reflexivityF QedF enother theorem —˜out ˜oole—ns illustr—tes —nother useful t—™ti™F Theorem not ineq X ∀ b X boolD destruct b Y discriminateF QedF not b = bF discriminate is used to prove th—t two v—lues of —n indu™tive type —re not equ—lD whenE ever the v—lues —re formed with di'erent ™onstru™torsF sn this ™—seD the di'erent ™onstru™tors —re true —nd falseF et this pointD it is pro˜—˜ly not h—rd to guess wh—t the underlying indu™tion prin™iple for bool isF Check bool indF bool ind X∀ P X bool → PropD P true → P false →∀ b X boolD P b 3.2 Simple Recursive Types „he n—tur—l num˜ers —re the simplest ™ommon ex—mple of —n indu™tive type th—t —™tu—lly deserves the n—meF Inductive nat X Set Xa | O X nat | S X nat → natF is zeroD —nd S is the su™™essor fun™tionD so th—t H is synt—™ti™ sug—r for P for S @S OAD —nd so onF €—ttern m—t™hing works —s we demonstr—ted in the l—st ™h—pterX O Definition isZero @n X natA X bool Xa match n with | O ⇒ true | S ⇒ false endF Definition pred @n X natA X nat Xa match n with RH OD I for S OD |O⇒O | S n' ⇒ n' endF ‡e ™—n prove theorems ˜y ™—se —n—lysisX Theorem S isZero X ∀ n X natD destruct n Y reflexivityF QedF isZero @pred @S @S n AAA a falseF ‡e ™—n —lso now get into genuine indu™tive theoremsF pirstD we will need — re™ursive fun™tionD to m—ke things interestingF Fixpoint plus @n m X natA X nat Xa match n with |O⇒m | S n' ⇒ S @plus n' m A endF ‚e™—ll th—t Fixpoint is goq9s me™h—nism for re™ursive fun™tion de(nitionsF ƒome theoE rems —˜out plus ™—n ˜e proved without indu™tionF Theorem O plus n X ∀ n X natD introY reflexivityF QedF plus O n a nF goq9s ™omput—tion rules —utom—ti™—lly simplify the —ppli™—tion of plusD ˜e™—use unfolding the de(nition of plus gives us — match expression where the ˜r—n™h to ˜e t—ken is o˜vious from synt—x —loneF sf we just reverse the order of the —rgumentsD thoughD this no longer worksD —nd we need indu™tionF Theorem n plus O X ∀ induction nF n yur (rst su˜go—l is X natD plus n plus O O a O OD a nF whi™h is trivi—l ˜y ™omput—tionF reflexivityF yur se™ond su˜go—l is more work —nd —lso demonstr—tes our (rst indu™tive hypothesisF n X nat IHn X plus n O a n aaaaaaaaaaaaaaaaaaaaaaaaaaaa plus @S n A O a S n ‡e ™—n st—rt out ˜y using ™omput—tion to simplify the go—l —s f—r —s we ™—nF simplF xow the ™on™lusion is rewrite S @plus n OA a S n F …sing our indu™tive hypothesisX IHnF RI FFFwe get — trivi—l ™on™lusion S a n S n F reflexivityF xot mu™h re—lly went on in this proofD so the prove this theorem —utom—ti™—llyF RestartF induction n Y QedF crush t—™ti™ from the Tactics module ™—n crushF ‡e ™—n ™he™k out the indu™tion prin™iple —t work hereX Check nat indF nat ind X∀ P X nat → PropD → @∀ n X natD P PO n → P @S nAA → ∀ n X natD P n i—™h of the two ™—ses of our l—st proof ™—me from the type of one of the —rguments to ‡e ™hose P to ˜e @fun n X nat ⇒ plus n O a nAF „he (rst proof ™—se ™orresponded to P O —nd the se™ond ™—se to @∀ n X natD P n → P @S nAAF „he free v—ri—˜le n —nd indu™tive hypothesis IHn ™—me from the —rgument types given hereF ƒin™e nat h—s — ™onstru™tor th—t t—kes —n —rgumentD we m—y sometimes need to know th—t th—t ™onstru™tor is inje™tiveF nat indF Theorem S inj X ∀ n m X natD injection IY trivialF QedF Sn a Sm → n a mF injection refers to — premise ˜y num˜erD —dding new equ—lities ˜etween the ™orreE sponding —rguments of equ—ted terms th—t —re formed with the s—me ™onstru™torF ‡e end up needing to prove n a m → n a mD so it is unsurprising th—t — t—™ti™ n—med trivial is —˜le to (nish the proofF „here is —lso — very useful t—™ti™ ™—lled congruence th—t ™—n prove this theorem immeE di—telyF congruence gener—lizes discriminate —nd injectionD —nd it —lso —dds re—soning —˜out the gener—l properties of equ—lityD su™h —s th—t — fun™tion returns equ—l results on equ—l —rgumentsF „h—t isD congruence is — complete decision procedure for the theory of equality and uninterpreted functionsD plus some sm—rts —˜out indu™tive typesF ‡e ™—n de(ne — type of lists of n—tur—l num˜ersF Inductive nat list X Set Xa | NNil X nat list | NCons X nat → nat list → nat listF ‚e™ursive de(nitions —re str—ightforw—rd extensions of wh—t we h—ve seen ˜eforeF Fixpoint nlength @ls X nat listA X nat Xa match ls with | NNil ⇒ O | NCons ls' ⇒ S @nlength ls' A RP endF Fixpoint napp @ls1 ls2 X nat listA X nat list Xa match ls1 with | NNil ⇒ ls2 | NCons n ls1' ⇒ NCons n @napp ls1' ls2 A endF sndu™tive theorem proving ™—n —g—in ˜e —utom—ted quite e'e™tivelyF Theorem nlength napp X ∀ ls1 ls2 X nat listD a plus @nlength ls1 A @nlength ls2 AF induction ls1 Y crushF QedF Check nlength @napp ls1 ls2 A nat list indF nat list ind X∀ P X nat list → PropD → @∀ @n X natA @n0 X nat ∀ n X nat listD P n P NNil listAD P n0 → P @NCons n n0 AA → sn gener—lD we ™—n implement —ny 4tree4 types —s indu™tive typesF por ex—mpleD here —re ˜in—ry trees of n—tur—lsF Inductive nat btree X Set Xa | NLeaf X nat btree | NNode X nat btree → nat → nat btree → nat btreeF Fixpoint nsize @tr X nat btreeA X nat Xa match tr with | NLeaf ⇒ S O | NNode tr1 tr2 ⇒ plus @nsize tr1 A @nsize endF tr2 A Fixpoint nsplice @tr1 tr2 X nat btreeA X nat btree Xa match tr1 with | NLeaf ⇒ NNode tr2 O NLeaf | NNode tr1' n tr2' ⇒ NNode @nsplice tr1' tr2 A n tr2' endF Theorem plus induction QedF assoc X∀ n1 n2 n3 n1 Y crushF X natD plus @plus n1 Theorem nsize nsplice X ∀ tr1 tr2 X nat btreeD a plus @nsize tr2 A @nsize tr1 AF Hint Rewrite n plus O plus assoc X cpdtF induction tr1 Y crushF RQ nsize n2 A n3 @nsplice a plus n1 tr1 tr2 A @plus n2 n3 AF QedF Check nat btree indF nat btree ind X∀ nat btree → PropD X P P NLeaf → nat btreeD natA @n1 X nat btreeAD P ∀ n X nat btreeD P n @∀ P X n n → ∀ @n0 X n1 → P @NNode n n0 n1 AA → 3.3 Parameterized Types ‡e ™—n —lso de(ne polymorphi™ indu™tive typesD —s with —lge˜r—i™ d—t—types in r—skell —nd wvF Inductive list @T X SetA X Set Xa | Nil X list T | Cons X T → list T → list TF Fixpoint length T @ls X list T A X nat Xa match ls with | Nil ⇒ O | Cons ls' ⇒ S @length ls' A endF Fixpoint app T @ls1 ls2 X list T A X list T Xa match ls1 with | Nil ⇒ ls2 | Cons x ls1' ⇒ Cons x @app ls1' ls2 A endF Theorem length app X ∀ T @ls1 ls2 X list a plus @length ls1 A @length ls2 AF induction ls1 Y crushF QedF T AD length @app ls1 ls2 A „here is — useful shorth—nd for writing m—ny de(nitions th—t sh—re the s—me p—r—meterD ˜—sed on goq9s section me™h—nismF „he following ˜lo™k of ™ode is equiv—lent to the —˜oveX Section listF Variable T X SetF Inductive list X Set Xa | Nil X list | Cons X T → list → listF Fixpoint length @ls X listA X nat Xa RR match ls with | Nil ⇒ O | Cons ls' ⇒ endF S @length ls' A Fixpoint app @ls1 ls2 X listA X list Xa match ls1 with | Nil ⇒ ls2 | Cons x ls1' ⇒ Cons x @app ls1' ls2 A endF Theorem length app X ∀ ls1 ls2 X listD a plus @length ls1 A @length ls2 AF induction ls1 Y crushF QedF End listF length @app ls1 ls2 A efter we end the se™tionD the Variables we used —re —dded —s extr— fun™tion p—r—meters for e—™h de(ned identi(erD —s neededF ‡e verify th—t this h—s h—ppened using the Print ™omm—ndD — ™ousin of Check whi™h shows the de(nition of — sym˜olD r—ther th—n just its typeF Print listF Inductive list @T X SetA X Set Xa Nil X list T | Cons X T → list T → list Tlist „he (n—l de(nition is the s—me —s wh—t we wrote m—nu—lly ˜eforeF „he other elements of the se™tion —re —ltered simil—rlyD turning out ex—™tly —s they were ˜eforeD though we m—n—ged to write their de(nitions more su™™in™tlyF Check lengthF length X ∀ T X SetD list T → nat „he p—r—meter T is tre—ted —s — new —rgument to the indu™tion prin™ipleD tooF Check list indF list ind X ∀ @T X SetA @P X list T → PropAD P @Nil T A → @∀ @t X T A @l X list T AD P l → P @Cons t l AA → ∀ l X list T D P l „husD even though we just s—w th—t T is —dded —s —n extr— —rgument to the ™onstru™tor ConsD there is no qu—nti(er for T in the type of the indu™tive ™—se like there is for e—™h of the other —rgumentsF RS 3.4 Mutually Inductive Types ‡e ™—n de(ne indu™tive types th—t refer to e—™h otherX Inductive even list X Set Xa | ENil X even list | ECons X nat → odd list → even list with odd list X Set Xa | OCons X nat → even list → odd listF Fixpoint elength @el X even listA X nat Xa match el with | ENil ⇒ O | ECons ol ⇒ S @olength ol A end with olength @ol X odd listA X nat Xa match ol with | OCons el ⇒ S @elength el A endF Fixpoint eapp @el1 el2 X even listA X even list Xa match el1 with | ENil ⇒ el2 | ECons n ol ⇒ ECons n @oapp ol el2 A end with oapp @ol X odd listA @el X even listA X odd list Xa match ol with | OCons n el' ⇒ OCons n @eapp el' el A endF iverything is going roughly the s—me —s in p—st ex—mplesD until we try to prove — theorem simil—r to those th—t ™—me ˜eforeF X ∀ el1 el2 X even listD elength @eapp el1 el2 A a plus @elength el1 A @elength induction el1 Y crushF Theorem elength eapp el2 AF yne go—l rem—insX nat odd list el2 X even list n o X X aaaaaaaaaaaaaaaaaaaaaaaaaaaa S @olength @oapp o el2 AA a S @plus @olength o A @elength RT el2 AA ‡e h—ve no indu™tion hypothesisD so we ™—nnot prove this go—l without st—rting —nother indu™tionD whi™h would re—™h — simil—r pointD sending us into — futile in(nite ™h—in of indu™E tionsF „he pro˜lem is th—t goq9s gener—tion of T ind prin™iples is in™ompleteF ‡e only get nonEmutu—l indu™tion prin™iples gener—ted ˜y def—ultF AbortF Check even list indF even list ind X∀ P X even list → PropD P ENil → @∀ @n X natA @o X odd ∀ e X even listD P e listAD P @ECons n o AA → ‡e see th—t no indu™tive hypotheses —re in™luded —nywhere in the typeF „o get themD we must —sk for mutu—l prin™iples —s we need themD using the Scheme ™omm—ndF Scheme even list mut Xa Induction for even list Sort Prop with odd list mut Xa Induction for odd list Sort PropF Check even list mutF even list mut X ∀ @P X even list → PropA @P0 X odd list → PropAD P ENil → @∀ @n X natA @o X odd @∀ @n X natA @e X even ∀ e X even listD P e listAD P0 o → P @ECons n o AA → listAD P e → P0 @OCons n eAA → „his is the prin™iple we w—nted in the (rst pl—™eF „here is one more wrinkle left in using itX the induction t—™ti™ will not —pply it for us —utom—ti™—llyF st will ˜e helpful to look —t how to prove one of our p—st ex—mples without using inductionD so th—t we ™—n then gener—lize the te™hnique to mutu—l indu™tive typesF Theorem n plus O' X ∀ n X natD plus n O a nF apply @nat ind @fun n ⇒ plus n O a n AAY crushF QedF prom this ex—mpleD we ™—n see th—t induction is not m—gi™F st only does some ˜ookE keeping for us to m—ke it e—sy to —pply — theoremD whi™h we ™—n do dire™tly with the apply t—™ti™F ‡e —pply not just —n identi(er ˜ut — p—rti—l —ppli™—tion of itD spe™ifying the predi™—te we me—n to prove holds for —ll n—tur—lsF „his te™hnique gener—lizes to our mutu—l ex—mpleX Theorem elength X ∀ el1 el2 X even listD el2 A a plus @elength el1 A @elength elength eapp @eapp el1 apply @even list mut @fun el1 X even list ⇒ ∀ el2 X even listD RU el2 AF elength @fun ol X olength QedF @eapp el1 el2 A @oapp ol odd list a @elength el1 A @elength el2 AA ⇒ ∀ el X even listD el A a plus @olength ol A @elength el AAAY crushF plus ‡e simply need to spe™ify two predi™—tesD one for e—™h of the mutu—lly indu™tive typesF sn gener—lD it would not ˜e — good ide— to —ssume th—t — proof —ssist—nt ™ould infer extr— predi™—tesD so this w—y of —pplying mutu—l indu™tion is —˜out —s str—ightforw—rd —s we ™ould hope forF 3.5 Reexive Types e kind of indu™tive type ™—lled — reexive type is de(ned in terms of fun™tions th—t h—ve the type ˜eing de(ned —s their r—ngeF yne very useful ™l—ss of ex—mples is in modeling v—ri—˜le ˜indersF por inst—n™eD here is — type for en™oding the synt—x of — su˜set of (rstEorder logi™X Inductive formula X Set Xa | Eq X nat → nat → formula | And X formula → formula → formula | Forall X @nat → formulaA → formulaF yur kinds of formul—s —re equ—lities ˜etween n—tur—lsD ™onjun™tionD —nd univers—l qu—nE ti(™—tion over n—tur—l num˜ersF ‡e —void needing to in™lude — notion of 4v—ri—˜les4 in our typeD ˜y using goq fun™tions to en™ode qu—nti(™—tionF por inst—n™eD here is the en™oding of ∀ x X natD x a x X Example forall re X formula Xa Forall @fun x ⇒ Eq x x AF ‡e ™—n write re™ursive fun™tions over re)exive types quite n—tur—llyF rere is one tr—nsE l—ting our formul—s into n—tive goq propositionsF Fixpoint formulaDenote @f X formulaA X Prop Xa match f with | Eq n1 n2 ⇒ n1 a n2 | And f1 f2 ⇒ formulaDenote f1 ∧ formulaDenote | Forall f ' ⇒ ∀ n X natD formulaDenote @f ' n A endF f2 ‡e ™—n —lso en™ode — trivi—l formul— tr—nsform—tion th—t sw—ps the order of equ—lity —nd ™onjun™tion oper—ndsF Fixpoint swapper @f X formulaA X formula Xa match f with | Eq n1 n2 ⇒ Eq n2 n1 | And f1 f2 ⇒ And @swapper f2 A @swapper f1 A | Forall f ' ⇒ Forall @fun n ⇒ swapper @f ' n AA endF RV st is helpful to prove th—t this tr—nsform—tion does not m—ke true formul—s f—lseF Theorem swapper preserves induction f Y crushF QedF truth X ∀ fD formulaDenote f → formulaDenote @swapper f AF ‡e ™—n t—ke — look —t the indu™tion prin™iple ˜ehind this proofF Check formula indF formula ind X ∀ P X formula → PropD @∀ n n0 X natD P @Eq n n0 AA → @∀ f0 X formulaD P f0 → ∀ f1 X formulaD P f1 → P @And f0 @∀ f1 X nat → formulaD @∀ n X natD P @f1 nAA → P @Forall f1 AA → ∀ f2 X formulaD P f2 f1 AA → po™using on the Forall ™—seD whi™h ™omes thirdD we see th—t we —re —llowed to —ssume th—t the theorem holds for any application of the argument function f1F „h—t isD goq indu™tion prin™iples do not follow — simple rule th—t the textu—l represent—tions of indu™tion v—ri—˜les must get shorter in —ppe—ls to indu™tion hypothesesF vu™kily for usD the people ˜ehind the met—theory of goq h—ve veri(ed th—t this )exi˜ility does not introdu™e unsoundnessF …p to this pointD we h—ve seen how to en™ode in goq more —nd more of wh—t is possi˜le with —lge˜r—i™ d—t—types in r—skell —nd wvF „his m—y h—ve given the in—™™ur—te impression th—t indu™tive types —re — stri™t extension of —lge˜r—i™ d—t—typesF sn f—™tD goq must rule out some types —llowed ˜y r—skell —nd wvD for re—sons of soundnessF ‚e)exive types provide our (rst good ex—mple of su™h — ™—seF qiven our l—st ex—mple of —n indu™tive typeD m—ny re—ders —re pro˜—˜ly e—ger to try en™oding the synt—x of l—m˜d— ™—l™ulusF sndeedD the fun™tionE˜—sed represent—tion te™hnique th—t we just usedD ™—lled higher-order abstract syntax (HOAS)D is the represent—tion of ™hoi™e for l—m˜d— ™—l™uli in „welf —nd in m—ny —ppli™—tions implemented in r—skell —nd wvF vet us try to import th—t ™hoi™e to goqX Inductive term X Set Xa | App X term → term → term | Abs X @term → term A → termF Error X Non strictly positive occurrence of 4term4 in 4@term → termA → term4 ‡e h—ve run —foul of the strict positivity requirement for indu™tive de(nitionsD whi™h s—ys th—t the type ˜eing de(ned m—y not o™™ur to the left of —n —rrow in the type of — ™onstru™tor —rgumentF st is import—nt th—t the type of — ™onstru™tor is viewed in terms of — series of —rguments —nd — resultD sin™e o˜viously we need re™ursive o™™urren™es to the lefts of the RW outermost —rrows if we —re to h—ve re™ursive o™™urren™es —t —llF ‡hy must goq enfor™e this restri™tionc sm—gine th—t our l—st de(nition h—d ˜een —™E ™eptedD —llowing us to write this fun™tionX Definition uhoh @t X match t with | Abs f ⇒ f t | ⇒t endF term A X term Xa …sing —n inform—l ide— of goq9s sem—nti™sD it is e—sy to verify th—t the —ppli™—tion uhoh @Abs uhohA will run foreverF „his would ˜e — mere ™uriosity in yg—ml —nd r—skellD where nonEtermin—tion is ™ommonpl—™eD though the f—™t th—t we h—ve — nonEtermin—ting progr—m without expli™it re™ursive fun™tion de(nitions is unusu—lF por goqD howeverD this would ˜e — dis—sterF „he possi˜ility of writing su™h — fun™tion would destroy —ll our ™on(den™e th—t proving — theorem me—ns —nythingF ƒin™e goq ™om˜ines progr—ms —nd proofs in one l—ngu—geD we would ˜e —˜le to prove every theorem with —n in(nite loopF xonethelessD the ˜—si™ insight of ryeƒ is — very useful oneD —nd there —re w—ys to re—lize most ˜ene(ts of ryeƒ in goqF ‡e will study — p—rti™ul—r te™hnique of this kind in the l—ter ™h—pters on progr—mming l—ngu—ge synt—x —nd sem—nti™sF 3.6 An Interlude on Proof Terms es we h—ve emph—sized — few times —lre—dyD goq proofs —re —™tu—lly progr—msD written in the s—me l—ngu—ge we h—ve ˜een using in our ex—mples —ll —longF ‡e ™—n get — (rst sense of wh—t this me—ns ˜y t—king — look —t the de(nitions of some of the indu™tion prin™iples we h—ve usedF Print unit indF unit ind a fun P X unit → Prop ⇒ unit rect P X ∀ P X unit → PropD P tt → ∀ u X unitD Pu ‡e see th—t this indu™tion prin™iple is de(ned in terms of — more gener—l prin™ipleD unit rectF Check unit rectF unit rect X∀ P X unit → TypeD P tt →∀ u X unitD P u type unit → Type inste—d of unit → PropF Type is —nother universeD like Set —nd PropF sn f—™tD it is — ™ommon supertype of ˜othF v—ter onD we will dis™uss unit rect gives P SH ex—™tly wh—t the signi(™—n™es of the di'erent universes —reF por nowD it is just import—nt th—t we ™—n use Type —s — sort of met—Euniverse th—t m—y turn out to ˜e either Set or PropF ‡e ™—n see the symmetry inherent in the su˜typing rel—tionship ˜y printing the de(nition of —nother prin™iple th—t w—s gener—ted for unit —utom—ti™—llyX Print unit recF a fun P X unit → Set ⇒ unit rect P X ∀ P X unit → SetD P tt → ∀ u X unitD unit rec Pu „his is identi™—l to the de(nition for unit indD ex™ept th—t we h—ve su˜stituted Set for PropF por most indu™tive types T D thenD we get not just indu™tion prin™iples T indD ˜ut —lso re™ursion prin™iples T recF ‡e ™—n use T rec to write re™ursive de(nitions without expli™it Fixpoint re™ursionF por inst—n™eD the following two de(nitions —re equiv—lentX Definition always match u with | tt ⇒ O endF O @u X unitA X nat Xa Definition always O' @u X unitA X nat Xa X unit ⇒ natA O uF unit rec @fun qoing even further down the r—˜˜it holeD unit fun™tion—l progr—m th—t we ™—n write m—nu—llyF Print rect itself is not even — primitiveF st is — unit rectF a fun @P X unit → TypeA @f X P ttA @u X unitA ⇒ match u as u0 return @P u0 A with | tt ⇒ f end X ∀ P X unit → TypeD P tt → ∀ u X unitD P unit rect u „he only new fe—ture we see is —n as ™l—use for — matchD whi™h is used in ™on™ert with the return ™l—use th—t we s—w in the introdu™tionF ƒin™e the type of the match is dependent on the v—lue of the o˜je™t ˜eing —n—lyzedD we must give th—t o˜je™t — n—me so th—t we ™—n refer to it in the return ™l—useF „o prove th—t unit rect is nothing spe™i—lD we ™—n reimplement it m—nu—llyF Definition unit match u with | tt ⇒ f endF rect' @P X unit → TypeA @f X P ttA @u X unitA Xa ‡e rely on goq9s heuristi™s for inferring match —nnot—tionsF ‡e ™—n ™he™k the implement—tion of nat rect —s wellX SI Print nat rectF nat rect a fun @P X nat → TypeA @f X P OA @f0 X ∀ n X natD P n → P @S nAA ⇒ @n X natA X P n Xa match n as n0 return @P n0 A with |O⇒f | S n0 ⇒ f0 n0 @F n0 A end X ∀ P X nat → TypeD P O → @∀ n X natD P n → P @S n AA → ∀ n X natD P n xow we h—ve —n —™tu—l re™ursive de(nitionF x expressions —re —n —nonymous form of FixpointD just —s fun expressions st—nd for —nonymous nonEre™ursive fun™tionsF feyond th—tD the synt—x of x mirrors th—t of FixpointF ‡e ™—n underst—nd the de(nition of nat rect ˜etter ˜y reimplementing nat ind using se™tionsF x F Section nat ind'F pirstD we h—ve the property of n—tur—l num˜ers th—t we —im to proveF Variable P X nat → PropF „hen we require — proof of the Hypothesis O case X xext is — proof of the Hypothesis S case O ™—seF P OF S X∀ ™—seD whi™h m—y —ssume —n indu™tive hypothesisF n X natD P n → P @S n AF pin—llyD we de(ne — re™ursive fun™tion to tie the pie™es togetherF Fixpoint nat ind' @n X natA X P n Xa match n with | O ⇒ O case | S n' ⇒ S case @nat ind' n' A endF End nat ind'F glosing the se™tion —dds the Variables —nd Hypothesises —s new funE˜ound —rguments to nat ind'D —ndD modulo the use of Prop inste—d of TypeD we end up with the ex—™t s—me de(nition th—t w—s gener—ted —utom—ti™—lly for nat rectF ‡e ™—n —lso ex—mine the de(nition of even — mutu—llyEre™ursive typeF Print list mutD whi™h we gener—ted with Scheme for even list mutF a fun @P X even list → PropA @P0 X odd list → PropA @f X P ENilA @f0 X ∀ @n X natA @o X odd listAD P0 o → P @ECons @f1 X ∀ @n X natA @e X even listAD P e → P0 @OCons n eAA ⇒ x F @e X even listA X P e Xa even list mut SP n o AA match e as e0 return @P e0 A with | ENil ⇒ f | ECons n o ⇒ f0 n o @F0 o A end with F0 @o X odd listA X P0 o Xa match o as o0 return @P0 o0 A with | OCons n e ⇒ f1 n e @F eA end for F X ∀ @P X even list → PropA @P0 X odd list → PropAD P ENil → @∀ @n X natA @o X odd listAD P0 o → P @ECons n o AA → @∀ @n X natA @e X even listAD P e → P0 @OCons n eAA → ∀ e X even listD P e ‡e see — mutu—llyEre™ursive xD with the di'erent fun™tions sep—r—ted ˜y with in the s—me w—y th—t they would ˜e sep—r—ted ˜y and in wvF e (n—l for ™l—use identi(es whi™h of the mutu—llyEre™ursive fun™tions should ˜e the (n—l v—lue of the x expressionF …sing this de(nition —s — templ—teD we ™—n reimplement even list mut dire™tlyF Section even list mut'F pirstD we need the properties th—t we —re provingF Variable Variable even list → PropF X odd list → PropF Peven Podd X xextD we need proofs of the three ™—sesF Hypothesis Hypothesis Hypothesis ENil case X ECons case OCons case Peven ENilF X ∀ @n X X ∀ @n X natA @o X odd listAD Podd o → Peven @ECons n o AF natA @e X even listAD Peven e → Podd @OCons n e AF pin—llyD we de(ne the re™ursive fun™tionsF Fixpoint even list mut' @e X even listA X Peven e Xa match e with | ENil ⇒ ENil case | ECons n o ⇒ ECons case n @odd list mut' o A end with odd list mut' @o X odd listA X Podd o Xa match o with | OCons n e ⇒ OCons case n @even list mut' e A endF End even list mut'F iven indu™tion prin™iples for re)exive types —re e—sy to implement dire™tlyF por our formula typeD we ™—n use — re™ursive de(nition mu™h like those we wrote —˜oveF Section formula ind'F SQ Variable P X formula → PropF Hypothesis Eq case X ∀ n1 n2 X natD P @Eq n1 Hypothesis And case X ∀ f1 f2 X formulaD P f1 → P f2 → P @And f1 f2 AF Hypothesis Forall case X ∀ f X nat → formulaD @∀ n X natD P @f n AA → P @Forall f AF n2 AF Fixpoint formula ind' @f X formulaA X P f Xa match f with | Eq n1 n2 ⇒ Eq case n1 n2 | And f1 f2 ⇒ And case @formula ind' f1 A @formula ind' f2 A | Forall f ' ⇒ Forall case f ' @fun n ⇒ formula ind' @f ' n AA endF End formula ind'F 3.7 Nested Inductive Types ƒuppose we w—nt to extend our e—rlier type of ˜in—ry trees to trees with —r˜itr—ry (nite ˜r—n™hingF ‡e ™—n use lists to give — simple de(nitionF Inductive nat tree X Set Xa | NLeaf ' X nat tree | NNode' X nat → list nat tree → nat treeF „his is —n ex—mple of — nested indu™tive type de(nitionD ˜e™—use we use the type we —re de(ning —s —n —rgument to — p—r—metrized type f—milyF goq will not —llow —ll su™h de(nitionsY it e'e™tively pretends th—t we —re de(ning nat tree mutu—lly with — version of list spe™i—lized to nat treeD ™he™king th—t the resulting exp—nded de(nition s—tis(es the usu—l rulesF por inst—n™eD if we repl—™ed list with — type f—mily th—t used its p—r—meter —s — fun™tion —rgumentD then the de(nition would ˜e reje™ted —s viol—ting the positivity restri™tionF vike we en™ountered for mutu—l indu™tive typesD we (nd th—t the —utom—ti™—llyEgener—ted indu™tion prin™iple for nat tree is too we—kF Check nat tree indF nat tree ind X∀ P X nat tree → PropD P NLeaf ' → @∀ @n X natA @l X list ∀ n X nat treeD P n nat treeAD P @NNode' n l AA → „here is no ™omm—nd like Scheme th—t will implement —n improved prin™iple for usF sn gener—lD it t—kes ™re—tivity to (gure out how to in™orpor—te nested uses to di'erent type f—miliesF xow th—t we know how to implement indu™tion prin™iples m—nu—llyD we —re in — SR position to —pply just su™h ™re—tivity to this pro˜lemF pirstD we will need —n —uxili—ry de(nitionD ™h—r—™terizing wh—t it me—ns for — property to hold of every element of — listF Section AllF Variable T X SetF Variable P X T → PropF Fixpoint All @ls X list T A X Prop Xa match ls with | Nil ⇒ True | Cons h t ⇒ P h ∧ All t endF End AllF st will ˜e useful to look —t the de(nitions of m—nu—l proofs of them ˜elowF True —nd ∧D sin™e we will w—nt to write Print TrueF Inductive True X Prop Xa I X True „h—t isD True is — proposition with ex—™tly one proofD ID whi™h we m—y —lw—ys supply trivi—llyF pinding the de(nition of ∧ t—kes — little more workF goq supports user registr—tion of —r˜itr—ry p—rsing rulesD —nd it is su™h — rule th—t is letting us write ∧ inste—d of —n —ppli™—tion of some indu™tive type f—milyF ‡e ™—n (nd the underlying indu™tive type with the Locate ™omm—ndF Locate 4∧4F Notation Scope 4e ∧ f4 Xa and AB X type scope @default interpretation A Print andF Inductive and @A X PropA @B X PropA X Prop Xa conj X For conjX Arguments AD B are implicit For and X Argument scopes are ‘type scope type scope “ For conjX Argument scopes are ‘type scope type scope A → B → A ∧ B “ sn —ddition to the de(nition of and itselfD we get inform—tion on impli™it —rguments —nd p—rsing rules for and —nd its ™onstru™tor conjF ‡e will ignore the p—rsing inform—tion for nowF „he impli™it —rgument inform—tion tells us th—t we ˜uild — proof of — ™onjun™tion ˜y ™—lling the ™onstru™tor conj on proofs of the ™onjun™tsD with no need to in™lude the types of those proofs —s expli™it —rgumentsF xow we ™re—te — se™tion for our indu™tion prin™ipleD following the s—me ˜—si™ pl—n —s in the l—st se™tion of this ™h—pterF SS Section nat tree ind'F Variable P X nat tree → PropF Hypothesis NLeaf ' case X P NLeaf 'F Hypothesis NNode' case X ∀ @n X natA @ls X list nat treeAD All P ls → P @NNode' n ls AF e (rst —ttempt —t writing the indu™tion prin™iple itself follows the intuition th—t nested indu™tive type de(nitions —re exp—nded into mutu—l indu™tive de(nitionsF Fixpoint nat tree ind' @tr X nat treeA X P tr Xa match tr with | NLeaf ' ⇒ NLeaf ' case | NNode' n ls ⇒ NNode' case n ls @list nat tree end ind ls A with list nat tree ind @ls X list nat treeA X All P ls Xa match ls with | Nil ⇒ I | Cons tr rest ⇒ conj @nat tree ind' tr A @list nat tree endF ind rest A goq reje™ts this de(nitionD s—ying 4‚e™ursive ™—ll to n—t tree ind9 h—s prin™ip—l —rgument equ—l to 4tr4 inste—d of restF4 „he term 4nested indu™tive type4 hints —t the solution to the pro˜lemF tust like true mutu—llyEindu™tive types require mutu—llyEre™ursive indu™tion prin™iplesD nested types require nested re™ursionF Fixpoint nat tree ind' @tr X nat treeA X P tr Xa match tr with | NLeaf ' ⇒ NLeaf ' case | NNode' n ls ⇒ NNode' case n ls @@x list nat tree ind @ls X list nat treeA X All P ls Xa match ls with | Nil ⇒ I | Cons tr rest ⇒ conj @nat tree ind' tr A @list nat tree endA ls A endF ind rest A ‡e in™lude —n —nonymous x version of list nat tree ind th—t is liter—lly nested inside the de(nition of the re™ursive fun™tion ™orresponding to the indu™tive de(nition th—t h—d the nested use of listF End nat tree ind'F ‡e ™—n try our indu™tion prin™iple out ˜y de(ning some re™ursive fun™tions on nat trees —nd proving — theorem —˜out themF pirstD we de(ne some helper fun™tions th—t oper—te on listsF ST Section mapF Variables T Variable f X T' T X SetF → T'F Fixpoint map @ls X list T A X list T' Xa match ls with | Nil ⇒ Nil | Cons h t ⇒ Cons @f h A @map t A endF End mapF Fixpoint sum @ls X list natA X nat Xa match ls with | Nil ⇒ O | Cons h t ⇒ plus h @sum t A endF xow we ™—n de(ne — size fun™tion over our treesF Fixpoint ntsize @tr X nat treeA X nat Xa match tr with | NLeaf ' ⇒ S O | NNode' trs ⇒ S @sum @map ntsize endF trs AA xoti™e th—t goq w—s sm—rt enough to exp—nd the de(nition of map to verify th—t we —re using proper nested re™ursionD even through — use of — higherEorder fun™tionF Fixpoint ntsplice @tr1 tr2 X nat treeA X nat tree Xa match tr1 with | NLeaf ' ⇒ NNode' O @Cons tr2 NilA | NNode' n Nil ⇒ NNode' n @Cons tr2 NilA | NNode' n @Cons tr trs A ⇒ NNode' n @Cons @ntsplice endF tr tr2 A trs A ‡e h—ve de(ned —nother —r˜itr—ry notion of tree spli™ingD simil—r to ˜eforeD —nd we ™—n prove —n —n—logous theorem —˜out its rel—tionship with tree sizeF ‡e st—rt with — useful lemm— —˜out —dditionF X natD @plus n1 induction n1 Y crushF QedF Lemma plus S plus n1 @S X∀ n2 A n1 n2 a S n2 AF xow we ˜egin the proof of the theoremD —dding the lemm— Theorem ntsize ntsplice X ∀ tr1 tr2 X nat treeD a plus @ntsize tr2 A @ntsize tr1 AF Hint Rewrite plus S X cpdtF SU ntsize @ntsplice plus S —s — hintF tr1 tr2 A ‡e know th—t the st—nd—rd indu™tion prin™iple is insu0™ient for the t—skD so we need to provide — using ™l—use for the induction t—™ti™ to spe™ify our —ltern—te prin™ipleF induction tr1 using nat tree ind'Y crushF yne su˜go—l rem—insX X nat ls X list nat tree H X All @fun tr1 X nat tree ⇒ ∀ tr2 X nat treeD ntsize @ntsplice tr1 tr2 A a plus @ntsize tr2 A @ntsize tr2 X nat tree aaaaaaaaaaaaaaaaaaaaaaaaaaaa n tr1 AA ls ntsize match ls with | Nil ⇒ NNode' n @Cons tr2 NilA | Cons tr trs ⇒ NNode' n @Cons @ntsplice tr end a S @plus @ntsize tr2 A @sum @map ntsize tr2 A trs A ls AAA efter — few moments of squinting —t this go—lD it ˜e™omes —pp—rent th—t we need to do — ™—se —n—lysis on the stru™ture of lsF „he rest is routineF destruct ls Y crushF ‡e ™—n go further in —utom—ting the proof ˜y exploiting the hint me™h—nismF RestartF Hint Extern I @ntsize @match cvƒ with Nil ⇒ destruct LS Y crushF induction tr1 using nat tree ind'Y crushF QedF | Cons ⇒ endA a A ⇒ ‡e will go into gre—t det—il on hints in — l—ter ™h—pterD ˜ut the only import—nt thing to note here is th—t we register — p—ttern th—t des™ri˜es — ™on™lusion we expe™t to en™ounter during the proofF „he p—ttern m—y ™ont—in uni(™—tion v—ri—˜lesD whose n—mes —re pre(xed with question m—rksD —nd we m—y refer to those ˜ound v—ri—˜les in — t—™ti™ th—t we —sk to h—ve run whenever the p—ttern m—t™hesF „he —dv—nt—ge of using the hint is not very ™le—r hereD ˜e™—use the origin—l proof w—s so shortF roweverD the hint h—s fund—ment—lly improved the re—d—˜ility of our proofF feforeD the proof referred to the lo™—l v—ri—˜le lsD whi™h h—s —n —utom—ti™—llyEgener—ted n—meF „o — hum—n re—ding the proof s™ript without stepping through it inter—™tivelyD it w—s not ™le—r where ls ™—me fromF „he hint expl—ins to the re—der the pro™ess for ™hoosing whi™h v—ri—˜les to ™—se —n—lyze onD —nd the hint ™—n ™ontinue working even if the rest of the proof stru™ture ™h—nges signi(™—ntlyF SV 3.8 Manual Proofs About Constructors st ™—n ˜e useful to underst—nd how t—™ti™s like discriminate —nd injection workD so it is worth stepping through — m—nu—l proof of e—™h kindF ‡e will st—rt with — proof (t for discriminateF Theorem true neq false X true = falseF ‡e ˜egin with the t—™ti™ redD whi™h is short for 4one step of redu™tionD4 to unfold the de(nition of logi™—l neg—tionF redF aaaaaaaaaaaaaaaaaaaaaaaaaaaa true a false → False „he neg—tion is repl—™ed with —n impli™—tion of f—lsehoodF ‡e use the t—™ti™ intro ™h—nge the —ssumption of the impli™—tion into — hypothesis n—med HF intro H to HF X true a false aaaaaaaaaaaaaaaaaaaaaaaaaaaa H False „his is the point in the proof where we —pply some ™re—tivityF ‡e de(ne — fun™tion whose utility will ˜e™ome ™le—r soonF Definition f @b X boolA Xa if b then True else FalseF st is worth re™—lling the di'eren™e ˜etween the lower™—se —nd upper™—se versions of truth —nd f—lsehoodX True —nd False —re logi™—l propositionsD while true —nd false —re ˜oole—n v—lues th—t we ™—n ™—seE—n—lyzeF ‡e h—ve de(ned f su™h th—t our ™on™lusion of False is ™omE put—tion—lly equiv—lent to f falseF „husD the change t—™ti™ will let us ™h—nge the ™on™lusion to f falseF change @f falseAF X true a false aaaaaaaaaaaaaaaaaaaaaaaaaaaa H f false xow the righth—nd side of H 9s equ—lity —ppe—rs in the ™on™lusionD so we ™—n rewriteD using the not—tion ← to request to repl—™e the righth—nd side the equ—lity with the lefth—nd sideF rewrite ← HF SW X true a false aaaaaaaaaaaaaaaaaaaaaaaaaaaa H f true ‡e —re —lmost doneF tust how ™lose we —re to done is reve—led ˜y ™omput—tion—l simpliE (™—tionF simplF X true a false aaaaaaaaaaaaaaaaaaaaaaaaaaaa H True trivialF QedF s h—ve no trivi—l —utom—ted version of this proof to suggestD ˜eyond using discriminate or congruence in the (rst pl—™eF ‡e ™—n perform — simil—r m—nu—l proof of inje™tivity of the ™onstru™tor S F s le—ve — w—lkE through of the det—ils to ™urious re—ders who w—nt to run the proof s™ript inter—™tivelyF Theorem S inj' X ∀ n m X natD S n a intros n m HF change @pred @S n A a pred @S m AAF rewrite HF reflexivityF QedF Sm → n a mF 3.9 Exercises IF he(ne —n indu™tive type truth with three ™onstru™torsD YesD NoD —nd MaybeF Yes st—nds for ™ert—in truthD No for ™ert—in f—lsehoodD —nd Maybe for —n unknown situ—tionF he(ne 4notD4 4—ndD4 —nd 4or4 for this repl—™ement ˜oole—n —lge˜r—F €rove th—t your implement—tion of 4—nd4 is ™ommut—tive —nd distri˜utes over your implement—tion of 4orF4 PF wodify the (rst ex—mple l—ngu—ge of gh—pter P to in™lude v—ri—˜lesD where v—ri—˜les —re represented with natF ixtend the synt—x —nd sem—nti™s of expressions to —™™ommod—te the ™h—ngeF ‰our new expDenote fun™tion should t—ke —s — new extr— (rst —rgument — v—lue of type var → natD where var is — synonym for n—tur—lsE—sEv—ri—˜lesD —nd the fun™tion —ssigns — v—lue to e—™h v—ri—˜leF he(ne — ™onst—nt folding fun™tion whi™h does — ˜ottomEup p—ss over —n expressionD —t e—™h st—ge repl—™ing every ˜in—ry oper—tion on ™onst—nts with —n equiv—lent ™onst—ntF €rove th—t ™onst—nt folding preserves the me—nings of expressionsF TH QF ‚eimplement the se™ond ex—mple l—ngu—ge of gh—pter P to use mutu—llyEindu™tive types inste—d of dependent typesF „h—t isD de(ne two sep—r—te @nonEdependentA indu™E tive types nat exp —nd bool exp for expressions of the two di'erent typesD r—ther th—n — single indexed typeF „o keep things simpleD you m—y ™onsider only the ˜in—ry oper—tors th—t t—ke n—tur—ls —s oper—ndsF edd n—tur—l num˜er v—ri—˜les to the l—ngu—geD —s in the l—st exer™iseD —nd —dd —n 4if4 expression form t—king —s —rguments one ˜oole—n exE pression —nd two n—tur—l num˜er expressionsF he(ne sem—nti™s —nd ™onst—ntEfolding fun™tions for this new l—ngu—geF ‰our ™onst—nt folding should simplify not just ˜iE n—ry oper—tions @returning n—tur—ls or ˜oole—nsA with known —rgumentsD ˜ut —lso 4if4 expressions with known v—lues for their test expressions ˜ut possi˜ly undetermined 4then4 —nd 4else4 ™—sesF €rove th—t ™onst—ntEfolding — n—tur—l num˜er expression preserves its me—ningF RF …sing — re)exive indu™tive de(nitionD de(ne — type nat tree of in(nit—ry treesD with n—tur—l num˜ers —t their le—ves —nd — ™ount—˜le in(nity of new trees ˜r—n™hing out of e—™h intern—l nodeF he(ne — fun™tion increment th—t in™rements the num˜er in every le—f of — nat treeF he(ne — fun™tion leapfrog over — n—tur—l i —nd — tree ntF leapfrog should re™urse into the ith ™hild of ntD the iCIst ™hild of th—t nodeD the iCPnd ™hild of the next nodeD —nd so onD until re—™hing — le—fD in whi™h ™—se leapfrog should return the num˜er —t th—t le—fF €rove th—t the result of —ny ™—ll to leapfrog is in™remented ˜y one ˜y ™—lling increment on the treeF SF he(ne — type of trees of trees of trees of @repe—t to in(nityAF „h—t isD de(ne —n indu™tive type trexpD whose mem˜ers —re either ˜—se ™—ses ™ont—ining n—tur—l num˜ers or ˜in—ry trees of trexp sF f—se your de(nition on — p—r—meterized ˜in—ry tree type btree th—t you will —lso de(neD so th—t trexp is de(ned —s — nested indu™tive typeF he(ne — fun™tion total th—t sums —ll of the n—tur—ls —t the le—ves of — trexpF he(ne — fun™tion increment th—t in™rements every le—f of — trexp ˜y oneF €rove th—tD for —ll trD total @increment tr A ≥ total trF yn the w—y to (nishing this proofD you will pro˜—˜ly w—nt to prove — lemm— —nd —dd it —s — hint using the synt—x Hint Resolve name of lemmaFF TF €rove dis™rimin—tion —nd inje™tivity theorems for the nat btree type de(ned e—rlier in this ™h—pterF sn p—rti™ul—rD without using the t—™ti™s discriminateD injectionD or congruenceD prove th—t no le—f equ—ls —ny nodeD —nd prove th—t two equ—l nodes ™—rry the s—me n—tur—l num˜erF TI Chapter 4 Inductive Predicates „he soE™—lled 4gurryErow—rd gorresponden™e4 st—tes — form—l ™onne™tion ˜etween fun™E tion—l progr—ms —nd m—them—ti™—l proofsF sn the l—st ™h—pterD we snu™k in — (rst introdu™E tion to this su˜je™t in goqF ‡itness the ™lose simil—rity ˜etween the types unit —nd True from the st—nd—rd li˜r—ryX Print unitF Inductive unit X Set Xa tt X unit Print TrueF Inductive True X Prop Xa I X True ‚e™—ll th—t unit is the type with only one v—lueD —nd True is the proposition th—t —lw—ys holdsF hespite this super(™i—l di'eren™e ˜etween the two ™on™eptsD in ˜oth ™—ses we ™—n use the s—me indu™tive de(nition me™h—nismF „he ™onne™tion goes further th—n thisF ‡e see th—t we —rrive —t the de(nition of True ˜y repl—™ing unit ˜y TrueD tt ˜y ID —nd Set ˜y PropF „he (rst two of these di'eren™es —re super(™i—l ™h—nges of n—mesD while the third di'eren™e is the ™ru™i—l one for sep—r—ting progr—ms from proofsF e term T of type Set is — type of progr—msD —nd — term of type T is — progr—mF e term T of type Prop is — logi™—l propositionD —nd its proofs —re of type T F unit h—s one v—lueD ttF True h—s one proofD IF ‡hy distinguish ˜etween these two typesc w—ny people who h—ve re—d —˜out gurryErow—rd in —n —˜str—™t ™ontext —nd not put it to use in proof engineering —nswer th—t the two types in f—™t should not ˜e distinguishedF „here is — ™ert—in —estheti™ —ppe—l to this point of viewD ˜ut s w—nt to —rgue th—t it is ˜est to tre—t gurryErow—rd very loosely in pr—™ti™—l provingF „here —re goqEspe™i(™ re—sons for preferring the distin™tionD involving e0™ient ™ompil—tion —nd —void—n™e of p—r—doxes in the presen™e of ™l—ssi™—l m—thD ˜ut s will —rgue th—t there is — more gener—l prin™iple th—t should le—d us to —void ™on)—ting progr—mming —nd provingF „he essen™e of the —rgument is roughly thisX to —n engineerD not —ll fun™tions of type A → B —re ™re—ted equ—lD ˜ut —ll proofs of — proposition P → Q —reF „his ide— is known —s proof irrelevanceD —nd its form—liz—tions in logi™s prevent us from distinguishing ˜etween —ltern—te proofs of the s—me propositionF €roof irrelev—n™e is ™omp—ti˜le withD ˜ut not deriv—˜le inD TP q—llin—F ep—rt from this theoreti™—l ™on™ernD s will —rgue th—t it is most e'e™tive to do engineering with goq ˜y employing di'erent te™hniques for progr—ms versus proofsF wost of this ˜ook is org—nized —round th—t distin™tionD des™ri˜ing how to progr—mD ˜y —pplying st—nd—rd fun™tion—l progr—mming te™hniques in the presen™e of dependent typesY —nd how to proveD ˜y writing ™ustom vt—™ de™ision pro™eduresF ‡ith th—t perspe™tive in mindD this ™h—pter is sort of — mirror im—ge of the l—st ™h—pterD introdu™ing how to de(ne predi™—tes with indu™tive de(nitionsF ‡e will point out simil—rities in pl—™esD ˜ut mu™h of the e'e™tive goq user9s ˜—g of tri™ks is disjoint for predi™—tes versus 4d—t—typesF4 „his ™h—pter is —lso — ™overt introdu™tion to dependent typesD whi™h —re the found—tion on whi™h interesting indu™tive predi™—tes —re ˜uiltD though we will rely on t—™ti™s to ˜uild dependentlyEtyped proof terms for us for nowF e future ™h—pter introdu™es more m—nu—l —ppli™—tion of dependent typesF 4.1 Propositional Logic vet us ˜egin with — ˜rief tour through the de(nitions of the ™onne™tives for proposition—l logi™F ‡e will work within — goq se™tion th—t provides us with — set of proposition—l v—ri—˜lesF sn goq p—rl—n™eD these —re just terms of type PropF Section PropositionalF Variables P Q R X PropF sn goqD the most ˜—si™ proposition—l ™onne™tive is impli™—tionD written →D whi™h we h—ve —lre—dy used in —lmost every proofF ‚—ther th—n ˜eing de(ned indu™tivelyD impli™—tion is ˜uilt into goq —s the fun™tion type ™onstru™torF ‡e h—ve —lso —lre—dy seen the de(nition of TrueF por — demonstr—tion of — lowerElevel w—y of est—˜lishing proofs of indu™tive predi™—tesD we turn to this trivi—l theoremF Theorem obvious X TrueF apply IF QedF ‡e m—y —lw—ys use the apply t—™ti™ to t—ke — proof step ˜—sed on —pplying — p—rti™ul—r ™onstru™tor of the indu™tive predi™—te th—t we —re trying to est—˜lishF ƒometimes there is only one ™onstru™tor th—t ™ould possi˜ly —pplyD in whi™h ™—se — short™ut is —v—il—˜leX Theorem obvious' constructorF X TrueF QedF „here is —lso — predi™—te from the l—st ™h—pterF FalseD whi™h is the gurryErow—rd mirror im—ge of Empty set Print FalseF Inductive False X Prop Xa TQ ‡e ™—n ™on™lude —nything from FalseD doing ™—se —n—lysis on — proof of False in the s—me w—y we might do ™—se —n—lysis onD s—yD — n—tur—l num˜erF ƒin™e there —re no ™—ses to ™onsiderD —ny su™h ™—se —n—lysis su™™eeds immedi—tely in proving the go—lF Theorem False imp X False → P C P a SF destruct IF QedF sn — ™onsistent ™ontextD we ™—n never ˜uild — proof of FalseF sn in™onsistent ™ontexts th—t —ppe—r in the ™ourses of proofsD it is usu—lly e—siest to pro™eed ˜y demonstr—ting th—t in™onsisten™y with —n expli™it proof of FalseF Theorem arith introF neq X P C P a S → W C W a VQSF et this pointD we h—ve —n in™onsistent hypothesis P C P a SD so the spe™i(™ ™on™lusion is not import—ntF ‡e use the elimtype t—™ti™ to st—te — propositionD telling goq th—t we wish to ™onstru™t — proof of the new proposition —nd then prove the origin—l go—l ˜y ™—se —n—lysis on the stru™ture of the new —uxili—ry proofF ƒin™e False h—s no ™onstru™torsD elimtype False simply le—ves us with the o˜lig—tion to prove FalseF elimtype FalseF XPCPaS aaaaaaaaaaaaaaaaaaaaaaaaaaaa H False por nowD we will le—ve the det—ils of this proof —˜out —rithmeti™ to crushF crushF QedF e rel—ted notion to Print False is logi™—l neg—tionF notF a fun A X Prop ⇒ X Prop → Prop not A → False ‡e see th—t not is just shorth—nd for impli™—tion of FalseF ‡e ™—n use th—t f—™t expli™itly in proofsF „he synt—x £€ exp—nds to not P F Theorem arith neq' X ¬ @P C P a SAF unfold notF aaaaaaaaaaaaaaaaaaaaaaaaaaaa P C P a S → False crushF QedF TR ‡e —lso h—ve ™onjun™tionD whi™h we introdu™ed in the l—st ™h—pterF Print andF Inductive and @A X PropA @B X PropA X Prop Xa conj X A → B → A ∧ B „he interested re—der ™—n ™he™k th—t and h—s — gurryErow—rd doppelg—nger ™—lled prodD the type of p—irsF roweverD it is gener—lly most ™onvenient to re—son —˜out ™onjun™tion using t—™ti™sF en expli™it proof of ™ommut—tivity of and illustr—tes the usu—l suspe™ts for su™h t—sksF ∧ is —n in(x shorth—nd for andF Theorem and comm X P ∧ Q → Q ∧ PF ‡e st—rt ˜y ™—se —n—lysis on the proof of P ∧ QF destruct IF H X P XQ aaaaaaaaaaaaaaaaaaaaaaaaaaaa Q∧P H0 ivery proof of — ™onjun™tion provides proofs for ˜oth ™onjun™tsD so we get — single su˜go—l re)e™ting th—tF ‡e ™—n pro™eed ˜y splitting this su˜go—l into — ™—se for e—™h ™onjun™t of Q ∧ PF splitF P subgoals H X P XQ aaaaaaaaaaaaaaaaaaaaaaaaaaaa H0 Q subgoal P is X P sn e—™h ™—seD the ™on™lusion is —mong our hypothesesD so the assumption t—™ti™ (nishes the pro™essF assumptionF assumptionF QedF goq disjun™tion is ™—lled Print orF Inductive or or —nd —˜˜revi—ted with the in(x oper—tor ∨F @A X PropA @B X PropA X Prop Xa TS or introl X A → ∨ A B | or intror X B → A ∨ B ‡e see th—t there —re two w—ys to prove — disjun™tionX prove the (rst disjun™t or prove the se™ondF „he gurryErow—rd —n—logue of this is the goq sum typeF ‡e ™—n demonstr—te the m—in t—™ti™s here with —nother proof of ™ommut—tivityF Theorem or comm X P es in the proof for ™—ses inste—d of oneF ∨ andD Q → Q ∨ PF we ˜egin with ™—se —n—lysisD though this time we —re met ˜y two destruct IF P subgoals XP aaaaaaaaaaaaaaaaaaaaaaaaaaaa Q∨P H subgoal P Q∨P is X ‡e ™—n see th—tD in the (rst su˜go—lD we w—nt to prove the disjun™tion ˜y proving its se™ond disjun™tF „he right t—™ti™ telegr—phs this intentF right Y assumptionF „he se™ond su˜go—l h—s — symmetri™ proofF I subgoal XQ aaaaaaaaaaaaaaaaaaaaaaaaaaaa Q∨P H left Y QedF assumptionF st would ˜e — sh—me to h—ve to plod m—nu—lly through —ll proofs —˜out proposition—l logi™F vu™kilyD there is no needF yne of the most ˜—si™ goq —utom—tion t—™ti™s is tautoD whi™h is — ™omplete de™ision pro™edure for ™onstru™tive proposition—l logi™F @wore on wh—t 4™onstru™tive4 me—ns in the next se™tionFA ‡e ™—n use tauto to disp—t™h —ll of the purely proposition—l theorems we h—ve proved so f—rF Theorem or tautoF QedF comm' X P ∨ Q → Q ∨ PF ƒometimes proposition—l re—soning forms import—nt plum˜ing for the proof of — theoremD TT ˜ut we still need to —pply some other sm—rts —˜outD s—yD —rithmeti™F intuition is — generE —liz—tion of tauto th—t proves everything it ™—n using proposition—l re—soningF ‡hen some go—ls rem—inD it uses proposition—l l—ws to simplify them —s f—r —s possi˜leF gonsider this ex—mpleD whi™h uses the list ™on™—ten—tion oper—tor CC from the st—nd—rd li˜r—ryF Theorem arith comm X∀ ls1 ls2 list natD X a length ls2 ∨ length ls1 C length ls2 a T → length @ls1 CC ls2 A a T ∨ length ls1 a length ls2F intuitionF length ls1 e lot of the proof stru™ture h—s ˜een gener—ted for us ˜y intuitionD ˜ut the (n—l proof depends on — f—™t —˜out listsF „he rem—ining su˜go—l hints —t wh—t ™leverness we need to inje™tF X list nat ls2 X list nat H0 X length ls1 C length ls2 a T aaaaaaaaaaaaaaaaaaaaaaaaaaaa length @ls1 CC ls2 A a T ∨ length ls1 a length ls2 ls1 ‡e ™—n see th—t we need — theorem —˜out lengths of ™on™—ten—ted listsD whi™h we proved l—st ™h—pter —nd is —lso in the st—nd—rd li˜r—ryF rewrite app lengthF X list nat X list nat H0 X length ls1 C length ls2 a T aaaaaaaaaaaaaaaaaaaaaaaaaaaa length ls1 C length ls2 a T ∨ length ls1 a length ls1 ls2 ls2 xow the su˜go—l follows ˜y purely proposition—l re—soningF „h—t isD we ™ould repl—™e length ls1 C length ls2 a T with P —nd length ls1 a length ls2 with Q —nd —rrive —t — t—utology of proposition—l logi™F tautoF QedF intuition is one of the m—in ˜its of glue in the implement—tion of crushD soD with — little helpD we ™—n get — short —utom—ted proof of the theoremF Theorem arith comm' X∀ ls1 ls2 X list natD a length ls2 ∨ length ls1 C length ls2 a T → length @ls1 CC ls2 A a T ∨ length ls1 a length ls2F Hint Rewrite app length X cpdtF length ls1 crushF TU QedF End PropositionalF 4.2 What Does It Mean to Be Constructive? yne potenti—l point of ™onfusion in the present—tion so f—r is the distin™tion ˜etween bool —nd PropF bool is — d—t—type whose two v—lues —re true —nd falseD while Prop is — more primitive type th—t in™ludes —mong its mem˜ers True —nd FalseF ‡hy not ™oll—pse these two ™on™epts into oneD —nd why must there ˜e more th—n two st—tes of m—them—ti™—l truthc „he —nswer ™omes from the f—™t th—t goq implements constructive or intuitionistic logi™D in ™ontr—st to the classical logi™ th—t you m—y ˜e more f—mili—r withF sn ™onstru™tive logi™D ™l—ssi™—l t—utologies like ¬ ¬ P → P —nd P ∨ ¬ P do not —lw—ys holdF sn gener—lD we ™—n only prove these t—utologies when P is decidableD in the sense of ™omput—˜ility theoryF „he gurryErow—rd en™oding th—t goq uses for or —llows us to extr—™t either — proof of P or — proof of ¬ P from —ny proof of P ∨ ¬ P F ƒin™e our proofs —re just fun™tion—l progr—ms whi™h we ™—n runD this would give us — de™ision pro™edure for the h—lting pro˜lemD where the inst—nti—tions of P would ˜e formul—s like 4this p—rti™ul—r „uring m—™hine h—ltsF4 ren™e the distin™tion ˜etween bool —nd PropF €rogr—ms of type bool —re ™omput—tion—l ˜y ™onstru™tionY we ™—n —lw—ys run them to determine their resultsF w—ny Props —re undeE ™id—˜leD —nd so we ™—n write more expressive formul—s with Props th—n with boolsD ˜ut the inevit—˜le ™onsequen™e is th—t we ™—nnot simply 4run — Prop to determine its truthF4 gonstru™tive logi™ lets us de(ne —ll of the logi™—l ™onne™tives in —n —estheti™—llyE—ppe—ling w—yD with orthogon—l indu™tive de(nitionsF „h—t isD e—™h ™onne™tive is de(ned independently using — simpleD sh—red me™h—nismF gonstru™tivity —lso en—˜les — tri™k ™—lled program extractionD where we write progr—ms ˜y phr—sing them —s theorems to ˜e provedF ƒin™e our proofs —re just fun™tion—l progr—msD we ™—n extr—™t exe™ut—˜le progr—ms from our (n—l proofsD whi™h we ™ould not do —s n—tur—lly with ™l—ssi™—l proofsF ‡e will see more —˜out goq9s progr—m extr—™tion f—™ility in — l—ter ™h—pterF roweverD s think it is worth interje™ting —nother w—rning —t this pointD following up on the prior w—rning —˜out t—king the gurryErow—rd ™orresponden™e too liter—llyF st is possi˜le to write progr—ms ˜y theoremEproving methods in goqD ˜ut h—rdly —nyone does itF st is —lmost —lw—ys most useful to m—int—in the distin™tion ˜etween progr—ms —nd proofsF sf you write — progr—m ˜y proving — theoremD you —re likely to run into —lgorithmi™ ine0™ien™ies th—t you introdu™ed in your proof to m—ke it e—sier to proveF st is — sh—me to h—ve to worry —˜out su™h situ—tions while proving tri™ky theoremsD —nd it is — h—ppy st—te of —'—irs th—t you —lmost ™ert—inly will not need toD with the ide—l of extr—™ting progr—ms from proofs ˜eing ™on(ned mostly to theoreti™—l studiesF TV 4.3 First-Order Logic „he ∀ ™onne™tive of (rstEorder logi™D whi™h we h—ve seen in m—ny ex—mples so f—rD is ˜uilt into goqF qetting —he—d of ourselves — ˜itD we ™—n see it —s the dependent fun™tion type ™onstru™torF sn f—™tD impli™—tion —nd univers—l qu—nti(™—tion —re just di'erent synt—™ti™ shorth—nds for the s—me goq me™h—nismF e formul— P → Q is equiv—lent to ∀ x X P D Q D where x does not —ppe—r in Q F „h—t isD the 4re—l4 type of the impli™—tion s—ys 4for every proof of P D there exists — proof of Q F4 ixistenti—l qu—nti(™—tion is de(ned in the st—nd—rd li˜r—ryF Print exF Inductive ex @A X TypeA @P X A → PropA X Prop Xa ex intro X ∀ x X AD P x → ex P ex is p—r—meterized ˜y the type A th—t we qu—ntify overD —nd ˜y — predi™—te P over AsF ‡e prove —n existenti—l ˜y exhi˜iting some x of type AD —long with — proof of P x F es usu—lD there —re t—™ti™s th—t s—ve us from worrying —˜out the lowElevel det—ils most of the timeF ‡e use the equ—lity oper—tor aD whi™hD depending on the settings in whi™h they le—rned logi™D di'erent people will s—y either is or is not p—rt of (rstEorder logi™F por our purposesD it isF Theorem exist1 X∃ x X natD x C I a PF ‡e ™—n st—rt this proof with — t—™ti™ existsD whi™h should not ˜e ™onfused with the formul— ™onstru™tor shorth—nd of the s—me n—meF @sn the €hp version of this do™umentD the reverse 9i9 —ppe—rs inste—d of the text 4exists4 in formul—sFA exists IF „he ™on™lusion is repl—™ed with — version using the existenti—l witness th—t we —nnoun™edF aaaaaaaaaaaaaaaaaaaaaaaaaaaa ICIaP reflexivityF QedF ‡e ™—n —lso use t—™ti™s to re—son —˜out existenti—l hypothesesF Theorem exist2 X ∀ n m X natD @∃ x X natD n C x a m A → n ≤ mF ‡e st—rt ˜y ™—se —n—lysis on the proof of the existenti—l f—™tF destruct IF nat m X nat x X nat n X XnCx am aaaaaaaaaaaaaaaaaaaaaaaaaaaa H TW n ≤ m „he go—l h—s ˜een repl—™ed ˜y — form where there is — new free v—ri—˜le x D —nd where we h—ve — new hypothesis th—t the ˜ody of the existenti—l holds with x su˜stituted for the old ˜ound v—ri—˜leF prom hereD the proof is just —˜out —rithmeti™ —nd is e—sy to —utom—teF crushF QedF „he t—™ti™ intuition h—s — (rstEorder ™ousin ™—lled firstorderF firstorder proves m—ny formul—s when only (rstEorder re—soning is neededD —nd it tries to perform (rstEorder simpli(™—tions in —ny ™—seF pirstEorder re—soning is mu™h h—rder th—n proposition—l re—sonE ingD so firstorder is mu™h more likely th—n intuition to get stu™k in — w—y th—t m—kes it run for long enough to ˜e uselessF 4.4 Predicates with Implicit Equality ‡e st—rt our explor—tion of — more ™ompli™—ted ™l—ss of predi™—tes with — simple ex—mpleX —n —ltern—tive w—y of ™h—r—™terizing when — n—tur—l num˜er is zeroF Inductive isZero X nat → Prop Xa | IsZero X isZero HF Theorem isZero zero constructorF X isZero HF QedF ‡e ™—n ™—ll isZero — judgmentD in the sense often used in the sem—nti™s of progr—mming l—ngu—gesF tudgments —re typi™—lly de(ned in the style of natural deductionD where we write — num˜er of inference rules with premises —ppe—ring —˜ove — solid line —nd — ™on™lusion —ppe—ring ˜elow the lineF sn this ex—mpleD the sole ™onstru™tor IsZero of isZero ™—n ˜e thought of —s the single inferen™e rule for dedu™ing isZeroD with nothing —˜ove the line —nd isZero H ˜elow itF „he proof of isZero zero demonstr—tes how we ™—n —pply —n inferen™e ruleF „he de(nition of isZero di'ers in —n import—nt w—y from —ll of the other indu™tive de(nitions th—t we h—ve seen in this —nd the previous ™h—pterF snste—d of writing just Set or Prop —fter the ™olonD here we write nat → PropF ‡e s—w ex—mples of p—r—meterized types like listD ˜ut there the p—r—meters —ppe—red with n—mes before the ™olonF ivery ™onstru™tor of — p—r—meterized indu™tive type must h—ve — r—nge type th—t uses the s—me p—r—meterD where—s the form we use here en—˜les us to use di'erent —rguments to the type for di'erent ™onstru™torsF por inst—n™eD isZero for™es its —rgument to ˜e HF ‡e ™—n see th—t the ™on™ept of equ—lity is somehow impli™it in the indu™tive de(nition me™h—nismF „he w—y this is —™™omplished is simil—r to the w—y th—t logi™ v—ri—˜les —re used in €rologD —nd it is — very powerful me™h—nism th—t forms — found—tion for form—lizing —ll of m—them—ti™sF sn f—™tD though it is n—tur—l to UH think of indu™tive types —s folding in the fun™tion—lity of equ—lityD in goqD the true situ—tion is reversedD with equ—lity de(ned —s just —nother indu™tive type3 Print eqF Inductive eq @A X TypeA @x X AA X A → Prop Xa re equal X x a x eq is the type we get ˜ehind the s™enes when uses of in(x a —re exp—ndedF ‡e see th—t eq h—s ˜oth — p—r—meter x th—t is (xed —nd —n extr— unn—med —rgument of the s—me typeF „he type of eq —llows us to st—te —ny equ—litiesD even those th—t —re prov—˜ly f—lseF roweverD ex—mining the type of equ—lity9s sole ™onstru™tor re equalD we see th—t we ™—n only prove equ—lity when its two —rguments —re synt—™ti™—lly equ—lF „his de(nition turns out to ™—pture —ll of the ˜—si™ properties of equ—lityD —nd the equ—lityEm—nipul—ting t—™ti™s th—t we h—ve seen so f—rD like reflexivity —nd rewriteD —re implemented tre—ting eq —s just —nother indu™tive type with — wellE™hosen de(nitionF ‚eturning to the ex—mple of isZeroD we ™—n see how to m—ke use of hypotheses th—t use this predi™—teF Theorem isZero plus X ∀ n m X natD isZero m → n C m a nF ‡e w—nt to pro™eed ˜y ™—ses on the proof of the —ssumption —˜out isZeroF destruct IF n X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa nCHan ƒin™e isZero h—s only one ™onstru™torD we —re presented with only one su˜go—lF „he —rgument m to isZero is repl—™ed with th—t type9s —rgument from the single ™onstru™tor IsZeroF prom this pointD the proof is trivi—lF crushF QedF enother ex—mple seems —t (rst like it should —dmit —n —n—logous proofD ˜ut in f—™t provides — demonstr—tion of one of the most ˜—si™ got™h—s of goq provingF Theorem isZero contra X isZero I → FalseF vet us try — proof ˜y ™—ses on the —ssumptionD —s in the l—st proofF destruct IF aaaaaaaaaaaaaaaaaaaaaaaaaaaa False st seems th—t ™—se —n—lysis h—s not helped us mu™h —t —ll3 yur sole hypothesis dis—ppe—rsD le—ving usD if —nythingD worse o' th—n we were ˜eforeF ‡h—t went wrongc ‡e h—ve met —n import—nt restri™tion in t—™ti™s like destruct —nd induction when —pplied to types with UI —rgumentsF sf the —rguments —re not —lre—dy free v—ri—˜lesD they will ˜e repl—™ed ˜y new free v—ri—˜les intern—lly ˜efore doing the ™—se —n—lysis or indu™tionF ƒin™e the —rgument I to isZero is repl—™ed ˜y — fresh v—ri—˜leD we lose the ™ru™i—l f—™t th—t it is not equ—l to HF ‡hy does goq use this restri™tionc ‡e will dis™uss the issue in det—il in — future ™h—pterD when we see the dependentlyEtyped progr—mming te™hniques th—t would —llow us to write this proof term m—nu—llyF por nowD we just s—y th—t the —lgorithmi™ pro˜lem of 4logi™—lly ™omplete ™—se —n—lysis4 is unde™id—˜le when phr—sed in goq9s logi™F e few t—™ti™s —nd design p—tterns th—t we will present in this ™h—pter su0™e in —lmost —ll ™—sesF por the ™urrent ex—mpleD wh—t we w—nt is — t—™ti™ ™—lled inversionD whi™h ™orresponds to the ™on™ept of inversion th—t is frequently used with n—tur—l dedu™tion proof systemsF UndoF inversion IF QedF ‡h—t does inversion doc „hink of it —s — version of destruct th—t does its ˜est to t—ke —dv—nt—ge of the stru™ture of —rguments to indu™tive typesF sn this ™—seD inversion ™ompleted the proof immedi—telyD ˜e™—use it w—s —˜le to dete™t th—t we were using isZero with —n impossi˜le —rgumentF ƒometimes using destruct when you should h—ve used inversion ™—n le—d to ™onfusing resultsF „o illustr—teD ™onsider —n —ltern—te proof —ttempt for the l—st theoremF Theorem isZero destruct IF contra' X isZero I → P C P a SF aaaaaaaaaaaaaaaaaaaaaaaaaaaa ICIaR ‡h—t on e—rth h—ppened herec sntern—llyD destruct repl—™ed I with — fresh v—ri—˜leD —ndD trying to ˜e helpfulD it —lso repl—™ed the o™™urren™e of I within the un—ry represent—tion of e—™h num˜er in the go—lF „his h—s the net e'e™t of de™rementing e—™h of these num˜ersF sf you —re doing — proof —nd en™ounter — str—nge tr—nsmut—tion like thisD there is — good ™h—n™e th—t you should go ˜—™k —nd repl—™e — use of destruct with inversionF AbortF 4.5 Recursive Predicates ‡e h—ve —lre—dy seen —ll of the ingredients we need to ˜uild interesting re™ursive predi™—tesD like this predi™—te ™—pturing evenEnessF Inductive even X nat → Prop Xa | EvenO X even O | EvenSS X ∀ nD even n → even @S @S n AAF UP „hink of even —s —nother judgment de(ned ˜y n—tur—l dedu™tion rulesF EvenO is — rule with nothing —˜ove the line —nd even O ˜elow the lineD —nd EvenSS is — rule with even n —˜ove the line —nd even @S @S nAA ˜elowF „he proof te™hniques of the l—st se™tion —re e—sily —d—ptedF Theorem even 0 constructorF X even HF X even RF QedF Theorem even 4 constructor Y constructor Y constructorF QedF st is not h—rd to see th—t sequen™es of ™onstru™tor —ppli™—tions like the —˜ove ™—n get tediousF ‡e ™—n —void them using goq9s hint f—™ilityF Hint Constructors evenF Theorem autoF QedF even 4' Theorem even 1 inversion IF QedF Theorem even 3 inversion IF X even RF contra X even I → FalseF contra X even Q → FalseF even Q n X nat H1 X even I H X X naI aaaaaaaaaaaaaaaaaaaaaaaaaaaa H0 False inversion ™—n ˜e — little overze—lous —t timesD —s we ™—n see here with the introdu™tion of the unused v—ri—˜le n —nd —n equ—lity hypothesis —˜out itF por more ™ompli™—ted predi™—tesD thoughD —dding su™h —ssumptions is ™riti™—l to de—ling with the unde™id—˜ility of gener—l inversionF inversion QedF H1F evenF → even m → even @n C m AF ‡e ™—n —lso do indu™tive proofs —˜out Theorem even plus X ∀ n mD even n st seems — re—son—˜le (rst ™hoi™e to pro™eed ˜y indu™tion on nF induction n Y crushF UQ n nat X IHn X X m H H0 X ∀ m X natD even n → even m → even @n C m A nat even @S nA X even m aaaaaaaaaaaaaaaaaaaaaaaaaaaa even @S @n C m AA ‡e will need to use the hypotheses invert HF inversion n nat X IHn X∀ m H —nd H0 somehowF „he most n—tur—l ™hoi™e is to HF X natD even n → even m → even @n C m A nat even @S nA H0 X even m n0 X nat H2 X even n0 m H X X H1 X S n0 a n aaaaaaaaaaaaaaaaaaaaaaaaaaaa even @S @S n0 C m AA ƒimplifying the ™on™lusion ˜rings us to — point where we ™—n —pply — ™onstru™torF simplF aaaaaaaaaaaaaaaaaaaaaaaaaaaa even @S @S @n0 C m AAA constructorF aaaaaaaaaaaaaaaaaaaaaaaaaaaa even @n0 C m A et this pointD we would like to —pply the indu™tive hypothesisD whi™h isX IHn X∀ m X natD even n → even m → even @n C m A …nfortun—telyD the go—l mentions n0 where it would need to mention n to m—t™h IHnF ‡e ™ould keep looking for — w—y to (nish this proof from hereD ˜ut it turns out th—t we ™—n m—ke our lives mu™h e—sier ˜y ™h—nging our ˜—si™ str—tegyF snste—d of indu™ting on the UR stru™ture of nD we should indu™t on the structure of one of the even proofsF „his te™hnique is ™ommonly ™—lled rule induction in progr—mming l—ngu—ge sem—nti™sF sn the setting of goqD we h—ve —lre—dy seen how predi™—tes —re de(ned using the s—me indu™tive type me™h—nism —s d—t—typesD so the fund—ment—l unity of rule indu™tion with 4norm—l4 indu™tion is —pp—rentF RestartF induction IF X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa even m → even @H C m A m subgoal P is X even m → even @S @S nA C mA „he (rst ™—se is e—sily dis™h—rged ˜y ™onstru™tors of evenF crushD ˜—sed on the hint we —dded e—rlier to try the crushF xow we fo™us on the se™ond ™—seX introF nat n X nat H X even n IHeven X even m → even @n C m A H0 X even m m X aaaaaaaaaaaaaaaaaaaaaaaaaaaa even @S @S nA C m A ‡e simplify —nd —pply — ™onstru™torD —s in our l—st proof —ttemptF simplY constructorF aaaaaaaaaaaaaaaaaaaaaaaaaaaa even @n C m A xow we h—ve —n ex—™t m—t™h with our indu™tive hypothesisD —nd the rem—inder of the proof is trivi—lF apply IHeven Y sn f—™tD str—tegyF crush assumptionF ™—n h—ndle —ll of the det—ils of the proof on™e we de™l—re the indu™tion RestartF US induction IY crushF QedF sndu™tion on re™ursive predi™—tes h—s simil—r pitf—lls to those we en™ountered with inverE sion in the l—st se™tionF Theorem even contra X ∀ nD even @S @n C n AA → FalseF induction IF X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa n False subgoal P False is X ‡e —re —lre—dy sunk trying to prove the (rst su˜go—lD sin™e the —rgument to even w—s repl—™ed ˜y — fresh v—ri—˜le intern—llyF „his timeD we (nd it e—siest to prove this theorem ˜y w—y of — lemm—F snste—d of trusting induction to repl—™e expressions with fresh v—ri—˜lesD we do it ourselvesD expli™itly —dding the —ppropri—te equ—lities —s new —ssumptionsF AbortF Lemma even contra' X ∀ n'D even n' → ∀ nD n' a S @n C n A → FalseF induction IY crushF et this pointD it is useful to ™onsider —ll ™—ses of n —nd n0 ˜eing zero or nonzeroF ynly one of these ™—ses h—s —ny tri™kiness to itF destruct n Y destruct n0 Y crushF n X H X nat even @S nA X ∀ n0 X natD S n a S @n0 C n0 A → False X nat H0 X S n a n0 C S n0 aaaaaaaaaaaaaaaaaaaaaaaaaaaa IHeven n0 False et this point it is useful to use — theorem from the st—nd—rd li˜r—ryD whi™h we —lso proved with — di'erent n—me in the l—st ™h—pterF Check plus n SmF plus n Sm X∀ n m X natD S @n C m A a n C S m rewrite ← plus n Sm in H0F „he indu™tion hypothesis lets us ™omplete the proofF UT apply IHeven with n0 Y assumptionF es usu—lD we ™—n rewrite the proof to —void referen™ing —ny lo™—llyEgener—ted n—mesD whi™h m—kes our proof s™ript more re—d—˜le —nd more ro˜ust to ™h—nges in the theorem st—tementF ‡e use the not—tion ← to request — hint th—t does rightEtoEleft rewritingD just like we ™—n with the rewrite t—™ti™F RestartF Hint Rewrite ← plus n Sm X cpdtF induction IY crush Y match goal with | ‘ H X S cx a cxH C cxH endY crush Y eautoF QedF “ ⇒ destruct NY destruct N0 ‡e write the proof in — w—y th—t —voids the use of lo™—l v—ri—˜le or hypothesis n—mesD using the match t—™ti™ form to do p—tternEm—t™hing on the go—lF ‡e use uni(™—tion v—ri—˜les pre(xed ˜y question m—rks in the p—tternD —nd we t—ke —dv—nt—ge of the possi˜ility to mention — uni(™—tion v—ri—˜le twi™e in one p—tternD to enfor™e equ—lity ˜etween o™™urren™esF „he hint to rewrite with plus n Sm in — p—rti™ul—r dire™tion s—ves us from h—ving to (gure out the right pl—™e to —pply th—t theoremD —nd we —lso t—ke ™riti™—l —dv—nt—ge of — new t—™ti™D eautoF crush uses the t—™ti™ intuitionD whi™hD when it runs out of tri™ks to try using only proposition—l logi™D ˜y def—ult tries the t—™ti™ autoD whi™h we s—w in —n e—rlier ex—mpleF auto —ttempts €rologEstyle logi™ progr—mmingD se—r™hing through —ll proof trees up to — ™erE t—in depth th—t —re ˜uilt only out of hints th—t h—ve ˜een registered with Hint ™omm—ndsF gomp—red to €rologD auto pl—™es —n import—nt restri™tionX it never introdu™es new uni(™—E tion v—ri—˜les during se—r™hF „h—t isD every time — rule is —pplied during proof se—r™hD —ll of its —rguments must ˜e dedu™i˜le ˜y studying the form of the go—lF eauto rel—xes this restri™tionD —t the ™ost of possi˜ly exponenti—lly gre—ter running timeF sn this p—rti™ul—r ™—seD we know th—t eauto h—s only — sm—ll sp—™e of proofs to se—r™hD so it m—kes sense to run itF st is ™ommon in e'e™tivelyE—utom—ted goq proofs to see — ˜—g of st—nd—rd t—™ti™s —pplied to pi™k o' the 4e—sy4 su˜go—lsD (nishing with eauto to h—ndle the tri™ky p—rts th—t ™—n ˜ene(t from —dEho™ exh—ustive se—r™hF „he origin—l theorem now follows trivi—lly from our lemm—F Theorem even contra X nD even @S @n C n AA → FalseF introsY eapply even contra'Y eautoF QedF ‡e use — v—ri—nt eapply of apply whi™h h—s the s—me rel—tionship to apply —s eauto h—s to autoF apply only su™™eeds if —ll —rguments to the rule ˜eing used ™—n ˜e determined from the form of the go—lD where—s eapply will introdu™e uni(™—tion v—ri—˜les for undetermined —rgumentsF eauto is —˜le to determine the right v—lues for those uni(™—tion v—ri—˜lesF fy ™onsidering —n —ltern—te —ttempt —t proving the lemm—D we ™—n see —nother ™ommon pitf—ll of indu™tive proofs in goqF sm—gine th—t we h—d tried to prove even contra' with —ll of the ∀ qu—nti(ers moved to the front of the lemm— st—tementF UU Lemma even contra X ∀ n' nD even induction IY crush Y match goal with | ‘ H X S cx a cxH C cxH endY crush Y eautoF n' → n' a S @n C n A → “ ⇒ destruct NY FalseF destruct N0 yne su˜go—l rem—insX n H X nat X even @S @n C nAA X S @n C nA a S @S @S @n C nAAA → False aaaaaaaaaaaaaaaaaaaaaaaaaaaa IHeven False ‡e —re out of lu™k hereF „he indu™tive hypothesis is trivi—lly trueD sin™e its —ssumption is f—lseF sn the version of this proof th—t su™™eededD IHeven h—d —n expli™it qu—nti(™—tion over nF „his is ˜e™—use the qu—nti(™—tion of n appeared after the thing we are inducting on in the theorem st—tementF sn gener—lD qu—nti(ed v—ri—˜les —nd hypotheses th—t —ppe—r ˜efore the indu™tion o˜je™t in the theorem st—tement st—y (xed throughout the indu™tive proofF †—ri—˜les —nd hypotheses th—t —re qu—nti(ed —fter the indu™tion o˜je™t m—y ˜e v—ried expli™itly in uses of indu™tive hypothesesF ‡hy should goq implement induction this w—yc yne —nswer is th—t it —voids ˜urdening this ˜—si™ t—™ti™ with —ddition—l heuristi™ sm—rtsD ˜ut th—t is not the whole pi™tureF sm—gine th—t induction —n—lyzed dependen™ies —mong v—ri—˜les —nd reordered qu—nti(ers to preE serve —s mu™h freedom —s possi˜le in l—ter uses of indu™tive hypothesesF „his ™ould m—ke the indu™tive hypotheses more ™omplexD whi™h ™ould in turn ™—use p—rti™ul—r —utom—tion m—™hinery to f—il when it would h—ve su™™eeded ˜eforeF sn gener—lD we w—nt to —void qu—nE ti(ers in our proofs whenever we ™—nD —nd th—t go—l is furthered ˜y the ref—™toring th—t the induction t—™ti™ for™es us to doF AbortF 4.6 Exercises IF €rove these t—utologies of proposition—l logi™D using only the t—™ti™s applyD assumptionD constructorD destructD introD introsD leftD rightD splitD —nd unfoldF @—A @True ∨ FalseA ∧ @False ∨ TrueA @˜A P →¬¬ @™A P ∧ @Q ∨ P RA → @P ∧ QA ∨ @P ∧ RA PF €rove the following t—utology of (rstEorder logi™D using only the t—™ti™s applyD assertD assumptionD destructD eapplyD eassumptionD —nd existsF ‰ou will pro˜—˜ly (nd UV assert useful for st—ting —nd proving —n intermedi—te lemm—D en—˜ling — kind of 4forE w—rd re—soningD4 in ™ontr—st to the 4˜—™kw—rd re—soning4 th—t is the def—ult for goq t—™ti™sF eassumption is — version of assumption th—t will do m—t™hing of uni(™—tion v—ri—˜lesF vet some v—ri—˜le T of type Set ˜e the set of individu—lsF x is — ™onst—nt sym˜olD p is — un—ry predi™—te sym˜olD q is — ˜in—ry predi™—te sym˜olD —nd f is — un—ry fun™tion sym˜olF @—A px → @∀ x D px → ∃ yD q x yA → @∀ x yD q x y → qy @f y AA → ∃ z D qz @f z A QF he(ne —n indu™tive predi™—te ™—pturing when — n—tur—l num˜er is —n integer multiple of either T or IHF €rove th—t IQ does not s—tisfy your predi™—teD —nd prove th—t —ny num˜er s—tisfying the predi™—te is not oddF st is pro˜—˜ly e—siest to prove the se™ond theorem ˜y indi™—ting 4oddEness4 —s equ—lity to P × n C I for some nF RF he(ne — simple progr—mming l—ngu—geD its sem—nti™sD —nd its typing rulesD —nd then prove th—t wellEtyped progr—ms ™—nnot go wrongF ƒpe™i(™—llyX @—A he(ne var —s — synonym for the n—tur—l num˜ersF @˜A he(ne —n indu™tive type exp of expressionsD ™ont—ining n—tur—l num˜er ™onst—ntsD n—tur—l num˜er —dditionD p—iring of two other expressionsD extr—™tion of the (rst ™omponent of — p—irD extr—™tion of the se™ond ™omponent of — p—irD —nd v—ri—˜les @˜—sed on the var type you de(nedAF @™A he(ne —n indu™tive type cmd of ™omm—ndsD ™ont—ining expressions —nd v—ri—˜le —ssignmentsF e v—ri—˜le —ssignment node should ™ont—in the v—ri—˜le ˜eing —sE signedD the expression ˜eing —ssigned to itD —nd the ™omm—nd to run —fterw—rdF @dA he(ne —n indu™tive type p—irings of v—luesF val of v—luesD ™ont—ining n—tur—l num˜er ™onst—nts —nd @eA he(ne — type of v—ri—˜le —ssignmentsD whi™h —ssign — v—lue to e—™h v—ri—˜leF @fA he(ne — ˜igEstep ev—lu—tion rel—tion evalD ™—pturing wh—t it me—ns for —n expresE sion to ev—lu—te to — v—lue under — p—rti™ul—r v—ri—˜le —ssignmentF 4fig step4 me—ns th—t the ev—lu—tion of every expression should ˜e proved with — single inE st—n™e of the indu™tive predi™—te you will de(neF por inst—n™eD 4I C I ev—lu—tes to P under —ssignment va 4 should ˜e deriv—˜le for —ny —ssignment vaF @gA he(ne — ˜igEstep ev—lu—tion rel—tion runD ™—pturing wh—t it me—ns for — ™omm—nd to run to — v—lue under — p—rti™ul—r v—ri—˜le —ssignmentF „he v—lue of — ™omm—nd is the result of ev—lu—ting its (n—l expressionF @hA he(ne — type of v—ri—˜le typingsD whi™h —re like v—ri—˜le —ssignmentsD ˜ut m—p v—ri—˜les to types inste—d of v—luesF ‰ou might use polymorphism to sh—re some ™ode with your v—ri—˜le —ssignmentsF @iA he(ne typing judgments for expressionsD v—luesD —nd ™omm—ndsF „he expression —nd ™omm—nd ™—ses will ˜e in terms of — typing —ssignmentF UW @jA he(ne — predi™—te varsType to express when — v—ri—˜le —ssignment —nd — v—ri—˜le typing —gree on the types of v—ri—˜lesF @kA €rove th—t —ny expression th—t h—s type t under v—ri—˜le typing vt ev—lu—tes under v—ri—˜le —ssignment va to some v—lue th—t —lso h—s type t in vtD —s long —s va —nd vt —greeF @lA €rove th—t —ny ™omm—nd th—t h—s type t under v—ri—˜le typing vt ev—lu—tes under v—ri—˜le —ssignment va to some v—lue th—t —lso h—s type t in vtD —s long —s va —nd vt —greeF e few hints th—t m—y ˜e helpfulX @—A yne e—sy w—y of de(ning v—ri—˜le —ssignments —nd typings is to de(ne ˜oth —s inE st—n™es of — polymorphi™ m—p typeF „he m—p type —t p—r—meter T ™—n ˜e de(ned to ˜e the type of —r˜itr—ry fun™tions from v—ri—˜les to T F e helpful fun™tion for implementing insertion into su™h — fun™tion—l m—p is eq nat decD whi™h you ™—n m—ke —v—il—˜le with Require Import ArithFF eq nat dec h—s — dependent type th—t tells you th—t it m—kes —™™ur—te de™isions on whether two n—tur—l num˜ers —re equ—lD ˜ut you ™—n use it —s if it returned — ˜oole—nD eFgFD if eq nat dec n m then E1 else E2F @˜A sf you follow the l—st hintD you m—y (nd yourself writing — proof th—t involves —n expression with eq nat dec th—t you would like to simplifyF ‚unning destruct on the p—rti™ul—r ™—ll to eq nat dec should do the tri™kF ‰ou ™—n —utom—te this —dvi™e with — pie™e of vt—™X match goal with | ‘ context ‘eq nat dec cˆ c‰“ “ ⇒ destruct @eq nat dec X Y A end @™A ‰ou pro˜—˜ly do not w—nt to use —n indu™tive de(nition for ™omp—ti˜ility of v—ri—˜le —ssignments —nd typingsF @dA „he Tactics module from this ˜ook ™ont—ins — v—ri—nt crush' of crushF crush' t—kes two —rgumentsF „he (rst —rgument is — list of lemm—s —nd other fun™tions to ˜e tried —utom—ti™—lly in 4forw—rd re—soning4 styleD where we —dd new f—™ts without ˜eing sure yet th—t they link into — proof of the ™on™lusionF „he se™ond —rgument is — list of predi™—tes on whi™h inverison should ˜e —ttempted —utom—ti™—llyF por inst—n™eD running crush' @lemma1D lemma2A pred will se—r™h for ™h—n™es to —pply lemma1 —nd lemma2 to hypotheses th—t —re —lre—dy —v—il—˜leD —dding the new ™on™luded f—™t if suit—˜le hypotheses ™—n ˜e foundF snversion will ˜e —ttempted on —ny hypothesis using predD ˜ut only those inversions th—t n—rrow the (eld of possi˜ilities to one possi˜le rule will ˜e keptF „he form—t of the list —rguments to crush' is th—t you ™—n p—ss —n empty list —s ttD — singleton list —s the un—dorned single elementD —nd — multipleEelement list —s — tuple of the elementsF VH @eA sf you w—nt crush' to —pply polymorphi™ lemm—sD you m—y h—ve to do — little extr— workD if the type p—r—meter is not — free v—ri—˜le of your proof ™ontext @so th—t crush' does not know to try itAF por inst—n™eD if you de(ne — polymorphi™ m—p insert fun™tion assign of some type ∀ T X SetD FFFD —nd you w—nt p—rti™ul—r —ppli™—tions of assign —dded —utom—ti™—lly with type p—r—meter UD you would need to in™lude assign in the lemm— list —s assign U @if you h—ve impli™it —rguments o'A or assign @T Xa U A or dassign U @if you h—ve impli™it —rguments onAF VI Chapter 5 Innite Data and Proofs sn l—zy fun™tion—l progr—mming l—ngu—ges like r—skellD in(nite d—t— stru™tures —re everyE whereF sn(nite lists —nd more exoti™ d—t—types provide ™onvenient —˜str—™tions for ™ommuE ni™—tion ˜etween p—rts of — progr—mF e™hieving simil—r ™onvenien™e without in(nite l—zy stru™tures wouldD in m—ny ™—sesD require —™ro˜—ti™ inversions of ™ontrol )owF v—ziness is e—sy to implement in r—skellD where —ll the de(nitions in — progr—m m—y ˜e thought of —s mutu—lly re™ursiveF sn su™h —n un™onstr—ined settingD it is e—sy to implement —n in(nite loop when you re—lly me—nt to ˜uild —n in(nite listD where —ny (nite pre(x of the list should ˜e for™e—˜le in (nite timeF r—skell progr—mmers le—rn how to —void su™h slipEupsF sn goqD su™h — l—issezEf—ire poli™y is not good enoughF ‡e spent some time in the l—st ™h—pter dis™ussing the gurryErow—rd isomorphismD where proofs —re identi(ed with fun™tion—l progr—msF sn su™h — settingD in(nite loopsD intended or otherwiseD —re dis—strousF sf goq —llowed the full ˜re—dth of de(nitions th—t r—skell didD we ™ould ™ode up —n in(nite loop —nd use it to prove —ny proposition v—™uouslyF „h—t isD the —ddition of gener—l re™ursion would m—ke gsg inconsistentF por —n —r˜itr—ry proposition P D we ™ould writeX Fixpoint bad @u X unitA X P Xa bad uF „his would le—ve us with bad tt —s — proof of P F „here —re —lso —lgorithmi™ ™onsider—tions th—t m—ke univers—l termin—tion very desir—˜leF ‡e h—ve seen how t—™ti™s like reflexivity ™omp—re terms up to equiv—len™e under ™ompuE t—tion—l rulesF g—lls to re™ursiveD p—tternEm—t™hing fun™tions —re simpli(ed —utom—ti™—llyD with no need for expli™it proof stepsF st would ˜e very h—rd to hold onto th—t kind of ˜ene(t if it ˜e™—me possi˜le to write nonEtermin—ting progr—msY we would ˜e running sm—™k into the h—lting pro˜lemF yne solution is to use types to ™ont—in the possi˜ility of nonEtermin—tionF por inst—n™eD we ™—n ™re—te — 4nonEtermin—tion mon—dD4 inside whi™h we must write —ll of our gener—lE re™ursive progr—msF „his is — he—vyweight solutionD —nd so we would like to —void it whenever possi˜leF VP vu™kilyD goq h—s spe™i—l support for — ™l—ss of l—zy d—t— stru™tures th—t h—ppens to ™ont—in most ex—mples found in r—skellF „h—t me™h—nismD co-inductive typesD is the su˜je™t of this ™h—pterF 5.1 Computing with Innite Data vet us ˜egin with the most ˜—si™ type of in(nite d—t—D streamsD or l—zy listsF Section streamF Variable A X SetF CoInductive | Cons X A → End streamF stream X Set Xa stream → streamF „he de(nition is surprisingly simpleF ƒt—rting from the de(nition of listD we just need to ™h—nge the keyword Inductive to CoInductiveF ‡e ™ould h—ve left — Nil ™onstru™tor in our de(nitionD ˜ut we will le—ve it out to for™e —ll of our stre—ms to ˜e in(niteF row do we write down — stre—m ™onst—ntc y˜viously simple —ppli™—tion of ™onstru™tors is not good enoughD sin™e we ™ould only denote (nite o˜je™ts th—t w—yF ‚—therD where—s re™ursive de(nitions were ne™ess—ry to use v—lues of re™ursive indu™tive types e'e™tivelyD here we (nd th—t we need co-recursive denitions to build v—lues of ™oEindu™tive types e'e™tivelyF ‡e ™—n de(ne — stre—m ™onsisting only of zeroesF CoFixpoint zeroes X stream nat Xa Cons H zeroesF ‡e ™—n —lso de(ne — stre—m th—t —ltern—tes ˜etween CoFixpoint trues X stream bool Xa Cons true with falses X stream bool Xa Cons false truesF true —nd falseF falses goEindu™tive v—lues —re f—ir g—me —s —rguments to re™ursive fun™tionsD —nd we ™—n use th—t f—™t to write — fun™tion to t—ke — (nite —pproxim—tion of — stre—mF Fixpoint approx A @s X stream AA @n X natA X list match n with | O ⇒ nil | S n' ⇒ match s with | Cons h t ⇒ h XX approx t n' end endF Eval simpl in approx zeroes IHF a H XX H XX H XX H XX H XX H XX H XX H XX H XX H XX X list nat Eval simpl in approx trues IHF VQ A nil Xa a X true XX false XX true XX list bool false XX XX true false XX true XX false XX true XX false XX nil ƒo f—rD it looks like ™oEindu™tive types might ˜e — m—gi™ ˜ulletD —llowing us to import —ll of the r—skeller9s usu—l tri™ksF roweverD there —re import—nt restri™tions th—t —re du—l to the restri™tions on the use of indu™tive typesF pixpoints consume v—lues of indu™tive typesD with restri™tions on whi™h arguments m—y ˜e p—ssed in re™ursive ™—llsF hu—llyD ™oE(xpoints produce v—lues of ™oEindu™tive typesD with restri™tions on wh—t m—y ˜e done with the results of ™oEre™ursive ™—llsF „he restri™tion for ™oEindu™tive types shows up —s the guardedness conditionD —nd it ™—n ˜e ˜roken into two p—rtsF pirstD ™onsider this stre—m de(nitionD whi™h would ˜e leg—l in r—skellF CoFixpoint Error X Recursive looper X stream nat Xa looperF denition of looper is ill EformedF In environment looper X stream nat unguarded recursive call in 4looper4 „he rule we h—ve run —foul of here is th—t every co-recursive call must be guarded by a constructor Y th—t isD every ™oEre™ursive ™—ll must ˜e — dire™t —rgument to — ™onstru™tor of the ™oEindu™tive type we —re gener—tingF st is — good thing th—t this rule is enfor™edF sf the de(nition of looper were —™™eptedD our approx fun™tion would run forever when p—ssed looperD —nd we would h—ve f—llen into in™onsisten™yF „he se™ond rule of gu—rdedness is e—siest to see ˜y (rst introdu™ing — more ™ompli™—tedD ˜ut leg—lD ™oE(xpointF Section mapF Variables A B X SetF Variable f X A → BF CoFixpoint map @s X stream AA X stream match s with | Cons h t ⇒ Cons @f h A @map t A endF End mapF B Xa „his ™ode is — liter—l ™opy of th—t for the list map fun™tionD with the Nil ™—se removed —nd VR Fixpoint ™h—nged to CoFixpointF w—ny other st—nd—rd fun™tions on l—zy d—t— stru™tures ™—n ˜e implemented just —s e—silyF ƒomeD like lterD ™—nnot ˜e implementedF ƒin™e the predi™—te p—ssed to lter m—y reje™t every element of the stre—mD we ™—nnot s—tisfy even the (rst gu—rdedness ™onditionF „he se™ond ™ondition is su˜tlerF „o illustr—te itD we st—rt o' with —nother ™oEre™ursive fun™tion de(nition th—t is leg—lF „he fun™tion interleave t—kes two stre—ms —nd produ™es — new stre—m th—t —ltern—tes ˜etween their elementsF Section interleaveF Variable A X SetF CoFixpoint interleave @s1 match s1D s2 with | Cons h1 t1D Cons h2 endF End interleaveF stream AA X stream A Xa s2 X t2 ⇒ Cons h1 @Cons h2 @interleave xow s—y we w—nt to write — weird stuttering version of p—rti™ul—r w—yD ˜—sed on interle—vingF map t1 t2 AA th—t repe—ts elements in — Section map'F Variables A B X SetF Variable f X A → BF CoFixpoint map' @s X stream AA X stream B Xa match s with | Cons h t ⇒ interleave @Cons @f h A @map' s AA @Cons @f h A @map' s AA endF ‡e get —nother error mess—ge —˜out —n ungu—rded re™ursive ™—llF „his is ˜e™—use we —re viol—ting the se™ond gu—rdedness ™onditionD whi™h s—ys th—tD not only must ™oEre™ursive ™—lls ˜e —rguments to ™onstru™torsD there must —lso not be anything but matches and calls to constructors of the same co-inductive type wr—pped —round these immedi—te uses of ™oE re™ursive ™—llsF „he —™tu—l implemented rule for gu—rdedness is — little more lenient th—n wh—t we h—ve just st—tedD ˜ut you ™—n ™ount on the illeg—lity of —ny ex™eption th—t would enh—n™e the expressive power of ™oEre™ursionF ‡hy enfor™e — rule like thisc sm—gine th—tD inste—d of interleaveD we h—d ™—lled some otherD less wellE˜eh—ved fun™tion on stre—msF €erh—ps this other fun™tion might ˜e de(ned mutu—lly with map'F st might de™onstru™t its (rst —rgumentD retrieving map' s from within Cons @f h A @map' s AF xext it might try — match on this retrieved v—lueD whi™h —mounts to de™onstru™ting map' s F „o (gure out how this match turns outD we need to know the topElevel stru™ture of map' s D ˜ut this is ex—™tly wh—t we st—rted out trying to determine3 ‡e run into — loop in the ev—lu—tion pro™essD —nd we h—ve re—™hed — witness of in™onsisten™y if we —re ev—lu—ting approx @map' s A I for —ny s F End map'F VS 5.2 Innite Proofs vet us s—y we w—nt to give two di'erent de(nitions of — stre—m of —ll onesD —nd then we w—nt to prove th—t they —re equiv—lentF CoFixpoint Definition ones ones' X stream nat Xa Cons I Xa map S zeroesF onesF „he o˜vious st—tement of the equ—lity is thisX Theorem ones eq X ones a ones'F roweverD f—™ed with the initi—l su˜go—lD it is not —t —ll ™le—r how this theorem ™—n ˜e provedF sn f—™tD it is unprov—˜leF „he eq predi™—te th—t we use is fund—ment—lly limited to equ—lities th—t ™—n ˜e demonstr—ted ˜y (niteD synt—™ti™ —rgumentsF „o prove this equiv—len™eD we will need to introdu™e — new rel—tionF AbortF goEindu™tive d—t—types m—ke sense ˜y —n—logy from r—skellF ‡h—t we need now is — co-inductive propositionF „h—t isD we w—nt to de(ne — proposition whose proofs m—y ˜e in(niteD su˜je™t to the gu—rdedness ™onditionF „he ide— of in(nite proofs does not show up in usu—l m—them—ti™sD ˜ut it ™—n ˜e very useful @unsurprisinglyA for re—soning —˜out in(nite d—t— stru™turesF fesides ex—mples from r—skellD in(nite d—t— —nd proofs will —lso turn out to ˜e useful for modelling inherently in(nite m—them—ti™—l o˜je™tsD like progr—m exe™utionsF ‡e —re re—dy for our (rst ™oEindu™tive predi™—teF Section stream eqF Variable A X SetF CoInductive stream eq X stream | Stream eq X ∀ h t1 t2D End stream eq t1 t2 → stream eq @Cons h stream eqF t1 A @Cons A → stream A → Prop Xa h t2 AF ‡e s—y th—t two stre—ms —re equ—l if —nd only if they h—ve the s—me he—ds —nd their t—ils —re equ—lF ‡e use the norm—l (niteEsynt—™ti™ equ—lity for the he—dsD —nd we refer to our new equ—lity re™ursively for the t—ilsF ‡e ™—n try rest—ting the theorem with stream eqF Theorem ones eq X stream eq ones ones'F goq does not support t—™ti™—l ™oEindu™tive proofs —s well —s it supports t—™ti™—l indu™tive proofsF „he usu—l st—rting point is the cox t—™ti™D whi™h —sks to stru™ture this proof —s — ™oE(xpointF coxF X stream eq ones ones' aaaaaaaaaaaaaaaaaaaaaaaaaaaa ones eq VT stream eq ones ones' st looks like this proof might ˜e e—sier th—n we expe™ted3 assumptionF Proof completedF …nfortun—telyD we —re due for some dis—ppointment in our vi™tory l—pF QedF Error X Recursive denition of ones eq is ill EformedF In environment ones eq X stream eq ones ones' unguarded recursive call in 4ones eq4 †i— the gurryErow—rd ™orresponden™eD the s—me gu—rdedness ™ondition —pplies to our ™oEindu™tive proofs —s to our ™oEindu™tive d—t— stru™turesF ‡e should ˜e gr—teful th—t this proof is reje™tedD ˜e™—useD if it were notD the s—me proof stru™ture ™ould ˜e used to prove —ny ™oEindu™tive theorem v—™uouslyD ˜y dire™t —ppe—l to itself3 „hinking —˜out how goq would gener—te — proof term from the proof s™ript —˜oveD we see th—t the pro˜lem is th—t we —re viol—ting the (rst p—rt of the gu—rdedness ™onditionF huring our proofsD goq ™—n help us ™he™k whether we h—ve yet gone wrong in this w—yF ‡e ™—n run the ™omm—nd Guarded in —ny ™ontext to see if it is possi˜le to (nish the proof in — w—y th—t will yield — properly gu—rded proof termF GuardedF ‚unning Guarded here gives us the s—me error mess—ge th—t we got when we tried to run QedF sn l—rger proofsD Guarded ™—n ˜e helpful in dete™ting pro˜lems before we think we —re re—dy to run QedF ‡e need to st—rt the ™oEindu™tion ˜y —pplying one of stream eq9s ™onstru™torsF „o do th—tD we need to know th—t ˜oth —rguments to the predi™—te —re ConsesF snform—llyD this is trivi—lD ˜ut simpl is not —˜le to help usF UndoF simplF X stream eq ones ones' aaaaaaaaaaaaaaaaaaaaaaaaaaaa ones eq VU stream eq ones ones' st turns out th—t we —re ˜est served ˜y proving —n —uxili—ry lemm—F AbortF pirstD we need to de(ne — fun™tion th—t seems pointless on (rst gl—n™eF Definition frob A @s X stream match s with | Cons h t ⇒ Cons h t endF AA X stream A Xa xextD we need to prove — theorem th—t seems equ—lly pointlessF Theorem frob eq X ∀ A @s X stream destruct s Y reflexivityF QedF AAD s a frob sF futD mir—™ulouslyD this theorem turns out to ˜e just wh—t we neededF Theorem coxF ones eq X stream eq ones ones'F ‡e ™—n use the theorem to rewrite the two stre—msF rewrite @frob rewrite @frob eq onesAF eq ones'AF X stream eq ones ones' aaaaaaaaaaaaaaaaaaaaaaaaaaaa stream eq @frob onesA @frob ones'A ones eq xow simpl is —˜le to redu™e the stre—msF simplF X stream eq ones ones' aaaaaaaaaaaaaaaaaaaaaaaaaaaa stream eq @Cons I onesA @Cons I @@cox map @s X stream natA X stream nat Xa ones eq match s with | Cons h t ⇒ Cons @S h A @map t A endA zeroesAA ƒin™e we h—ve exposed the of stream eqF Cons stru™ture of e—™h stre—mD we ™—n —pply the ™onstru™tor constructorF VV X stream eq ones ones' aaaaaaaaaaaaaaaaaaaaaaaaaaaa ones eq stream eq ones @@cox map @s X stream natA X stream nat Xa match s with | Cons h t ⇒ Cons @S endA zeroesA hA @map t A xowD modulo unfolding of the de(nition of mapD we h—ve m—t™hed our —ssumptionF assumptionF QedF ‡hy did this sillyElooking tri™k helpc „he —nswer h—s to do with the ™onstr—ints pl—™ed on goq9s ev—lu—tion rules ˜y the need for termin—tionF „he cox Erel—ted restri™tion th—t foiled our (rst —ttempt —t using simpl is du—l to — restri™tion for xF sn p—rti™ul—rD —n —ppli™—tion of —n —nonymous x only redu™es when the topElevel stru™ture of the re™ursive —rgument is knownF ytherwiseD we would ˜e unfolding the re™ursive de(nition —d in(nitumF pixpoints only redu™e when enough is known —˜out the denitions of their —rgumentsF hu—llyD ™oE(xpoints only redu™e when enough is known —˜out how their results will be usedF sn p—rti™ul—rD — cox is only exp—nded when it is the dis™riminee of — matchF ‚ewriting with our super(™i—lly silly lemm— wr—pped new matches —round the two cox esD triggering redu™tionF sf cox es redu™ed h—ph—z—rdlyD it would ˜e e—sy to run into in(nite loops in ev—lu—tionD sin™e we —reD —fter —llD ˜uilding in(nite o˜je™tsF yne ™ommon sour™e of di0™ulty with ™oEindu™tive proofs is ˜—d inter—™tion with st—nd—rd goq —utom—tion m—™hineryF sf we try to prove ones eq' with —utom—tionD like we h—ve in previous indu™tive proofsD we get —n inv—lid proofF Theorem ones eq' X stream eq cox Y crushF ones ones'F GuardedF AbortF „he st—nd—rd auto m—™hinery sees th—t our go—l m—t™hes —n —ssumption —nd so —pplies th—t —ssumptionD even though this viol—tes gu—rdednessF yne usu—lly st—rts — proof like this ˜y destructing some p—r—meter —nd running — ™ustom t—™ti™ to (gure out the (rst proof rule to —pply for e—™h ™—seF eltern—tivelyD there —re tri™ks th—t ™—n ˜e pl—yed with 4hiding4 the ™oEindu™tive hypothesisF VW 5.3 Simple Modeling of Non-Terminating Programs ‡e ™lose the ™h—pter with — qui™k motiv—ting ex—mple for more ™omplex uses of ™oEindu™tive typesF ‡e will de(ne — ™oEindu™tive sem—nti™s for — simple —ssem˜ly l—ngu—ge —nd use th—t sem—nti™s to prove th—t —ssem˜ly progr—ms —lw—ys run foreverF „his ˜—si™ te™hnique ™—n ˜e ™om˜ined with typing judgments for more —dv—n™ed l—ngu—gesD where some illEtyped progr—ms ™—n go wrongD ˜ut no wellEtyped progr—ms go wrongF ‡e de(ne suggestive synonyms for natD for ™—ses where we use n—tur—l num˜ers —s regE isters or progr—m l—˜elsF „h—t isD we ™onsider our ide—lized m—™hine to h—ve in(nitely m—ny registers —nd in(nitely m—ny ™ode —ddressesF Definition Definition Xa natF label Xa natF reg yur instru™tions —re lo—ding of — ™onst—nt into — registerD ™opying from one register to —notherD un™ondition—l jumpD —nd ™ondition—l jump ˜—sed on whether the v—lue in — register is not zeroF Inductive instr X Set Xa | Imm X reg → nat → instr | Copy X reg → reg → instr | Jmp X label → instr | Jnz X reg → label → instrF ‡e de(ne — type regs of m—ps from registers to v—luesF „o de(ne — fun™tion set for setting — register9s v—lue in — m—pD we import the Arith module from goq9s st—nd—rd li˜r—ryD —nd we use its fun™tion eq nat dec for ™omp—ring n—tur—l num˜ersF Definition regs Xa reg → natF Require Import ArithF Definition set @rs X regsA @r X regA @v X natA X fun r' ⇒ if eq nat dec r r' then v else rs regs r'F Xa en indu™tive exec judgment ™—ptures the e'e™t of —n instru™tion on the progr—m ™ounter —nd register ˜—nkF Inductive exec X label → regs → instr → label → regs → Prop Xa | E Imm X ∀ pc rs r nD exec pc rs @Imm r n A @S pc A @set rs r n A | E Copy X ∀ pc rs r1 r2D exec pc rs @Copy r1 r2 A @S pc A @set rs r1 @rs r2 AA | E Jmp X ∀ pc rs pc'D exec pc rs @Jmp pc' A pc' rs | E JnzF X ∀ pc rs r pc'D rs r a H → exec pc rs @Jnz r pc' A @S pc A rs | E JnzT X ∀ pc rs r pc' nD rs r a S n → exec pc rs @Jnz r pc' A pc' rsF ‡e prove th—t exec represents — tot—l fun™tionF sn our proof s™riptD we use — match t—™ti™ with — context p—tternF „his p—rti™ul—r ex—mple (nds —n o™™urren™e of — p—ttern Jnz cr —nywhere in the ™urrent su˜go—l9s ™on™lusionF ‡e use — goq li˜r—ry t—™ti™ case eq to do ™—se —n—lysis on whether the ™urrent v—lue rs r of the register r is zero or notF case eq di'ers from destruct in s—ving —n equ—lity rel—ting the old v—ri—˜le to the new form we dedu™e for WH itF Lemma exec total X ∀ pc rs iD ∃ pc'D ∃ rs'D exec pc rs i pc' Hint Constructors execF rs'F destruct i Y crush Y eautoY match goal with | ‘ context ‘Jnz cr “ “ ⇒ endY eautoF QedF case eq @rs r A ‡e —re re—dy to de(ne — ™oEindu™tive judgment ™—pturing the ide— th—t — progr—m runs foreverF ‡e de(ne the judgment in terms of — progr—m progD represented —s — fun™tion m—pping e—™h l—˜el to the instru™tion found thereF Section safeF Variable prog X label → instrF CoInductive safe X label → | Step X ∀ pc r pc' r'D exec pc r @prog pc A pc' r' → safe pc' r' → safe pc rF regs → Prop Xa xow we ™—n prove th—t —ny st—rting —ddress —nd register ˜—nk le—d to s—fe in(nite exE e™utionF ‚e™—ll th—t proofs of existenti—llyEqu—nti(ed formul—s —re —ll ˜uilt with — single ™onstru™tor of the indu™tive type exF „his me—ns th—t we ™—n use destruct to 4open up4 su™h proofsF sn the proof ˜elowD we w—nt to perform this opening up on —n —ppropri—te use of the exec total lemm—F „his lemm—9s ™on™lusion ˜egins with two existenti—l qu—nti(ersD so we w—nt to tell destruct th—t it should not stop —t the (rst qu—nti(erF ‡e —™™omplish our go—l ˜y using —n intro pattern with destructF gonsult the goq m—nu—l for the det—ils of intro p—tternsY the spe™i(™ p—ttern ‘c ‘c c““ th—t we use here —™™omplishes our go—l of destru™ting ˜oth qu—nti(ers —t on™eF Theorem always safe safe pc rsF X∀ pc rsD introsY destruct @exec total pc econstructor Y eautoF cox Y rs @prog pc AA as ‘c ‘c c““Y QedF End safeF sf we print the proof term th—t w—s gener—tedD we ™—n verify th—t the proof is stru™tured —s — coxD with e—™h ™oEre™ursive ™—ll properly gu—rdedF Print always safeF WI 5.4 Exercises IF @—A he(ne — ™oEindu™tive type of in(nite trees ™—rrying d—t— of — (xed p—r—meter typeF i—™h node should ™ont—in — d—t— v—lue —nd two ™hild treesF @˜A he(ne — fun™tion everywhere for ˜uilding — tree with the s—me d—t— v—lue —t every nodeF @™A he(ne — fun™tion map for ˜uilding —n output tree out of two input trees ˜y tr—versE ing them in p—r—llel —nd —pplying — twoE—rgument fun™tion to their ™orresponding d—t— v—luesF @dA he(ne — tree falses where every node h—s the v—lue falseF @eA he(ne — tree true false where the root node h—s v—lue trueD its ™hildren h—ve v—lue falseD —ll nodes —t the next h—ve the v—lue trueD —nd so onD —ltern—ting ˜oole—n v—lues from level to levelF @fA €rove th—t true false is equ—l to the result of m—pping the ˜oole—n 4or4 fun™tion orb over true false —nd falsesF ‰ou ™—n m—ke orb —v—il—˜le with Require Import BoolFF ‰ou m—y (nd the lemm— orb false r from the s—me module helpfulF ‰our proof here should not ˜e —˜out the st—nd—rd equ—lity aD ˜ut r—ther —˜out some new equ—lity rel—tion th—t you de(neF WP Part II Programming with Dependent Types WQ Chapter 6 Subset Types and Variations ƒo f—rD we h—ve seen m—ny ex—mples of wh—t we might ™—ll 4™l—ssi™—l progr—m veri(™—tionF4 ‡e write progr—msD write their spe™i(™—tionsD —nd then prove th—t the progr—ms s—tisfy their spe™i(™—tionsF „he progr—ms th—t we h—ve written in goq h—ve ˜een norm—l fun™tion—l progr—ms th—t we ™ould just —s well h—ve written in r—skell or wvF sn this ™h—pterD we st—rt investig—ting uses of dependent types to integr—te progr—mmingD spe™i(™—tionD —nd proving into — single ph—seF 6.1 Introducing Subset Types vet us ™onsider sever—l w—ys of implementing the n—tur—l num˜er prede™essor fun™tionF ‡e st—rt ˜y displ—ying the de(nition from the st—nd—rd li˜r—ryX Print predF pred a fun n X nat ⇒ match n with |H⇒H |S u⇒u end X nat → nat ‡e ™—n use — new ™omm—ndD ExtractionD to produ™e —n yg—ml version of this fun™tionF Extraction predF (** val pred : nat -> nat **) let pred = function | O -> O | S u -> u ‚eturning H —s the prede™essor of H ™—n ™ome —™ross —s somewh—t of — h—™kF sn some WR situ—tionsD we might like to ˜e sure th—t we never try to t—ke the prede™essor of HF ‡e ™—n enfor™e this ˜y giving pred — strongerD dependent typeF Lemma zgtz crushF X HbH→ FalseF QedF Definition pred strong1 @n X natA X n b H → nat Xa match n with | O ⇒ fun pf X H b H ⇒ match zgtz pf with end | S n' ⇒ fun ⇒ n' endF ‡e exp—nd the type of pred to in™lude — proof th—t its —rgument n is gre—ter th—n HF ‡hen n is HD we use the proof to derive — ™ontr—di™tionD whi™h we ™—n use to ˜uild — v—lue of —ny type vi— — v—™uous p—ttern m—t™hF ‡hen n is — su™™essorD we h—ve no need for the proof —nd just return the —nswerF „he proof —rgument ™—n ˜e s—id to h—ve — dependent typeD ˜e™—use its type depends on the value of the —rgument nF yne —spe™ts in p—rti™ul—r of the de(nition of pred strong1 th—t m—y ˜e surprisingF ‡e took —dv—nt—ge of Definition9s synt—™ti™ sug—r for de(ning fun™tion —rguments in the ™—se of nD ˜ut we ˜ound the proofs l—ter with expli™it fun expressionsF vet us see wh—t h—ppens if we write this fun™tion in the w—y th—t —t (rst seems most n—tur—lF Definition pred strong1' @n X natA @pf X match n with | O ⇒ match zgtz pf with end | S n' ⇒ n' endF n b HA X nat Xa Error X In environment n X nat bH The term 4pf4 4H b H4 pf X n has type 4n b H4 while it is expected to have type „he term zgtz pf f—ils to typeE™he™kF ƒomehow the type ™he™ker h—s f—iled to t—ke into —™™ount inform—tion th—t follows from whi™h match ˜r—n™h th—t term —ppe—rs inF „he pro˜lem is th—tD ˜y def—ultD match does not let us use su™h implied inform—tionF „o get re(ned typingD we must —lw—ys rely on match —nnot—tionsD either written expli™itly or inferredF sn this ™—seD we must use — return —nnot—tion to de™l—re the rel—tionship ˜etween the value of the match dis™riminee —nd the type of the resultF „here is no —nnot—tion th—t lets us de™l—re — rel—tionship ˜etween the dis™riminee —nd the type of — v—ri—˜le th—t is —lre—dy in s™opeY hen™eD we del—y the ˜inding of pfD so th—t we ™—n use the return —nnot—tion to express the needed rel—tionshipF ‡e —re lu™ky th—t goq9s heuristi™s infer the return ™l—use @spe™i(™—llyD return n b H → WS natA for us in this ™—seF sn gener—lD howeverD the inferen™e pro˜lem is unde™id—˜leF „he known unde™id—˜le pro˜lem of higher-order unication redu™es to the match type inferen™e pro˜lemF yver timeD goq is enh—n™ed with more —nd more heuristi™s to get —round this pro˜lemD ˜ut there must —lw—ys exist matches whose types goq ™—nnot infer without —nnot—tionsF vet us now t—ke — look —t the yg—ml ™ode goq gener—tes for pred strong1F Extraction pred strong1F (** val pred_strong1 : nat -> nat **) let pred_strong1 = function | O -> assert false (* absurd case *) | S n' -> n' „he proof —rgument h—s dis—ppe—red3 ‡e get ex—™tly the yg—ml ™ode we would h—ve written m—nu—llyF „his is our (rst demonstr—tion of the m—in te™hni™—lly interesting fe—ture of goq progr—m extr—™tionX progr—m ™omponents of type Prop —re er—sed system—ti™—llyF ‡e ™—n reimplement our dependentlyEtyped pred ˜—sed on subset typesD de(ned in the st—nd—rd li˜r—ry with the type f—mily sigF Print sigF Inductive sig @A X TypeA @P X A → PropA X Type Xa exist X ∀ x X AD P x → sig P For sigX Argument A is implicit For existX Argument A is implicit sig is — gurryErow—rd twin of exD ex™ept th—t sig is in TypeD while ex is in PropF „h—t me—ns th—t sig v—lues ™—n survive extr—™tionD while ex proofs will —lw—ys ˜e er—sedF „he —™tu—l det—ils of extr—™tion of sigs —re more su˜tleD —s we will see shortlyF ‡e rewrite Locate pred strong1D using some synt—™ti™ sug—r for su˜set typesF 4{ X | }4F Notation Scope 4{ x X e | € }4 Xa sig @fun x X A ⇒ P A X type scope @default interpretation A Definition pred strong2 @s X {n X nat | n b H}A X nat Xa match s with | exist O pf ⇒ match zgtz pf with end | exist @S n' A ⇒ n' endF Extraction pred strong2F (** val pred_strong2 : nat -> nat **) WT let pred_strong2 = function | O -> assert false (* absurd case *) | S n' -> n' ‡e —rrive —t the s—me yg—ml ™ode —s w—s extr—™ted from pred strong1D whi™h m—y seem surprising —t (rstF „he re—son is th—t — v—lue of sig is — p—ir of two pie™esD — v—lue —nd — proof —˜out itF ixtr—™tion er—ses the proofD whi™h redu™es the ™onstru™tor exist of sig to t—king just — single —rgumentF en optimiz—tion elimin—tes uses of d—t—types with single ™onstru™tors t—king single —rgumentsD —nd we —rrive ˜—™k where we st—rtedF ‡e ™—n ™ontinue on in the pro™ess of re(ning pred9s typeF vet us ™h—nge its result type to ™—pture th—t the output is re—lly the prede™essor of the inputF Definition pred strong3 @s X {n X nat | n b H}A X {m X nat | match s return {m X nat | proj1 sig s a S m } with | exist H pf ⇒ match zgtz pf with end | exist @S n' A pf ⇒ exist n' @re equal A endF proj1 sig s a S m} Xa „he fun™tion proj1 sig extr—™ts the ˜—se v—lue from — su˜set typeF fesides the use of th—t fun™tionD the only other new thing is the use of the exist ™onstru™tor to ˜uild — new sig v—lueD —nd the det—ils of how to do th—t follow from the output of our e—rlier Print ™omm—ndF st —lso turns out th—t we need to in™lude —n expli™it return ™l—use hereD sin™e goq9s heuristi™s —re not sm—rt enough to prop—g—te the result type th—t we wrote e—rlierF fy nowD the re—der is pro˜—˜ly re—dy to ˜elieve th—t the new pred strong le—ds to the s—me yg—ml ™ode —s we h—ve seen sever—l times so f—rD —nd goq does not dis—ppointF Extraction pred strong3F (** val pred_strong3 : nat -> nat **) let pred_strong3 = function | O -> assert false (* absurd case *) | S n' -> n' ‡e h—ve m—n—ged to re—™h — type th—t isD in — form—l senseD the most expressive possi˜le for predF eny other implement—tion of the s—me type must h—ve the s—me inputEoutput ˜eh—viorF roweverD there is still room for improvement in m—king this kind of ™ode e—sier to writeF rere is — version th—t t—kes —dv—nt—ge of t—™ti™E˜—sed theorem provingF ‡e swit™h ˜—™k to p—ssing — sep—r—te proof —rgument inste—d of using — su˜set type for the fun™tion9s inputD ˜e™—use this le—ds to ™le—ner ™odeF Definition pred strong4 @n X natA X refine @fun n ⇒ match n with | O ⇒ fun ⇒ False rec n b H → {m X WU nat | n a S m }F | S n' ⇒ fun endAF ⇒ exist n' ‡e ˜uild pred strong4 using t—™ti™E˜—sed provingD ˜eginning with — Definition ™omm—nd th—t ends in — period ˜efore — de(nition is givenF ƒu™h — ™omm—nd enters the inter—™tive proving modeD with the type given for the new identi(er —s our proof go—lF ‡e do most of the work with the refine t—™ti™D to whi™h we p—ss — p—rti—l 4proof4 of the type we —re trying to proveF „here m—y ˜e some pie™es left to (ll inD indi™—ted ˜y unders™oresF eny unders™ore th—t goq ™—nnot re™onstru™t with type inferen™e is —dded —s — proof su˜go—lF sn this ™—seD we h—ve two su˜go—lsX P subgoals X nat X HbH aaaaaaaaaaaaaaaaaaaaaaaaaaaa n False subgoal P S n' a S is X n' ‡e ™—n see th—t the (rst su˜go—l ™omes from the se™ond unders™ore p—ssed to False recD —nd the se™ond su˜go—l ™omes from the se™ond unders™ore p—ssed to existF sn the (rst ™—seD we see th—tD though we ˜ound the proof v—ri—˜le with —n unders™oreD it is still —v—il—˜le in our proof ™ontextF st is h—rd to refer to unders™oreEn—med v—ri—˜les in m—nu—l proofsD ˜ut —utom—tion m—kes short work of themF foth su˜go—ls —re e—sy to dis™h—rge th—t w—yD so let us ˜—™k up —nd —sk to prove —ll su˜go—ls —utom—ti™—llyF UndoF refine @fun n ⇒ match n with | O ⇒ fun ⇒ False rec | S n' ⇒ fun ⇒ exist n' endAY crushF DefinedF ‡e end the 4proof4 with Defined inste—d of QedD so th—t the de(nition we ™onstru™ted rem—ins visi˜leF „his ™ontr—sts to the ™—se of ending — proof with QedD where the det—ils of the proof —re hidden —fterw—rdF vet us see wh—t our proof s™ript ™onstru™tedF Print pred strong4F a fun n X nat ⇒ match n as n0 return @n0 b H → {m X nat | |H⇒ pred strong4 n0 WV a S m }A with fun False | S end X HbH⇒ rec {m X nat | H a S m} @Bool.di false true @Bool.absurd eq true false @Bool.di false true @Bool.absurd eq true false @pred strong4 subproof n' ⇒ fun X S n' b H ⇒ exist @fun m X nat ⇒ S n' a S m A n' @re equal @S n' AA X∀ n X natD n b H → {m X nat | n a S n AAAAA m} ‡e see the ™ode we enteredD with some proofs (lled inF „he (rst proof o˜lig—tionD the se™ond —rgument to False recD is (lled in with — n—styElooking proof term th—t we ™—n ˜e gl—d we did not enter ˜y h—ndF „he se™ond proof o˜lig—tion is — simple re)exivity proofF ‡e —re —lmost done with the ide—l implement—tion of dependent prede™essorF ‡e ™—n use goq9s synt—x extension f—™ility to —rrive —t ™ode with —lmost no ™omplexity ˜eyond — r—skell or wv progr—m with — ™omplete spe™i(™—tion in — ™ommentF Notation 434 Xa @False rec Notation 4‘ e “4 Xa @exist e AF AF Definition pred strong5 @n X natA X refine @fun n ⇒ match n with | O ⇒ fun ⇒ 3 | S n' ⇒ fun ⇒ ‘n' “ endAY crushF DefinedF n b H → {m X nat | n a S m }F yne other —ltern—tive is worth demonstr—tingF ‚e™ent goq versions in™lude — f—™ility ™—lled Program th—t stre—mlines this style of de(nitionF rere is — ™omplete implement—tion using ProgramF Obligation Tactic Xa Program Definition match n with |O⇒ | S n' ⇒ n' endF crushF pred strong6 @n X natA @ X n b HA X {m X nat | n a S m } Xa €rinting the resulting de(nition of pred strong6 yields — term very simil—r to wh—t we ˜uilt with refineF Program ™—n s—ve time in writing progr—ms th—t use su˜set typesF xonethelessD refine is often just —s e'e™tiveD —nd refine gives you more ™ontrol over the form the (n—l term t—kesD whi™h ™—n ˜e useful when you w—nt to prove —ddition—l theorems —˜out your de(nitionF Program will sometimes insert type ™—sts th—t ™—n ™ompli™—te theoremEprovingF WW 6.2 Decidable Proposition Types „here is —nother type in the st—nd—rd li˜r—ry whi™h ™—ptures the ide— of progr—m v—lues th—t indi™—te whi™h of two propositions is trueF Print sumboolF Inductive sumbool @A X PropA @B X PropA X Set Xa left X A → {A} C {B } | right X B → {A} C {B } For leftX Argument A is implicit For rightX Argument B is implicit ‡e ™—n de(ne some not—tions to m—ke working with AF Notation 49‰es94 Xa @left AF Notation 49xo94 Xa @right Notation 49‚edu™e9 x4 Xa @if x then Yes else No A sumbool @at level more ™onvenientF SHAF „he Reduce not—tion is not—˜le ˜e™—use it demonstr—tes how if is overlo—ded in goqF „he if form —™tu—lly works when the test expression h—s —ny twoE™onstru™tor indu™tive typeF woreoverD in the then —nd else ˜r—n™hesD the —ppropri—te ™onstru™tor —rguments —re ˜oundF „his is import—nt when working with sumbool sD when we w—nt to h—ve the proof stored in the test expression —v—il—˜le when proving the proof o˜lig—tions gener—ted in the —ppropri—te ˜r—n™hF xow we ™—n write eq nat decD whi™h ™omp—res two n—tur—l num˜ersD returning either — proof of their equ—lity or — proof of their inequ—lityF Definition eq nat dec @n m X natA X {n a m } C {n = refine @x f @n m X natA X {n a m } C {n = m } Xa match nD m with | OD O ⇒ Yes | S n'D S m' ⇒ Reduce @f n' m' A | D ⇒ No endAY congruenceF DefinedF yur de(nition extr—™ts to re—son—˜le yg—ml ™odeF Extraction eq nat decF (** val eq_nat_dec : nat -> nat -> sumbool **) let rec eq_nat_dec n m = match n with | O -> (match m with | O -> Left | S n0 -> Right) | S n' -> (match m with IHH m }F | O -> Right | S m' -> eq_nat_dec n' m') €roving this kind of de™id—˜le equ—lity result is so ™ommon th—t goq ™omes with — t—™ti™ for —utom—ting itF Definition eq nat dec' decide equalityF @n m X natA X {n a m } C {n = m }F DefinedF gurious re—ders ™—n verify th—t the decide equality version extr—™ts to the s—me yg—ml ™ode —s our more m—nu—l version doesF „h—t yg—ml ™ode h—d one undesir—˜le propertyD whi™h is th—t it uses Left —nd Right ™onstru™tors inste—d of the ˜oole—n v—lues ˜uilt into yg—mlF ‡e ™—n (x thisD ˜y using goq9s f—™ility for m—pping goq indu™tive types to yg—ml v—ri—nt typesF Extract Inductive sumbool Extraction eq nat dec'F ⇒ 4˜ool4 ‘4true4 4f—lse4“F (** val eq_nat_dec' : nat -> nat -> bool **) let rec eq_nat_dec' n m0 = match n with | O -> (match m0 with | O -> true | S n0 -> false) | S n0 -> (match m0 with | O -> false | S n1 -> eq_nat_dec' n0 n1) ‡e ™—n ˜uild 4sm—rt4 versions of the usu—l ˜oole—n oper—tors —nd put them to good use in ™erti(ed progr—mmingF por inst—n™eD here is — sumbool version of ˜oole—n 4orF4 Notation 4x || y4 Xa @if x then Yes else Reduce y AF vet us use it for ˜uilding — fun™tion th—t de™ides list mem˜ershipF ‡e need to —ssume the existen™e of —n equ—lity de™ision pro™edure for the type of list elementsF Section In decF Variable A X SetF Variable A eq dec X ∀ xy X AD {x a y } C {x = y }F „he (n—l fun™tion is e—sy to write using the te™hniques we h—ve developed so f—rF Definition In dec X ∀ @x X AA @ls X list AAD {In x ls } C {¬ In x ls }F refine @x f @x X AA @ls X list AA X {In x ls } C {¬ In x ls } Xa match ls with | nil ⇒ No IHI QedF End In | x' XX ls' ⇒ endAY crushF A eq dec x x' || f x ls' decF In dec h—s — re—son—˜le extr—™tion to yg—mlF Extraction In decF (** val in_dec : ('a1 -> 'a1 -> bool) -> 'a1 -> 'a1 list -> bool **) let rec in_dec a_eq_dec x = function | Nil -> false | Cons (x', ls') -> (match a_eq_dec x x' with | true -> true | false -> in_dec a_eq_dec x ls') 6.3 Partial Subset Types yur (n—l implement—tion of dependent prede™essor used — very spe™i(™ —rgument type to ensure th—t exe™ution ™ould —lw—ys ™omplete norm—llyF ƒometimes we w—nt to —llow exe™ution to f—ilD —nd we w—nt — more prin™ipled w—y of sign—ling th—t th—n returning — def—ult v—lueD —s pred does for HF yne —ppro—™h is to de(ne this type f—mily maybeD whi™h is — version of sig th—t —llows o˜lig—tionEfree f—ilureF Inductive maybe @A X SetA @P X A → PropA X Set Xa | Unknown X maybe P | Found X ∀ x X AD P x → maybe PF ‡e ™—n de(ne some new not—tionsD —n—logous to those we de(ned for su˜set typesF Notation 4{{ x | € }}4 Xa @maybe @fun Notation 4cc4 Xa @Unknown AF Notation 4‘‘ x ““4 Xa @Found x AF xow our next version of pred x ⇒ P AAF is trivi—l to writeF Definition pred strong7 @n X natA X {{m | refine @fun n ⇒ match n with | O ⇒ cc | S n' ⇒ ‘‘n' ““ endAY trivialF DefinedF n a IHP S m }}F fe™—use we used maybeD one v—lid implement—tion of the type we g—ve pred strong7 would return cc in every ™—seF ‡e ™—n strengthen the type to rule out su™h v—™uous implement—tionsD —nd the type f—mily sumor from the st—nd—rd li˜r—ry provides the e—siest st—rting pointF por type A —nd proposition B D A C {B } desug—rs to sumor A B D whose v—lues —re either v—lues of A or proofs of B F Print sumorF Inductive sumor @A X TypeA @B X PropA X Type Xa inleft X A → A C {B } | inright X B → A C {B } For inleftX Argument A is implicit For inrightX Argument B is implicit ‡e —dd not—tions for e—sy use of the sumor ™onstru™torsF „he se™ond not—tion is speE ™i—lized to sumor s whose A p—r—meters —re inst—nti—ted with regul—r su˜set typesD sin™e this is how we will use sumor ˜elowF AF Notation 4334 Xa @inright Notation 4‘‘‘ x “““4 Xa @inleft ‘x “AF xow we —re re—dy to give the (n—l version of possi˜lyEf—iling prede™essorF „he sumor E ˜—sed type th—t we use is m—xim—lly expressiveY —ny implement—tion of the type h—s the s—me inputEoutput ˜eh—viorF Definition pred strong8 @n X natA X {m X nat | refine @fun n ⇒ match n with | O ⇒ 33 | S n' ⇒ ‘‘‘n' “““ endAY trivialF DefinedF n a S m} C {n a H}F 6.4 Monadic Notations ‡e ™—n tre—t maybe like — mon—dD in the s—me w—y th—t the r—skell Maybe type is interpreted —s — f—ilure mon—dF yur maybe h—s the wrong type to ˜e — liter—l mon—dD ˜ut — 4˜ind4Elike not—tion will still ˜e helpfulF Notation 4x ← eI Y eP4 Xa @match e1 with | Unknown ⇒ cc | Found x ⇒ e2 endA @right associativityD at level THAF „he me—ning of x ← e1 Y e2 isX pirst run e1 F sf it f—ils to (nd —n —nswerD then —nnoun™e f—ilure for our derived ™omput—tionD tooF sf e1 does (nd —n —nswerD p—ss th—t —nswer on to e2 to (nd the (n—l resultF „he v—ri—˜le x ™—n ˜e ™onsidered ˜ound in e2F IHQ „his not—tion is very helpful for ™omposing ri™hlyEtyped pro™eduresF por inst—n™eD here is — very simple implement—tion of — fun™tion to t—ke the prede™essors of two n—tur—ls —t on™eF Definition doublePred @n1 n2 X natA X {{p | refine @fun n1 n2 ⇒ m1 ← pred strong7 n1 Y m2 ← pred strong7 n2 Y ‘‘@m1D m2 A““AY tautoF DefinedF n1 a S @fst p A ∧ n2 a S @snd p A}}F ‡e ™—n ˜uild — sumor version of the 4˜ind4 not—tion —nd use it to write — simil—rly str—ightforw—rd version of this fun™tionF Notation 4x ←− eI Y eP4 Xa @match e1 with | inright ⇒ 33 | inleft @exist x A ⇒ endA @right associativityD at level THAF Definition doublePred' @n1 n2 X natA X {p X nat × nat | n1 a S @fst p A ∧ n2 a C {n1 a H ∨ n2 a H}F refine @fun n1 n2 ⇒ m1 ←− pred strong8 n1 Y m2 ←− pred strong8 n2 Y ‘‘‘@m1D m2 A“““AY tautoF DefinedF S e2 @snd p A} 6.5 A Type-Checking Example ‡e ™—n —pply these spe™i(™—tion types to ˜uild — ™erti(ed typeE™he™ker for — simple expression l—ngu—geF Inductive exp X Set Xa | Nat X nat → exp | Plus X exp → exp → exp | Bool X bool → exp | And X exp → exp → expF ‡e de(ne — simple l—ngu—ge of types —nd its typing rulesD in the style introdu™ed in gh—pter RF Inductive type X Set Xa TNat | TBoolF Inductive hasType X exp → type → Prop Xa | HtNat X ∀ nD IHR hasType @Nat n A TNat | HtPlus X∀ e1 e2D | HtBool X ∀ bD | HtAnd hasType e1 TNat → hasType e2 TNat → hasType @Plus e1 e2 A TNat hasType @Bool b A TBool X∀ e1 e2D hasType e1 TBool → hasType e2 TBool → hasType @And e1 e2 A TBoolF st will ˜e helpful to h—ve — fun™tion for ™omp—ring two typesF ‡e ˜uild one using equalityF Definition eq type dec decide equalityF X∀ t1 t2 X decide typeD {t1 a t2 } C {t1 = t2 }F DefinedF enother not—tion ™omplements the mon—di™ not—tion for maybe th—t we de(ned e—rlierF ƒometimes we w—nt to in™lude 4—ssertions4 in our pro™eduresF „h—t isD we w—nt to run — de™ision pro™edure —nd f—il if it f—ilsY otherwiseD we w—nt to ™ontinueD with the proof th—t it produ™ed m—de —v—il—˜le to usF „his in(x not—tion ™—ptures th—t ide—D for — pro™edure th—t returns —n —r˜itr—ry twoE™onstru™tor typeF Notation 4eI YY eP4 Xa @if e1 then @right associativityD at level THAF e2 else ccA ‡ith th—t not—tion de(nedD we ™—n implement — typeCheck fun™tionD whose ™ode is only more ™omplex th—n wh—t we would write in wv ˜e™—use it needs to in™lude some extr— type —nnot—tionsF ivery ‘‘e““ expression —dds — hasType proof o˜lig—tionD —nd crush m—kes short work of them when we —dd hasType9s ™onstru™tors —s hintsF Definition typeCheck @e X expA X {{t | hasType Hint Constructors hasTypeF refine @x F @e X expA X {{t | hasType match e with | Nat ⇒ ‘‘TNat““ | Plus e1 e2 ⇒ t1 ← F e1 Y t2 ← F e2 Y eq type dec t1 TNatYY eq type dec t2 TNatYY ‘‘TNat““ | Bool ⇒ ‘‘TBool““ | And e1 e2 ⇒ t1 ← F e1 Y e t }} IHS e t }}F Xa t2 ← F e2 Y eq type dec t1 TBoolYY eq type dec t2 TBoolYY ‘‘TBool““ endAY crushF DefinedF hespite m—nipul—ting proofsD our type ™he™ker is e—sy to runF Eval simpl in typeCheck @Nat HAF a ‘‘TNat““ X {{t | hasType @Nat HA t }} Eval simpl in typeCheck @Plus @Nat IA @Nat PAAF a ‘‘TNat““ X {{t | hasType @Plus @Nat IA @Nat PAA t }} Eval simpl in typeCheck @Plus @Nat IA @Bool falseAAF a cc X {{t | hasType @Plus @Nat IA @Bool falseAA t }} „he typeE™he™ker —lso extr—™ts to some re—son—˜le yg—ml ™odeF Extraction typeCheckF (** val typeCheck : exp -> type0 maybe **) let rec typeCheck = function | Nat n -> Found TNat | Plus (e1, e2) -> (match typeCheck e1 with | Unknown -> Unknown | Found t1 -> (match typeCheck e2 with | Unknown -> Unknown | Found t2 -> (match eq_type_dec t1 TNat with | true -> (match eq_type_dec t2 TNat with | true -> Found TNat | false -> Unknown) | false -> Unknown))) | Bool b -> Found TBool | And (e1, e2) -> (match typeCheck e1 with | Unknown -> Unknown IHT | Found t1 -> (match typeCheck e2 with | Unknown -> Unknown | Found t2 -> (match eq_type_dec t1 TBool with | true -> (match eq_type_dec t2 TBool with | true -> Found TBool | false -> Unknown) | false -> Unknown))) ‡e ™—n —d—pt this implement—tion to use sumorD so th—t we know our typeE™he™ker only f—ils on illEtyped inputsF pirstD we de(ne —n —n—logue to the 4—ssertion4 not—tionF Notation 4eI YYY eP4 Xa @if e1 then @right associativityD at level THAF e2 else 33A xextD we prove — helpful lemm—D whi™h st—tes th—t — given expression ™—n h—ve —t most one typeF Lemma hasType det hasType e →∀ X∀ e t1D t1 t2D hasType e t2 → t1 a t2F induction IY inversion IY QedF crushF xow we ™—n de(ne the typeE™he™kerF sts type expresses th—t it only f—ils on untyp—˜le expressionsF Definition typeCheck' @e X expA X {t X type | hasType Hint Constructors hasTypeF ‡e register —ll of the typing rules —s hintsF e t} C {∀ tD ¬ hasType e t }F Hint Resolve hasType detF hasType det will —lso ˜e useful for proving proof o˜lig—tions with ™ontr—di™tory ™ontextsF ƒin™e its st—tement in™ludes ∀E˜ound v—ri—˜les th—t do not —ppe—r in its ™on™lusionD only eauto will —pply this hintF pin—llyD the implement—tion of not—tions —s neededF typeCheck ™—n ˜e tr—ns™ri˜ed liter—llyD simply swit™hing refine @x F @e X expA X {t X type | hasType match e with | Nat ⇒ ‘‘‘TNat“““ | Plus e1 e2 ⇒ t1 ←− F e1 Y IHU e t} C {∀ tD ¬ hasType e t } Xa t2 ←− F e2 Y eq type dec t1 TNatYYY eq type dec t2 TNatYYY ‘‘‘TNat“““ | Bool ⇒ ‘‘‘TBool“““ | And e1 e2 ⇒ t1 ←− F e1 Y t2 ←− F e2 Y eq type dec t1 TBoolYYY eq type dec t2 TBoolYYY ‘‘‘TBool“““ endAY clear F Y crush' tt hasTypeY eautoF ‡e ™le—r FD the lo™—l n—me for the re™ursive fun™tionD to —void str—nge proofs th—t refer to re™ursive ™—lls th—t we never m—keF „he crush v—ri—nt crush' helps us ˜y performing —utom—ti™ inversion on inst—n™es of the predi™—tes spe™i(ed in its se™ond —rgumentF yn™e we throw in eauto to —pply hasType det for usD we h—ve dis™h—rged —ll the su˜go—lsF DefinedF „he short implement—tion here hides just how timeEs—ving —utom—tion isF ivery use of one of the not—tions —dds — proof o˜lig—tionD giving us IP in tot—lF wost of these o˜lig—tions require multiple inversions —nd either uses of hasType det or —ppli™—tions of hasType rulesF „he results of simplifying ™—lls to typeCheck' look de™eptively simil—r to the results for typeCheckD ˜ut now the types of the results provide more inform—tionF Eval simpl in typeCheck' @Nat HAF a ‘‘‘TNat“““ X {t X type | hasType @Nat HA t } C {@∀ t X typeD ¬ hasType @Nat HA t A} Eval simpl in typeCheck' @Plus @Nat IA @Nat PAAF a ‘‘‘TNat“““ X {t X type | hasType @Plus @Nat IA @Nat PAA t } C {@∀ t X typeD ¬ hasType @Plus @Nat IA @Nat PAA t A} Eval simpl in typeCheck' @Plus @Nat IA @Bool falseAAF a 33 X {t X type | hasType @Plus @Nat IA @Bool falseAA t } C {@∀ t X typeD ¬ hasType @Plus @Nat IA @Bool falseAA t A} 6.6 Exercises ell of the not—tions de(ned in this ™h—pterD plus some extr—sD —re —v—il—˜le for import from the module MoreSpecif of the ˜ook sour™eF IHV IF ‡rite — fun™tion of type ∀ n m X natD {n ≤ m } C {n b m }F „h—t isD this fun™tion de™ides whether one n—tur—l is less th—n —notherD —nd its dependent type gu—r—ntees th—t its results —re —™™ur—teF PF @—A he(ne var D — type of proposition—l v—ri—˜lesD —s — synonym for natF @˜A he(ne —n indu™tive type prop of proposition—l logi™ formul—sD ™onsisting of v—riE —˜lesD neg—tionD —nd ˜in—ry ™onjun™tion —nd disjun™tionF @™A he(ne — fun™tion propDenote from v—ri—˜le truth —ssignments —nd props to PropD ˜—sed on the usu—l me—nings of the ™onne™tivesF ‚epresent truth —ssignments —s fun™tions from var to boolF @dA he(ne — fun™tion bool true dec th—t ™he™ks whether — ˜oole—n is trueD with — m—xim—lly expressive dependent typeF „h—t isD the fun™tion should h—ve type ∀ bD {b a true} C {b a true → False}F @eA he(ne — fun™tion decide th—t determines whether — p—rti™ul—r prop is true under — p—rti™ul—r truth —ssignmentF „h—t isD the fun™tion should h—ve type ∀ @truth X var → boolA @p X propAD {propDenote truth p } C {¬ propDenote truth p }F „his fun™tion is pro˜—˜ly e—siest to write in the usu—l t—™ti™—l styleD inste—d of progr—mming with refineF bool true dec m—y ™ome in h—ndy —s — hintF @fA he(ne — fun™tion negate th—t returns — simpli(ed version of the neg—tion of — propF „h—t isD the fun™tion should h—ve type ∀ p X propD {p' X prop | ∀ truthD propDenote truth p ↔ ¬ propDenote truth p' }F „o simplify — v—ri—˜leD just neg—te itF ƒimplify — neg—tion ˜y returning its —rgumentF ƒimplify ™onjun™tions —nd disjun™tions using he worg—n9s l—wsD neg—ting the —rguments re™ursively —nd swit™hing the kind of ™onne™tiveF decide m—y ˜e useful in some of the proof o˜lig—tionsD even if you do not use it in the ™omput—tion—l p—rt of negate 9s de(nitionF vemm—s like decide —llow us to ™ompens—te for the l—™k of — gener—l v—w of the ix™luded widdle in gsgF QF smplement the h€vv s—tis(—˜ility de™ision pro™edure for ˜oole—n formul—s in ™onjun™E tive norm—l formD with — dependent type th—t gu—r—ntees its ™orre™tnessF en ex—mple of — re—son—˜le type for this fun™tion would ˜e ∀ f X formulaD {truth X tvals | formulaTrue truth f } C {∀ truthD ¬ formulaTrue truth f }F smplement —t le—st 4the ˜—si™ ˜—™ktr—™king —lgorithm4 —s de(ned hereX http://en.wikipedia.org/wiki/DPLL_algorithm st might —lso ˜e instru™tive to implement the unit prop—g—tion —nd pure liter—l elimiE n—tion optimiz—tions des™ri˜ed there or some other optimiz—tions th—t h—ve ˜een used in modern ƒe„ solversF IHW Chapter 7 More Dependent Types ƒu˜set types —nd their rel—tives help us integr—te veri(™—tion with progr—mmingF „hough they reorg—nize the ™erti(ed progr—mmer9s work)owD they tend not to h—ve deep e'e™ts on proofsF ‡e write l—rgely the s—me proofs —s we would for ™l—ssi™—l veri(™—tionD with some of the stru™ture moved into the progr—ms themselvesF st turns out th—tD when we use dependent types to their full potenti—lD we w—rp the development —nd proving pro™ess even more th—n th—tD pi™king up 4free theorems4 to the extent th—t often — ™erti(ed progr—m is h—rdly more ™omplex th—n its un™erti(ed ™ounterp—rt in r—skell or wvF sn p—rti™ul—rD we h—ve only s™r—t™hed the tip of the i™e˜erg th—t is goq9s indu™tive defE inition me™h—nismF „he indu™tive types we h—ve seen so f—r h—ve their ™ounterp—rts in the other proof —ssist—nts th—t we surveyed in gh—pter IF „his ™h—pter explores the str—nge new world of dependent indu™tive d—t—types @th—t isD dependent indu™tive types outside PropAD — possi˜ility whi™h sets goq —p—rt from —ll of the ™ompetition not ˜—sed on type theoryF 7.1 Length-Indexed Lists w—ny introdu™tions to dependent types st—rt out ˜y showing how to use them to elimin—te —rr—y ˜ounds ™he™ksF ‡hen the type of —n —rr—y tells you how m—ny elements it h—sD your ™ompiler ™—n dete™t outEofE˜ounds dereferen™es st—ti™—llyF ƒin™e we —re working in — pure fun™tion—l l—ngu—geD the next ˜est thing is lengthEindexed listsD whi™h the following ™ode de(nesF Section ilistF Variable A X SetF Inductive ilist X nat → Set Xa | Nil X ilist O | Cons X ∀ nD A → ilist n → ilist @S n AF ‡e see th—tD within its se™tionD ilist is given type nat → SetF €reviouslyD every indu™tive type we h—ve seen h—s either h—d pl—in Set —s its type or h—s ˜een — predi™—te with some type ending in PropF „he full gener—lity of indu™tive de(nitions lets us integr—te the expressivity IIH of predi™—tes dire™tly into our norm—l progr—mmingF „he nat —rgument to ilist tells us the length of the listF „he types of ilist9s ™onstru™tors tell us th—t — Nil list h—s length O —nd th—t — Cons list h—s length one gre—ter th—n the length of its su˜listF ‡e m—y —pply ilist to —ny n—tur—l num˜erD even n—tur—l num˜ers th—t —re only known —t runtimeF st is this ˜re—king of the phase distinction th—t ™h—r—™terizes ilist —s dependently typedF sn expositions of list typesD we usu—lly see the length fun™tion de(ned (rstD ˜ut here th—t would not ˜e — very produ™tive fun™tion to ™odeF snste—dD let us implement list ™on™—ten—E tionF Fixpoint app n1 @ls1 X ilist n1 A n2 @ls2 X ilist match ls1 with | Nil ⇒ ls2 | Cons x ls1' ⇒ Cons x @app ls1' ls2 A endF n2 A X ilist @n1 C n2 A Xa sn goq version VFI —nd e—rlierD this de(nition le—ds to —n error mess—geX 4lsP4 has 4ilist @cIR C nPA4 The term type 4ilist nP4 while it is expected to have type sn goq9s ™ore l—ngu—geD without expli™it —nnot—tionsD goq does not enri™h our typing —ssumptions in the ˜r—n™hes of — match expressionF st is ™le—r th—t the uni(™—tion v—ri—˜le cIR should ˜e resolved to H in this ™ontextD so th—t we h—ve H C n2 redu™ing to n2D ˜ut goq does not re—lize th—tF ‡e ™—nnot (x the pro˜lem using just the simple return ™l—uses we —pplied in the l—st ™h—pterF ‡e need to ™om˜ine — return ™l—use with — new kind of —nnot—tionD —n in ™l—useF „his is ex—™tly wh—t the inferen™e heuristi™s do in goq VFP —nd l—terF ƒpe™i(™—llyD goq infers the following de(nition from the simpler oneF Fixpoint app' n1 @ls1 X ilist n1 A n2 @ls2 X ilist n2 A X ilist @n1 C match ls1 in @ilist n1 A return @ilist @n1 C n2 AA with | Nil ⇒ ls2 | Cons x ls1' ⇒ Cons x @app' ls1' ls2 A endF n2 A Xa …sing return —lone —llowed us to express — dependen™y of the match result type on the value of the dis™rimineeF ‡h—t in —dds to our —rsen—l is — w—y of expressing — dependen™y on the type of the dis™rimineeF ƒpe™i(™—llyD the n1 in the in ™l—use —˜ove is — binding occurrence whose s™ope is the return ™l—useF ‡e m—y use in ™l—uses only to ˜ind n—mes for the —rguments of —n indu™tive type f—milyF „h—t isD e—™h in ™l—use must ˜e —n indu™tive type f—mily n—me —pplied to — sequen™e of unders™ores —nd v—ri—˜le n—mes of the proper lengthF „he positions for parameters to the type f—mily must —ll ˜e unders™oresF €—r—meters —re those —rguments de™l—red with se™tion v—ri—˜les or with entries to the left of the (rst ™olon in —n indu™tive de(nitionF „hey ™—nnot III v—ry depending on whi™h ™onstru™tor w—s used to ˜uild the dis™rimineeD so goq prohi˜its pointless m—t™hes on themF st is those —rguments de(ned in the type to the right of the ™olon th—t we m—y n—me with in ™l—usesF yur app fun™tion ™ould ˜e typed in soE™—lled stratied type systemsD whi™h —void true dependen™yF ‡e ™ould ™onsider the length indi™es to lists to live in — sep—r—teD ™ompileEtimeE only universe from the lists themselvesF yur next ex—mple would ˜e h—rder to implement in — str—ti(ed systemF ‡e write —n inje™tion fun™tion from regul—r lists to lengthEindexed listsF e str—ti(ed implement—tion would need to dupli™—te the de(nition of lists —™ross ™ompileE time —nd runEtime versionsD —nd the runEtime versions would need to ˜e indexed ˜y the ™ompileEtime versionsF Fixpoint inject @ls X list AA X ilist @length match ls with | nil ⇒ Nil | h XX t ⇒ Cons h @inject t A endF ls A Xa ‡e ™—n de(ne —n inverse ™onversion —nd prove th—t it re—lly is —n inverseF Fixpoint unject n @ls X ilist n A X list match ls with | Nil ⇒ nil | Cons h t ⇒ h XX unject t endF Theorem inject inverse X ∀ lsD induction ls Y crushF QedF unject A Xa @inject ls A a lsF xow let us —ttempt — fun™tion th—t is surprisingly tri™ky to writeF sn wvD the list he—d fun™tion r—ises —n ex™eption when p—ssed —n empty listF ‡ith lengthEindexed listsD we ™—n rule out su™h inv—lid ™—lls st—ti™—llyD —nd here is — (rst —ttempt —t doing soF Definition hd n @ls X ilist @S nAA X match ls with | Nil ⇒ ccc | Cons h ⇒ h endF A Xa st is not ™le—r wh—t to write for the Nil ™—seD so we —re stu™k ˜efore we even turn our fun™tion over to the type ™he™kerF ‡e ™ould try omitting the Nil ™—seX Definition hd n @ls X ilist @S nAA X match ls with | Cons h ⇒ h endF A Xa IIP Error X Non exhaustive patternEm—t™hingX no clause found for pattern Nil …nlike in wvD we ™—nnot use inexh—ustive p—ttern m—t™hingD ˜e™—use there is no ™on™epE tion of — Match ex™eption to ˜e thrownF ‡e might try using —n in ™l—use somehowF Definition hd n @ls X ilist @S nAA X match ls in @ilist @S nAA with | Cons h ⇒ h endF Error X The reference n A Xa was not found in the current environment sn this —nd other ™—sesD we feel like we w—nt in ™l—uses with type f—mily —rguments th—t —re not v—ri—˜lesF …nfortun—telyD goq only supports v—ri—˜les in those positionsF e ™ompletely gener—l me™h—nism ™ould only ˜e supported with — solution to the pro˜lem of higherEorder uni(™—tionD whi™h is unde™id—˜leF „here are useful heuristi™s for h—ndling nonE v—ri—˜le indi™es whi™h —re gr—du—lly m—king their w—y into goqD ˜ut we will spend some time in this —nd the next few ™h—pters on e'e™tive p—ttern m—t™hing on dependent types using only the primitive match —nnot—tionsF yur (n—lD working —ttempt —t hd uses —n —uxili—ry fun™tion —nd — surprising return —nnot—tionF Definition hd' n @ls X ilist n A Xa match ls in @ilist n A return @match | Nil ⇒ tt | Cons h ⇒ h endF Definition hd n @ls X ilist @S n AA X A n with Xa O ⇒ unit | S ⇒ A endA with hd' lsF ‡e —nnot—te our m—in match with — type th—t is itself — matchF ‡e write th—t the fun™tion hd' returns unit when the list is empty —nd returns the ™—rried type A in —ll other ™—sesF sn the de(nition of hdD we just ™—ll hd'F fe™—use the index of ls is known to ˜e nonzeroD the type ™he™ker redu™es the match in the type of hd' to AF End ilistF 7.2 A Tagless Interpreter e f—vorite ex—mple for motiv—ting the power of fun™tion—l progr—mming is implement—tion of — simple expression l—ngu—ge interpreterF sn wv —nd r—skellD su™h interpreters —re often implemented using —n —lge˜r—i™ d—t—type of v—luesD where —t m—ny points it is ™he™ked th—t — v—lue w—s ˜uilt with the right ™onstru™tor of the v—lue typeF ‡ith dependent typesD we IIQ ™—n implement — tagless interpreter th—t ˜oth removes this sour™e of runtime ine0en™y —nd gives us more ™on(den™e th—t our implement—tion is ™orre™tF Inductive type X Set Xa | Nat X type | Bool X type | Prod X type → type → typeF Inductive exp X type → Set Xa | NConst X nat → exp Nat | Plus X exp Nat → exp Nat → exp Nat | Eq X exp Nat → exp Nat → exp Bool X bool → exp Bool X exp Bool → exp Bool → exp Bool X ∀ tD exp Bool → exp t → exp t → exp | | | And | | | X ∀ t1 t2D exp t1 → exp t2 → exp @Prod Fst X ∀ t1 t2D exp @Prod t1 t2 A → exp t1 Snd X ∀ t1 t2D exp @Prod t1 t2 A → exp t2F BConst If t Pair t1 t2 A ‡e h—ve — st—nd—rd —lge˜r—i™ d—t—type typeD de(ning — type l—ngu—ge of n—tur—lsD ˜oole—nsD —nd produ™t @p—irA typesF „hen we h—ve the indexed indu™tive type expD where the —rgument to exp tells us the en™oded type of —n expressionF sn e'e™tD we —re de(ning the typing rules for expressions simult—neously with the synt—xF ‡e ™—n give types —nd expressions sem—nti™s in — new styleD ˜—sed ™riti™—lly on the ™h—n™e for type-level computationF Fixpoint typeDenote @t X typeA X Set Xa match t with | Nat ⇒ nat | Bool ⇒ bool | Prod t1 t2 ⇒ typeDenote t1 × typeDenote end7typeF t2 typeDenote ™ompiles types of our o˜je™t l—ngu—ge into 4n—tive4 goq typesF st is de™epE tively e—sy to implementF „he only new thing we see is the 7type —nnot—tionD whi™h tells goq to p—rse the match expression using the not—tions —sso™i—ted with typesF ‡ithout this —nnot—tionD the × would ˜e interpreted —s multipli™—tion on n—tur—lsD r—ther th—n —s the produ™t type ™onstru™torF type is one ex—mple of —n identifer ˜ound to — notation scopeF ‡e will de—l more expli™itly with not—tions —nd not—tion s™opes in l—ter ™h—ptersF ‡e ™—n de(ne — fun™tion expDenote th—t is typed in terms of typeDenoteF Fixpoint expDenote t @e X exp t A X typeDenote t Xa match e with | NConst n ⇒ n | Plus e1 e2 ⇒ expDenote e1 C expDenote e2 IIR ⇒ if | Eq e1 e2 | | | @expDenote e1 A @expDenote And e1 e2 eq nat dec ⇒b ⇒ expDenote e1 88 expDenote e2 e1 e2 ⇒ if expDenote e' then expDenote e2 A then true else false BConst b If | Pair | Fst | Snd endF e' ⇒ @expDenote e1D e' ⇒ fst @expDenote e' A e' ⇒ snd @expDenote e' A e1 e2 e1 else expDenote e2 expDenote e2 A hespite the f—n™y typeD the fun™tion de(nition is routineF sn f—™tD it is less ™ompli™—ted th—n wh—t we would write in wv or r—skell WVD sin™e we do not need to worry —˜out pushing (n—l v—lues in —nd out of —n —lge˜r—i™ d—t—typeF „he only unusu—l thing is the use of —n expression of the form if E then true else false in the Eq ™—seF ‚emem˜er th—t eq nat dec h—s — ri™h dependent typeD r—ther th—n — simple ˜oole—n typeF goq9s n—tive if is overlo—ded to work on — test of —ny twoE™onstru™tor typeD so we ™—n use if to ˜uild — simple ˜oole—n from the sumbool th—t eq nat dec returnsF ‡e ™—n implement our old f—voriteD — ™onst—nt folding fun™tionD —nd prove it ™orre™tF st will ˜e useful to write — fun™tion pairOut th—t ™he™ks if —n exp of Prod type is — p—irD returning its two ™omponents if soF …nsurprisinglyD — (rst —ttempt le—ds to — type errorF Definition pairOut t1 t2 @e X exp @Prod t1 t2AA X option @exp t1 × exp match e in @exp @Prod t1 t2AA return option @exp t1 × exp t2A with e1 e2 ⇒ Some @e1 D e2 A | Pair | ⇒ None endF t2A Xa in the current environment ‡e run —g—in into the pro˜lem of not ˜eing —˜le to spe™ify nonEv—ri—˜le —rguments in in ™l—usesF „he pro˜lem would just ˜e hopeless without — use of —n in ™l—useD thoughD sin™e the result type of the match depends on —n —rgument to expF yur solution will ˜e to use — more gener—l typeD —s we did for hdF pirstD we de(ne — typeEv—lued fun™tion to use in —ssigning — type to pairOutF Error X The reference t2 was not found Definition pairOutType @t X typeA Xa match t with | Prod t1 t2 ⇒ option @exp t1 × exp | ⇒ unit endF t2 A ‡hen p—ssed — type th—t is — produ™tD pairOutType returns our (n—l desired typeF yn —ny other input typeD pairOutType returns unitD sin™e we do not ™—re —˜out extr—™ting ™omponents of nonEp—irsF xow we ™—n write —nother helper fun™tion to provide the def—ult ˜eh—vior of IIS pairOutD whi™h we will —pply for inputs th—t —re not liter—l p—irsF Definition pairOutDefault @t X typeA Xa match t return @pairOutType t A with | Prod ⇒ None | ⇒ tt endF xow pairOut is de™eptively e—sy to writeF Definition pairOut t @e X exp t A Xa match e in @exp t A return @pairOutType t A with | Pair e1 e2 ⇒ Some @e1D e2 A | ⇒ pairOutDefault endF „here is one import—nt su˜tlety in this de(nitionF goq —llows us to use ™onvenient wvE style p—ttern m—t™hing not—tionD ˜utD intern—lly —nd in proofsD we see th—t p—tterns —re exp—nded out ™ompletelyD m—t™hing one level of indu™tive stru™ture —t — timeF „husD the def—ult ™—se in the match —˜ove exp—nds out to one ™—se for e—™h ™onstru™tor of exp ˜esides is resolved di'erently in e—™h ™—seF prom —n PairD —nd the unders™ore in pairOutDefault wv or r—skell progr—mmer9s perspe™tiveD wh—t we h—ve here is type inferen™e determining whi™h ™ode is run @returning either None or ttAD whi™h goes ˜eyond wh—t is possi˜le with type inferen™e guiding p—r—metri™ polymorphism in rindleyEwilner l—ngu—gesD ˜ut is simil—r to wh—t goes on with r—skell type ™l—ssesF ‡ith pairOut —v—il—˜leD we ™—n write cfold in — str—ightforw—rd w—yF „here —re re—lly no surprises ˜eyond th—t goq veri(es th—t this ™ode h—s su™h —n expressive typeD given the sm—ll —nnot—tion ˜urdenF sn some pl—™esD we see th—t goq9s match —nnot—tion inferen™e is too sm—rt for its own goodD —nd we h—ve to turn th—t inferen™e o' ˜y writing return F Fixpoint cfold t @e X exp t A X exp t Xa match e with | NConst n ⇒ NConst n | Plus e1 e2 ⇒ let e1' Xa cfold e1 in let e2' Xa cfold e2 in match e1'D e2' return with | NConst n1D NConst n2 ⇒ NConst @n1 C | D ⇒ Plus e1' e2' end | Eq e1 e2 ⇒ let e1' Xa cfold e1 in let e2' Xa cfold e2 in match e1'D e2' return with | NConst n1D NConst n2 ⇒ BConst @if eq | D ⇒ Eq e1' e2' IIT n2 A nat dec n1 n2 then true else falseA end | | ⇒ BConst b ⇒ let e1' Xa cfold e1 in let e2' Xa cfold e2 in match e1'D e2' return with | BConst b1D BConst b2 ⇒ BConst @b1 88 | D ⇒ And e1' e2' end | If e e1 e2 ⇒ let e' Xa cfold e in match e' with | BConst true ⇒ cfold e1 | BConst false ⇒ cfold e2 | ⇒ If e' @cfold e1 A @cfold e2 A end | | BConst b And e1 e2 e1 e2 Pair ⇒ Pair @cfold e1 A @cfold b2 A e2 A ⇒ Xa cfold e Fst let e' e in match pairOut e' with | Some p ⇒ fst p | None ⇒ Fst e' end e⇒ | Snd let e' Xa cfold e in match pairOut e' with | Some p ⇒ snd p | None ⇒ Snd e' end endF „he ™orre™tness theorem for serious hurdleF Theorem cfold correct X ∀ induction e Y crushF t @e X cfold turns out to ˜e e—sy to proveD on™e we get over one exp t AD expDenote e a expDenote @cfold e AF „he (rst rem—ining su˜go—l isX expDenote @cfold e1 A C expDenote @cfold e2 A a expDenote match cfold e1 with | NConst n1 ⇒ IIU match cfold e2 with | NConst n2 ⇒ NConst @n1 C n2 A ⇒ Plus @cfold e1 A @cfold e2 A | Plus | Eq ⇒ Plus @cfold e1 A @cfold e2 A | BConst ⇒ Plus @cfold e1 A @cfold e2 A | And ⇒ Plus @cfold e1 A @cfold e2 A ⇒ Plus @cfold e1 A @cfold e2 A | If | Pair ⇒ Plus @cfold e1 A @cfold e2 A ⇒ Plus @cfold e1 A @cfold e2 A | Fst | Snd ⇒ Plus @cfold e1 A @cfold e2 A end ⇒ Plus @cfold e1 A @cfold e2 A | Plus ⇒ Plus @cfold e1 A @cfold e2 A | Eq | BConst ⇒ Plus @cfold e1 A @cfold e2 A | And ⇒ Plus @cfold e1 A @cfold e2 A ⇒ Plus @cfold e1 A @cfold e2 A | If | Pair ⇒ Plus @cfold e1 A @cfold e2 A | Fst ⇒ Plus @cfold e1 A @cfold e2 A ⇒ Plus @cfold e1 A @cfold e2 A | Snd end ‡e would like to do — ™—se —n—lysis on cfold e1 D —nd we —ttempt th—t in the w—y th—t h—s worked so f—rF destruct @cfold e1 AF User error X e1 is used in hypothesis e goq gives us —nother ™rypti™ error mess—geF vike so m—ny othersD this one ˜—si™—lly me—ns th—t goq is not —˜le to ˜uild some proof —˜out dependent typesF st is h—rd to gener—te helpful —nd spe™i(™ error mess—ges for pro˜lems like thisD sin™e th—t would require some kind of underst—nding of the dependen™y stru™ture of — pie™e of ™odeF ‡e will en™ounter m—ny ex—mples of ™—seEspe™i(™ tri™ks for re™overing from errors like this oneF por our ™urrent proofD we ™—n use — t—™ti™ dep destruct de(ned in the ˜ook Tactics moduleF qener—l elimin—tionGinversion of dependentlyEtyped hypotheses is unde™id—˜leD sin™e it must ˜e implemented with match expressions th—t h—ve the restri™tion on in ™l—uses th—t we h—ve —lre—dy dis™ussedF dep destruct m—kes — ˜est e'ort to h—ndle some ™ommon ™—sesD relying upon the more primitive dependent destruction t—™ti™ th—t ™omes with goqF sn — future ™h—pterD we will le—rn —˜out the expli™it m—nipul—tion of equ—lity proofs th—t is ˜ehind dep destruct 9s implement—tion in vt—™D ˜ut for nowD we tre—t it —s — useful ˜l—™k ˜oxF dep destruct @cfold e1 AF „his su™™essfully ˜re—ks the su˜go—l into S new su˜go—lsD one for e—™h ™onstru™tor of IIV exp th—t ™ould produ™e —n exp NatF xote th—t dep destruct is su™™essful in ruling out the other ™—ses —utom—ti™—llyD in e'e™t —utom—ting some of the work th—t we h—ve done m—nu—lly in implementing fun™tions like hd —nd pairOutF „his is the only new tri™k we need to le—rn to ™omplete the proofF ‡e ™—n ˜—™k up —nd give — shortD —utom—ted proofF „he m—in in™onvenien™e in the proof is th—t we ™—nnot write — p—ttern th—t m—t™hes — match without in™luding — ™—se for every ™onstru™tor of the indu™tive type we m—t™h overF RestartF induction e Y crush Y repeat @match goal with | ‘ context ‘match cfold | | | dep destruct |‘ If Fst @cfold EA context ‘match pairOut dep destruct QedF Eq ⇒ ci with NConst ⇒ | Plus ⇒ | BConst ⇒ | And ⇒ ⇒ | Pair ⇒ ⇒ | Snd ⇒ end“ “ ⇒ | None @cfold E A | ‘ @if ci then endY crush AF @cfold ciA with ⇒ end“ “ ⇒ else A a Some “ ⇒ destruct ⇒ E 7.3 Dependently-Typed Red-Black Trees ‚edE˜l—™k trees —re — f—vorite purelyEfun™tion—l d—t— stru™ture with —n interesting inv—ri—ntF ‡e ™—n use dependent types to enfor™e th—t oper—tions on redE˜l—™k trees preserve the inv—ri—ntF por simpli™ityD we spe™i—lize our redE˜l—™k trees to represent sets of natsF Inductive color X Set Xa Red | BlackF Inductive rbtree X color → nat → Set Xa | Leaf X rbtree Black H | RedNode X ∀ nD rbtree Black n → nat → rbtree Black n → rbtree Red n | BlackNode X ∀ c1 c2 nD rbtree c1 n → nat → rbtree c2 n → rbtree Black @S n AF e v—lue of type rbtree c d is — redE˜l—™k tree node whose root h—s ™olor c —nd th—t h—s ˜l—™k depth dF „he l—tter property me—ns th—t there —re no more th—n d ˜l—™kE™olored nodes on —ny p—th from the root to — le—fF et (rstD it ™—n ˜e un™le—r th—t this ™hoi™e of type indi™es tr—™ks —ny useful propertyF „o ™onvin™e ourselvesD we will prove th—t every redE˜l—™k tree is ˜—l—n™edF ‡e will phr—se our theorem in terms of — depth ™—l™ul—ting fun™tion th—t ignores the extr— inform—tion in the typesF st will ˜e useful to p—r—meterize this fun™tion over — ™om˜ining oper—tionD so th—t IIW we ™—n reEuse the s—me ™ode to ™—l™ul—te the minimum or m—ximum height —mong —ll p—ths from root to le—fF Require Import Max MinF Section depthF Variable f X nat → nat → natF Fixpoint depth c n @t X rbtree c n A X nat Xa match t with | Leaf ⇒ H | RedNode t1 t2 ⇒ S @f @depth t1 A @depth t2 AA | BlackNode t1 t2 ⇒ S @f @depth t1 A @depth endF End depthF t2 AA yur proof of ˜—l—n™edEness de™omposes n—tur—lly into — lower ˜ound —nd —n upper ˜oundF ‡e prove the lower ˜ound (rstF …nsurprisinglyD — tree9s ˜l—™k depth provides su™h — ˜ound on the minimum p—th lengthF ‡e use the ri™hlyEtyped pro™edure min dec to do ™—se —n—lysis on whether min X Y equ—ls X or YF Theorem depth min X ∀ c n @t X rbtree c n AD depth min t ≥ nF induction t Y crush Y match goal with | ‘ context ‘min cˆ c‰“ “ ⇒ destruct @min dec X Y A endY crushF QedF „here is —n —n—logous upperE˜ound theorem ˜—sed on ˜l—™k depthF …nfortun—telyD — symmetri™ proof s™ript does not su0™e to est—˜lish itF Theorem depth max X ∀ c n @t X rbtree c n AD depth max t ≤ P × induction t Y crush Y match goal with | ‘ context ‘max cˆ c‰“ “ ⇒ destruct @max dec X Y A endY crushF „wo su˜go—ls rem—inF yne of them isX X nat t1 X rbtree Black n n0 X nat t2 X rbtree Black n IHt1 X depth max t1 ≤ n C @n C HA C I IHt2 X depth max t2 ≤ n C @n C HA C I e X max @depth max t1A @depth max t2A a depth max aaaaaaaaaaaaaaaaaaaaaaaaaaaa S @depth max t1A ≤ n C @n C HA C I n IPH t1 n C IF ‡e see th—t IHt1 is almost the f—™t we needD ˜ut it is not quite strong enoughF ‡e will need to strengthen our indu™tion hypothesis to get the proof to go throughF AbortF sn p—rti™ul—rD we prove — lemm— th—t provides — stronger upper ˜ound for trees with ˜l—™k root nodesF ‡e got stu™k —˜ove in — ™—se —˜out — red root nodeF ƒin™e red nodes h—ve only ˜l—™k ™hildrenD our sr strengthening will en—˜le us to (nish the proofF Lemma depth max' X ∀ c n @t X rbtree c n AD match c with | Red ⇒ depth max t ≤ P × n C I | Black ⇒ depth max t ≤ P × n endF induction t Y crush Y match goal with | ‘ context ‘max cˆ c‰“ “ ⇒ destruct @max dec X Y A endY crush Y repeat @match goal with “⇒ | ‘ H X context ‘match cg with Red ⇒ | Black ⇒ end“ destruct C endY crush AF QedF „he origin—l theorem follows e—sily from the lemm—F ‡e use the t—™ti™ generalize pfD whi™hD when pf proves the proposition P D ™h—nges the go—l from Q to P → Q F st is useful to do this ˜e™—use it m—kes the truth of P m—nifest synt—™ti™—llyD so th—t —utom—tion m—™hinery ™—n rely on P D even if th—t m—™hinery is not sm—rt enough to est—˜lish P on its ownF Theorem depth max X ∀ c n @t X rbtree c n AD depth max t ≤ P × n C IF introsY generalize @depth max' t AY destruct c Y crushF QedF „he (n—l ˜—l—n™e theorem est—˜lishes th—t the minimum —nd m—ximum p—th lengths of —ny tree —re within — f—™tor of two of e—™h otherF Theorem balanced X ∀ c n @t X rbtree c n AD P × depth min t C I ≥ depth max tF introsY generalize @depth min t AY generalize @depth max t AY crushF QedF xow we —re re—dy to implement —n ex—mple oper—tion on our treesD insertionF snsertion ™—n ˜e thought of —s ˜re—king the tree inv—ri—nts lo™—lly ˜ut then re˜—l—n™ingF sn p—rti™ul—rD in intermedi—te st—tes we (nd red nodes th—t m—y h—ve red ™hildrenF „he type rtree ™—ptures the ide— of su™h — nodeD ™ontinuing to tr—™k ˜l—™k depth —s — type indexF Inductive rtree X nat → Set Xa | RedNode' X ∀ c1 c2 nD rbtree c1 n → nat → rbtree c2 n → rtree nF fefore st—rting to de(ne insertD we de(ne predi™—tes ™—pturing when — d—t— v—lue is in the set represented ˜y — norm—l or possi˜lyEinv—lid treeF Section presentF IPI Variable x X natF Fixpoint present c n @t X rbtree c n A X Prop Xa match t with | Leaf ⇒ False | RedNode a y b ⇒ present a ∨ x a y ∨ present b | BlackNode a y b ⇒ present a ∨ x a y ∨ present endF Definition rpresent match t with | RedNode' endF End presentF n @t X b rtree n A X Prop Xa ayb ⇒ present a ∨ x a y ∨ present b snsertion relies on two ˜—l—n™ing oper—tionsF st will ˜e useful to give types to these oper—tions using — rel—tive of the su˜set types from l—st ™h—pterF ‡hile su˜set types let us p—ir — v—lue with — proof —˜out th—t v—lueD here we w—nt to p—ir — v—lue with —nother nonEproof dependentlyEtyped v—lueF „he sigT type (lls this roleF Locate 4{ X 8 }4F Notation Scope 4{ x X e 8 € }4 Xa Print sigT @fun x X A ⇒ PA sigTF Inductive existT sigT X∀ x @A X TypeA @P X A → TypeA X Type Xa X AD P x → sigT P st will ˜e helpful to de(ne — ™on™ise not—tion for the ™onstru™tor of Notation 4{` x b}4 Xa @existT sigTF x AF i—™h ˜—l—n™e fun™tion is used to ™onstru™t — new tree whose keys in™lude the keys of two input treesD —s well —s — new keyF yne of the two input trees m—y viol—te the redE˜l—™k —ltern—tion inv—ri—nt @th—t isD it h—s —n rtree typeAD while the other tree is known to ˜e v—lidF gru™i—llyD the two input trees h—ve the s—me ˜l—™k depthF e ˜—l—n™e oper—tion m—y return — tree whose root is of either ™olorF „husD we use — sigT type to p—™k—ge the result tree with the ™olor of its rootF rere is the de(nition of the (rst ˜—l—n™e oper—tionD whi™h —pplies when the possi˜lyEinv—lid rtree ˜elongs to the left of the v—lid rbtreeF Definition balance1 n @a X rtree n A @data X natA c2 Xa match a in rtree n return rbtree c2 n → { c X color 8 rbtree c @S n A } with t1 y t2 ⇒ | RedNode' match t1 in rbtree c n return rbtree n → rbtree → { c X color 8 rbtree c @S n A } with IPP c2 n | RedNode axb ⇒ fun {`‚edxode @BlackNode | t1' ⇒ fun t2 ⇒ endF end ⇒ x bA cd a y @BlackNode c data d Ab} match t2 in rbtree c n return rbtree n → rbtree c2 n → { c X color 8 rbtree c @S n A } with | RedNode b x c ⇒ fun a d ⇒ {`‚edxode @BlackNode a y b A x @BlackNode c data d Ab} | b ⇒ fun a t ⇒ {`fl—™kxode @RedNode a y b A data t b} end t1' t2 ‡e —pply — tri™k th—t s ™—ll the convoy patternF ‚e™—ll th—t match —nnot—tions only m—ke it possi˜le to des™ri˜e — dependen™e of — match result type on the dis™rimineeF „here is no —utom—ti™ re(nement of the types of free v—ri—˜lesF roweverD it is possi˜le to e'e™t su™h — re(nement ˜y (nding — w—y to en™ode free v—ri—˜le type dependen™ies in the match result typeD so th—t — return ™l—use ™—n express the ™onne™tionF sn p—rti™ul—rD we ™—n extend the match to return functions over the free variables whose types we want to reneF sn the ™—se of balance1D we only (nd ourselves w—nting to re(ne the type of one tree v—ri—˜le —t — timeF ‡e m—t™h on one su˜tree of — nodeD —nd we w—nt the type of the other su˜tree to ˜e re(ned ˜—sed on wh—t we le—rnF ‡e indi™—te this with — return ™l—use st—rting like rbtree n → FFFD where n is ˜ound in —n in p—tternF ƒu™h — match expression is —pplied immedi—tely to the 4old version4 of the v—ri—˜le to ˜e re(nedD —nd the type ™he™ker is h—ppyF efter writing this ™odeD even s do not underst—nd the pre™ise det—ils of how ˜—l—n™ing worksF s ™onsulted ghris yk—s—ki9s p—per 4‚edEfl—™k „rees in — pun™tion—l ƒetting4 —nd tr—ns™ri˜ed the ™ode to use dependent typesF vu™kilyD the det—ils —re not so import—nt hereY types —lone will tell us th—t insertion preserves ˜—l—n™edEnessD —nd we will prove th—t insertion produ™es trees ™ont—ining the right keysF rere is the symmetri™ fun™tion balance2D for ™—ses where the possi˜lyEinv—lid tree —ppe—rs on the right r—ther th—n on the leftF Definition balance2 n @a X rtree n A @data X natA c2 Xa match a in rtree n return rbtree c2 n → { c X color 8 rbtree c @S n A } with t1 z t2 ⇒ | RedNode' match t1 in rbtree c n return rbtree n → rbtree c2 n → { c X color 8 rbtree c @S n A } with | RedNode b y c ⇒ fun d a ⇒ {`‚edxode @BlackNode a data b A y @BlackNode c z d Ab} | t1' ⇒ fun t2 ⇒ match t2 in rbtree c n return rbtree n → rbtree c2 n → { c X color 8 rbtree c @S n A } with | RedNode c z' d ⇒ fun b a ⇒ {`‚edxode @BlackNode a data b A z @BlackNode c z' d Ab} IPQ endF end | b ⇒ fun end t1' at ⇒ {`fl—™kxode t data @RedNode a z b Ab} t2 xow we —re —lmost re—dy to get down to the ˜usiness of writing —n insert fun™tionF pirstD we enter — se™tion th—t de™l—res — v—ri—˜le x D for the key we w—nt to insertF Section insertF Variable x X natF wost of the work of insertion is done ˜y — helper fun™tion expressed using — typeElevel fun™tion insResultF Definition insResult c n Xa match c with | Red ⇒ rtree n | Black ⇒ { c' X color 8 rbtree endF c' n insD whose return types —re } „h—t isD inserting into — tree with root ™olor c —nd ˜l—™k depth nD the v—riety of tree we get out depends on cF sf we st—rted with — red rootD then we get ˜—™k — possi˜lyEinv—lid tree of depth nF sf we st—rted with — ˜l—™k rootD we get ˜—™k — v—lid tree of depth n with — root node of —n —r˜it—ry ™olorF rere is the de(nition of insF eg—inD we do not w—nt to dwell on the fun™tion—l det—ilsF Fixpoint ins c n @t X rbtree c n A X insResult c n Xa match t with | Leaf ⇒ {` RedNode Leaf x Leaf b} | RedNode a y b ⇒ if le lt dec x y then RedNode' @projT2 @ins a AA y b else RedNode' a y @projT2 @ins b AA | BlackNode c1 c2 a y b ⇒ if le lt dec x y then match c1 return insResult c1 → with | Red ⇒ fun ins a ⇒ balance1 ins a y b | ⇒ fun ins a ⇒ {` BlackNode @projT2 ins a A y b b} end @ins a A else match c2 return insResult c2 → with | Red ⇒ fun ins b ⇒ balance2 ins b y a | ⇒ fun ins b ⇒ {` BlackNode a y @projT2 ins b A b} end @ins b A endF „he one new tri™k is — vri—tion of the ™onvoy p—tternF sn e—™h of the l—st two p—ttern IPR m—t™hesD we w—nt to t—ke —dv—nt—ge of the typing ™onne™tion ˜etween the trees a —nd bF ‡e might n—ively —pply the ™onvoy p—ttern dire™tly on a in the (rst match —nd on b in the se™ondF „his s—tisi(es the type ™he™ker per seD ˜ut it does not s—tisfy the termin—tion ™he™kerF snside e—™h matchD we would ˜e ™—lling ins re™ursively on — lo™—llyE˜ound v—ri—˜leF „he termin—tion ™he™ker is not sm—rt enough to tr—™e the d—t—)ow into th—t v—ri—˜leD so the ™he™ker does not know th—t this re™ursive —rgument is sm—ller th—n the origin—l —rgumentF ‡e m—ke this f—™t ™le—rer ˜y —pplying the ™onvoy p—ttern on the result of a recursive callD r—ther th—n just on th—t ™—ll9s —rgumentF pin—llyD we —re in the home stret™h of our e'ort to de(ne insertF ‡e just need — few more de(nitions of nonEre™ursive fun™tionsF pirstD we need to give the (n—l ™h—r—™teriz—tion of insert9s return typeF snserting into — redErooted tree gives — ˜l—™kErooted tree where ˜l—™k depth h—s in™re—sedD —nd inserting into — ˜l—™kErooted tree gives — tree where ˜l—™k depth h—s st—yed the s—me —nd where the root is —n —r˜itr—ry ™olorF Definition insertResult c n Xa match c with | Red ⇒ rbtree Black @S n A | Black ⇒ { c' X color 8 rbtree endF c' n e simple ™le—nEup pro™edure tr—nsl—tes Definition makeRbtree c n X match c with | Red ⇒ fun r ⇒ match r with ax | RedNode' end | Black ⇒ fun r ⇒ r endF } insResults insResult c n b ⇒ → into insertResultsF insertResult c n Xa BlackNode a x b ‡e modify goq9s def—ult ™hoi™e of impli™it —rguments for makeRbtreeD so th—t we do not need to spe™ify the c —nd n —rguments expli™itly in l—ter ™—llsF Implicit Arguments pin—llyD we de(ne Definition insert insert c n makeRbtree makeRbtree ‘c n “F @ins t AF —s — simple ™omposition of @t X rbtree c n A X ins —nd insertResult c n makeRbtreeF Xa es we noted e—rlierD the type of insert gu—r—ntees th—t it outputs ˜—l—n™ed trees whose depths h—ve not in™re—sed too mu™hF ‡e —lso w—nt to know th—t insert oper—tes ™orre™tly on trees interpreted —s (nite setsD so we (nish this se™tion with — proof of th—t f—™tF Section presentF Variable z X natF „he v—ri—˜le z st—nds for —n —r˜itr—ry keyF ‡e will re—son —˜out z 9s presen™e in p—rti™ul—r treesF es usu—lD outside the se™tion the theorems we prove will qu—ntify over —ll possi˜le keysD IPS giving us the f—™ts we w—ntedF ‡e st—rt ˜y proving the ™orre™tness of the ˜—l—n™e oper—tionsF st is useful to de(ne — ™ustom t—™ti™ present balance th—t en™—psul—tes the re—soning ™ommon to the two proofsF ‡e use the keyword Ltac to —ssign — n—me to — proof s™riptF „his p—rti™ul—r s™ript just iter—tes ˜etween crush —nd identi(™—tion of — tree th—t is ˜eing p—tternEm—t™hed on —nd should ˜e destru™tedF Ltac present balance crush Y Xa repeat @match goal with | ‘ H X context ‘match c„ with | Leaf ⇒ | RedNode ⇒ | BlackNode ⇒ end“ “ ⇒ dep destruct T | ‘ context ‘match c„ with | Leaf ⇒ | RedNode ⇒ | BlackNode ⇒ end“ “ ⇒ dep destruct T endY crush AF „he ˜—l—n™e ™orre™tness theorems —re simple (rstEorder logi™ equiv—len™esD where we use the fun™tion projT2 to proje™t the p—ylo—d of — sigT v—lueF Lemma present balance1 Lemma present balance2 X∀ n X∀ n @a X rtree n A @y X natA c2 @b X rbtree c2 n A D @a X rtree n A @y X natA c2 @b X rbtree c2 n AD present z @projT2 @balance1 a y b AA ↔ rpresent z a ∨ z a y ∨ present z bF destruct a Y present balanceF QedF present z @projT2 @balance2 a y b AA ↔ rpresent z a ∨ z a y ∨ present z bF destruct a Y present balanceF QedF „o st—te the theorem for insD it is useful to de(ne — new typeElevel fun™tionD sin™e ins returns di'erent result types ˜—sed on the type indi™es p—ssed to itF ‚e™—ll th—t x is the se™tion v—ri—˜le st—nding for the key we —re insertingF Definition present insResult c n Xa match c return @rbtree c n → insResult c n → PropA with | Red ⇒ fun t r ⇒ rpresent z r ↔ z a x ∨ present z t | Black ⇒ fun t r ⇒ present z @projT2 r A ↔ z a x ∨ present endF xow the st—tement —nd proof of the ins zt ™orre™tness theorem —re str—ightforw—rdD if verE IPT ˜oseF ‡e pro™eed ˜y indu™tion on the stru™ture of — treeD followed ˜y (nding ™—se —n—lysis opportunities on expressions we see ˜eing —n—lyzed in if or match expressionsF efter th—tD we p—tternEm—t™h to (nd opportunities to use the theorems we proved —˜out ˜—l—n™ingF piE n—llyD we identify two v—ri—˜les th—t —re —sserted ˜y some hypothesis to ˜e equ—lD —nd we use th—t hypothesis to repl—™e one v—ri—˜le with the other everywhereF X ∀ c n @t X rbtree c n AD @ins t AF induction t Y crush Y repeat @match goal with “ ⇒ destruct E | ‘ H X context ‘if ci then else “ | ‘ context ‘if ci then else “ “ ⇒ destruct E | ‘ H X context ‘match cg with Red ⇒ | Black ⇒ end“ “ ⇒ destruct C endY crush AY Theorem present ins present insResult t QedF try match goal with “⇒ | ‘ H X context ‘balance1 ce cf cg“ generalize @present balance1 A B C A endY try match goal with | ‘ H X context ‘balance2 ce cf cg“ “⇒ generalize @present balance2 A B C A endY try match goal with | ‘ context ‘balance1 ce cf cg“ “ ⇒ generalize @present balance1 A B C A endY try match goal with | ‘ context ‘balance2 ce cf cg“ “ ⇒ generalize @present balance2 A B C A endY crush Y match goal with | ‘ z X natD x X nat “⇒ match goal with |‘H Xz ax “ ⇒ rewrite H in ∗Y clear end endY tautoF H „he h—rd work is doneF „he most re—d—˜le w—y to st—te ™orre™tness of insert involves splitting the property into two ™olorEspe™i(™ theoremsF ‡e write — t—™ti™ to en™—psul—te the IPU re—soning steps th—t work to est—˜lish ˜oth f—™tsF Ltac present insert Xa unfold insert Y intros n t Y inversion t Y generalize @present ins t AY simplY dep destruct @ins t AY tautoF Theorem present insert Red @insert t A ↔ @z a x ∨ present present insertF QedF X∀ @t X n rbtree Red n AD present z Theorem z t AF present insert Black @projT2 @insert t AA ∨ present z t AF insertF X∀ n @t X rbtree Black n AD present z ↔ @z a present QedF End presentF End insertF x 7.4 A Certied Regular Expression Matcher enother interesting ex—mple is regul—r expressions with dependent types th—t express whi™h predi™—tes over strings p—rti™ul—r regexps implementF ‡e ™—n then —ssign — dependent type to — regul—r expression m—t™hing fun™tionD gu—r—nteeing th—t it —lw—ys de™ides the string property th—t we expe™t it to de™ideF fefore de(ning the synt—x of expressionsD it is helpful to de(ne —n indu™tive type ™—pturing the me—ning of the uleene st—rF ‡e use goq9s string supportD whi™h ™omes through — ™om˜in—tion of the Strings li˜r—ry —nd some p—rsing not—tions ˜uilt into goqF yper—tors like CC —nd fun™tions like length th—t we know from lists —re de(ned —g—in for stringsF xot—tion s™opes help us ™ontrol whi™h versions we w—nt to use in p—rti™ul—r ™ontextsF Require Import Ascii StringF Open Scope string scopeF Section starF Variable P X string → PropF Inductive star X string → Prop Xa | Empty X star 44 | Iter X ∀ s1 s2D P s1 → → End star s2 star @s1 CC s2 AF starF IPV xow we ™—n m—ke our (rst —ttempt —t de(ning — regexp type th—t is indexed ˜y predi™—tes on stringsF rere is — re—son—˜leElooking de(nition th—t is restri™ted to ™onst—nt ™h—r—™ters —nd ™on™—ten—tionF Inductive regexp X @string → PropA → Set Xa | Char X ∀ ch X asciiD regexp @fun s ⇒ s a String ch 44A | Concat X ∀ @P1 P2 X string → PropA @r1 X regexp P1 A @r2 X regexp regexp @fun s ⇒ ∃ s1 D ∃ s2 D s a s1 CC s2 ∧ P1 s1 ∧ P2 s2 AF User error X Large non Eproposition—l inductive types must be P2 AD in Type ‡h—t is — l—rge indu™tive typec sn goqD it is —n indu™tive type th—t h—s — ™onstru™tor whi™h qu—nti(es over some type of type TypeF ‡e h—ve not worked with Type very mu™h to this pointF ivery term of gsg h—s — typeD in™luding Set —nd PropD whi™h —re —ssigned type TypeF „he type string → Prop from the f—iled de(nition —lso h—s type TypeF st turns out th—t —llowing l—rge indu™tive types in Set le—ds to ™ontr—di™tions when ™om˜ined with ™ert—in kinds of ™l—ssi™—l logi™ re—soningF „husD ˜y def—ultD su™h types —re ruled outF „here is — simple (x for our regexp de(nitionD whi™h is to pl—™e our new type in TypeF ‡hile (xing the pro˜lemD we —lso exp—nd the list of ™onstru™tors to ™over the rem—ining regul—r expression oper—torsF Inductive regexp X @string → PropA → Type Xa | Char X ∀ ch X asciiD regexp @fun s ⇒ s a String ch 44A | Concat X ∀ P1 P2 @r1 X regexp P1 A @r2 X regexp P2 AD regexp @fun s ⇒ ∃ s1D ∃ s2D s a s1 CC s2 ∧ P1 s1 ∧ | Or X ∀ P1 P2 @r1 X regexp P1 A @r2 X regexp P2 AD regexp @fun s ⇒ P1 s ∨ P2 s A | Star X ∀ P @r X regexp P AD regexp @star P AF P2 s2 A w—ny theorems —˜out strings —re useful for implementing — ™erti(ed regexp m—t™herD —nd few of them —re in the Strings li˜r—ryF „he ˜ook sour™e in™ludes st—tementsD proofsD —nd hint ™omm—nds for — h—ndful of su™h omittted theoremsF ƒin™e they —re orthogon—l to our use of dependent typesD we hide them in the rendered versions of this ˜ookF e few —uxili—ry fun™tions help us in our (n—l m—t™her de(nitionF „he fun™tion split will ˜e used to implement the regexp ™on™—ten—tion ™—seF Section splitF Variables P1 P2 X string → PropF Variable P1 dec X ∀ sD {P1 s } C {¬ P1 s }F Variable P2 dec X ∀ sD {P2 s } C {¬ P2 s }F ‡e require — ™hoi™e of two —r˜itr—ry string predi™—tes —nd fun™tions for de™iding themF IPW Variable s X stringF yur ™omput—tion will t—ke pl—™e rel—tive to — single (xed stringD so it is e—siest to m—ke it — VariableD r—ther th—n —n expli™it —rgument to our fun™tionsF is the workhorse ˜ehind splitF st se—r™hes through the possi˜le w—ys of splitting s into two pie™esD ™he™king the two predi™—tes —g—inst e—™h su™h p—irF split' progresses rightE toEleftD from splitting —ll of s into the (rst pie™e to splitting —ll of s into the se™ond pie™eF st t—kes —n extr— —rgumentD nD whi™h spe™i(es how f—r —long we —re in this se—r™h pro™essF split' Definition split' @n X natA X n ≤ length s → {∃ s1D ∃ s2D length s1 ≤ n ∧ s1 CC s2 a s ∧ P1 s1 ∧ P2 s2 } C {∀ s1 s2D length s1 ≤ n → s1 CC s2 a s → ¬ P1 s1 ∨ ¬ P2 s2 }F refine @x F @n X natA X n ≤ length s → {∃ s1D ∃ s2D length s1 ≤ n ∧ s1 CC s2 a s ∧ P1 s1 ∧ P2 s2 } C {∀ s1 s2D length s1 ≤ n → s1 CC s2 a s → ¬ P1 s1 ∨ ¬ P2 s2 } Xa match n with | O ⇒ fun ⇒ Reduce @P1 dec 44 88 P2 dec s A | S n' ⇒ fun ⇒ @P1 dec @substring H @S n' A s A 88 P2 dec @substring @S n' A @length s E S n' A s AA || F n' endAY clear F Y crush Y eauto UY match goal with | ‘ X length cƒ ≤ H “ ⇒ destruct S “⇒ | ‘ X length cƒ9 ≤ S cx generalize @eq nat dec @length S' A @S N AAY destruct I endY crushF DefinedF „here is one su˜tle point in the split' ™ode th—t is worth mentioningF „he m—in ˜ody of the fun™tion is — match on nF sn the ™—se where n is known to ˜e S n'D we write S n' in sever—l pl—™es where we might ˜e tempted to write nF roweverD without further work to ™r—ft proper match —nnot—tionsD the typeE™he™ker does not use the equ—lity ˜etween n —nd S n'F „husD it is ™ommon to see p—tterns repe—ted in match ™—se ˜odies in dependentlyEtyped goq ™odeF ‡e ™—n —t le—st use — let expression to —void ™opying the p—ttern more th—n on™eD repl—™ing the (rst ™—se ˜ody withX | ⇒ fun ⇒ let n Xa S n' in @P1 dec @substring H n s A 88 P2 dec @substring n @length s E nA s AA || F n' S n' split itself is trivi—l to implement in terms of split'F ‡e just —sk split' to ˜egin its se—r™h with n a length s F Definition split X {∃ s1D ∃ s2D s a s1 CC s2 IQH ∧ P1 s1 ∧ P2 s2 } C {∀ s1 s2D s a CC s2 → ¬ P1 s1 ∨ ¬ P2 s2 }F refine @Reduce @split' @n Xa length s A AAY crush Y eautoF DefinedF End splitF s1 Implicit Arguments split ‘P1 P2 “F yne more helper fun™tion will ™ome in h—ndyX dec starD for implementing —nother line—r se—r™h through w—ys of splitting — stringD this time for implementing the uleene st—rF Section dec starF Variable P X string → PropF Variable P dec X ∀ sD {P s } C {¬ P s }F ƒome new lemm—s —nd hints —˜out the star type f—mily —re useful hereF ‡e omit them hereY they —re in™luded in the ˜ook sour™e —t this pointF „he fun™tion dec star implements — single iter—tion of the st—rF „h—t isD it tries to (nd — string pre(x m—t™hing P D —nd it ™—lls — p—r—meter fun™tion on the rem—inder of the stringF Section dec star F Variable n X natF n is the length of the pre(x of s th—t we h—ve —lre—dy pro™essedF Variable P' X string → PropF Variable P' dec X ∀ n' X natD n' b n → {P' @substring n' @length s E n' A s A} C {¬ P' @substring n' @length s E n' A s A}F ‡hen we use dec star D we will inst—nti—te se—r™h for more inst—n™es of P in s F P' dec with — fun™tion for ™ontinuing the xow we ™ome to dec star itselfF st t—kes —s —n input — n—tur—l l th—t re™ords how mu™h of the string h—s ˜een se—r™hed so f—rD —s we did for split'F „he return type expresses th—t dec star is looking for —n index into s th—t splits s into — nonempty pre(x —nd — su0xD su™h th—t the pre(x s—tis(es P —nd the su0x s—tis(es P' F Definition dec star @l X natA X {∃ l'D S l' ≤ l ∧ P @substring n @S l' A s A ∧ P' @substring @n C S l' A @length C {∀ l'D S l' ≤ l → ¬ P @substring n @S l' A s A ∨ ¬ P' @substring @n C S l' A @length s E @n C S l' AA s A}F refine @x F @l X natA X {∃ l'D S l' ≤ l ∧ P @substring n @S l' A s A ∧ P' @substring @n C S l' A @length C {∀ l'D S l' ≤ l → ¬ P @substring n @S l' A s A ∨ ¬ P' @substring @n C S l' A @length s E @n C S l' AA s A} Xa match l with IQI s E @n C S l' AA s A} s E @n C S l' AA s A} | | O S ⇒ l' ⇒ @P dec @substring n @S l' A s A 88 || F l' endAY clear F Y crush Y eauto UY match goal with | ‘ H X cˆ ≤ S c‰ endF DefinedF End dec star F P' dec “ ⇒ destruct @eq @n' Xa n nat dec X C S l' A @S A Y AAY crush „he work of dec star is nested inside —nother line—r se—r™h ˜y dec star'D whi™h provides the (n—l fun™tion—lity we needD ˜ut for —r˜itr—ry su0xes of s D r—ther th—n just for s over—llF Definition dec star' @n n' X natA X length s E n' ≤ n → {star P @substring n' @length s E n' A s A} C {¬ star P @substring n' @length s E n' A s A}F refine @x F @n n' X natA X length s E n' ≤ n → {star P @substring n' @length s E n' A s A} C {¬ star P @substring n' @length s E n' A s A} Xa match n with | O ⇒ fun ⇒ Yes | S n ⇒ fun ⇒ le gt dec @length s A n' || dec star @n Xa n' A @star P A @fun n0 ⇒ Reduce @F n n0 AA @length endAY clear F Y crush Y eautoY match goal with “ ⇒ apply star substring inv in H Y crush Y eauto | ‘ H X star endY match goal with | ‘ H1 X ` E D H2 X ∀ l' X natD ≤ E → “⇒ H1 AAY tauto generalize @H2 @lt le S endF DefinedF s E n' A pin—llyD we h—ve dec starF st h—s — str—ightforw—rd implement—tionF ‡e introdu™e — spurious m—t™h on s so th—t simpl will know to redu™e ™—lls to dec starF „he heuristi™ th—t simpl uses is only to unfold identi(er de(nitions when doing so would simplify some match expressionF Definition dec star X {star P s } C {¬ star P s }F refine @match s return with | 44 ⇒ Reduce @dec star' @n Xa length s A H A | ⇒ Reduce @dec star' @n Xa length s A H A endAY crushF IQP DefinedF End dec starF ‡ith these helper fun™tions ™ompletedD the implement—tion of our matches fun™tion is refreshingly str—ightforw—rdF ‡e only need one sm—ll pie™e of spe™i(™ t—™ti™ work ˜eyond wh—t crush does for usF Definition matches P @r X regexp P A s X {P s } C {¬ P s }F refine @x F P @r X regexp P A s X {P s } C {¬ P s } Xa match r with | Char ch ⇒ string dec s @String ch 44A | Concat r1 r2 ⇒ Reduce @split @F r1 A @F r2 A s A | Or r1 r2 ⇒ F r1 s || F r2 s | Star r ⇒ dec star endAY crush Y match goal with “ ⇒ generalize @H @re equal AA |‘H X endY tautoF DefinedF 7.5 Exercises IF he(ne — kind of dependentlyEtyped listsD where — list9s type index gives — lower ˜ound on how m—ny of its elements s—tisfy — p—rti™ul—r predi™—teF sn p—rti™ul—rD for —n —r˜iE tr—ry set A —nd — predi™—te P over itX @—A he(ne — type plist X nat → SetF i—™h plist n should ˜e — list of AsD where it is gu—r—nteed th—t —t le—st n distin™t elements s—tisfy P F „here is wide l—titude in ™hoosing how to en™ode thisF ‰ou should try to —void using su˜set types or —ny other me™h—nism ˜—sed on —nnot—ting nonEdependent types with propositions —fterEtheEf—™tF @˜A he(ne — version of list ™on™—ten—tion th—t works on plist sF „he type of this new fun™tion should express —s mu™h inform—tion —s possi˜le —˜out the output plistF @™A he(ne — fun™tion plistOut for tr—nsl—ting plist s to norm—l listsF @dA he(ne — fun™tion plistIn for tr—nsl—ting lists to plist sF „he type of plistIn should m—ke it ™le—r th—t the ˜est ˜ound on P Em—t™hing elements is ™hosenF ‰ou m—y —ssume th—t you —re given — dependentlyEtyped fun™tion for de™iding inst—n™es of PF @eA €rove th—tD for —ny list lsD plistOut @plistIn ls A a lsF „his should ˜e the only p—rt of the exer™ise where you use t—™ti™E˜—sed provingF @fA he(ne — fun™tion grab X ∀ n @ls X plist @S nAAD sig P F „h—t isD when given — plist gu—r—nteed to ™ont—in —t le—st one element s—tisfying P D grab produ™es su™h IQQ —n elementF sig is the type f—mily of sigm— typesD —nd sig P is extension—lly equiv—lent to {x X A | P x }D though the l—tter form uses —n et—Eexp—nsion of P inste—d of P itself —s the predi™—teF IQR Chapter 8 Dependent Data Structures yur redE˜l—™k tree ex—mple from the l—st ™h—pter illustr—ted how dependent types en—˜le st—ti™ enfor™ement of d—t— stru™ture inv—ri—ntsF „o (nd interesting uses of dependent d—t— stru™turesD howeverD we need not look to the f—vorite ex—mples of d—t— stru™tures —nd —lgoE rithms text˜ooksF wore ˜—si™ ex—mples like lengthEindexed —nd heterogeneous lists ™ome up —g—in —nd —g—in —s the ˜uilding ˜lo™ks of dependent progr—msF „here is — surprisingly l—rge design sp—™e for this ™l—ss of d—t— stru™tureD —nd we will spend this ™h—pter exploring itF 8.1 More Length-Indexed Lists ‡e ˜egin with — deeper look —t the lengthEindexed lists th—t ˜eg—n the l—st ™h—pterF Section ilistF Variable A X SetF Inductive ilist X nat → Set Xa | Nil X ilist O | Cons X ∀ nD A → ilist n → ilist @S n AF ‡e might like to h—ve — ™erti(ed fun™tion for sele™ting —n element of —n ilist ˜y positionF ‡e ™ould do this using su˜set types —nd expli™it m—nipul—tion of proofsD ˜ut dependent types let us do it more dire™tlyF st is helpful to de(ne — type f—mily nD where n n is isomorphi™ to {m X nat | m ` n}F „he type f—mily n—mes st—nds for 4(niteF4 Inductive n X nat → Set Xa | First X ∀ nD n @S n A | Next X ∀ nD n n → n @S n AF n essenti—lly m—kes — more ri™hlyEtyped ™opy of the n—tur—l num˜ersF ivery element is — First iter—ted through —pplying Next — num˜er of times th—t indi™—tes whi™h num˜er is ˜eing sele™tedF xow it is e—sy to pi™k — PropEfree type for — sele™tion fun™tionF es usu—lD our (rst implement—tion —ttempt will not ™onvin™e the type ™he™kerD —nd we will —tt—™k the de(™ien™ies IQS one —t — timeF Fixpoint get n @ls X ilist nA X n n → match ls with | Nil ⇒ fun idx ⇒ c | Cons x ls' ⇒ fun idx ⇒ match idx with | First ⇒ x | Next idx' ⇒ get ls' idx' end endF A Xa ‡e —pply the usu—l wisdom of del—ying —rguments in Fixpoints so th—t they m—y ˜e in™luded in return ™l—usesF „his still le—ves us with — qu—nd—ry in e—™h of the match ™—sesF pirstD we need to (gure out how to t—ke —dv—nt—ge of the ™ontr—di™tion in the Nil ™—seF ivery n h—s — type of the form S nD whi™h ™—nnot unify with the O v—lue th—t we le—rn for n in the Nil ™—seF „he solution we —dopt is —nother ™—se of matchEwithinEreturnF Fixpoint get n @ls X ilist nA X n n → A Xa match ls with | Nil ⇒ fun idx ⇒ match idx in n n' return @match n' with |O⇒A | S ⇒ unit endA with | First ⇒ tt | Next ⇒ tt end | Cons x ls' ⇒ fun idx ⇒ match idx with | First ⇒ x | Next idx' ⇒ get ls' idx' end endF xow the (rst match ™—se typeE™he™ksD —nd we see th—t the pro˜lem with the Cons ™—se is th—t the p—tternE˜ound v—ri—˜le idx' does not h—ve —n —pp—rent type ™omp—ti˜le with ls'F ‡e need to use match —nnot—tions to m—ke the rel—tionship expli™itF …nfortun—telyD the usu—l tri™k of postponing —rgument ˜inding will not help us hereF ‡e need to m—t™h on ˜oth ls —nd idx Y one or the other must ˜e m—t™hed (rstF „o get —round thisD we —pply the ™onvoy p—ttern th—t we met l—st ™h—pterF „his —ppli™—tion is — little more ™lever th—n those we s—w ˜eforeY we use the n—tur—l num˜er prede™essor fun™tion pred to express the rel—tionship IQT ˜etween the types of these v—ri—˜lesF Fixpoint get n @ls X ilist nA X n n → A Xa match ls with | Nil ⇒ fun idx ⇒ match idx in n n' return @match n' with |O⇒A | S ⇒ unit endA with | First ⇒ tt ⇒ tt | Next end | Cons x ls' ⇒ fun idx ⇒ match idx in n n' return ilist @pred n' A → A with | First ⇒ fun ⇒ x | Next idx' ⇒ fun ls' ⇒ get ls' idx' end ls' endF „here is just one pro˜lem left with this implement—tionF „hough we know th—t the lo™—l ls' in the Next ™—se is equ—l to the origin—l ls'D the typeE™he™ker is not s—tis(ed th—t the re™ursive ™—ll to get does not introdu™e nonEtermin—tionF ‡e solve the pro˜lem ˜y ™onvoyE ˜inding the p—rti—l —ppli™—tion of get to ls'D r—ther th—n ls' ˜y itselfF Fixpoint get n @ls X ilist n A X n n → A Xa match ls with | Nil ⇒ fun idx ⇒ match idx in n n' return @match n' with |O⇒A | S ⇒ unit endA with | First ⇒ tt | Next ⇒ tt end | Cons x ls' ⇒ fun idx ⇒ match idx in n n' return @n @pred n' A → AA → | First ⇒ fun ⇒ x | Next idx' ⇒ fun get ls' ⇒ get ls' idx' end @get ls' A endF End ilistF Implicit Arguments Implicit Arguments Nil ‘A“F First ‘n “F IQU A with e few ex—mples show how to m—ke use of these de(nitionsF Check Cons Cons X H @Cons I @Cons P H @Cons I @Cons P ilist nat Q Eval simpl in aH X nat Eval simpl in aI X nat Eval simpl in aP X nat NilAAF NilAA get @Cons H @Cons I @Cons P NilAAA FirstF get @Cons H @Cons I @Cons P NilAAA @Next get @Cons H @Cons I @Cons P NilAAA @Next @Next FirstAF FirstAAF yur get fun™tion is —lso quite e—sy to re—son —˜outF ‡e show how with — short ex—mple —˜out —n —n—logue to the list map fun™tionF Section ilist mapF Variables A B X SetF Variable f X A → BF Fixpoint imap n @ls X ilist A n A X ilist B n Xa match ls with | Nil ⇒ Nil | Cons x ls' ⇒ Cons @f x A @imap ls' A endF st is e—sy to prove th—t get 4distri˜utes over4 imap ™—llsF „he only tri™ky ˜it is rememE ˜ering to use the dep destruct t—™ti™ in pl—™e of pl—in destruct when f—™ed with — ˜—1ing t—™ti™ error mess—geF Theorem get imap X ∀ n @idx X n n A @ls X ilist get @imap ls A idx a f @get ls idx AF induction ls Y dep destruct idx Y crushF QedF End ilist mapF A n AD 8.2 Heterogeneous Lists €rogr—mmers who move to st—ti™—llyEtyped fun™tion—l l—ngu—ges from 4s™ripting l—ngu—ges4 often ™ompl—in —˜out the requirement th—t every element of — list h—ve the s—me typeF ‡ith fn™y type systemsD we ™—n p—rti—lly lift this requirementF ‡e ™—n index — list type with — 4typeElevel4 list th—t expl—ins wh—t type e—™h element of the list should h—veF „his h—s ˜een IQV done in — v—riety of w—ys in r—skell using type ™l—ssesD —nd we ™—n do it mu™h more ™le—nly —nd dire™tly in goqF Section hlistF Variable A X TypeF Variable B X A → TypeF ‡e p—r—meterize our heterogeneous lists ˜y — type Inductive hlist X list A → Type Xa | MNil X hlist nil | MCons X ∀ @x X AA @ls X list AAD B x → hlist ls → A —nd —n AEindexed type BF hlist @x XX ls AF ‡e ™—n implement — v—ri—nt of the l—st se™tion9s get fun™tion for hlistsF „o get the dependent typing to work outD we will need to index our element sele™tors ˜y the types of d—t— th—t they point toF Variable elm X AF Inductive member X list A → Type Xa | MFirst X ∀ lsD member @elm XX ls A | MNext X ∀ x lsD member ls → member @x XX ls AF fe™—use the element elm th—t we —re 4se—r™hing for4 in — list does not ™h—nge —™ross the ™onstru™tors of memberD we simplify our de(nitions ˜y m—king elm — lo™—l v—ri—˜leF sn the de(nition of memberD we s—y th—t elm is found in —ny list th—t ˜egins with elm D —ndD if removing the (rst element of — list le—ves elm presentD then elm is present in the origin—l listD tooF „he form looks mu™h like — predi™—te for list mem˜ershipD ˜ut we purposely de(ne member in Type so th—t we m—y de™ompose its v—lues to guide ™omput—tionsF ‡e ™—n use member to —d—pt our de(nition of get to hlistsF „he s—me ˜—si™ match tri™ks —pplyF sn the MCons ™—seD we form — twoEelement ™onvoyD p—ssing ˜oth the d—t— element x —nd the re™ursor for the su˜list mls' to the result of the inner matchF ‡e did not need to do th—t in get9s de(nition ˜e™—use the types of list elements were not dependent thereF Fixpoint hget ls @mls X hlist ls A X member ls → B elm Xa match mls with | MNil ⇒ fun mem ⇒ match mem in member ls' return @match ls' with | nil ⇒ B elm | XX ⇒ unit endA with | MFirst ⇒ tt | MNext ⇒ tt end | MCons x mls' ⇒ fun mem ⇒ match mem in member ls' return @match ls' with | nil ⇒ Empty set | x' XX ls ⇒ IQW → @member ls → B endA with B x' End endF | MFirst ⇒ fun x ⇒ x | MNext mem' ⇒ fun end x @hget mls' A get mls' ⇒ elm A →B elm get mls' mem' hlistF Implicit Arguments Implicit Arguments MNil ‘A B “F Implicit Arguments Implicit Arguments MFirst ‘A elm ls “F MCons ‘A B x ls “F MNext ‘A elm x ls “F fy putting the p—r—meters A —nd B in TypeD we —llow some very higherEorder usesF por inst—n™eD one use of hlist is for the simple heterogeneous lists th—t we referred to e—rlierF Definition Example MCons someTypes someValues S @MCons X X list Set Xa nat XX bool XX nilF hlist @fun T X Set ⇒ T A someTypes Xa true MNilAF Eval simpl in hget someValues MFirstF aS X @fun T X Set ⇒ T A nat Eval simpl in hget someValues @MNext a true X @fun T X Set ⇒ T A bool MFirstAF ‡e ™—n —lso ˜uild indexed lists of p—irs in this w—yF Example MCons somePairs X hlist @fun T X Set ⇒ T × T A7type someTypes Xa @ID PA @MCons @trueD falseA MNilAF 8.2.1 A Lambda Calculus Interpreter reterogeneous lists —re very useful in implementing interpreters for fun™tion—l progr—mming l—ngu—gesF …sing the types —nd oper—tions we h—ve —lre—dy de(nedD it is trivi—l to write —n interpreter for simplyEtyped l—m˜d— ™—l™ulusF yur interpreter ™—n —ltern—tively ˜e thought of —s — denot—tion—l sem—nti™sF ‡e st—rt with —n —lge˜r—i™ d—t—type for typesF Inductive type X Set Xa | Unit X type | Arrow X type → type → typeF xow we ™—n de(ne — type f—mily for expressionsF en exp ts t will st—nd for —n expression th—t h—s type t —nd whose free v—ri—˜les h—ve types in the list tsF ‡e e'e™tively use the IRH de fruijn v—ri—˜le represent—tionD whi™h we will dis™uss in more det—il in l—ter ™h—ptersF †ri—˜les —re represented —s member v—luesY th—t isD — v—ri—˜le is more or less — ™onstru™tive proof th—t — p—rti™ul—r type is found in the type environmentF Inductive exp X list type → type → Set Xa | Const X ∀ tsD exp ts Unit | | | X ∀ ts tD member t ts → exp ts t App X ∀ ts dom ranD exp ts @Arrow dom ran A → Abs X ∀ ts dom ranD exp @dom XX ts A ran → exp Var Implicit Arguments exp ts ts dom @Arrow → exp ts ran dom ran AF Const ‘ts “F ‡e write — simple re™ursive fun™tion to tr—nsl—te Fixpoint typeDenote @t X typeA X Set Xa match t with | Unit ⇒ unit | Arrow t1 t2 ⇒ typeDenote t1 → typeDenote endF types into SetsF t2 xow it is str—ightforw—rd to write —n expression interpreterF „he type of the fun™tionD expDenoteD tells us th—t we tr—nsl—te expressions into fun™tions from properlyEtyped environE ments to (n—l v—luesF en environment for — free v—ri—˜le list ts is simply — hlist typeDenote tsF „h—t isD for e—™h free v—ri—˜leD the heterogeneous list th—t is the environment must h—ve — v—lue of the v—ri—˜le9s —sso™i—ted typeF ‡e use hget to implement the Var ™—seD —nd we use MCons to extend the environment in the Abs ™—seF Fixpoint expDenote ts t @e X exp match e with | Const ⇒ fun ⇒ tt | Var | App | Abs endF ts t A X hlist typeDenote ts → typeDenote t Xa ⇒ fun s ⇒ hget s mem e1 e2 ⇒ fun s ⇒ @expDenote e1 s A @expDenote e2 s A e' ⇒ fun s ⇒ fun x ⇒ expDenote e' @MCons x s A mem vike for previous ex—mplesD our interpreter is e—sy to run with simplF Eval simpl in expDenote a tt X typeDenote Unit Const MNilF Eval simpl in expDenote @Abs @dom Xa a fun x X unit ⇒ x X typeDenote @Arrow Unit UnitA UnitA @Var MFirstAA MNilF Eval simpl in expDenote @Abs @dom Xa UnitA @Abs @dom Xa UnitA @Var @MNext MFirstAAAA MNilF IRI a fun x X unit ⇒ X typeDenote @Arrow x Unit @Arrow Unit UnitAA Eval simpl in expDenote @Abs @dom Xa UnitA @Abs @dom Xa a fun x0 X unit ⇒ x0 X typeDenote @Arrow Unit @Arrow Unit UnitAA Eval simpl in expDenote @App @Abs @Var a tt X typeDenote Unit UnitA @Var MFirstAAA MNilF MFirstAA ConstA MNilF ‡e —re st—rting to develop the tools ˜ehind dependent typing9s —m—zing —dv—nt—ge over —ltern—tive —ppro—™hes in sever—l import—nt —re—sF rereD we h—ve implemented ™omplete synt—xD typing rulesD —nd ev—lu—tion sem—nti™s for simplyEtyped l—m˜d— ™—l™ulus without even needing to de(ne — synt—™ti™ su˜stitution oper—tionF ‡e did it —ll without — single line of proofD —nd our implement—tion is m—nifestly exe™ut—˜leF sn — l—ter ™h—pterD we will meet otherD more ™ommon —ppro—™hes to l—ngu—ge form—liz—tionF ƒu™h —ppro—™hes often st—te —nd prove expli™it theorems —˜out type s—fety of l—ngu—gesF sn the —˜ove ex—mpleD we got type s—fetyD termin—tionD —nd other met—Etheorems for freeD ˜y redu™tion to gsgD whi™h we know h—s those propertiesF 8.3 Recursive Type Denitions „here is —nother style of d—t—type de(nition th—t le—ds to mu™h simpler de(nitions of the get —nd hget de(nitions —˜oveF fe™—use goq supports 4typeElevel ™omput—tionD4 we ™—n redo our indu™tive de(nitions —s recursive de(nitionsF Section listF Variable A X SetF Fixpoint list @n X natA X Set Xa match n with | O ⇒ unit | S n' ⇒ A × list n' end7typeF ‡e s—y th—t — list of length H h—s no ™ontentsD —nd — list of length v—lue —nd — list of length n'F Fixpoint n @n X natA X Set Xa match n with | O ⇒ Empty set | S n' ⇒ option @n n' A endF IRP S n' is — p—ir of — d—t— ‡e express th—t there —re no index v—lues when n a OD ˜y de(ning su™h indi™es —s type Empty setY —nd we express th—tD —t n a S n'D there is — ™hoi™e ˜etween pi™king the (rst element of the list @represented —s NoneA or ™hoosing — l—ter element @represented ˜y Some idxD where idx is —n index into the list t—ilAF Fixpoint fget @n X natA X list n → n n → match n with | O ⇒ fun idx ⇒ match idx with end | S n' ⇒ fun ls idx ⇒ match idx with | None ⇒ fst ls | Some idx' ⇒ fget n' @snd ls A idx' end endF A Xa yur new get implement—tion needs only one dependent matchD —nd its —nnot—tion is inferred for usF yur ™hoi™es of d—t— stru™ture implement—tions le—d to just the right typing ˜eh—vior for this new de(nition to work outF End listF reterogeneous lists —re — little tri™kier to de(ne with re™ursionD ˜ut we then re—p simil—r ˜ene(ts in simpli™ity of useF Section fhlistF Variable A X TypeF Variable B X A → TypeF Fixpoint fhlist @ls X list AA X Type Xa match ls with | nil ⇒ unit | x XX ls' ⇒ B x × fhlist ls' end7typeF „he de(nition of fhlist follows the de(nition of listD with the —dded wrinkle of dependentlyE typed d—t— elementsF Variable elm X AF Fixpoint fmember @ls X list AA X Type Xa match ls with | nil ⇒ Empty set | x XX ls' ⇒ @x a elm A C fmember ls' end7typeF „he de(nition of fmember follows the de(nition of nF impty lists h—ve no mem˜ersD —nd mem˜er types for nonempty lists —re ˜uilt ˜y —dding one new option to the type of mem˜ers of the list t—ilF ‡hile for index we needed no new inform—tion —sso™i—ted with the option th—t we —ddD here we need to know th—t the he—d of the list equ—ls the element we IRQ —re se—r™hing forF ‡e express th—t with — sum type whose left ˜r—n™h is the —ppropri—te equ—lity propositionF ƒin™e we de(ne fmember to live in TypeD we ™—n insert Prop types —s neededD ˜e™—use Prop is — su˜type of TypeF ‡e know —ll of the tri™ks needed to write — (rst —ttempt —t — get fun™tion for fhlistsF Fixpoint fhget @ls X list AA X fhlist ls → fmember match ls with | nil ⇒ fun idx ⇒ match idx with end | XX ls' ⇒ fun mls idx ⇒ match idx with | inl ⇒ fst mls | inr idx' ⇒ fhget ls' @snd mls A idx' end endF ls → B elm Xa ynly one pro˜lem rem—insF „he expression fst mls is not known to h—ve the proper typeF „o demonstr—te th—t it doesD we need to use the proof —v—il—˜le in the inl ™—se of the inner matchF Fixpoint fhget @ls X list AA X fhlist ls → fmember match ls with | nil ⇒ fun idx ⇒ match idx with end | XX ls' ⇒ fun mls idx ⇒ match idx with | inl pf ⇒ match pf with | re equal ⇒ fst mls end | inr idx' ⇒ fhget ls' @snd mls A idx' end endF ls → B elm Xa fy p—tternEm—t™hing on the equ—lity proof pfD we m—ke th—t equ—lity known to the typeE ™he™kerF ix—™tly why this works ™—n ˜e seen ˜y studying the de(nition of equ—lityF Print eqF Inductive eq @A X TypeA @x X AA X A → Prop Xa re equal X x a x sn — proposition x a yD we see th—t x is — p—r—meter —nd y is — regul—r —rgumentF „he type of the ™onstru™tor re equal shows th—t y ™—n only ever ˜e inst—nti—ted to x F „husD within — p—tternEm—t™h with re equalD o™™urren™es of y ™—n ˜e repl—™ed with o™™urren™es of x for typing purposesF End fhlistF Implicit Arguments fhget ‘A B elm ls “F IRR 8.4 Data Structures as Index Functions sndexed lists ™—n ˜e useful in de(ning other indu™tive types with ™onstru™tors th—t t—ke v—riE —˜le num˜ers of —rgumentsF sn this se™tionD we ™onsider p—r—meterized trees with —r˜itr—ry ˜r—n™hing f—™torF Section treeF Variable A X SetF Inductive tree X Set Xa | Leaf X A → tree | Node X ∀ nD ilist tree n → treeF End treeF ivery Node of — tree h—s — n—tur—l num˜er —rgumentD whi™h gives the num˜er of ™hild trees in the se™ond —rgumentD typed with ilistF ‡e ™—n de(ne two oper—tions on trees of n—tur—lsX summing their elements —nd in™rementing their elementsF st is useful to de(ne — generi™ fold fun™tion on ilists (rstF Section ifoldrF Variables A B X SetF Variable f X A → B → BF Variable i X BF Fixpoint ifoldr n @ls X ilist A n A X B Xa match ls with | Nil ⇒ i | Cons x ls' ⇒ f x @ifoldr ls' A endF End ifoldrF Fixpoint sum @t X tree natA X nat Xa match t with | Leaf n ⇒ n | Node ls ⇒ ifoldr @fun t' n ⇒ sum endF t' C nA O ls Fixpoint inc @t X tree natA X tree nat Xa match t with | Leaf n ⇒ Leaf @S n A | Node ls ⇒ Node @imap inc ls A endF xow we might like to prove th—t Theorem sum inc X ∀ tD induction t Y crushF sum inc @inc t A ≥ does not de™re—se — tree9s sum tF IRS sumF nat i X ilist @tree natA n n X aaaaaaaaaaaaaaaaaaaaaaaaaaaa ifoldr @fun @t' X tree natA @n0 X natA ⇒ sum t' C ifoldr @fun @t' X tree natA @n0 X natA ⇒ sum t' C n0 A H @imap n0 A H i inc iA ≥ ‡e —re left with — single su˜go—l whi™h does not seem prov—˜le dire™tlyF „his is the s—me pro˜lem th—t we met in gh—pter Q with other nested indu™tive typesF Check tree indF tree ind X ∀ @A X SetA @P X tree A → PropAD @∀ a X AD P @Leaf a AA → @∀ @n X natA @i X ilist @tree AA nAD ∀ t X tree AD P t P @Node iAA → „he —utom—ti™—llyEgener—ted indu™tion prin™iple is too we—kF por the Node ™—seD it gives us no indu™tive hypothesisF ‡e ™ould write our own indu™tion prin™ipleD —s we did in gh—pter QD ˜ut there is —n e—sier w—yD if we —re willing to —lter the de(nition of treeF AbortF Reset treeF pirstD let us try using our re™ursive de(nition of ilists inste—d of the indu™tive versionF Section treeF Variable A X SetF Inductive tree X Set Xa | Leaf X A → tree | Node X ∀ nD list tree n → treeF Error X Non strictly positive occurrence of 4for—ll n X n—tD (list tree n → tree4 4tree4 in „he spe™i—lE™—se rule for nested d—t—types only works with nested uses of other indu™tive typesD whi™h ™ould ˜e repl—™ed with uses of new mutu—llyEindu™tive typesF ‡e de(ned list re™ursivelyD so it m—y not ˜e used for nested re™ursionF yur (n—l solution uses yet —nother of the indu™tive de(nition te™hniques introdu™ed in gh—pter QD re)exive typesF snste—d of merely using n to get elements out of ilistD we ™—n dene ilist in terms of nF por the re—sons outlined —˜oveD it turns out to ˜e e—sier to work with n in pl—™e of nF Inductive tree X Set Xa | Leaf X A → tree | Node X ∀ nD @n n → treeA → treeF IRT e Node is indexed ˜y — n—tur—l num˜er nD —nd the node9s n ™hildren —re represented —s — fun™tion from n n to treesD whi™h is isomorphi™ to the ilistE˜—sed represent—tion th—t we used —˜oveF End treeF Implicit Arguments Node ‘A n “F ‡e ™—n rede(ne sum —nd inc for our new tree typeF eg—inD it is useful to de(ne — generi™ fold fun™tion (rstF „his timeD it t—kes in — fun™tion whose r—nge is some n typeD —nd it folds —nother fun™tion over the results of ™—lling the (rst fun™tion —t every possi˜le n v—lueF Section rifoldrF Variables A B X SetF Variable f X A → B → BF Variable i X BF Fixpoint rifoldr @n X natA X @n n → AA → B Xa match n with | O ⇒ fun ⇒ i | S n' ⇒ fun get ⇒ f @get NoneA @rifoldr n' @fun endF End rifoldrF Implicit Arguments idx ⇒ get @Some idx AAA rifoldr ‘A B n “F Fixpoint sum @t X tree natA X nat Xa match t with | Leaf n ⇒ n | Node f ⇒ rifoldr plus O @fun idx ⇒ endF Fixpoint inc @t X tree natA X tree nat Xa match t with | Leaf n ⇒ Leaf @S n A | Node f ⇒ Node @fun idx ⇒ inc @f endF sum @f idx AA idx AA xow we —re re—dy to prove the theorem where we got stu™k ˜eforeF ‡e will not need to de(ne —ny new indu™tion prin™ipleD ˜ut it will ˜e helpful to prove some lemm—sF Lemma plus ge X ∀ x1 y1 x2 x1 ≥ x2 → y1 ≥ y2 → x1 C y1 ≥ x2 C y2F crushF QedF y2D Lemma sum inc' X ∀ n @f1 f2 X @∀ idxD f1 idx ≥ f2 idx A n n → natAD IRU → rifoldr plus H f1 ≥ rifoldr Hint Resolve plus geF induction n Y QedF plus H f2F crushF Theorem sum inc X ∀ tD sum @inc t A ≥ Hint Resolve sum inc'F induction t Y QedF sum tF crushF iven if goq would gener—te ™omplete indu™tion prin™iples —utom—ti™—lly for nested inE du™tive de(nitions like the one we st—rted withD there would still ˜e —dv—nt—ges to using this style of re)exive en™odingF ‡e see one of those —dv—nt—ges in the de(nition of incD where we did not need to use —ny kind of —uxili—ry fun™tionF sn gener—lD re)exive en™odings often —dmit dire™t implement—tions of oper—tions th—t would require re™ursion if performed with more tr—dition—l indu™tive d—t— stru™turesF 8.4.1 Another Interpreter Example ‡e develop —nother ex—mple of v—ri—˜leE—rity ™onstru™torsD in the form of optimiz—tion of — sm—ll expression l—ngu—ge with — ™onstru™t like ƒ™heme9s condF i—™h of our ™ondition—l expressions t—kes — list of p—irs of ˜oole—n tests —nd ˜odiesF „he v—lue of the ™ondition—l ™omes from the ˜ody of the (rst test in the list to ev—lu—te to trueF „o simplify the interpreter we will writeD we for™e e—™h ™ondition—l to in™lude — (n—lD def—ult ™—seF Inductive type' X Type Xa Nat | BoolF Inductive exp' X type' → Type Xa | NConst X nat → exp' Nat | Plus X exp' Nat → exp' Nat → exp' Nat | Eq X exp' Nat → exp' Nat → exp' Bool | BConst | Cond bool → exp' Bool X X∀ → @n n tD n → @n exp' → exp' BoolA t A → exp' t → exp' tF n e Cond is p—r—meterized ˜y — n—tur—l nD whi™h tells us how m—ny ™—ses this ™ondition—l h—sF „he test expressions —re represented with — fun™tion of type n n → exp' BoolD —nd the ˜odies —re represented with — fun™tion of type n n → exp' t D where t is the over—ll typeF „he (n—l exp' t —rgument is the def—ult ™—seF ‡e st—rt implementing our interpreter with — st—nd—rd type denot—tion fun™tionF Definition type'Denote @t X type'A X Set Xa match t with | Nat ⇒ nat IRV | Bool ⇒ endF bool „o implement the expression interpreterD it is useful to h—ve the following fun™tion th—t implements the fun™tion—lity of Cond without involving —ny synt—xF Section condF Variable A X SetF Variable default X AF Fixpoint cond @n X natA X @n n → boolA → @n n → AA → A Xa match n with ⇒ default | O ⇒ fun | S n' ⇒ fun tests bodies ⇒ if tests None then bodies None else cond n' @fun idx ⇒ tests @Some idx AA @fun idx ⇒ bodies @Some idx AA endF End condF Implicit Arguments cond ‘A n “F xow the expression interpreter is str—ightforw—rd to writeF Fixpoint exp'Denote t @e X exp' t A X type'Denote t Xa match e with | NConst n ⇒ n | Plus e1 e2 ⇒ exp'Denote e1 C exp'Denote e2 | Eq e1 e2 ⇒ if eq nat dec @exp'Denote e1 A @exp'Denote e2 A then true else false | | BConst b ⇒ Cond tests bodies default b ⇒ cond @exp'Denote @fun idx ⇒ @fun idx ⇒ default A exp'Denote exp'Denote @tests idx AA @bodies idx AA endF ‡e will implement — ™onst—ntEfolding fun™tion th—t optimizes ™ondition—lsD removing ™—ses with knownEfalse tests —nd ™—ses th—t ™ome —fter knownEtrue testsF e fun™tion cfoldCond implements the he—rt of this logi™F „he ™onvoy p—ttern is used —g—in ne—r the end of the implement—tionF Section cfoldCondF IRW type'F default X exp' tF Fixpoint cfoldCond @n X natA X @n n → exp' BoolA → @n n → exp' t A → exp' t Xa Variable Variable t X match n with ⇒ default | O ⇒ fun | S n' ⇒ fun tests bodies ⇒ match tests None return with | BConst true ⇒ bodies None | BConst false ⇒ cfoldCond n' @fun idx ⇒ tests @Some idx AA @fun idx ⇒ bodies @Some idx AA |⇒ let e Xa cfoldCond n' @fun idx ⇒ tests @Some idx AA @fun idx ⇒ bodies @Some idx AA in match e in exp' t return exp' t → exp' t with | Cond n tests' bodies' default' ⇒ fun body ⇒ Cond @S n A @fun idx ⇒ match idx with | None ⇒ tests None | Some idx ⇒ tests' idx endA @fun idx ⇒ match idx with | None ⇒ body | Some idx ⇒ bodies' idx endA default' | e ⇒ fun body ⇒ Cond I @fun @fun ⇒ ⇒ tests NoneA body A e End endF end end @bodies NoneA cfoldCondF Implicit Arguments cfoldCond ‘t n “F vike for the interpretersD most of the —™tion w—s in this helper fun™tionD —nd is e—sy to writeF ISH cfold itself Fixpoint cfold t @e X exp' t A X exp' t Xa match e with | NConst n ⇒ NConst n | Plus e1 e2 ⇒ let e1' Xa cfold e1 in let e2' Xa cfold e2 in match e1'D e2' return with | NConst n1D NConst n2 ⇒ NConst @n1 C | D ⇒ Plus e1' e2' end | Eq e1 e2 ⇒ let e1' Xa cfold e1 in let e2' Xa cfold e2 in match e1'D e2' return with | NConst n1D NConst n2 ⇒ BConst @if eq | D ⇒ Eq e1' e2' end | | BConst b ⇒ Cond tests bodies default n2 A nat dec n1 n2 then true else falseA BConst b ⇒ cfoldCond @cfold default A @fun idx ⇒ cfold @tests idx AA @fun idx ⇒ cfold @bodies idx AA endF „o prove our (n—l ™orre™tness theoremD it is useful to know th—t cfoldCond preserves expression me—ningsF „his lemm— form—lizes th—t propertyF „he proof is — st—nd—rd mostlyE —utom—ted oneD with the only wrinkle ˜eing — guided inst—nt—tion of the qu—nti(ers in the indu™tion hypothesisF Lemma cfoldCond correct X ∀ t @default X exp' t A n @tests X n n → exp' BoolA @bodies X n n → exp' t AD exp'Denote @cfoldCond default tests bodies A a exp'Denote @Cond n tests bodies default AF induction n Y crush Y match goal with | ‘ IHn X ∀ tests bodiesD D tests X → D bodies X → generalize @IHn @fun idx ⇒ tests @Some idx AA @fun clear IHn Y intro IHn endY repeat @match goal with ISI idx “⇒ ⇒ bodies @Some idx AAAY ci with | NConst ⇒ | Plus ⇒ | Eq ⇒ | BConst ⇒ | Cond ⇒ end“ “ ⇒ dep destruct E | ‘ context ‘if cf then else “ “ ⇒ destruct endY crush AF |‘ QedF context ‘match B st is —lso useful to know th—t the result of — ™—ll to cond is not ™h—nged ˜y su˜stituting new tests —nd ˜odies fun™tionsD so long —s the new fun™tions h—ve the s—me inputEoutput ˜eh—vior —s the oldF st turns out th—tD in goqD it is not possi˜le to prove in gener—l th—t fun™tions rel—ted in this w—y —re equ—lF ‡e tre—t this issue with our dis™ussion of —xioms in — l—ter ™h—pterF por nowD it su0™es to prove th—t the p—rti™ul—r fun™tion cond is extensional Y th—t isD it is un—'e™ted ˜y su˜stitution of fun™tions with inputEoutput equiv—lentsF Lemma cond ext X ∀ @A X SetA @default X AA n @tests tests' X @bodies bodies' X n n → AAD @∀ idxD tests idx a tests' idx A → @∀ idxD bodies idx a bodies' idx A → cond default tests bodies a cond default tests' bodies'F induction n Y crush Y match goal with | ‘ context ‘if ci then else “ “ ⇒ destruct E endY crushF QedF n n → boolA xow the (n—l theorem is e—sy to proveF ‡e —dd our two lemm—s —s hints —nd perform st—nd—rd —utom—tion with p—tternEm—t™hing of su˜terms to destru™tF X ∀ t @e X exp' t AD exp'Denote @cfold e A a exp'Denote eF Hint Rewrite cfoldCond correct X cpdtF Hint Resolve cond extF Theorem cfold correct induction e Y crush Y repeat @match goal with | ‘ context ‘cfold ci“ “ ⇒ endY crush AF QedF dep destruct ISP @cfold EA 8.5 Choosing Between Representations st is not —lw—ys ™le—r whi™h of these represent—tion te™hniques to —pply in — p—rti™ul—r situ—tionD ˜ut s will try to summ—rize the pros —nd ™ons of e—™hF sndu™tive types —re often the most ple—s—nt to work withD —fter someone h—s spent the time implementing some ˜—si™ li˜r—ry fun™tions for themD using f—n™y match —nnot—tionsF w—ny —spe™ts of goq9s logi™ —nd t—™ti™ support —re spe™i—lized to de—l with indu™tive typesD —nd you m—y miss out if you use —ltern—te en™odingsF ‚e™ursive types usu—lly involve mu™h less initi—l e'ortD ˜ut they ™—n ˜e less ™onvenient to use with proof —utom—tionF por inst—n™eD the simpl t—™ti™ @whi™h is —mong the ingredients in crush A will sometimes ˜e overze—lous in simplifying uses of fun™tions over re™ursive typesF gonsider — ™—ll get l f D where v—ri—˜le l h—s type list A @S nAF „he type of l would ˜e simpli(ed to —n expli™it p—ir typeF sn — proof involving m—ny re™ursive typesD this kind of unhelpful 4simpli(™—tion4 ™—n le—d to r—pid ˜lo—t in the sizes of su˜go—lsF enother dis—dv—nt—ge of re™ursive types is th—t they only —pply to type f—milies whose indi™es determine their 4skeletonsF4 „his is not true for —ll d—t— stru™turesY — good ™ounE terex—mple ™omes from the ri™hlyEtyped progr—mming l—ngu—ge synt—x types we h—ve used sever—l times so f—rF „he f—™t th—t — pie™e of synt—x h—s type Nat tells us nothing —˜out the tree stru™ture of th—t synt—xF ‚e)exive en™odings of d—t— types —re seen rel—tively r—relyF es our ex—mples demonE str—tedD m—nipul—ting index v—lues m—nu—lly ™—n le—d to h—rdEtoEre—d ™odeF e norm—l inE du™tive type is gener—lly e—sier to work withD on™e someone h—s gone through the trou˜le of implementing —n indu™tion prin™iple m—nu—lly with the te™hniques we studied in gh—pE ter QF por sm—ll developmentsD —voiding th—t kind of ™oding ™—n justify the use of re)exive d—t— stru™turesF „here —re —lso some useful inst—n™es of ™oEindu™tive de(nitions with nested d—t— stru™tures @eFgFD lists of v—lues in the ™oEindu™tive typeA th—t ™—n only ˜e de™onstru™ted e'e™tively with re)exive en™oding of the nested stru™turesF 8.6 Exercises ƒome of the type f—mily de(nitions —nd —sso™i—ted fun™tions from this ™h—pter —re dupli™—ted in the DepList module of the ˜ook sour™eF ƒome of their n—mes h—ve ˜een ™h—nged to ˜e more sensi˜le in — gener—l ™ontextF IF he(ne — tree —n—logue of hlistF „h—t isD de(ne — p—r—meterized type of ˜in—ry trees with d—t— —t their le—vesD —nd de(ne — type f—mily htree indexed ˜y treesF „he stru™ture of —n htree mirrors its index treeD with the type of e—™h d—t— element @whi™h only o™™ur —t le—vesA determined ˜y —pplying — type fun™tion to the ™orresponding element of the index treeF he(ne — type st—nding for —ll possi˜le p—ths from the root of — tree to le—ves —nd use it to implement — fun™tion tget for extr—™ting —n element of —n htree ˜y p—thF he(ne — fun™tion htmap2 for 4m—pping over two trees in p—r—llelF4 „h—t isD ISQ t—kes in two htree s with the s—me index treeD —nd it forms — new the s—me index ˜y —pplying — ˜in—ry fun™tion pointwiseF htmap2 htree with ‚epe—t this pro™ess so th—t you implement e—™h de(nition for e—™h of the three de(niE tion styles ™overed in this ™h—pterX indu™tiveD re™ursiveD —nd index fun™tionF PF ‡rite — dependentlyEtyped interpreter for — simple progr—mming l—ngu—ge with wvE style p—tternEm—t™hingD using one of the en™odings of heterogeneous lists to represent the di'erent ˜r—n™hes of — case expressionF @„here —re other w—ys to represent the s—me thingD ˜ut the point of this exer™ise is to pr—™ti™e using those heterogeneous list typesFA „he o˜je™t l—ngu—ge is de(ned inform—lly ˜y this gr—mm—rX t p e XXa bool | t C t XXa x | b | inl p | inr p XXa x | b | inl e | inr e | case e of ‘p ⇒ e“B | ⇒ e st—nds for — v—ri—˜leD —nd b st—nds for — ˜oole—n ™onst—ntF „he produ™tion for case expressions me—ns th—t — p—tternEm—t™h in™ludes zero or more p—irs of p—tterns —nd expressionsD —long with — def—ult ™—seF ‰our interpreter should ˜e implemented in the style demonstr—ted in this ™h—pterF „h—t isD your de(nition of expressions should use dependent types —nd de fruijn indi™es to ™om˜ine synt—x —nd typing rulesD su™h th—t the type of —n expression tells the types of v—ri—˜les th—t —re in s™opeF ‰ou should implement — simple re™ursive fun™tion tr—nsl—ting types t to SetD —nd your interpreter should produ™e v—lues in the im—ge of this tr—nsl—tionF x ISR Chapter 9 Reasoning About Equality Proofs sn tr—dition—l m—them—ti™sD the ™on™ept of equ—lity is usu—lly t—ken —s — givenF yn the other h—ndD in type theoryD equ—lity is — very ™ontentious su˜je™tF „here —re —t le—st three di'erent notions of equ—lity th—t —re import—ntD —nd rese—r™hers —re —™tively investig—ting new de(nitions of wh—t it me—ns for two terms to ˜e equ—lF iven on™e we (x — notion of equ—lityD there —re inevit—˜ly tri™ky issues th—t —rise in proving properties of progr—ms th—t m—nipul—te equ—lity proofs expli™itlyF sn this ™h—pterD we will fo™us on design p—tterns for ™ir™umventing these tri™ky issuesD —nd we will introdu™e the di'erent notions of equ—lity —s they —re germ—neF 9.1 The Denitional Equality ‡e h—ve seen m—ny ex—mples so f—r where proof go—ls follow 4˜y ™omput—tionF4 „h—t isD we —pply ™omput—tion—l redu™tion rules to redu™e the go—l to — norm—l formD —t whi™h point it follows trivi—llyF ix—™tly when this works —nd when it does not depends on the det—ils of goq9s denitional equalityF „his is —n untyped ˜in—ry rel—tion —ppe—ring in the form—l met—theory of gsgF gsg ™ont—ins — typing rule —llowing the ™on™lusion E : T from the premise E : T —nd — proof th—t T —nd T —re de(nition—lly equ—lF „he cbv t—™ti™ will help us illustr—te the rules of goq9s de(nition—l equ—lityF ‡e rede(ne the n—tur—l num˜er prede™essor fun™tion in — somewh—t ™onvoluted w—y —nd ™onstru™t — m—nu—l proof th—t it returns H when —pplied to IF Definition pred' @x X natA Xa match x with |O⇒O | S n' ⇒ let y Xa n' in y endF Theorem reduce me X pred' I a HF gsg follows the tr—ditions of l—m˜d— ™—l™ulus in —sso™i—ting redu™tion rules with qreek lettersF goq ™—n ™ert—inly ˜e s—id to support the f—mili—r —lph— redu™tion ruleD whi™h —llows ISS ™—ptureE—voiding ren—ming of ˜ound v—ri—˜lesD ˜ut we never need to —pply —lph— expli™itlyD sin™e goq uses — de fruijn represent—tion th—t en™odes terms ™—noni™—llyF „he delt— rule is for unfolding glo˜—l de(nitionsF ‡e ™—n use it here to unfold the de(nition of pred'F ‡e do this with the cbv t—™ti™D whi™h t—kes — list of redu™tion rules —nd m—kes —s m—ny ™—llE˜yEv—lue redu™tion steps —s possi˜leD using only those rulesF „here is —n —n—logous t—™ti™ lazy for ™—llE˜yEneed redu™tionF cbv deltaF aaaaaaaaaaaaaaaaaaaaaaaaaaaa @fun x X nat ⇒ match x with |H⇒H | S n' ⇒ let y Xa n' in y endA I a H et this pointD we w—nt to —pply the f—mous ˜et— redu™tion of l—m˜d— ™—l™ulusD to simplify the —ppli™—tion of — known fun™tion —˜str—™tionF cbv betaF aaaaaaaaaaaaaaaaaaaaaaaaaaaa match I with |H⇒H | S n' ⇒ let y Xa n' in y end a H xext on the list is the iot— redu™tionD whi™h simpli(es — single match term ˜y determining whi™h p—ttern m—t™hesF cbv iotaF aaaaaaaaaaaaaaaaaaaaaaaaaaaa @fun n' X nat ⇒ let y Xa n' in y A H a H xow we need —nother ˜et— redu™tionF cbv betaF aaaaaaaaaaaaaaaaaaaaaaaaaaaa @let y Xa H in y A a H „he (n—l redu™tion rule is zet—D whi™h repl—™es — let expression ˜y its ˜ody with the —ppropri—te term su˜situtedF cbv zetaF IST aaaaaaaaaaaaaaaaaaaaaaaaaaaa HaH reflexivityF QedF „he st—nd—rd eq rel—tion is ™riti™—lly dependent on the de(nition—l equ—lityF eq is often ™—lled — propositional equalityD ˜e™—use it rei(es de(nition—l equ—lity —s — proposition th—t m—y or m—y not holdF ƒt—nd—rd —xiom—tiz—tions of —n equ—lity predi™—te in (rstEorder logi™ de(ne equ—lity in terms of properties it h—sD like re)exivityD symmetryD —nd tr—nsitivityF sn ™ontr—stD for eq in goqD those properties —re impli™it in the properties of the de(nition—l equ—lityD whi™h —re ˜uilt into gsg9s met—theory —nd the implement—tion of q—llin—F ‡e ™ould —dd new rules to the de(nition—l equ—lityD —nd eq would keep its de(nition —nd methods of useF „his —ll m—y m—ke it sound like the ™hoi™e of eq9s de(nition is unimport—ntF „o the ™ontr—ryD in this ™h—pterD we will see ex—mples where —ltern—te de(nitions m—y simplify proofsF fefore th—t pointD we will introdu™e e'e™tive proof methods for go—ls th—t use proofs of the st—nd—rd proposition—l equ—lity 4—s d—t—F4 9.2 Heterogeneous Lists Revisited yne of our ex—mple dependent d—t— stru™tures from the l—st ™h—pter w—s heterogeneous lists —nd their —sso™i—ted 4™ursor4 typeF „he re™ursive version poses some spe™i—l ™h—llenges rel—ted to equ—lity proofsD sin™e it uses su™h proofs in its de(nition of member typesF Section fhlistF Variable A X TypeF Variable B X A → TypeF Fixpoint fhlist @ls X list AA X Type Xa match ls with | nil ⇒ unit | x XX ls' ⇒ B x B fhlist ls' end7typeF Variable elm X AF Fixpoint fmember @ls X list AA X Type Xa match ls with | nil ⇒ Empty set | x XX ls' ⇒ @x a elm A C fmember ls' end7typeF Fixpoint fhget @ls X list AA X fhlist ls → fmember ls → B match ls return fhlist ls → fmember ls → B elm with | nil ⇒ fun idx ⇒ match idx with end ISU elm Xa | End endF ⇒ fun mls idx ⇒ match idx with | inl pf ⇒ match pf with | re equal ⇒ fst mls end | inr idx' ⇒ fhget ls' @snd mls A idx' end XX ls' fhlistF Implicit Arguments ‡e ™—n de(ne — fhget ‘A B elm ls “F mapElike fun™tion for fhlistsF Section fhlist mapF Variables A X TypeF Variables B C X A → TypeF Variable f X ∀ xD B x → C xF Fixpoint fhmap @ls X list AA X fhlist B ls → fhlist C ls Xa match ls return fhlist B ls → fhlist C ls with | nil ⇒ fun ⇒ tt | XX ⇒ fun hls ⇒ @f @fst hls AD fhmap @snd hls AA endF Implicit Arguments fhmap ‘ls “F por the indu™tive versions of the ilist de(nitionsD we proved — lemm— —˜out the inter—™tion of get —nd imapF st w—s — str—tegi™ ™hoi™e not to —ttempt su™h — proof for the de(nitions th—t we just g—veD ˜e™—use th—t sets us on — ™ollision ™ourse with the pro˜lems th—t —re the su˜je™t of this ™h—pterF Variable elm X AF Theorem get imap X ∀ ls @mem X fmember elm ls A @hls X fhget @fhmap hls A mem a f @fhget hls mem AF induction ls Y crushF fhlist B ls AD €—rt of our single rem—ining su˜go—l isX X a a elm aaaaaaaaaaaaaaaaaaaaaaaaaaaa match a0 in @ a a2 A return @C a2 A with | re equal ⇒ f a1 end a f match a0 in @ a a2 A return @B a2 A with | re equal ⇒ a1 a0 end „his seems like — trivi—l enough o˜lig—tionF „he equ—lity proof ISV a0 must ˜e re equalD sin™e th—t is the only ™onstru™tor of eqF „hereforeD ˜oth the matches redu™e to the point where the ™on™lusion follows ˜y re)exivityF destruct a0F User error X Cannot solve a second Eorder unication problem „his is one of goq9s st—nd—rd error mess—ges for informing us th—t its heuristi™s for —ttempting —n inst—n™e of —n unde™id—˜le pro˜lem —˜out dependent typing h—ve f—iledF ‡e might try to nudge things in the right dire™tion ˜y st—ting the lemm— th—t we ˜elieve m—kes the ™on™lusion trivi—lF assert @a0 a The term AF re equal 4re) equ—l cWV4 type 4cWV a cWV4 type 4— a elm4 has while it is expected to have sn retrospe™tD the pro˜lem is not so h—rd to seeF ‚e)exivity proofs only show x a x for p—rti™ul—r v—lues of x D where—s here we —re thinking in terms of — proof of a a elm D where the two sides of the equ—lity —re not equ—l synt—™ti™—llyF „husD the essenti—l lemm— we need does not even typeE™he™k3 ss it time to throw in the towelc vu™kilyD the —nswer is 4noF4 sn this ™h—pterD we will see sever—l useful p—tterns for proving o˜lig—tions like thisF por this p—rti™ul—r ex—mpleD the solution is surprisingly str—ightforw—rdF destruct h—s — simpler si˜ling case whi™h should ˜eh—ve identi™—lly for —ny indu™tive type with one ™onstru™tor of no —rgumentsF case a0F aaaaaaaaaaaaaaaaaaaaaaaaaaaa f a1 a f a1 st seems th—t destruct w—s trying to ˜e too sm—rt for its own goodF reflexivityF QedF st will ˜e helpful to ex—mine the proof terms gener—ted ˜y this sort of str—tegyF e simpler ex—mple illustr—tes wh—t is going onF Lemma @pf X x a elm AD O a match destruct pf Y reflexivityF lemma1 simple QedF X∀ x pf with re equal ⇒ O endF destruct pf is — ™onvenient form for —pplying caseF st runs intro to ˜ring into s™ope —ll qu—nti(ed v—ri—˜les up to its —rgumentF simple ISW Print lemma1F lemma1 a fun @x X AA @pf X x a elm A ⇒ match pf as e in @ a y A return @H a match e with | re equal ⇒ H endA with | re equal ⇒ re equal H end X ∀ @x X AA @pf X x a elm AD H a match pf with | re equal ⇒ H end …sing wh—t we know —˜out shorth—nds for match —nnot—tionsD we ™—n write this proof in shorter form m—nu—llyF Definition lemma1' Xa fun @x X AA @pf X x a elm A ⇒ match pf return @H a match pf with | re equal ⇒ H endA with | re equal ⇒ re equal H endF ƒurprisinglyD wh—t seems —t (rst like — Lemma lemma2 simple X ∀ @x X destruct AA @pf X x a x AD simpler O lemm— is h—rder to proveF a match pf with re equal ⇒ O endF pfF User error X Cannot solve a second Eorder unication problem AbortF xonethelessD we ™—n —d—pt the l—st m—nu—l proof to h—ndle this theoremF Definition lemma2 Xa fun @x X AA @pf X x a x A ⇒ match pf return @H a match pf with | re equal ⇒ H endA with | re equal ⇒ re equal H endF ‡e ™—n try to prove — lemm— th—t would simplify proofs of m—ny f—™ts like Lemma lemma3 simple X ∀ @x X destruct AA @pf X x a x AD pf a pfF ITH re equal xF lemma2X User error X Cannot solve a second Eorder unication problem AbortF „his timeD even our m—nu—l —ttempt f—ilsF Definition lemma3' Xa fun @x X AA @pf X x a x A ⇒ match pf as pf ' in @ a x' A return @pf ' a | re equal ⇒ re equal endF The term 4x a x94 4re) equ—l x94 has type 4x9 a x94 while re equal x' A with it is expected to have type „he type error ™omes from our return —nnot—tionF sn th—t —nnot—tionD the asE˜ound v—ri—˜le pf ' h—s type x a x'D refering to the inE˜ound v—ri—˜le x'F „o do — dependent matchD we must ™hoose — fresh n—me for the se™ond —rgument of eqF ‡e —re just —s ™onstr—ined to use the 4re—l4 v—lue x for the (rst —rgumentF „husD within the return ™l—useD the proof we —re m—t™hing on must equ—te two nonEm—t™hing termsD whi™h m—kes it impossi˜le to equ—te th—t proof with re)exivityF xonethelessD it turns out th—tD with one ™—t™hD we can prove this lemm—F Lemma lemma3 X ∀ @x X AA @pf X introsY apply UIP reF QedF Check x a x AD pf a re equal xF UIP reF UIP re X ∀ @U X TypeA @x X UA @p X x a x AD p a re equal x UIP re ™omes from the Eqdep module of the st—nd—rd li˜r—ryF ho the goq —uthors know of some ™lever tri™k for ˜uilding su™h proofs th—t we h—ve not seen yetc sf they doD they did not use it for this proofF ‚—therD the proof is ˜—sed on —n axiomF Print eq rect eqF eq rect eq fun a X Type ⇒ Eq rect eq.eq rect eq U X ∀ @U X TypeA @p X U A @Q X U → TypeA @x X x a eq rect p Q x p h U Q pA @h X p a p AD st—tes — 4f—™t4 th—t seems like ™ommon senseD on™e the not—tion is de™ipheredF eq rect is the —utom—ti™—llyEgener—ted re™ursion prin™iple for eqF g—lling eq rect is —nother w—y of matching on —n equ—lity proofF „he proof we m—t™h on is the —rgument hD —nd x is the ˜ody of the matchF eq rect eq just s—ys th—t matches on proofs of p a pD for —ny pD —re eq rect eq ITI super)uous —nd m—y ˜e removedF €erh—ps surprisinglyD we ™—nnot prove eq rect eq from within goqF „his proposition is introdu™ed —s —n —xiomY th—t isD — proposition —sserted —s true without proofF ‡e ™—nnot —ssert just —ny st—tement without proofF edding False —s —n —xiom would —llow us to prove —ny propositionD for inst—n™eD defe—ting the point of using — proof —ssist—ntF sn gener—lD we need to ˜e sure th—t we never —ssert inconsistent sets of —xiomsF e set of —xioms is in™onsistent if its ™onjun™tion implies FalseF por the ™—se of eq rect eq D ™onsisten™y h—s ˜een veri(ed outside of goq vi— 4inform—l4 met—theoryF „his —xiom is equiv—lent to —nother th—t is more ™ommonly known —nd mentioned in type theory ™ir™lesF Print Streicher KF a fun U X Type ⇒ UIP re Streicher K U @UIP re X ∀ @U X TypeA @x X U A @P X x a x → PropAD P @re equal x A → ∀ p X x a x D P p Streicher K UA „his is the unfortun—telyEn—med 4ƒtrei™her9s —xiom uD4 whi™h s—ys th—t — predi™—te on properlyEtyped equ—lity proofs holds of —ll su™h proofs if it holds of re)exivityF End fhlist mapF 9.3 Type-Casts in Theorem Statements ƒometimes we need to use tri™ks with equ—lity just to st—te the theorems th—t we ™—re —˜outF „o illustr—teD we st—rt ˜y de(ning — ™on™—ten—tion fun™tion for fhlistsF Section fhappF Variable A X TypeF Variable B X A → TypeF Fixpoint fhapp @ls1 ls2 X list AA X fhlist B ls1 → fhlist B ls2 → fhlist B @ls1 CC ls2 A Xa match ls1 with | nil ⇒ fun hls2 ⇒ hls2 | XX ⇒ fun hls1 hls2 ⇒ @fst hls1D fhapp @snd hls1 A endF Implicit Arguments hls2 A fhapp ‘ls1 ls2 “F ‡e might like to prove th—t fhapp is —sso™i—tiveF Theorem fhapp ass X ∀ ls1 ls2 ls3 @hls1 X fhlist B ls1 A @hls2 X fhlist B ls2 A @hls3 X fhlist B ls3 AD fhapp hls1 @fhapp hls2 hls3 A a fhapp @fhapp hls1 hls2 A hls3F ITP The term 4fh—pp @lsIXalsI CC lsPA @lsPXalsQA @fh—pp @lsIXalsIA @lsPXalsPA hlsI hlsPA hlsQ4 has type 4fhlist f @@lsI CC lsPA CC lsQA4 while it is expected to have type 4fhlist f @lsI CC lsP CC lsQA4 „his (rst ™ut —t the theorem st—tement does not even typeE™he™kF ‡e know th—t the two fhlist types —ppe—ring in the error mess—ge —re —lw—ys equ—lD ˜y —sso™i—tivity of norm—l list —ppendD ˜ut this f—™t is not —pp—rent to the type ™he™kerF „his stems from the f—™t th—t goq9s equ—lity is intensionalD in the sense th—t type equ—lity theorems ™—n never ˜e —pplied —fter the f—™t to get — term to typeE™he™kF snste—dD we need to m—ke use of equ—lity expli™itly in the theorem st—tementF Theorem fhapp ass X ∀ ls1 ls2 ls3 @pf X @ls1 CC ls2 A CC ls3 a ls1 CC @ls2 CC ls3 AA @hls1 X fhlist B ls1 A @hls2 X fhlist B ls2 A @hls3 X fhlist fhapp hls1 @fhapp hls2 hls3 A a match pf in @ a ls A return fhlist ls with | re equal ⇒ fhapp @fhapp hls1 hls2 A hls3 endF induction ls1 Y crushF B ls3 AD „he (rst rem—ining su˜go—l looks trivi—l enoughX aaaaaaaaaaaaaaaaaaaaaaaaaaaa fhapp @ls1 XalsPA @ls2 XalsQA hls2 hls3 a match pf in @ a ls A return @fhlist B ls A with | re equal ⇒ fhapp @ls1 XalsPA @ls2 XalsQA hls2 hls3 end ‡e ™—n try wh—t worked in previous ex—mplesF case pfF User error X Cannot solve a second Eorder unication problem st seems we h—ve re—™hed —nother ™—se where it is un™le—r how to use — dependent match to implement ™—se —n—lysis on our proofF „he UIP re theorem ™—n ™ome to our res™ue —g—inF rewrite @UIP re pf AF aaaaaaaaaaaaaaaaaaaaaaaaaaaa fhapp @ls1 XalsPA @ls2 XalsQA hls2 hls3 a fhapp @ls1 XalsPA @ls2 XalsQA hls2 hls3 ITQ reflexivityF yur se™ond su˜go—l is tri™kierF X a XX @ls1 CC ls2 A CC ls3 a a XX ls1 CC ls2 CC aaaaaaaaaaaaaaaaaaaaaaaaaaaa @a0D fhapp @ls1 XalsIA @ls2 XalsP CC ls3 A b @fhapp @ls1 XalsPA @ls2 XalsQA hls2 hls3 AA a match pf in @ a ls A return @fhlist B ls A with | re equal ⇒ @a0D fhapp @ls1 XalsI CC ls2 A @ls2 XalsQA @fhapp @ls1 XalsIA @ls2 XalsPA b hls2 A hls3 A pf ls3 end rewrite @UIP The term 4pf4 re has pf AF type 4— XX @lsI CC lsPA CC lsQ a — XX lsI CC lsP CC lsQ4 type 4cSST a cSST4 while it is expected to have ‡e ™—n only —pply UIP re on proofs of equ—lity with synt—™ti™—lly equ—l oper—ndsD whi™h is not the ™—se of pf hereF ‡e will need to m—nipul—te the form of this su˜go—l to get us to — point where we m—y use UIP reF e (rst step is o˜t—ining — proof suit—˜le to use in —pplying the indu™tion hypothesisF snversion on the stru™ture of pf is su0™ient for th—tF injection pf Y intro pf 'F a XX @ls1 CC ls2 A CC ls3 a a XX ls1 CC ls2 CC X @ls1 CC ls2 A CC ls3 a ls1 CC ls2 CC ls3 aaaaaaaaaaaaaaaaaaaaaaaaaaaa @a0D fhapp @ls1 XalsIA @ls2 XalsP CC ls3 A b @fhapp @ls1 XalsPA @ls2 XalsQA hls2 hls3 AA a match pf in @ a ls A return @fhlist B ls A with | re equal ⇒ @a0D fhapp @ls1 XalsI CC ls2 A @ls2 XalsQA @fhapp @ls1 XalsIA @ls2 XalsPA b hls2 A hls3 A pf X pf ' end xow we ™—n rewrite using the indu™tive hypothesisF ITR ls3 rewrite @IHls1 pf ' AF aaaaaaaaaaaaaaaaaaaaaaaaaaaa @a0D match pf ' in @ a ls A return @fhlist B ls A with | re equal ⇒ fhapp @ls1 XalsI CC ls2 A @ls2 XalsQA @fhapp @ls1 XalsIA @ls2 XalsPA b hls2 A hls3 endA a match pf in @ a ls A return @fhlist B ls A with | re equal ⇒ @a0D fhapp @ls1 XalsI CC ls2 A @ls2 XalsQA @fhapp @ls1 XalsIA @ls2 XalsPA b hls2 A hls3 A end ‡e h—ve m—de —n import—nt ˜it of progressD —s now only — single ™—ll to fhapp —ppe—rs in the ™on™lusionF „rying ™—se —n—lysis on our proofs still will not workD ˜ut there is — move we ™—n m—ke to en—˜le itF xot only does just one ™—ll to fhapp m—tter to us nowD ˜ut it —lso does not matter what the result of the call isF sn other wordsD the su˜go—l should rem—in true if we repl—™e this fhapp ™—ll with — fresh v—ri—˜leF „he generalize t—™ti™ helps us do ex—™tly th—tF generalize @fhapp @fhapp b hls2 A hls3 AF ∀ f X fhlist B @@ls1 CC ls2 A CC ls3 AD @a0D match pf ' in @ a ls A return @fhlist B ls A with | re equal ⇒ f endA a match pf in @ a ls A return @fhlist B ls A with | re equal ⇒ @a0D f A end „he ™on™lusion h—s gotten m—rkedly simplerF st seems ™ounterintuitive th—t we ™—n h—ve —n e—sier time of proving — more gener—l theoremD ˜ut th—t is ex—™tly the ™—se here —nd for m—ny other proofs th—t use dependent types he—vilyF ƒpe—king inform—llyD the re—son why this kind of —™tivity helps is th—t match —nnot—tions only support v—ri—˜les in ™ert—in positionsF fy redu™ing more elements of — go—l to v—ri—˜lesD ˜uiltEin t—™ti™s ™—n h—ve more su™™ess ˜uilding match terms under the hoodF sn this ™—seD it is helpful to gener—lize over our two proofs —s wellF generalize pf pf 'F ITS ∀ @pf0 X a XX @ls1 CC ls2 A CC ls3 a a XX ls1 CC ls2 CC @pf '0 X @ls1 CC ls2 A CC ls3 a ls1 CC ls2 CC ls3 A @f X fhlist B @@ls1 CC ls2 A CC ls3 AAD @a0D match pf '0 in @ a ls A return @fhlist B ls A with | re equal ⇒ f endA a match pf0 in @ a ls A return @fhlist B ls A with | re equal ⇒ @a0D f A end ls3 A „o —n experien™ed dependent types h—™kerD the —ppe—r—n™e of this go—l term ™—lls for — ™ele˜r—tionF „he formul— h—s — ™riti™—l property th—t indi™—tes th—t our pro˜lems —re overF „o get our proofs into the right form to —pply UIP reD we need to use —sso™i—tivity of list —ppend to rewrite their typesF ‡e ™ould not do th—t ˜efore ˜e™—use other p—rts of the go—l require the proofs to ret—in their origin—l typesF sn p—rti™ul—rD the ™—ll to fhapp th—t we gener—lized must h—ve type @ls1 CC ls2 A CC ls3D for some v—lues of the list v—ri—˜lesF sf we rewrite the type of the proof used to typeE™—st this v—lue to something like ls1 CC ls2 CC ls3 a ls1 CC ls2 CC ls3D then the lefth—nd side of the equ—lity would no longer m—t™h the type of the term we —re trying to ™—stF roweverD now th—t we h—ve gener—lized over the fhapp ™—llD the type of the term ˜eing typeE™—st —ppe—rs expli™itly in the go—l —nd may be rewritten as wellF sn p—rti™ul—rD the (n—l m—sterstroke is rewriting everywhere in our go—l using —sso™i—tivity of list —ppendF rewrite app assF aaaaaaaaaaaaaaaaaaaaaaaaaaaa ∀ @pf0 X a XX ls1 CC ls2 CC ls3 a a XX ls1 CC ls2 CC @pf '0 X ls1 CC ls2 CC ls3 a ls1 CC ls2 CC ls3 A @f X fhlist B @ls1 CC ls2 CC ls3 AAD @a0D match pf '0 in @ a ls A return @fhlist B ls A with | re equal ⇒ f endA a match pf0 in @ a ls A return @fhlist B ls A with | re equal ⇒ @a0D f A ls3 A end ‡e ™—n see th—t we h—ve —™hieved the ™ru™i—l propertyX the type of e—™h gener—lized equ—lity proof h—s synt—™ti™—lly equ—l oper—ndsF „his m—kes it e—sy to (nish the proof with UIP reF introsF rewrite @UIP re pf0 AF ITT rewrite @UIP reflexivityF QedF End fhappF pf '0 AF re Implicit Arguments fhapp ‘A B ls1 ls2 “F 9.4 Heterogeneous Equality „here is —nother equ—lity predi™—teD de(ned in the implementing heterogeneous equalityF Print JMeqF Inductive JMeq @A X TypeA @x X JMeq re X JMeq x x AA X∀ B X TypeD JMeq module of the st—nd—rd li˜r—ryD B → Prop Xa JMeq st—nds for 4tohn w—jor equ—lityD4 — n—me ™oined ˜y gonor w™fride —s — sort of pun —˜out fritish politi™sF JMeq st—rts out looking — lot like eqF „he ™ru™i—l di'eren™e is th—t we m—y use JMeq on arguments of dierent typesF por inst—n™eD — lemm— th—t we f—iled to est—˜lish ˜efore is trivi—l with JMeqF st m—kes for prettier theorem st—tements to de(ne some synt—™ti™ shorth—nd (rstF Infix 4aa4 Xa JMeq @at level UHD no associativity AF Definition UIP re' @A X TypeA @x X AA @pf X match pf return @pf aa re equal A with | re equal ⇒ JMeq re endF x a xA X pf aa re equal x Xa „here is no qui™k w—y to write su™h — proof ˜y t—™ti™sD ˜ut the underlying proof term th—t we w—nt is trivi—lF ƒuppose th—t we w—nt to use UIP re' to est—˜lish —nother lemm— of the kind of we h—ve run into sever—l times so f—rF Lemma lemma4 X ∀ @A X TypeA @x X AA @pf X x a x AD O a match pf with re equal ⇒ O endF introsY rewrite @UIP re' pf AY reflexivityF QedF ell in —llD refreshingly str—ightforw—rdD ˜ut there re—lly is no su™h thing —s — free lun™hF „he use of rewrite is implemented in terms of —n —xiomX Check JMeq eq F JMeq eq X ∀ @A X TypeA @x y X AAD x aa y → x a ITU y st m—y ˜e surprising th—t we ™—nnot prove th—t heterogeneous equ—lity implies norm—l equ—lityF „he di0™ulties —re the s—me kind we h—ve seen so f—rD ˜—sed on limit—tions of match —nnot—tionsF ‡e ™—n redo our fhapp —sso™i—tivity proof ˜—sed —round JMeqF Section fhapp'F Variable A X TypeF Variable B X A → TypeF „his timeD the n—ive theorem st—tement typeE™he™ksF Theorem fhapp ass' X ∀ ls1 ls2 ls3 @hls1 X fhlist B ls1 A @hls2 X fhlist fhapp hls1 @fhapp hls2 hls3 A aa induction ls1 Y crushF iven ˜etterD crush B ls2 A fhapp @hls3 X fhlist B ls3 AD @fhapp hls1 hls2 A hls3F dis™h—rges the (rst su˜go—l —utom—ti™—llyF „he se™ond su˜go—l isX aaaaaaaaaaaaaaaaaaaaaaaaaaaa @a0D fhapp @B XafA @ls1 XalsIA @ls2 XalsP CC ls3 A b @fhapp @B XafA @ls1 XalsPA @ls2 XalsQA hls2 hls3 AA aa @a0D fhapp @B XafA @ls1 XalsI CC ls2 A @ls2 XalsQA @fhapp @B XafA @ls1 XalsIA @ls2 XalsPA b hls2 A hls3 A st looks like one rewrite with the indu™tive hypothesis should ˜e enough to m—ke the go—l trivi—lF rewrite IHls1F 4fhlist f @@lsI CC cISUPA CC cISUQA4 with 4fhlist f @lsI CC cISUP CC cISUQA4 Error X Impossible to unify ‡e see th—t JMeq is not — silver ˜ulletF ‡e ™—n use it to simplify the st—tements of equ—lity f—™tsD ˜ut the goq typeE™he™ker uses nonEtrivi—l heterogeneous equ—lity f—™ts no more re—dily th—n it uses st—nd—rd equ—lity f—™tsF rereD the pro˜lem is th—t the form @e1 D e2 A is synt—™ti™ sug—r for —n expli™it —ppli™—tion of — ™onstru™tor of —n indu™tive typeF „h—t —ppli™—tion mentions the type of e—™h tuple element expli™itlyD —nd our rewrite tries to ™h—nge one of those elements without upd—ting the ™orresponding type —rgumentF ‡e ™—n get —round this pro˜lem ˜y —nother multiple use of generalizeF ‡e w—nt to ˜ring into the go—l the proper inst—n™e of the indu™tive hypothesisD —nd we —lso w—nt to gener—lize the two relev—nt uses of fhappF generalize @fhapp b @fhapp hls2 @fhapp @fhapp b hls2 A hls3 A hls3 AA ITV @IHls1 b hls2 hls3 AF aaaaaaaaaaaaaaaaaaaaaaaaaaaa ∀ @f X fhlist B @ls1 CC ls2 CC ls3 AA @f0 X fhlist B @@ls1 CC ls2 A CC ls3 AAD f aa f0 → @a0D f A aa @a0D f0 A xow we ™—n rewrite with —ppend —sso™i—tivityD —s ˜eforeF rewrite app assF aaaaaaaaaaaaaaaaaaaaaaaaaaaa ∀ f f0 X fhlist B @ls1 CC ls2 CC ls3 AD f aa f0 → @a0D f A aa @a0D f0 A prom this pointD the go—l is trivi—lF intros QedF End fhapp'F f f0 H Y rewrite HY reflexivityF 9.5 Equivalence of Equality Axioms essuming —xioms @like —xiom u —nd JMeq eq A is — h—z—rdous ˜usinessF „he due diligen™e —sso™i—ted with it is ne™ess—rily glo˜—l in s™opeD sin™e two —xioms m—y ˜e ™onsistent —lone ˜ut in™onsistent togetherF st turns out th—t —ll of the m—jor —xioms proposed for re—soning —˜out equ—lity in goq —re logi™—lly equiv—lentD so th—t we only need to pi™k one to —ssert without proofF sn this se™tionD we demonstr—te this ˜y showing how e—™h the previous two se™tions9 —ppro—™hes redu™es to the other logi™—llyF „o show th—t JMeq —nd its —xiom let us prove UIP reD we st—rt from the lemm— UIP re' from the previous se™tionF „he rest of the proof is trivi—lF Lemma UIP re X ∀ @A X TypeA @x X AA @pf X x a x AD pf a re equal xF introsY rewrite @UIP re' pf AY reflexivityF QedF „he other dire™tion is perh—ps more interestingF essume th—t we only h—ve the —xiom of the Eqdep module —v—il—˜leF ‡e ™—n de(ne JMeq in — w—y th—t s—tis(es the s—me interf—™e —s the ™om˜in—tion of the JMeq module9s indu™tive de(nition —nd —xiomF Definition JMeq' @A X TypeA @x X AA @B X TypeA @y X B A X Prop Xa ∃ pf X B a AD x a match pf with re equal ⇒ y endF Infix 4aaa4 Xa JMeq' @at level UHD no associativity AF ‡e s—y th—tD ˜y de(nitionD x —nd y —re equ—l if —nd only if there exists — proof pf th—t their types —re equ—lD su™h th—t x equ—ls the result of ™—sting y with pfF „his st—tement ™—n look str—nge from the st—ndpoint of ™l—ssi™—l m—thD where we —lmost never mention proofs expli™itly with qu—nti(ers in formul—sD ˜ut it is perfe™tly leg—l goq ™odeF ITW ‡e ™—n e—sily prove — theorem with the s—me type —s th—t of the of JMeqF JMeq re ™onstru™tor Theorem JMeq re' X ∀ @A X TypeA @x X AAD x aaa xF introsY unfold JMeq' Y exists @re equal AAY reflexivityF QedF „he proof of —n —n—logue to is in —ppe—ling to UIP reF JMeq eq Theorem JMeq eq' X ∀ @A X TypeA @x x aaa y → x a yF unfold JMeq' Y introsF H X∃ pf x X A a AD a match pf in @ a | re equal ⇒ y TA y X is — little more interestingD ˜ut most of the —™tion AAD return T with end aaaaaaaaaaaaaaaaaaaaaaaaaaaa x ay destruct x0 H HF X AaA X x a match x0 in @ a | re equal ⇒ y TA return T with end aaaaaaaaaaaaaaaaaaaaaaaaaaaa x ay rewrite HF X AaA aaaaaaaaaaaaaaaaaaaaaaaaaaaa match x0 in @ a T A return T with | re equal ⇒ y end a y x0 rewrite @UIP QedF re x0 AY reflexivityF ‡e see th—tD in — very form—l senseD we —re free to swit™h ˜—™k —nd forth ˜etween the two styles of proofs —˜out equ—lity proofsF yne style m—y ˜e more ™onvenient th—n the other for some proofsD ˜ut we ™—n —lw—ys inter™overt ˜etween our resultsF „he style th—t does not IUH use heterogeneous equ—lity m—y ˜e prefer—˜le in ™—ses where m—ny results do not require the tri™ks of this ™h—pterD sin™e then the use of —xioms is —voided —ltogether for the simple ™—sesD —nd — wider —udien™e will ˜e —˜le to follow those 4simple4 proofsF yn the other h—ndD heterogeneous equ—lity often m—kes for shorter —nd more re—d—˜le theorem st—tementsF st is worth rem—rking th—t it is possi˜le to —void —xioms —ltogether for equ—lities on types with de™id—˜le equ—lityF „he Eqdep dec module of the st—nd—rd li˜r—ry ™ont—ins — p—r—metri™ proof of UIP re for su™h ™—sesF 9.6 Equality of Functions „he following seems like — re—son—˜le theorem to w—nt to holdD —nd it does hold in set theoryF Theorem X S eta S a @fun n ⇒ S n AF …nfortun—telyD this theorem is not prov—˜le in gsg without —ddition—l —xiomsF xone of the de(nition—l equ—lity rules for™e fun™tion equ—lity to ˜e extensionalF „h—t isD the f—™t th—t two fun™tions return equ—l results on equ—l inputs does not imply th—t the fun™tions —re equ—lF ‡e can —ssert fun™tion extension—lity —s —n —xiomF Axiom ext eq X ∀ A @∀ xD f x a g x A → f a gF B @f g X A → B AD „his —xiom h—s ˜een veri(ed met—theoreti™—lly to ˜e ™onsistent with gsg —nd the two equ—lity —xioms we ™onsidered previouslyF ‡ith itD the proof of S eta is trivi—lF Theorem S eta X S a @fun n ⇒ apply ext eq Y reflexivityF QedF S n AF „he s—me —xiom ™—n help us prove equ—lity of typesD where we need to 4re—son under qu—nti(ersF4 Theorem a @∀ forall eq X X @∀ x X natD match x with | O ⇒ True | S ⇒ True endA natD TrueAF „here —re no immedi—te opportunities to —pply th—tF change @@∀ x rewrite @ext X ext eq D ˜ut we ™—n use natD @fun x ⇒ match x with eq @fun x ⇒ match x | H ⇒ True | S ⇒ True endA x A a @nat → with IUI TrueAAF change to (x | H ⇒ True | S ⇒ True endA @fun ⇒ TrueAAF P subgoals aaaaaaaaaaaaaaaaaaaaaaaaaaaa @nat → TrueA a @nat → TrueA subgoal P is X ∀ x X natD match with | H ⇒ True | S ⇒ True end a True x reflexivityF destruct x Y constructorF QedF 9.7 Exercises IF smplement —nd prove ™orre™t — su˜stitution fun™tion for simplyEtyped l—m˜d— ™—l™ulusF sn p—rti™ul—rX @—A he(ne — d—t—type typesF type of l—m˜d— typesD in™luding just ˜oole—ns —nd fun™tion @˜A he(ne — type f—mily exp X list type → type → Type of l—m˜d— expressionsD in™luding ˜oole—n ™onst—ntsD v—ri—˜lesD —nd fun™tion —ppli™—tion —nd —˜str—™tionF @™A smplement — de(nition—l interpreter for expsD ˜y w—y of — re™ursive fun™tion over expressions —nd su˜stitutions for free v—ri—˜lesD like in the rel—ted ex—mple from the l—st ™h—pterF @dA smplement — fun™tion subst X ∀ t' ts t D exp @t' XX ts A t → exp ts t' → exp ts t F „he type of the (rst expression indi™—tes th—t its most re™ently ˜ound free v—ri—˜le h—s type t'F „he se™ond expression —lso h—s type t'D —nd the jo˜ of subst is to su˜stitute the se™ond expression for every o™™urren™e of the 4(rst4 v—ri—˜le of the (rst expressionF @eA €rove th—t subst preserves progr—m me—ningsF „h—t isD prove ∀ t' ts t @e X exp @t' XX ts A t A @e' X exp ts t' A @s X hlist typeDenote expDenote @subst e e' A s a expDenote e @expDenote e' s XXX s A ts AD where XXX is —n in(x oper—tor for heterogeneous 4™ons4 th—t is de(ned in the ˜ook9s DepList moduleF IUP „he m—teri—l presented up to this point should ˜e su0™ient to en—˜le — good solution of this exer™iseD with enough ingenuityF sf you get stu™kD it m—y ˜e helpful to use the following stru™tureF xone of these elements need to —ppe—r in your solutionD ˜ut we ™—n —t le—st gu—r—ntee th—t there is — re—son—˜le solution ˜—sed on themF @—A „he DepList module will ˜e usefulF ‰ou ™—n get the st—nd—rd dependent list de(nitions thereD inste—d of ™opyingE—ndEp—sting from the l—st ™h—pterF st is worth re—ding the sour™e for th—t module overD sin™e it de(nes some new helpful fun™tions —nd not—tions th—t we did not use l—st ™h—pterF @˜A he(ne — re™ursive fun™tion liftVar X ∀ ts1 ts2 t t'D member t @ts1 CC ts2 A → member t @ts1 CC t' XX ts2 AF „his fun™tion should 4lift4 — de fruijn v—ri—˜le so th—t its type refers to — new v—ri—˜le inserted somewhere in the index listF @™A he(ne — re™ursive fun™tion lift' X ∀ ts t @e X exp ts t A ts1 ts2 t'D ts a ts1 CC ts2 → exp @ts1 CC t' XX ts2 A t whi™h performs — simil—r lifting on —n expF „he ™onvoluted type is to get —round restri™tions on match —nnot—tionsF ‡e del—y 4re—lizing4 th—t the (rst index of e is ˜uilt with list ™on™—ten—tion until —fter — dependent matchD —nd the new expli™it proof —rgument must ˜e used to ™—st some terms th—t ™ome up in the match ˜odyF @dA he(ne — fun™tion lift X ∀ ts t t'D exp ts t → exp @t' XX ts A t D whi™h h—ndles simpler topElevel liftsF „his should ˜e —n e—sy oneEliner ˜—sed on lift'F @eA he(ne — re™ursive fun™tion substVar X ∀ ts1 ts2 t t'D member t @ts1 CC t' XX ts2 A → @t' a t A C member t @ts1 CC ts2 AF „his fun™tion is the workhorse ˜ehind su˜stitution —pplied to — v—ri—˜leF st returns inl to indi™—te th—t the v—ri—˜le we p—ss to it is the v—ri—˜le th—t we —re su˜stituting forD —nd it returns inr to indi™—te th—t the v—ri—˜le we —re ex—mining is not the one we —re su˜stituting forF sn the (rst ™—seD we get — proof th—t the ne™ess—ry typing rel—tionship holdsD —ndD in the se™ond ™—seD we get the origin—l v—ri—˜le modi(ed to re)e™t the remov—l of the su˜stitutee from the typing ™ontextF @fA he(ne — re™ursive fun™tion subst' X ∀ ts t @e X exp ts t A ts1 t' ts2D ts a ts1 CC t' XX ts2 → exp @ts1 CC ts2 A t' → exp @ts1 CC ts2 A t F „his is the workhorse of su˜stitution in expressionsD employing the s—me proofEp—ssing tri™k —s for lift'F ‰ou will pro˜—˜ly w—nt to use lift somewhere in the de(nition of subst'F @gA xow subst should ˜e — oneElinerD de(ned in terms of subst'F @hA €rove — ™orre™tness theorem for e—™h —uxili—ry fun™tionD le—ding up to the proof of subst ™orre™tnessF @iA ell of the re—soning —˜out equ—lity proofs in these theorems follows — regul—r p—tternF sf you h—ve —n equ—lity proof th—t you w—nt to repl—™e with re equal somehowD run generalize on th—t proof v—ri—˜leF ‰our go—l is to get to the point where you ™—n rewrite with the origin—l proof to ™h—nge the type of the gener—lized versionF „o —void type errors @the inf—mous 4se™ondEorder uni(™—tion4 IUQ f—ilure mess—gesAD it will ˜e helpful to run generalize on other pie™es of the proof ™ontext th—t mention the equ—lity9s lefth—nd sideF ‰ou might —lso w—nt to use generalize dependentD whi™h gener—lizes not just one v—ri—˜le ˜ut —lso —ll v—ri—˜les whose types depend on itF generalize dependent h—s the sometimesE helpful property of removing from the ™ontext —ll v—ri—˜les th—t it gener—lizesF yn™e you do m—n—ge the mindE˜ending tri™k of using the equ—lity proof to rewrite its own typeD you will ˜e —˜le to rewrite with UIP reF @jA e v—ri—nt of the ext eq —xiom from the end of this ™h—pter is —v—il—˜le in the ˜ook module AxiomsD —nd you will pro˜—˜ly w—nt to use it in the lift' —nd subst' ™orre™tness proofsF @kA „he change t—™ti™ should ™ome in h—ndy in the proofs —˜out lift —nd substD where you w—nt to introdu™e 4extr—neous4 list ™on™—ten—tions with nil to m—t™h the forms of e—rlier theoremsF @lA fe ™—reful —˜out destructing — term 4too e—rlyF4 ‰ou ™—n use generalize on proof terms to ˜ring into the proof ™ontext —ny import—nt propositions —˜out the termF „henD when you destruct the termD it is upd—ted in the extr— propositionsD tooF „he case eq t—™ti™ is —nother —ltern—tive to this —ppro—™hD ˜—sed on s—ving —n equ—lity ˜etween the origin—l term —nd its new formF IUR Chapter 10 Generic Programming m—kes it possi˜le to write fun™tions th—t oper—te over di'erent types of d—t—F €—r—metri™ polymorphism in wv —nd r—skell is one of the simplest ex—mplesF wvEstyle module systems —nd r—skell type ™l—sses —re more )exi˜le ™—sesF „hese l—ngu—ge fe—tures —re often not —s powerful so we would likeF por inst—n™eD while r—skell in™ludes — type ™l—ss ™l—ssifying those types whose v—lues ™—n ˜e prettyEprintedD perEtype prettyEprinting is usu—lly either implemented m—nu—lly or implemented vi— — deriving ™l—useD whi™h triggers —dEho™ ™ode gener—tionF ƒome ™lever en™oding tri™ks h—ve ˜een used to —™hieve ˜etter within r—skell —nd other l—ngu—gesD ˜ut we ™—n do d—t—typeEgeneri™ progr—mming mu™h more ™le—nly with dependent typesF „h—nks to the expressive power of gsgD we need no spe™i—l l—ngu—ge supportF qeneri™ progr—mming ™—n often ˜e very useful in goq developmentsD so we devote this ™h—pter to studying itF sn — proof —ssist—ntD there is the new possi˜ility of generi™ proofs —˜out generi™ progr—msD whi™h we —lso devote some sp—™e toF Generic programming 10.1 Reecting Datatype Denitions „he key to generi™ progr—mming with dependent types is universe typesF „his ™on™ept should not ˜e ™onfused with the ide— of universes from the met—theory of gsg —nd rel—ted l—ngu—gesF ‚—therD the ide— of universe types is to de(ne indu™tive types th—t provide syntactic representations of goq typesF ‡e ™—nnot dire™tly write gsg progr—ms th—t do ™—se —n—lysis on typesD ˜ut we can ™—se —n—lyze on re)e™ted synt—™ti™ versions of those typesF „husD to ˜eginD we must de(ne — synt—™ti™ represent—tion of some ™l—ss of d—t—typesF sn this ™h—pterD our running ex—mple will h—ve to do with ˜—si™ —lge˜r—i™ d—t—typesD of the kind found in wv —nd r—skellD ˜ut without —ddition—l ˜ells —nd whistles like type p—r—meters —nd mutu—llyEre™ursive de(nitionsF „he (rst step is to de(ne — represent—tion for ™onstru™tors of our d—t—typesF Record constructor X Type Xa nonrecursive X TypeY Con { IUS recursive }F X nat „he ide— is th—t — ™onstru™tor represented —s Con T n h—s n —rguments of the type th—t we —re de(ningF eddition—llyD —ll of the otherD nonEre™ursive —rguments ™—n ˜e en™oded in the type T F ‡hen there —re no nonEre™ursive —rgumentsD T ™—n ˜e unitF ‡hen there —re two nonEre™ursive —rgumentsD of types A —nd B D T ™—n ˜e A B B F ‡e ™—n gener—lizer to —ny num˜er of —rguments vi— tuplingF ‡ith this de(nitionD it —s e—sy to de(ne — d—t—type represent—tion in terms of lists of ™onstru™torsF Definition datatype Xa list constructorF rere —re — few ex—mple en™odings for some ™ommon types from the goq st—nd—rd li˜r—ryF ‡hile our synt—x type does not support type p—r—meters dire™tlyD we ™—n implement them —t the met— levelD vi— fun™tions from types to datatypesF Definition Definition Definition Definition Definition Empty set dt X datatype Xa nilF X datatype Xa Con unit H XX nilF X datatype Xa Con unit H XX Con unit H XX nilF dt X datatype Xa Con unit H XX Con unit I XX nilF dt @A X TypeA X datatype Xa Con unit H XX Con A I XX unit dt bool dt nat list nilF Empty set h—s no ™onstru™torsD so its represent—tion is the empty listF unit h—s one ™onstru™tor with no —rgumentsD so its one re)e™ted ™onstru™tor indi™—tes no nonEre™ursive d—t— —nd H re™ursive —rgumentsF „he represent—tion for bool just dupli™—tes this single —rgumentless ™onstru™torF ‡e get from bool to nat ˜y ™h—nging one of the ™onstru™tors to indi™—te I re™ursive —rgumentF ‡e get from nat to list ˜y —dding — nonEre™ursive —rgument of — p—r—meter type AF es — further ex—mpleD we ™—n do the s—me en™oding for — generi™ ˜in—ry tree typeF Section treeF Variable A X TypeF Inductive tree X Type Xa | Leaf X A → tree | Node X tree → tree → treeF End treeF Definition tree dt @A X TypeA X datatype Xa Con A H XX Con unit P XX nilF i—™h d—t—type represent—tion st—nds for — f—mily of indu™tive typesF por — spe™i(™ re—l d—t—type —nd — reputed represent—tion for itD it is useful to de(ne — type of evidence th—t the d—t—type is ™omp—ti˜le with the en™odingF Section denoteF Variable T X TypeF „his v—ri—˜le st—nds for the ™on™rete d—t—type th—t we —re interested inF Definition constructorDenote @c X constructorA Xa IUT → ilist T @recursive c A → TF ‡e write th—t — ™onstru™tor is represented —s — fun™tion returning — T F ƒu™h — fun™tion t—kes two —rgumentsD whi™h p—™k together the nonEre™ursive —nd re™ursive —rguments of the ™onstru™torF ‡e represent — tuple of —ll re™ursive —rguments using the lengthEindexed list type ilist th—t we met in gh—pter UF nonrecursive c Definition datatypeDenote Xa hlist constructorDenoteF pin—llyD the eviden™e for type T is — hetergeneous listD in™luding — ™onstru™tor denot—tion for every ™onstru™tor en™oding in — d—t—type en™odingF ‚e™—ll th—tD sin™e we —re inside — se™tion ˜inding T —s — v—ri—˜leD constructorDenote is —utom—ti™—lly p—r—meterized ˜y T F End denoteF ƒome ex—mple pie™es of eviden™e should help ™l—rify the ™onventionF pirstD we de(ne some helpful not—tionsD providing di'erent w—ys of writing ™onstru™tor denot—tionsF „here is re—lly just one not—tionD ˜ut we need sever—l versions of it to ™over di'erent ™hoi™es of whi™h v—ri—˜les will ˜e used in the ˜ody of — de(nitionF „he eƒgss ~> from the not—tion will ˜e rendered l—ter —s F Notation Notation Notation Notation 4‘ 4‘ 4‘ 4‘ 3 D 3 £b x “4 Xa @@fun v D 3 £b x “4 Xa @@fun 3 D r £b x “4 Xa @@fun v D r £b x “4 Xa @@fun ⇒ x A X constructorDenote @Con ⇒ x A X constructorDenote @Con r ⇒ x A X constructorDenote @Con @Con v r ⇒ x A X constructorDenote v AAF AAF AAF AAF Definition Empty set den X datatypeDenote Empty set Empty set dt Xa HNilF Definition unit den X datatypeDenote unit unit dt Xa ‘3D 3 tt“ XXX HNilF Definition bool den X datatypeDenote bool bool dt Xa ‘3D 3 true“ XXX ‘3D 3 false“ XXX HNilF Definition nat den X datatypeDenote nat nat dt Xa ‘3D 3 O“ XXX ‘3D r S @hd r A“ XXX HNilF Definition list den @A X TypeA X datatypeDenote @list AA @list dt AA Xa ‘3D 3 nil“ XXX ‘xD r x XX hd r “ XXX HNilF Definition tree den @A X TypeA X datatypeDenote @tree AA @tree dt AA Xa ‘ vD 3 Leaf v “ XXX ‘3D r Node @hd r A @hd @tl r AA“ XXX HNilF 10.2 Recursive Denitions ‡e ˜uilt these en™odings of d—t—types to help us write d—t—typeEgeneri™ re™ursive fun™tionsF „o do soD we will w—nt — re)e™ted represent—tion of — recursion scheme for e—™h typeD simil—r to the T rect prin™iple gener—ted —utom—ti™—lly for —n indu™tive de(nition of T F e ™lever reuse of datatypeDenote yields — short de(nitionF Definition xDenote @T X TypeA @dt X datatypeA IUU Xa ∀ @R X TypeAD datatypeDenote R dt → @T → R AF „he ide— of — re™ursion s™heme is p—r—meterized ˜y — type —nd — reputed en™oding of itF „he prin™iple itself is polymorphi™ in — type R D whi™h is the return type of the re™ursive fun™tion th—t we me—n to writeF „he next —rgument is — hetergeneous list of one ™—se of the re™ursive fun™tion de(nition for e—™h d—t—type ™onstru™torF „he datatypeDenote fun™tion turns out to h—ve just the right de(nition to express the type we needY — set of fun™tion ™—ses is just like —n —ltern—te set of ™onstru™tors where we repl—™e the origin—l type T with the fun™tion result type R F qiven su™h — re)e™ted de(nitionD — xDenote invo™—tion returns — fun™tion from T to R D whi™h is just wh—t we w—ntedF ‡e —re re—dy to write some ex—mple fun™tions nowF st will ˜e useful to use one new fun™tion from the DepList li˜r—ry in™luded in the ˜ook sour™eF Check hmakeF hmake X ∀ @A X TypeA @B X A → TypeAD @∀ x X AD B x A → ∀ ls X list AD hlist B l is — kind of map —ltern—tive th—t goes from — regul—r list to —n hlistF ‡e ™—n use it to de(ne — generi™ size fun™tion whi™h ™ounts the num˜er of ™onstru™tors used to ˜uild — v—lue in — d—t—typeF hmake Definition size T dt @fx X xDenote T dt A X T → nat Xa r⇒ fx nat @hmake @B Xa constructorDenote natA @fun foldr plus I rA dt AF yur de(nition is p—r—meterized over — re™ursion s™heme fx F ‡e inst—nti—te fx ˜y p—ssing it the fun™tion result type —nd — set of fun™tion ™—sesD where we ˜uild the l—tter with hmakeF „he fun™tion —rgument to hmake t—kes three —rgumentsX the represent—tion of — ™onstru™torD its nonEre™ursive —rgumentsD —nd the results of re™ursive ™—lls on —ll of its re™ursive —rgumentsF ‡e only need the re™ursive ™—ll results hereD so we ™—ll them r —nd ˜ind the other two inputs with wild™—rdsF „he —™tu—l ™—se ˜ody is simpleX we —dd together the re™ursive ™—ll results —nd in™rement the result ˜y one @to —™™ount for the ™urrent ™onstru™torAF „his foldr fun™tion is —n hlistEspe™i(™ version de(ned in the DepList moduleF st is instru™tive to ˜uild xDenote v—lues for our ex—mple types —nd see wh—t spe™i—lized size fun™tions result from themF Definition Empty set x X xDenote Empty set Empty set dt Xa fun R emp ⇒ match emp with endF Eval compute in size Empty set xF a fun emp X Empty set ⇒ match emp return nat with end X Empty set → nat hespite —ll the f—n™iness of the generi™ size fun™tionD gsg9s st—nd—rd ™omput—tion rules su0™e to norm—lize the generi™ fun™tion spe™i—liz—tion to ex—™tly wh—t we would h—ve written m—nu—llyF IUV Definition unit x X xDenote unit unit fun R cases ⇒ @hhd cases A tt INilF Eval compute in size unit xF a fun X unit ⇒ I X unit → nat dt Xa eg—in norm—liz—tion gives us the n—tur—l fun™tion de(nitionF ‡e see this p—ttern repe—ted for our other ex—mple typesF Definition bool x X xDenote bool bool dt Xa fun R cases b ⇒ if b then @hhd cases A tt INil else @hhd @htl cases AA tt INilF Eval compute in size bool xF a fun b X bool ⇒ if b then I else I X bool → nat Definition nat x X xDenote nat nat dt Xa fun R cases ⇒ x F @n X natA X R Xa match n with | O ⇒ @hhd cases A tt INil | S n' ⇒ @hhd @htl cases AA tt @ICons @F endF n' A INilA „o peek —t the size fun™tion for natD it is useful to —void full ™omput—tionD so th—t the re™ursive de(nition of —ddition is not exp—nded inlineF ‡e ™—n —™™omplish this with proper )—gs for the cbv redu™tion str—tegyF Eval cbv beta iota delta a X x F @n X nat → nat E‘plus “ in size nat xF natA X nat Xa match n with |H⇒I | S n' ⇒ end F n' CI Definition list x @A X TypeA X xDenote @list AA @list dt AA Xa fun R cases ⇒ x F @ls X list AA X R Xa match ls with | nil ⇒ @hhd cases A tt INil | x XX ls' ⇒ @hhd @htl cases AA x @ICons @F ls' A INilA endF Eval cbv beta iota delta E‘plus “ in fun A ⇒ size @dlist x AAF a fun A X Type ⇒ x F @ls X list AA X nat Xa match ls with IUW | nil ⇒ I | XX ls' ⇒ F ls' C I end X ∀ A X TypeD list A → nat Definition tree x @A X TypeA X xDenote @tree AA @tree dt AA Xa fun R cases ⇒ x F @t X tree AA X R Xa match t with | Leaf x ⇒ @hhd cases A x INil | Node t1 t2 ⇒ @hhd @htl cases AA tt @ICons @F t1 A @ICons @F t2 A endF Eval cbv beta iota delta E‘plus “ in fun A ⇒ size @dtree x AAF a fun A X Type ⇒ x F @t X tree AA X nat Xa match t with | Leaf ⇒ I | Node t1 t2 ⇒ F t1 C @F t2 C IA end X ∀ A X TypeD tree A → n INilAA 10.2.1 Pretty-Printing st is —lso useful to do generi™ prettyEprinting of d—t—type v—luesD rendering them —s hum—nE re—d—˜le stringsF „o do soD we will need — ˜it of met—d—t— for e—™h ™onstru™torF ƒpe™i(™—llyD we need the n—me to print for the ™onstru™tor —nd the fun™tion to use to render its nonE re™ursive —rgumentsF iverything else ™—n ˜e done generi™—llyF Record print constructor @c X constructorA X Type Xa printName X stringY printNonrec X nonrecursive c → string }F PI { st is useful to de(ne — shorth—nd for —pplying the ™onstru™tor PIF fy —pplying it expli™itly to —n unknown —ppli™—tion of the ™onstru™tor ConD we help type inferen™e workF Notation 4¢4 Xa @PI @Con AAF es in e—rlier ex—mplesD we de(ne the type of met—d—t— for — d—t—type to ˜e — heterogeE neous list type ™olle™ting met—d—t— for e—™h ™onstru™torF Definition print datatype Xa hlist print constructorF ‡e will ˜e doing some string m—nipul—tion hereD so we import the not—tions —sso™i—ted with stringsF Local Open Scope string scopeF xow it is e—sy to implement our generi™ printerD using —nother fun™tion from IVH DepListF Check hmapF hmap X ∀ @A X TypeA @B1 B2 X A → TypeAD @∀ x X AD B1 x → B2 x A → ∀ ls X list AD hlist B1 ls → hlist B2 ls Definition print T dt @pr X print datatype dt A @fx X xDenote T dt A X T → string Xa fx string @hmap @B1 Xa print constructorA @B2 Xa constructorDenote stringA @fun pc x r ⇒ printName pc CC 4@4 CC printNonrec pc x CC foldr @fun s acc ⇒ 4D 4 CC s CC acc A 4A4 r A pr AF ƒome simple tests est—˜lish th—t print gets the jo˜ doneF Eval compute in print HNil Empty set xF a fun emp X Empty set ⇒ match emp return string with end X Empty set → string Eval compute in print @¢ 4tt4 @fun a fun X unit ⇒ 4tt@A4 X unit → string ⇒ 44A XXX HNilA unit xF Eval compute in print @¢ 4true4 @fun ⇒ 44A XXX ¢ 4f—lse4 @fun ⇒ 44A XXX HNilA bool xF a fun b X bool ⇒ if b then 4true@A4 else 4f—lse@A4 X bool → s Definition print nat Xa print @¢ 4y4 @fun ⇒ 44A XXX ¢ 4ƒ4 @fun ⇒ 44A XXX HNilA nat xF Eval cbv beta iota delta E‘append “ in print natF a x F @n X natA X string Xa match n with | H7n—t ⇒ 4y4 CC 4@4 CC 44 CC 4A4 | S n' ⇒ 4ƒ4 CC 4@4 CC 44 CC 4D 4 CC end X nat → string Eval simpl in a 4y@A4 X string print nat Eval simpl in print a 4ƒ@D y@AA4 X string nat HF IF IVI F n' CC 4A4 Eval simpl in print nat PF a 4ƒ@D ƒ@D y@AAA4 X string Eval E‘append “ in fun ⇒ 44A cbv beta iota delta @¢ 4nil4 @fun XXX ¢ 4™ons4 pr XXX HNilA @dlist x AAF print A @pr X A → stringA ⇒ a fun @A X TypeA @pr X A → stringA ⇒ x F @ls X list AA X string Xa match ls with | nil ⇒ 4nil4 CC 4@4 CC 44 CC 4A4 | x XX ls' ⇒ 4™ons4 CC 4@4 CC pr x CC 4D 4 CC end X ∀ A X TypeD @A → stringA → list A → string Eval cbv beta iota delta E‘append “ in fun print @¢ 4ve—f4 pr XXX ¢ 4xode4 @fun ⇒ 44A XXX HNilA @dtree x AAF A @pr X A → F ls' CC 4A4 stringA ⇒ a fun @A X TypeA @pr X A → stringA ⇒ x F @t X tree AA X string Xa match t with | Leaf x ⇒ 4ve—f4 CC 4@4 CC pr x CC 4A4 | Node t1 t2 ⇒ 4xode4 CC 4@4 CC 44 CC 4D 4 CC F t1 CC 4D 4 CC end X ∀ A X TypeD @A → stringA → tree A → string F t2 CC 4A4 10.2.2 Mapping fy this pointD we h—ve developed enough m—™hinery th—t it is old h—t to de(ne — generi™ fun™tion simil—r to the list map fun™tionF Definition map T dt @dd X datatypeDenote T dt A @fx X xDenote T dt A @f X X T → T Xa fx T @hmap @B1 Xa constructorDenote T A @B2 Xa constructorDenote T A @fun c x r ⇒ f @c x r AA dd AF Eval compute in map Empty set den Empty set xF a fun @ X Empty set → Empty setA @emp X Empty setA ⇒ match emp return Empty set with end X @Empty set → Empty setA → Empty set → Empty set IVP T → TA Eval compute in map unit den unit xF a fun @f X unit → unitA @ X unitA ⇒ X @unit → unitA → unit → unit f tt Eval compute in map bool den bool xF a fun @f X bool → boolA @b X boolA ⇒ if X @bool → boolA → bool → bool b then f true Eval compute in map nat den nat xF a fun f X nat → nat ⇒ x F @n X natA X nat Xa match n with | H7n—t ⇒ f H7n—t | S n' ⇒ f @S @F n' AA end X @nat → natA → nat → nat Eval compute in fun A ⇒ map @list den AA @dlist x AAF a fun @A X TypeA @f X list A → list AA ⇒ x F @ls X list AA X list A Xa match ls with | nil ⇒ f nil | x XX ls' ⇒ f @x XX F ls' A end X ∀ A X TypeD @list A → list AA → list A → list A Eval compute in fun A ⇒ map @tree den AA @dtree x AAF a fun @A X TypeA @f X tree A → tree AA ⇒ x F @t X tree AA X tree A Xa match t with | Leaf x ⇒ f @Leaf x A | Node t1 t2 ⇒ f @Node @F t1A @F t2AA end X ∀ A X TypeD @tree A → tree AA → tree A → tree A Definition map nat Xa map Eval simpl in map nat S HF a I7n—t X nat Eval simpl in a Q7n—t X nat Eval simpl in a S7n—t map nat S IF map nat S nat den nat xF PF IVQ else f false X nat 10.3 Proving Theorems about Recursive Denitions ‡e would like to ˜e —˜le to prove theorems —˜out our generi™ fun™tionsF „o do soD we need to est—˜lish —ddition—l wellEformedness properties th—t must hold of pie™es of eviden™eF Section okF Variable T X TypeF Variable dt X datatypeF Variable Variable dd fx X datatypeDenote X xDenote T dtF T dtF pirstD we ™h—r—™terize when — pie™e of eviden™e —˜out — d—t—type is —™™ept—˜leF „he ˜—si™ ide— is th—t the type T should re—lly ˜e —n indu™tive type with the de(nition given ˜y dd F ƒem—nti™—llyD indu™tive types —re ™h—r—™terized ˜y the —˜ility to do indu™tion on themF „hereforeD we require th—t the usu—l indu™tion prin™iple is trueD with respe™t to the ™onstru™tors given in the en™oding dd F Definition datatypeDenoteOk Xa ∀ P X T → PropD @∀ c @m X member c dt A @x X nonrecursive c A @r X ilist @ i X n @recursive c AD P @get r i AA → P @@hget dd m A x r AA → ∀ vD P vF T @recursive c AAD „his de(nition ™—n t—ke — while to digestF „he qu—nti(er over m X member c dt is ™onsidering e—™h ™onstru™tor in turnY like in norm—l indu™tion prin™iplesD e—™h ™onstru™tor h—s —n —sso™i—ted proof ™—seF „he expression hget dd m then n—mes the ™onstru™tor we h—ve sele™tedF efter ˜inding mD we qu—ntify over —ll possi˜le —rguments @en™oded with x —nd r A to the ™onstru™tor th—t m sele™tsF ‡ithin e—™h spe™i(™ ™—seD we qu—ntify further over i X n @recursive c A to ™onsider —ll of our indu™tion hypothesesD one for e—™h re™ursive —rgument of the ™urrent ™onstru™torF ‡e h—ve ™ompleted h—lf the ˜urden of de(ning side ™onditionsF „he other h—lf ™omes in ™h—r—™terizing when — re™ursion s™heme fx is v—lidF „he n—tur—l ™ondition is th—t fx ˜eh—ves —ppropri—tely when —pplied to —ny ™onstru™tor —ppli™—tionF Definition xDenoteOk Xa ∀ @R X TypeA @cases X datatypeDenote R dt A c @m X member c dt A @x X nonrecursive c A @r X ilist T @recursive c AAD fx cases @@hget dd m A x r A a @hget cases m A x @imap @fx cases A r AF es for datatypeDenoteOkD we ™onsider —ll ™onstru™tors —nd —ll possi˜le —rguments to them ˜y qu—ntifying over mD x D —nd rF „he lefth—nd side of the equ—lity th—t follows shows — ™—ll to IVR the re™ursive fun™tion on the spe™i(™ ™onstru™tor —ppli™—tion th—t we sele™tedF „he righth—nd side shows —n —ppli™—tion of the fun™tion ™—se —sso™i—ted with ™onstru™tor mD —pplied to the nonEre™ursive —rguments —nd to —ppropri—te re™ursive ™—lls on the re™ursive —rgumentsF End okF ‡e —re now re—dy to prove th—t the size fun™tion we de(ned e—rlier —lw—ys returns positive resultsF pirstD we est—˜lish — simple lemm—F Lemma X ∀ n @ils X b HF induction ils Y crushF QedF foldr plus foldr plus I ilist nat n AD ils Theorem size positive X ∀ T dt @dd X datatypeDenote T dt A @fx X xDenote T dt A @dok X datatypeDenoteOk dd A @fok X xDenoteOk dd @v X T AD size fx v b HF unfold size Y introsF fx A aaaaaaaaaaaaaaaaaaaaaaaaaaaa fx nat @hmake @fun @x X constructorA @ X nonrecursive x A @r X ilist nat @recursive x AA ⇒ foldr plus I7n—t r A dt A v bH yur go—l is —n inequ—lity over — p—rti™ul—r ™—ll to sizeD with its de(nition exp—ndedF row ™—n we pro™eed herec ‡e ™—nnot use induction dire™tlyD ˜e™—use there is no w—y for goq to know th—t T is —n indu™tive typeF snste—dD we need to use the indu™tion prin™iple en™oded in our hypothesis dok of type datatypeDenoteOk dd F vet us try —pplying it dire™tlyF apply dokF 4d—t—typehenoteyk dd4 with 4fx n—t @hm—ke @fun @x X ™onstru™torA @ X nonre™ursive xA @r X ilist n—t @re™ursive xAA ⇒ foldr plus I7n—t rA dtA v b H4F Error X Impossible to unify w—t™hing the type of dok with the type of our ™on™lusion requires more th—n simple (rstEorder uni(™—tionD so apply is not up to the ™h—llengeF ‡e ™—n use the pattern t—™ti™ to get our go—l into — form th—t m—kes it —pp—rent ex—™tly wh—t the indu™tion hypothesis isF pattern vF IVS aaaaaaaaaaaaaaaaaaaaaaaaaaaa @fun t X T ⇒ fx nat @hmake @fun @x X constructorA @ X nonrecursive x A @r X ilist nat @recursive x AA ⇒ foldr plus I7n—t r A apply H dt A t b HA v dok Y crushF n @recursive c AD nat X∀iX fx @hmake @fun @x X constructorA @ X nonrecursive x A @r X ilist nat @recursive x AA ⇒ foldr plus I7n—t r A @get r iA b H aaaaaaaaaaaaaaaaaaaaaaaaaaaa dt A hget @hmake @fun @x0 X constructorA @ X nonrecursive x0 A @r0 X ilist nat @recursive x0 AA ⇒ foldr plus I7n—t r0 A @imap @fx nat @hmake @fun @x0 X constructorA @ X nonrecursive x0 A @r0 X ilist nat @recursive x0 AA ⇒ foldr plus I7n—t r0 A dt AA r A b H dt A m x en indu™tion hypothesis H is gener—tedD ˜ut we turn out not to need it for this ex—mpleF ‡e ™—n simplify the go—l using — li˜r—ry theorem —˜out the ™omposition of hget —nd hmakeF rewrite hget hmakeF aaaaaaaaaaaaaaaaaaaaaaaaaaaa foldr plus I7n—t @imap @fx nat @hmake @fun @x0 X constructorA @ X nonrecursive @r0 X ilist nat @recursive x0 AA ⇒ foldr plus I7n—t r0 A dt AA r A b H „he lemm— we proved e—rlier (nishes the proofF apply foldr plusF IVT x0 A …sing hintsD we ™—n redo this proof in — ni™e —utom—ted formF RestartF Hint Rewrite hget hmake X cpdtF Hint Resolve foldr plusF unfold size Y introsY pattern v Y apply dok Y crushF QedF st turned out th—tD in this ex—mpleD we only needed to use indu™tion degener—tely —s ™—se —n—lysisF e more involved theorem m—y only ˜e proved using indu™tion hypothesesF ‡e will give its proof only in un—utom—ted form —nd le—ve e'e™tive —utom—tion —s —n exer™ise for the motiv—ted re—derF sn p—rti™ul—rD it ought to ˜e the ™—se th—t generi™ map —pplied to —n identity fun™tion is itself —n identity fun™tionF Theorem map id X ∀ T dt @dd X datatypeDenote T dt A @fx X xDenote T dt A @dok X datatypeDenoteOk dd A @fok X xDenoteOk dd fx A @v X T AD map dd fx @fun x ⇒ x A v a vF vet us ˜egin —s we did in the l—st theoremD —fter —dding —nother useful li˜r—ry equ—lity —s — hintF Hint Rewrite hget hmap X cpdtF unfold map Y introsY pattern v Y apply dok Y crushF H X∀iX n @recursive c AD fx T @hmap @fun @x X constructorA @c X constructorDenote T x A @x0 X nonrecursive x A @r X ilist T @recursive x AA ⇒ c x0 r A dd A @get r iA a get r i aaaaaaaaaaaaaaaaaaaaaaaaaaaa hget dd m x @imap @fx T @hmap @fun @x0 X constructorA @c0 X constructorDenote T x0 A @x1 X nonrecursive x0 A @r0 X ilist T @recursive x0 AA ⇒ c0 x1 r0 A dd AA r A a hget dd m x r yur go—l is —n equ—lity whose two sides ˜egin with the s—me fun™tion ™—ll —nd initi—l —rgumentsF ‡e ˜elieve th—t the rem—ining —rguments —re in f—™t equ—l —s wellD —nd the f equal t—™ti™ —pplies this re—soning step for us form—llyF f equalF IVU aaaaaaaaaaaaaaaaaaaaaaaaaaaa imap @fx T @hmap @fun @x0 X constructorA @c0 X constructorDenote T x0 A @x1 X nonrecursive x0 A @r0 X ilist T @recursive x0 AA ⇒ c0 x1 r0 A dd AA r a r et this pointD it is helpful to pro™eed ˜y —n inner indu™tion on the heterogeneous list r of re™ursive ™—ll resultsF ‡e ™ould —rrive —t — ™le—ner proof ˜y ˜re—king this step out into —n expli™it lemm—D ˜ut here we will do the indu™tion inline to s—ve sp—™eF induction r Y crushF „he ˜—se ™—se is dis™h—rged —utom—ti™—llyD —nd the indu™tive ™—se looks like thisD where is the outer sr @for indu™tion over T v—luesA —nd IHn is the inner sr @for indu™tion over the re™ursive —rgumentsAF H H X∀iX n @S nAD fx T IHr @hmap @fun @x X constructorA @c X constructorDenote T x A @x0 X nonrecursive x A @r X ilist T @recursive x AA ⇒ c x0 r A dd A @match i in @n n' A return @@n @pred n' A → T A → T A with | First n ⇒ fun X n n → T ⇒ a | Next n idx' ⇒ fun get ls' X n n → T ⇒ get ls' idx' end @get r AA a match i in @n n' A return @@n @pred n' A → T A → T A with | First n ⇒ fun X n n → T ⇒ a | Next n idx' ⇒ fun get ls' X n n → T ⇒ get ls' idx' end @get r A X @∀ i X n nD fx T @hmap @fun @x X constructorA @c X constructorDenote T x A @x0 X nonrecursive x A @r X ilist T @recursive x AA ⇒ c x0 r A dd A @get r iA a get r iA → imap @fx T @hmap @fun @x X constructorA @c X constructorDenote T x A @x0 X nonrecursive x A @r X ilist T @recursive x AA ⇒ IVV c x0 r A dd AA r ar aaaaaaaaaaaaaaaaaaaaaaaaaaaa ICons @fx T @hmap @fun @x0 X constructorA @c0 X constructorDenote T x0 A @x1 X nonrecursive x0 A @r0 X ilist T @recursive x0 AA ⇒ c0 x1 r0 A dd A a A @imap @fx T @hmap @fun @x0 X constructorA @c0 X constructorDenote T x0 A @x1 X nonrecursive x0 A @r0 X ilist T @recursive x0 AA ⇒ c0 x1 r0 A dd AA r A a ICons a r ‡e see —nother opportunity to —pply f equalD this time to split our go—l into two di'erent equ—lities over ™orresponding —rgumentsF efter th—tD the form of the (rst go—l m—t™hes our outer indu™tion hypothesis HD when we give type inferen™e some help ˜y spe™ifying the right qu—nti(er inst—nti—tionF f equalF apply @H FirstAF aaaaaaaaaaaaaaaaaaaaaaaaaaaa imap @fx T @hmap @fun @x0 X constructorA @c0 X constructorDenote T x0 A @x1 X nonrecursive x0 A @r0 X ilist T @recursive x0 AA ⇒ c0 x1 r0 A dd AA r a r xow the go—l m—t™hes the inner sr apply IHrF IHr Y crushF X n n aaaaaaaaaaaaaaaaaaaaaaaaaaaa i fx T @hmap @fun @x0 X constructorA @c0 X constructorDenote T x0 A @x1 X nonrecursive x0 A @r0 X ilist T @recursive x0 AA ⇒ c0 x1 r0 A dd A @get r iA a get r i ‡e ™—n (nish the proof ˜y —pplying the outer sr —g—inD spe™i—lized to — di'erent IVW n v—lueF apply @H @Next i AAF QedF IWH Chapter 11 Universes and Axioms w—ny tr—dition—l theorems ™—n ˜e proved in goq without spe™i—l knowledge of gsgD the logi™ ˜ehind the proverF e development just seems to ˜e using — p—rti™ul—r eƒgss not—tion for st—nd—rd formul—s ˜—sed on set theoryF xonethelessD —s we s—w in gh—pter RD gsg di'ers from set theory in st—rting from fewer orthogon—l primitivesF st is possi˜le to de(ne the usu—l logi™—l ™onne™tives —s derived notionsF „he found—tion of it —ll is — dependentlyEtyped fun™tion—l progr—mming l—ngu—geD ˜—sed on dependent fun™tion types —nd indu™tive type f—miliesF fy using the f—™ilities of this l—ngu—ge dire™tlyD we ™—n —™™omplish some things mu™h more e—sily th—n in m—instre—m m—thF q—llin—D whi™h —dds fe—tures to the more theoreti™—l gsgD is the logi™ implemented in goqF st h—s — rel—tively simple found—tion th—t ™—n ˜e de(ned rigorously in — p—ge or two of form—l proof rulesF ƒtillD there —re some import—nt su˜tleties th—t h—ve pr—™ti™—l r—mi(™—tionsF „his ™h—pter fo™uses on those su˜tletiesD —voiding form—l met—theory in f—vor of ex—mple ™odeF 11.1 The Type Hierarchy ivery o˜je™t in q—llin— h—s — typeF Check HF H X nat st is n—tur—l enough th—t zero ˜e ™onsidered —s — n—tur—l num˜erF Check natF nat X Set prom — set theory perspe™tiveD it is unsurprising to ™onsider the n—tur—l num˜ers —s — 4setF4 Check SetF IWI Set X Type „he type Set m—y ˜e ™onsidered —s the set of —ll setsD — ™on™ept th—t set theory h—ndles in terms of classesF sn goqD this more gener—l notion is TypeF Check TypeF Type X Type ƒtr—ngely enoughD Type —ppe—rs to ˜e its own typeF st is known th—t polymorphi™ l—nE gu—ges with this property —re in™onsistentF „h—t isD using su™h — l—ngu—ge to en™ode proofs is unwiseD ˜e™—use it is possi˜le to 4prove4 —ny propositionF ‡h—t is re—lly going on herec vet us repe—t some of our queries —fter toggling — )—g rel—ted to goq9s printing ˜eh—viorF Set Printing UniversesF Check natF nat X Set Check SetF Set X Type @B @HACI BA Check TypeF Type @B TopFQ BA X Type @B @TopFQACI BA y™™urren™es of Type —re —nnot—ted with some —ddition—l inform—tionD inside ™ommentsF „hese —nnot—tions h—ve to do with the se™ret ˜ehind TypeX it re—lly st—nds for —n in(nite hier—r™hy of typesF „he type of Set is Type@HAD the type of Type@HA is Type@IAD the type of Type@IA is Type@PAD —nd so onF „his is how we —void the 4Type X Type4 p—r—doxF es — ™onvenien™eD the universe hier—r™hy drives goq9s one v—riety of su˜typingF eny term whose type is Type —t level i is —utom—ti™—lly —lso des™ri˜ed ˜y Type —t level j when j b iF sn the outputs of our (rst Check queryD we see th—t the type level of Set9s type is @HACIF rere H st—nds for the level of SetD —nd we in™rement it to —rrive —t the level th—t classies SetF sn the se™ond query9s outputD we see th—t the o™™urren™e of Type th—t we ™he™k is —ssigned — fresh universe variable TopFQF „he output type in™rements TopFQ to move up — level in the universe hier—r™hyF es we write ™ode th—t uses de(nitions whose types mention universe v—ri—˜lesD uni(™—tion m—y re(ne the v—lues of those v—ri—˜lesF vu™kilyD the user r—rely h—s to worry —˜out the det—ilsF enother ™ru™i—l ™on™ept in gsg is predicativityF gonsider these queriesF IWP Check ∀ T X natD n TF ∀ T X natD n T X Set Check ∀ T X SetD TF ∀ T X SetD T X Type @B max@HD @HACIA BA Check ∀ T X TypeD TF ∀ T X Type @B TopFW BA D T X Type @B max@TopFWD @TopFWACIA BA „hese outputs demonstr—te the rule for determining whi™h universe — ∀ type lives inF sn p—rti™ul—rD for — type ∀ x X T1D T2D we t—ke the m—ximum of the universes of T1 —nd T2F sn the (rst ex—mple queryD ˜oth T1 @natA —nd T2 @n T A —re in SetD so the ∀ type is in SetD tooF sn the se™ond queryD T1 is SetD whi™h is —t level @HACIY —nd T2 is T D whi™h is —t level HF „husD the ∀ exists —t the m—ximum of these two levelsF „he third ex—mple illustr—tes the s—me out™omeD where we repl—™e Set with —n o™™urren™e of Type th—t is —ssigned universe v—ri—˜le TopFWF „his universe v—ri—˜le —ppe—rs in the pl—™es where H —ppe—red in the previous queryF „he ˜ehindEtheEs™enes m—nipul—tion of universe v—ri—˜les gives us predi™—tivityF gonsider this simple de(nition of — polymorphi™ identity fun™tionF Definition id @T X SetA @x X TA X T Xa xF Check id HF id H X nat Check SetF id Error X Illegal application FFF The Ist term has @Type Error AX type 4„ype @B @„opFISACI BA4 which should be coercible to 4ƒet4F „he p—r—meter T of id must ˜e inst—nti—ted with — SetF nat is — SetD ˜ut Set is notF ‡e ™—n try (xing the pro˜lem ˜y gener—lizing our de(nition of idF Reset idF Definition Check id HF id H X nat Check id id @T X TypeA @x X TA X T Xa xF SetF IWQ id Set X Type @B TopFIU BA Check id TypeF id Type @B TopFIV BA X Type @B TopFIW BA ƒo f—r so goodF es we —pply id to di'erent T v—luesD the inferred index for o™™urren™e —utom—ti™—lly moves higher up the type hier—r™hyF Check T 9s Type id idF Error X Universe inconsistency @cannot enforce TopFIT ` TopFITAF „his error mess—ge reminds us th—t the universe v—ri—˜le for T still existsD even though it is usu—lly hiddenF „o —pply id to itselfD th—t v—ri—˜le would need to ˜e less th—n itself in the type hier—r™hyF …niverse in™onsisten™y error mess—ges —nnoun™e ™—ses like this one where — term ™ould only typeE™he™k ˜y viol—ting —n implied ™onstr—int over universe v—ri—˜lesF ƒu™h errors demonstr—te th—t Type is predicativeD where this word h—s — gsg me—ning ™losely rel—ted to its usu—l m—them—ti™—l me—ningF e predi™—tive system enfor™es the ™onstr—int th—tD for —ny o˜je™t of qu—nti(ed typeD none of those qu—nti(ers m—y ever ˜e inst—nti—ted with the o˜je™t itselfF smpredi™—tivity is —sso™i—ted with popul—r p—r—doxes in set theoryD involving in™onsistent ™onstru™tions like 4the set of —ll sets th—t do not ™ont—in themselvesF4 ƒimil—r p—r—doxes result from un™ontrolled impredi™—tivity in goqF 11.1.1 Inductive Denitions €redi™—tivity restri™tions —lso —pply to indu™tive de(nitionsF es —n ex—mpleD let us ™onsider — type of expression trees th—t —llows inje™tion of —ny n—tive goq v—lueF „he ide— is th—t —n exp T st—nds for — re)e™ted expression of type T F Inductive exp X Set → Set Xa | Const X ∀ T X SetD T → exp T | Pair X ∀ T1 T2D exp T1 → exp T2 → exp @T1 B | Eq X ∀ T D exp T → exp T → exp boolF T2 A Error X Large non Eproposition—l inductive types must be in TypeF „his de(nition is large in the sense th—t —t le—st one of its ™onstru™tors t—kes —n —rgument whose type h—s type TypeF goq would ˜e in™onsistent if we —llowed de(nitions like this one in their full gener—lityF snste—dD we must ™h—nge exp to live in TypeF ‡e will go even further —nd move exp9s index to Type —s wellF Inductive exp X Type → Type Xa IWR | | | X ∀ TD T → exp T Pair X ∀ T1 T2D exp T1 → exp T2 → exp @T1 B Eq X ∀ TD exp T → exp T → exp boolF Const T2 A xote th—t ˜efore we h—d to in™lude —n —nnot—tion X Set for the v—ri—˜le T in Const9s typeD ˜ut we need no —nnot—tion nowF ‡hen the type of — v—ri—˜le is not knownD —nd when th—t v—ri—˜le is used in — ™ontext where only types —re —llowedD goq infers th—t the v—ri—˜le is of type TypeF „h—t is the right ˜eh—vior hereD ˜ut it w—s wrong for the Set version of expF yur new de(nition is —™™eptedF ‡e ™—n ˜uild some s—mple expressionsF Check Const Const H X exp Check Pair HF nat @Const HA @Const ttAF @Const HA @Const ttA X exp @nat B unitA Pair Check Eq @Const SetA @Const TypeAF Eq @Const SetA @Const Type @B TopFSW BA A X exp bool ‡e ™—n ™he™k m—ny expressionsD in™luding f—n™y expressions th—t in™lude typesF roweverD it is not h—rd to hit — typeE™he™king w—llF Check Const @Const OAF Error X Universe inconsistency @cannot enforce TopFRP ` TopFRPAF ‡e —re un—˜le to inst—nti—te the p—r—meter T of Const with —n exp typeF „o see whyD it is helpful to print the —nnot—ted version of exp9s indu™tive de(nitionF Print expF Inductive exp X Type @B TopFV BA → Type @B max@HD @TopFIIACID @TopFIRACID @TopFISACID @TopFIWACIA BA Xa Const X ∀ T X Type @B TopFII BA D T → exp T | Pair X ∀ @T1 X Type @B TopFIR BA A @T2 X Type @B TopFIS BA AD exp T1 → exp T2 → exp @T1 B T2 A | Eq X ∀ T X Type @B TopFIW BA D exp T → exp T → exp bool ‡e see th—t the index type of exp h—s ˜een —ssigned to universe level TopFVF sn —dditionD e—™h of the four o™™urren™es of Type in the types of the ™onstru™tors gets its own universe v—ri—˜leF i—™h of these v—ri—˜les —ppe—rs expli™itly in the type of expF sn p—rti™ul—rD —ny IWS type exp T lives —t — universe level found ˜y in™rementing ˜y one the m—ximum of the four —rgument v—ri—˜lesF e ™onsequen™e of this is th—t exp must live —t — higher universe level th—n —ny type whi™h m—y ˜e p—ssed to one of its ™onstru™torsF „his ™onsequen™e led to the universe in™onsisten™yF ƒtr—ngelyD the universe v—ri—˜le TopFV only —ppe—rs in one pl—™eF ss there no restri™tion imposed on whi™h types —re v—lid —rguments to expc sn f—™tD there is — restri™tionD ˜ut it only —ppe—rs in — glo˜—l set of universe ™onstr—ints th—t —re m—int—ined 4o' to the sideD4 not —ppe—ring expli™itly in typesF ‡e ™—n print the ™urrent d—t—˜—seF Print UniversesF TopFIW ` TopFW ≤ TopFIS ` TopFW ≤ TopFIR ` TopFW ≤ TopFII ` TopFW ≤ TopFV TopFV TopFV TopFV ≤ ≤ Coq.Init.DatatypesFQV Coq.Init.DatatypesFQU Print Universes outputs m—ny more ™onstr—intsD ˜ut we h—ve ™olle™ted only those th—t mention Top v—ri—˜lesF ‡e see one ™onstr—int for e—™h universe v—ri—˜le —sso™i—ted with — ™onstru™tor —rgument from exp9s de(nitionF TopFIW is the type —rgument to EqF „he ™onstr—int for TopFIW e'e™tively s—ys th—t TopFIW must ˜e less th—n TopFVD the universe of exp9s indi™esY —n intermedi—te v—ri—˜le TopFW —ppe—rs —s —n —rtif—™t of the w—y the ™onstr—int w—s gener—tedF „he next ™onstr—intD for TopFISD is more ™ompli™—tedF „his is the universe of the se™ond —rgument to the Pair ™onstru™torF xot only must TopFIS ˜e less th—n TopFVD ˜ut it —lso ™omes out th—t TopFV must ˜e less th—n Coq.Init.DatatypesFQVF ‡h—t is this new universe v—ri—˜lec st is from the de(nition of the prod indu™tive f—milyD to whi™h types of the form A B B —re desug—redF Print prodF Inductive prod @A X Type @B Coq.Init.DatatypesFQU BA A @B X Type @B Coq.Init.DatatypesFQV BA A X Type @B max@Coq.Init.DatatypesFQUD Coq.Init.DatatypesFQVA BA Xa pair X A → B → A B B ‡e see th—t the ™onstr—int is enfor™ing th—t indi™es to exp must not live in — higher universe level th—n B Eindi™es to prodF „he next ™onstr—int —˜ove est—˜lishes — symmetri™ ™ondition for AF „hus it is —pp—rent th—t goq m—int—ins — tortuous set of universe v—ri—˜le inequ—lities ˜ehind the s™enesF st m—y look like some fun™tions re polymorphi™ in the universe levels of their —rgumentsD ˜ut wh—t is re—lly h—ppening is imper—tive upd—ting of — system of ™onstr—intsD su™h th—t —ll uses of — fun™tion —re ™onsistent with — glo˜—l set of universe levelsF ‡hen the ™onstr—int system m—y not ˜e evolved soundlyD we get — universe in™onsisten™y errorF ƒomething interesting is reve—led in the —nnot—ted de(nition of IWT prodF e type prod A lives —t — universe th—t is the m—ximum of the universes of A —nd B F prom our e—rlier experimentsD we might expe™t th—t prod 9s universe would in f—™t need to ˜e one higher th—n the m—ximumF „he ™riti™—l di'eren™e is th—tD in the de(nition of prodD A —nd B —re de(ned —s parameters Y th—t isD they —ppe—r n—med to the left of the m—in ™olonD r—ther th—n —ppe—ring @possi˜ly unn—medA to the rightF €—r—meters —re not —s )exi˜le —s norm—l indu™tive type —rgumentsF „he r—nge types of —ll of the ™onstru™tors of — p—r—meterized type must sh—re the s—me p—r—metersF xonethelessD when it is possi˜le to de(ne — polymorphi™ type in this w—yD we g—in the —˜ility to use the new type f—mily in more w—ysD without triggering universe in™onsisten™iesF por inst—n™eD nested p—irs of types —re perfe™tly leg—lF B Check @natD @TypeD SetAAF @natD @Type @B TopFRR BA D SetAA X Set B @Type @B TopFRS BA B Type @B TopFRT BA A „he s—me ™—nnot ˜e done with — ™ounterp—rt to prod th—t does not use p—r—metersF Inductive prod' X Type → Type → Type Xa | pair' X ∀ A B X TypeD A → B → prod' A BF Check @pair' nat @pair' Type SetAAF Error X Universe inconsistency @cannot enforce TopFSI ` TopFSIAF „he key ˜ene(t p—r—meters ˜ring us is the —˜ility to —void qu—ntifying over types in the types of ™onstru™torsF ƒu™h qu—nti(™—tion indu™es lessEth—n ™onstr—intsD while p—r—meters only introdu™e lessEth—nEorEequ—lEto ™onstr—intsF goq in™ludes one more @potenti—lly ™onfusingA fe—ture rel—ted to p—r—metersF ‡hile q—llin— does not support re—l universe polymorphismD there is — ™onvenien™e f—™ility th—t mimi™s universe polymorphism in some ™—sesF ‡e ™—n illustr—te wh—t this me—ns with — simple ex—mpleF Inductive foo @A X TypeA X Type Xa | Foo X A → foo AF Check foo natF foo nat X Set Check foo SetF foo Set X Type Check foo TrueF foo True IWU X Prop „he ˜—si™ p—ttern here is th—t goq is willing to —utom—ti™—lly ˜uild — 4™opiedE—ndEp—sted4 version of —n indu™tive de(nitionD where some o™™urren™es of Type h—ve ˜een repl—™ed ˜y Set or PropF sn e—™h ™ontextD the typeE™he™ker tries to (nd the v—lid repl—™ements th—t —re lowest in the type hier—r™hyF eutom—ti™ ™loning of de(nitions ™—n ˜e mu™h more ™onvenient th—n m—nu—l ™loningF ‡e h—ve —lre—dy t—ken —dv—nt—ge of the f—™t th—t we m—y reEuse the s—me f—milies of tuple —nd list types to form v—lues in Set —nd TypeF smit—tion polymorphism ™—n ˜e ™onfusing in some ™ontextsF por inst—n™eD it is wh—t is responsi˜le for this weird ˜eh—viorF Inductive bar X Type Xa Check barF Bar X barF bar X Prop „he type th—t goq ™omes up with m—y ˜e used in stri™tly more ™ontexts th—n the type one might h—ve expe™tedF 11.2 The Prop Universe sn gh—pter RD we s—w p—r—llel versions of useful d—t—types for 4progr—ms4 —nd 4proofsF4 „he ™onvention w—s th—t progr—ms live in SetD —nd proofs live in PropF ‡e g—ve little expl—n—tion for why it is useful to m—int—in this distin™tionF „here is ™ert—inly do™ument—tion v—lue from sep—r—ting progr—ms from proofsY in pr—™ti™eD di'erent ™on™erns —pply to ˜uilding the two types of o˜je™tsF st turns outD howeverD th—t these ™on™erns motiv—te form—l di'eren™es ˜etween the two universes in goqF ‚e™—ll the types sig —nd exD whi™h —re the progr—m —nd proof versions of existenti—l qu—nti(™—tionF „heir de(nitions di'er only in one pl—™eD where sig uses Type —nd ex uses PropF Print sigF Inductive sig @A X TypeA @P X A → PropA X Type Xa exist X ∀ x X AD P x → sig P Print exF Inductive ex @A X TypeA @P X A → PropA X Prop Xa ex intro X ∀ x X AD P x → ex P st is n—tur—l to w—nt — fun™tion to extr—™t the (rst ™omponents of d—t— stru™tures like theseF hoing so is e—sy enough for sigF Definition projS match x with A @P X A → PropA @x X sig P A X A Xa IWV | exist endF v ⇒ v ‡e run into trou˜le with — version th—t h—s ˜een ™h—nged to work with Definition projE A @P X match x with | ex intro v ⇒ v endF Error X Incorrect elimination of the return type A → PropA @x X exF ex P A X A Xa 4x4 in the inductive type 4ex4X 4„ype4 while it should be 4€rop4F has sort Elimination of an inductive object of sort is not allowed on a predicate in sort Type Prop because proofs can be eliminated only to build proofsF sn form—l goq p—rl—n™eD 4elimin—tion4 me—ns 4p—tternEm—t™hingF4 „he typing rules of q—llin— for˜id us from p—tternEm—t™hing on — dis™riminee whose type ˜elongs to PropD whenE ever the result type of the match h—s — type ˜esides PropF „his is — sort of 4inform—tion )ow4 poli™yD where the type system ensures th—t the det—ils of proofs ™—n never h—ve —ny e'e™t on p—rts of — development th—t —re not —lso m—rked —s proofsF „his restri™tion m—t™hes inform—l pr—™ti™eF ‡e think of progr—ms —nd proofs —s ™le—rly sep—r—tedD —ndD outside of ™onstru™tive logi™D the ide— of ™omputing with proofs is illEformedF „he distin™tion —lso h—s pr—™ti™—l import—n™e in goqD where it —'e™ts the ˜eh—vior of extr—™E tionF ‚e™—ll th—t extr—™tion is goq9s f—™ility for tr—nsl—ting goq developments into progr—ms in gener—lEpurpose progr—mming l—ngu—ges like yg—mlF ixtr—™tion erases proofs —nd le—ves progr—ms int—™tF e simple ex—mple with sig —nd ex demonstr—tes the distin™tionF Definition sym sig @x X sig @fun n ⇒ n a HAA X sig @fun match x with | exist n pf ⇒ exist n @sym eq pf A endF n ⇒ H a n A Xa Extraction sym sigF (** val sym_sig : nat -> nat **) let sym_sig x = x ƒin™e extr—™tion er—ses proofsD the se™ond ™omponents of sig v—lues —re elidedD m—king sig — simple identity type f—milyF „he sym sig oper—tion is thus —n identity fun™tionF Definition sym match x with ex @x X ex @fun n ⇒ n a HAA X ex @fun n ⇒ H a n A Xa IWW | ex endF intro n pf ⇒ ex intro n @sym eq pf A Extraction sym exF (** val sym_ex : __ **) let sym_ex = __ sn this ex—mpleD the ex type itself is in PropD so whole ex p—™k—ges —re er—sedF goq extr—™ts every proposition —s the type D whose single ™onstru™tor is F xot only —re proofs repl—™ed ˜y D ˜ut proof —rguments to fun™tions —re —lso removed ™ompletelyD —s we see hereF ixtr—™tion is very helpful —s —n optimiz—tion over progr—ms th—t ™ont—in proofsF sn l—ngu—ges like r—skellD —dv—n™ed fe—tures m—ke it possi˜le to progr—m with proofsD —s — w—y of ™onvin™ing the type ™he™ker to —™™ept p—rti™ul—r de(nitionsF …nfortun—telyD when proofs —re en™oded —s v—lues in qeh„sD these proofs exist —t runtime —nd ™onsume resour™esF sn ™ontr—stD with goqD —s long —s you keep —ll of your proofs within PropD extr—™tion is gu—r—nteed to er—se themF w—ny f—ns of the gurryErow—rd ™orresponden™e support the ide— of extracting programs from proofsF sn re—lityD few users of goq —nd rel—ted tools do —ny su™h thingF snste—dD extr—™tion is ˜etter thought of —s —n optimiz—tion th—t redu™es the runtime ™osts of expressive typingF ‡e h—ve seen two of the di'eren™es ˜etween proofs —nd progr—msX proofs —re su˜je™t to —n elimin—tion restri™tion —nd —re elided ˜y extr—™tionF „he rem—ining di'eren™e is th—t Prop is impredicativeD —s this ex—mple showsF Check ∀ P Q X PropD P ∨ Q → Q ∨ PF ∀ P Q X PropD P ∨ Q → Q ∨ P X Prop ‡e see th—t it is possi˜le to de(ne — Prop th—t qu—nti(es over other PropsF „his is fortuE n—teD —s we st—rt w—nting th—t —˜ility even for su™h ˜—si™ purposes —s st—ting proposition—l t—utologiesF sn the next se™tion of this ™h—pterD we will see some re—sons why unrestri™ted impredi™—tivity is undesir—˜leF „he impredi™—tivity of Prop inter—™ts ™ru™i—lly with the elimE in—tion restri™tion to —void those pitf—llsF smpredi™—tivity —lso —llows us to implement — version of our e—rlier exp type th—t does not su'er from the we—kness th—t we foundF Inductive expP X Type → Prop Xa | ConstP X ∀ TD T → expP T | PairP X ∀ T1 T2D expP T1 → expP T2 → expP @T1 B | EqP X ∀ TD expP T → expP T → expP boolF Check ConstP HF PHH T2 A ConstP X Check H expP nat PairP @ConstP HA @ConstP @ConstP HA @ConstP X expP @nat B unitA PairP Check EqP X Check EqP ttAF ttA @ConstP SetA @ConstP TypeAF @ConstP SetA @ConstP TypeA expP bool ConstP @ConstP OAF @ConstP HA X expP @expP natA ConstP sn this ™—seD our vi™tory is re—lly — sh—llow oneF es we h—ve m—rked expP —s — f—mily of proofsD we ™—nnot de™onstru™t our expressions in the usu—l progr—mm—ti™ w—ysD whi™h m—kes them —lmost useless for the usu—l purposesF smpredi™—tive qu—nti(™—tion is mu™h more useful in de(ning indu™tive f—milies th—t we re—lly think of —s judgmentsF por inst—n™eD this ™ode de(nes — notion of equ—lity th—t is stri™tly stronger th—n the ˜—se equ—lity aF Inductive eqPlus X ∀ TD T → T → Prop Xa | Base X ∀ T @x X T AD eqPlus x x | Func X ∀ dom ran @f1 f2 X dom → ran AD @∀ x X domD eqPlus @f1 x A @f2 x AA → eqPlus f1 f2F Check @Base HAF Base H X eqPlus H H Check @Func @fun n ⇒ n A @fun n ⇒ H C n A @fun n ⇒ Base n AAF Func @fun n X nat ⇒ n A @fun n X nat ⇒ H C n A @fun n X nat ⇒ X eqPlus @fun n X nat ⇒ nA @fun n X nat ⇒ H C nA Base n A Check @Base @Base IAAF Base @Base IA X eqPlus @Base IA @Base IA 11.3 Axioms ‡hile the spe™i(™ logi™ q—llin— is h—rd™oded into goq9s implement—tionD it is possi˜le to —dd ™ert—in logi™—l rules in — ™ontrolled w—yF sn other wordsD goq m—y ˜e used to re—son —˜out m—ny di'erent re(nements of q—llin— where stri™tly more theorems —re prov—˜leF ‡e —™hieve this ˜y —sserting axioms without proofF PHI ‡e will motiv—te the ide— ˜y touring through some st—nd—rd —xiomsD —s enumer—ted in goq9s online peF s will —dd —ddition—l ™omment—ry —s —ppropri—teF 11.3.1 The Basics yne simple ex—mple of — useful —xiom is the l—w of the ex™luded middleF Require Import Classical PropF Print classicF BBB ‘ classic X ∀ P X PropD P ∨ ¬ P sn the implement—tion of module m—nd “ Classical PropD this —xiom w—s de(ned with the ™omE Axiom classic X ∀ P X PropD P ∨ ¬ PF en Axiom m—y ˜e de™l—red with —ny typeD in —ny of the universesF „here is — synonym Parameter for AxiomD —nd th—t synonym is often ™le—rer for —ssertions not of type PropF por inst—n™eD we ™—n —ssert the existen™e of o˜je™ts with ™ert—in propertiesF Parameter n X natF Axiom positive X n b HF Reset nF „his kind of 4—xiom—ti™ present—tion4 of — theory is very ™ommon outside of higherEorder logi™F roweverD in goqD it is —lmost —lw—ys prefer—˜le to sti™k to de(ning your o˜je™tsD fun™tionsD —nd predi™—tes vi— indu™tive de(nitions —nd fun™tion—l progr—mmingF sn gener—lD there is — signi(™—nt ˜urden —sso™i—ted with —ny use of —xiomsF st is e—sy to —ssert — set of —xioms th—t together is inconsistentF „h—t isD — set of —xioms m—y imply FalseD whi™h —llows —ny theorem to provedD whi™h defe—ts the purpose of — proof —ssist—ntF por ex—mpleD we ™ould —ssert the following —xiomD whi™h is ™onsistent ˜y itself ˜ut in™onsistent when ™om˜ined with classic F Axiom not classic X ∃ P X PropD ¬ @P ∨ ¬ P AF Theorem uhoh X FalseF generalize classic not classic Y firstorderF QedF Theorem uhoh again X I C I a QF destruct uhohF QedF Reset not classicF yn the su˜je™t of the l—w of the ex™luded middle itselfD this —xiom is usu—lly quite h—rmE lessD —nd m—ny pr—™ti™—l goq developments —ssume itF st h—s ˜een proved met—theoreti™—lly to ˜e ™onsistent with gsgF rereD 4proved met—theoreti™—lly4 me—ns th—t someone proved on p—per th—t ex™luded middle holds in — model of gsg in set theoryF ell of the other —xioms th—t we will survey in this se™tion hold in the s—me modelD so they —re —ll ™onsistent togetherF PHP ‚e™—ll th—t goq implements constructive logi™ ˜y def—ultD where ex™luded middle is not prov—˜leF €roofs in ™onstru™tive logi™ ™—n ˜e thought of —s progr—msF e ∀ qu—nti(er denotes — dependent fun™tion typeD —nd — disjun™tion denotes — v—ri—nt typeF sn su™h — settingD ex™luded middle ™ould ˜e interpreted —s — de™ision pro™edure for —r˜itr—ry propositionsD whi™h ™omput—˜ility theory tells us ™—nnot existF „husD ™onstru™tive logi™ with ex™luded middle ™—n no longer ˜e —sso™i—ted with our usu—l notion of progr—mmingF qiven —ll thisD why is it —ll right to —ssert ex™luded middle —s —n —xiomc „he intuitive justi(™—tion is th—t the elimin—tion restri™tion for Prop prevents us from tre—ting proofs —s progr—msF en ex™luded middle —xiom th—t qu—nti(ed over Set inste—d of Prop would ˜e pro˜lem—ti™F sf — development used th—t —xiomD we would not ˜e —˜le to extr—™t the ™ode to yg—ml @soundlyA without implementing — genuine univers—l de™ision pro™edureF sn ™ontr—stD v—lues whose types ˜elong to Prop —re —lw—ys er—sed ˜y extr—™tionD so we sidestep the —xiom9s —lgorithmi™ ™onsequen™esF fe™—use the proper use of —xioms is so pre™—riousD there —re helpful ™omm—nds for deterE mining whi™h —xioms — theorem relies onF Theorem t1 X ∀ tautoF QedF Print P X PropD P → ¬ ¬ PF Assumptions t1F Closed under Theorem t2 X∀ the global context P X PropD ¬ ¬ P → PF tautoF Error X tauto intro QedF Print PY failedF destruct @classic P AY tautoF Assumptions t2F AxiomsX classic X∀ P X PropD P ∨¬ P st is possi˜le to —void this dependen™e in some spe™i(™ ™—sesD where ex™luded middle prov—˜leD for de™id—˜le f—milies of propositionsF Theorem classic nat eq X ∀ n m X natD n a m ∨ n = mF induction n Y destruct m Y intuitionY generalize @IHn QedF Theorem t2' X ∀ n m X natD ¬ ¬ @n a intros n m Y destruct @classic nat QedF mA a mF m AY tautoF → eq n n PHQ m AY intuitionF is Print Assumptions t2'F Closed under the global context w—instre—m m—them—ti™—l pr—™ti™e —ssumes ex™luded middleD so it ™—n ˜e useful to h—ve it —v—il—˜le in goq developmentsD though it is —lso ni™e to know th—t — theorem is proved in — simpler form—l system th—n ™l—ssi™—l logi™F „here is — simil—r story for proof irrelevanceD whi™h simpli(es proof issues th—t would not even —rise in m—instre—m m—thF Require Import ProofIrrelevanceF Print proof irrelevanceF BBB ‘ proof irrelevance X ∀ @P X PropA @p1 p2 X P AD p1 a p2 “ „his —xiom —sserts th—t —ny two proofs of the s—me proposition —re equ—lF sf we repl—™ed p1 a p2 ˜y p1 ↔ p2D then the st—tement would ˜e prov—˜leF roweverD equ—lity is — stronger notion th—n logi™—l equiv—len™eF ‚e™—ll this ex—mple fun™tion from gh—pter TF Definition pred strong1 @n X natA X n b H → nat Xa match n with | O ⇒ fun pf X H b H ⇒ match zgtz pf with end | S n' ⇒ fun ⇒ n' endF ‡e might w—nt to prove th—t di'erent proofs of from our ri™hlyEtyped prede™essor fun™tionF Theorem pred strong1 destruct n Y crushF QedF irrel X∀ n @pf1 pf2 X n b HAD n b H do not le—d to di'erent results pred strong1 pf1 a pred strong1 pf2F „he proof s™ript is simpleD ˜ut it involved peeking into the de(nition of pred strong1F por more ™ompli™—ted fun™tion de(nitionsD it ™—n ˜e ™onsider—˜ly more work to prove th—t they do not dis™rimin—te on det—ils of proof —rgumentsF „his ™—n seem like — sh—meD sin™e the Prop elimin—tion restri™tion m—kes it impossi˜le to write —ny fun™tion th—t does othE erwiseF …nfortun—telyD this f—™t is only true met—theoreti™—llyD unless we —ssert —n —xiom like proof irrelevance F ‡ith th—t —xiomD we ™—n prove our theorem without ™onsulting the de(nition of pred strong1F Theorem pred strong1 irrel' X ∀ n @pf1 pf2 X n b HAD introsY f equalY apply proof irrelevance F QedF pred strong1 pf1 a pred strong1 pf2F sn the ™h—pter on equ—lityD we —lre—dy dis™ussed some —xioms th—t —re rel—ted to proof irrelev—n™eF sn p—rti™ul—rD goq9s st—nd—rd li˜r—ry in™ludes this —xiomX Require Import EqdepF Import Eq rect eqF Print eq rect eqF PHR BBB ‘ eq rect eq X ∀ @U X TypeA @p X U A @Q X x a eq rect p Q x p h “ like U → TypeA @x X Q pA @h X p a p AD „his —xiom s—ys th—t it is permissi˜le to simplify p—ttern m—t™hes over proofs of equ—lities e a eF „he —xiom is logi™—lly equiv—lent to some simpler ™oroll—riesF Corollary UIP re X ∀ A @x X AA @pf X x a x AD pf a re equal xF introsY replace pf with @eq rect x @eq x A @re equal x A x pf AY ‘ symmetryY apply eq rect eq | exact @match pf as pf ' return match pf ' in a y return x a y with | re equal ⇒ re equal x end a pf ' with | re equal ⇒ re equal endA “F QedF Corollary UIP X ∀ A @x y X AA @pf1 pf2 X x a y AD pf1 a pf2F introsY generalize pf1 pf2 Y substY introsY match goal with | ‘ cpfI a cpfP “ ⇒ rewrite @UIP re pf1 AY rewrite @UIP re pf2 AY reflexivity endF QedF „hese ™oroll—ries —re spe™i—l ™—ses of proof irrelev—n™eF sn developments th—t only need proof irrelev—n™e for equ—lityD there is no need to —ssert full irrelev—n™eF enother f—™et of proof irrelev—n™e is th—tD like ex™luded middleD it is often prov—˜le for spe™i(™ propositionsF por inst—n™eD UIP is prov—˜le whenever the type A h—s — de™id—˜le equ—lity oper—tionF „he module Eqdep dec of the st—nd—rd li˜r—ry ™ont—ins — proofF e simil—r phenomenon —pplies to other not—˜le ™—sesD in™luding lessEth—n proofsF „husD it is often possi˜le to use proof irrelev—n™e without —sserting —xiomsF „here —re two more ˜—si™ —xioms th—t —re often —ssumedD to —void ™ompli™—tions th—t do not —rise in set theoryF Require Import FunctionalExtensionalityF Print functional extensionality depF BBB ‘ functional extensionality dep X ∀ @A X TypeA @B X A → TypeA @f g X ∀ x X @∀ x X AD f x a g x A → f a g “ AD B x AD „his —xiom s—ys th—t two fun™tions —re equ—l if they m—p equ—l inputs to equ—l outputsF ƒu™h f—™ts —re not prov—˜le in gener—l in gsgD ˜ut it is ™onsistent to —ssume th—t they —reF e simple ™oroll—ry shows th—t the s—me property —pplies to predi™—tesF sn some ™—sesD one might prefer to —ssert this ™oroll—ry —s the —xiomD to restri™t the ™onsequen™es to proofs PHS —nd not progr—msF Corollary predicate extensionality X ∀ @A X TypeA @B X A → PropA @f @∀ x X AD f x a g x A → f a gF introsY apply functional extensionality dep Y assumptionF QedF g X∀ x X AD B x AD 11.3.2 Axioms of Choice ƒome goq —xioms —re —lso points of ™ontention in m—instre—m m—thF „he most prominent ex—mple is the —xiom of ™hoi™eF sn f—™tD there —re multiple versions th—t we might ™onsiderD —ndD ™onsidered in isol—tionD none of these versions me—ns quite wh—t it me—ns in ™l—ssi™—l set theoryF pirstD it is possi˜le to implement — ™hoi™e oper—tor without —xioms in some potenti—lly surprising ™—sesF Require Import ConstructiveEpsilonF Check constructive denite descriptionF constructive denite description X ∀ @A X SetA @f X A → natA @g X nat → @∀ x X AD g @f x A a x A → ∀ P X A → PropD @∀ x X AD {P x } C {¬ P x }A → @∃3 x X AD P x A → {x X A | P x } Print AAD Assumptions constructive denite descriptionF Closed under the global context „his fun™tion tr—nsforms — de™id—˜le predi™—te P into — fun™tion th—t produ™es —n elE ement s—tisfying P from — proof th—t su™h —n element existsF „he fun™tions f —nd g D in ™onjun™tion with —n —sso™i—ted inje™tivity propertyD —re used to express the ide— th—t the set A is ™ount—˜leF …nder these ™onditionsD — simple ˜rute for™e —lgorithm gets the jo˜ doneX we just enumer—te —ll elements of AD stopping when we (nd one s—tisfying P F „he existen™e proofD spe™i(ed in terms of unique existen™e ∃3D gu—r—ntees termin—tionF „he de(nition of this oper—tor in goq uses some interesting te™hniquesD —s seen in the implement—tion of the ConstructiveEpsilon moduleF gount—˜le ™hoi™e is prov—˜le in set theory without —ppe—ling to the gener—l —xiom of ™hoi™eF „o support the more gener—l prin™iple in goqD we must —lso —dd —n —xiomF rere is — fun™tion—l version of the —xiom of unique ™hoi™eF Require Import ClassicalUniqueChoiceF Check dependent unique choice F dependent unique choice X ∀ @A X TypeA @B X A → TypeA @R X ∀ @∀ x X AD ∃3 y X B x D R x y A → x X PHT AD B x → PropAD ∃ f X∀ x X AD B x D ∀ x X AD R x @f x A „his —xiom lets us ™onvert — rel—tion—l spe™i(™—tion R into — fun™tion implementing th—t spe™i(™—tionF ‡e need only prove th—t R is truly — fun™tionF en —ltern—teD stronger formul—tion —pplies to ™—ses where R m—ps e—™h input to one or more outputsF ‡e —lso simplify the st—tement of the theorem ˜y ™onsidering only nonEdependent fun™tion typesF Require Import Check choiceF ClassicalChoiceF choice X ∀ @A B X TypeA @R X A → B → PropAD @ ∀ x X AD ∃ y X B D R x y A → ∃ f X A → B D ∀ x X AD R x @f x A „his prin™iple is proved —s — theoremD ˜—sed on the unique ™hoi™e —xiom —nd —n —ddition—l —xiom of rel—tion—l ™hoi™e from the RelationalChoice moduleF sn set theoryD the —xiom of ™hoi™e is — fund—ment—l philosophi™—l ™ommitment one m—kes —˜out the universe of setsF sn goqD the ™hoi™e —xioms s—y something we—kerF por inst—n™eD ™onsider the simple rest—tement of the choice —xiom where we repl—™e existenti—l qu—nti(™—E tion ˜y its gurryErow—rd —n—logueD su˜set typesF Definition choice Set @A B X TypeA @R X A → B → PropA @H X ∀ X {f X A → B | ∀ x X AD R x @f x A} Xa exist @fun f ⇒ ∀ x X AD R x @f x AA @fun x ⇒ proj1 sig @H x AA @fun x ⇒ proj2 sig @H x AAF x X AD {y X B | R x y }A †i— the gurryErow—rd ™orresponden™eD this 4—xiom4 ™—n ˜e t—ken to h—ve the s—me me—ning —s the origin—lF st is implemented trivi—lly —s — tr—nsform—tion not mu™h deeper th—n un™urryingF „husD we see th—t the utility of the —xioms th—t we mentioned e—rlier ™omes in their us—ge to ˜uild progr—ms from proofsF xorm—l set theory h—s no expli™it proofsD so the me—ning of the usu—l —xiom of ™hoi™e is su˜tlely di'erentF sn q—llin—D the —xioms implement — ™ontrolled rel—x—tion of the restri™tions on inform—tion )ow from proofs to progr—msF roweverD when we ™om˜ine —n —xiom of ™hoi™e with the l—w of the ex™luded middleD the ide— of 4™hoi™e4 ˜e™omes more interestingF ix™luded middle gives us — highly nonE ™omput—tion—l w—y of ™onstru™ting proofsD ˜ut it does not ™h—nge the ™omput—tion—l n—ture of progr—msF „husD the —xiom of ™hoi™e is still giving us — w—y of tr—nsl—ting ˜etween two di'erent sorts of 4progr—msD4 ˜ut the input progr—ms @whi™h —re proofsA m—y ˜e written in — ri™h l—ngu—ge th—t goes ˜eyond norm—l ™omput—˜ilityF „his truly is more th—n rep—™k—ging — fun™tion with — di'erent typeF „he goq tools support — ™omm—ndEline )—g -impredicative-setD whi™h modi(es q—llin— in — more fund—ment—l w—y ˜y m—king Set impredi™—tiveF e term like ∀ T X SetD T h—s type SetD —nd indu™tive de(nitions in Set m—y h—ve ™onstru™tors th—t qu—ntify over —rguments of —ny typesF „o m—int—in ™onsisten™yD —n elimin—tion restri™tion must ˜e imposedD simil—rly to the restri™tion for PropF „he restri™tion only —pplies to l—rge indu™tive typesD where some PHU ™onstru™tor qu—nti(es over — type of type TypeF sn su™h ™—sesD — v—lue in this indu™tive type m—y only ˜e p—tternEm—t™hed over to yield — result type whose type is Set or PropF „his ™ontr—sts with PropD where the restri™tion —pplies even to nonEl—rge indu™tive typesD —nd where the result type m—y only h—ve type PropF sn old versions of goqD Set w—s impredi™—tive ˜y def—ultF v—ter versions m—ke Set predi™—tive to —void in™onsisten™y with some ™l—ssi™—l —xiomsF sn p—rti™ul—rD one should w—t™h out when using impredi™—tive Set with —xioms of ™hoi™eF sn ™om˜in—tion with ex™luded middle or predi™—te extension—lityD this ™—n le—d to in™onsisten™yF smpredi™—tive Set ™—n ˜e useful for modeling inherently impredi™—tive m—them—ti™—l ™on™eptsD ˜ut —lmost —ll goq developments get ˜y (ne without itF 11.3.3 Axioms and Computation yne —ddition—l —xiomErel—ted wrinkle —rises from —n —spe™t of q—llin— th—t is very di'erent from set theoryX — notion of computational equivalence is ™entr—l to the de(nition of the form—l systemF exioms tend not to pl—y well with ™omput—tionF gonsider this ex—mpleF ‡e st—rt ˜y implementing — fun™tion th—t uses — type equ—lity proof to perform — s—fe typeE™—stF Definition cast @x y X SetA @pf X match pf with | re equal ⇒ v endF x a y A @v X gomput—tion over progr—ms th—t use Eval compute in @cast @re equal cast @nat → xA X y Xa ™—n pro™eed smoothlyF natAA @fun n ⇒ S n AA IPF a IQ X nat „hings do not go —s smoothly when we use cast with proofs th—t rely on —xiomsF X @∀ n X natD n @S n AA a @∀ n X natD n @n C IAAF @@∀ n X natD @fun n ⇒ n @S n AA n A a @∀ n X natD @fun n ⇒ n @n C IAA n AAY rewrite @functional extensionality @fun n ⇒ n @n C IAA @fun n ⇒ n @S n AAAY crushF Theorem t3 change QedF Eval compute in @cast t3 @fun ⇒ FirstAA IPF a match t3 in @ a P A return P with | re equal ⇒ fun n X nat ⇒ First end IP X n @IP C IA gomput—tion gets stu™k in — p—tternEm—t™h on the proof t3F „he stru™ture of t3 is not knownD so the m—t™h ™—nnot pro™eedF st turns out — more ˜—si™ pro˜lem le—ds to this PHV p—rti™ul—r situ—tionF ‡e ended the proof of t3 with QedD so the de(nition of t3 is not —v—il—˜le to ™omput—tionF „h—t is e—sily (xedF Reset t3F X @∀ n X natD n @S n AA a @∀ n X natD n @n C IAAF @@∀ n X natD @fun n ⇒ n @S n AA n A a @∀ n X natD @fun n ⇒ n @n C IAA n AAY rewrite @functional extensionality @fun n ⇒ n @n C IAA @fun n ⇒ n @S n AAAY crushF DefinedF Theorem t3 change Eval compute in @cast t3 @fun ⇒ FirstAA IPF a match match match functional extensionality FFFF ‡e elide most of the det—ilsF e very unwieldy tree of nested m—t™hes on equ—lity proofs —ppe—rsF „his time ev—lu—tion re—lly is stu™k on — use of —n —xiomF sf we —re ™—reful in using t—™ti™s to prove —n equ—lityD we ™—n still ™ompute with ™—sts over the proofF Lemma plus1 X ∀ nD S n a n C IF induction n Y simplY intuitionF DefinedF Theorem t4 X ∀ nD n @S n A a n @n C IAF introY f equalY apply plus1F DefinedF Eval compute in cast @t4 IQA a First X n @IQ C IA FirstF PHW Part III Proof Engineering PIH Chapter 12 Proof Search in Ltac ‡e h—ve seen m—ny ex—mples of proof —utom—tion so f—rF „his ™h—pter —ims to give — prin™ipled present—tion of the fe—tures of vt—™D fo™using in p—rti™ul—r on the vt—™ match ™onstru™tD whi™h supports — novel —ppro—™h to ˜—™ktr—™king se—r™hF pirstD thoughD we will run through some useful —utom—tion t—™ti™s th—t —re ˜uilt into goqF „hey —re des™ri˜ed in det—il in the m—nu—lD so we only outline wh—t is possi˜leF 12.1 Some Built-In Automation Tactics e num˜er of t—™ti™s —re ™—lled repe—tedly ˜y crushF intuition simpli(es proposition—l stru™ture of go—lsF congruence —pplies the rules of equ—lity —nd ™ongruen™e ™losureD plus properties of ™onstru™tors of indu™tive typesF „he omega t—™ti™ provides — ™omplete de™ision pro™edure for — theory th—t is ™—lled qu—nti(erEfree line—r —rithmeti™ or €res˜urger —rithmeti™D depending on whom you —skF „h—t isD omega proves —ny go—l th—t follows from looking only —t p—rts of th—t go—l th—t ™—n ˜e interpreted —s proposition—l formul—s whose —tomi™ formul—s —re ˜—si™ ™omp—rison oper—tions on n—tur—l num˜ers or integersF „he ring t—™ti™ solves go—ls ˜y —ppe—ling to the —xioms of rings or semiErings @—s in —lge˜r—AD depending on the type involvedF goq developments m—y de™l—re new types to ˜e p—rts of rings —nd semiErings ˜y proving the —sso™i—ted —xiomsF „here is — siml—r t—™ti™ eld for simplifying v—lues in (elds ˜y ™onversion to fr—™tions over ringsF foth ring —nd eld ™—n only solve go—ls th—t —re equ—litiesF „he fourier t—™ti™ uses pourier9s method to prove inequ—lities over re—l num˜ersD whi™h —re —xiom—tized in the goq st—nd—rd li˜r—ryF „he setoid f—™ility m—kes it possi˜le to register new equiv—len™e rel—tions to ˜e understood ˜y t—™ti™s like rewriteF por inst—n™eD Prop is registered —s — setoid with the equiv—len™e rel—tion 4if —nd only ifF4 „he —˜ility to register new setoids ™—n ˜e very useful in proofs of — kind ™ommon in m—thD where —ll re—soning is done —fter 4modding out ˜y — rel—tionF4 PII 12.2 Hint Databases enother ™l—ss of ˜uiltEin t—™ti™s in™ludes autoD eautoD —nd autorewriteF „hese —re ˜—sed on hint databasesD whi™h we h—ve seen extended in m—ny ex—mples so f—rF „hese t—™ti™s —re import—ntD ˜e™—useD in vt—™ progr—mmingD we ™—nnot ™re—te 4glo˜—l v—ri—˜les4 whose v—lues ™—n ˜e extended se—mlessly ˜y di'erent modules in di'erent sour™e (lesF ‡e h—ve seen the —dv—nt—ges of hints so f—rD where crush ™—n ˜e de(ned on™e —nd for —llD while still —utom—ti™—lly —pplying the hints we —dd throughout developmentsF „he ˜—si™ hints for auto —nd eauto —re Hint Immediate lemmaD —sking to try solving — go—l immedi—tely ˜y —pplying — lemm— —nd dis™h—rging —ny hypotheses with — single proof step e—™hY Resolve lemmaD whi™h does the s—me ˜ut m—y —dd new premises th—t —re themselves to ˜e su˜je™ts of nested proof se—r™hY Constructor typeD whi™h —™ts like Resolve —pplied to every ™onstru™tor of —n indu™tive typeY —nd Unfold identD whi™h tries unfolding ident when it —ppe—rs —t the he—d of — proof go—lF i—™h of these Hint ™omm—nds m—y ˜e used with — su0xD —s in Hint Resolve lemma X my dbF „his —dds the hint only to the spe™i(ed d—t—˜—seD so th—t it would only ˜e used ˜yD for inst—n™eD auto with my dbF en —ddition—l —rgument to auto spe™i(es the m—ximum depth of proof trees to se—r™h in depthE(rst orderD —s in auto V or auto V with my dbF „he def—ult depth is SF ell of these Hint ™omm—nds ™—n ˜e issued —ltern—tively with — more primitive hint kindD ExternF e few ex—mples should do ˜est to expl—in how Hint Extern worksF Theorem autoF bool neq X true = falseF crush would h—ve dis™h—rged this go—lD ˜ut the def—ult hint d—t—˜—se for auto ™ont—ins no hint th—t —ppliesF AbortF st is h—rd to ™ome up with — boolEspe™i(™ hint th—t is not just — rest—tement of the theorem we me—n to proveF vu™kilyD — simpler form su0™esF Hint Extern I @ = A ⇒ congruenceF Theorem autoF QedF bool neq X true = falseF = D try —pplying yur hint s—ysX 4whenever the ™on™lusion m—t™hes the p—ttern congruenceF4 „he I is — ™ost for this ruleF huring proof se—r™hD whenever multiple rules —pplyD rules —re tried in in™re—sing ™ost orderD so it p—ys to —ssign high ™osts to rel—tively expensive Extern hintsF Extern hints m—y ˜e implemented with the full vt—™ l—ngu—geF „his ex—mple shows — ™—se where — hint uses — matchF Section forall andF Variable A X SetF Variables P Q X A → PropF PIP Hypothesis Theorem crushF both X ∀ xD forall and Px X ∀ zD ∧ Q xF P zF crush m—kes no progress ˜eyond wh—t intros would h—ve —™™omplishedF auto will not —pply the hypothesis both to prove the go—lD ˜e™—use the ™on™lusion of both does not unify with the ™on™lusion of the go—lF roweverD we ™—n te—™h auto to h—ndle this kind of go—lF Hint Extern I @P cˆA ⇒ match goal with | ‘ H X ∀ xD P x ∧ endF “ ⇒ apply @proj1 @H X AA autoF QedF ‡e see th—t —n Extern p—ttern m—y ˜ind uni(™—tion v—ri—˜les th—t we use in the —sso™i—ted t—™ti™F proj1 is — fun™tion from the st—nd—rd li˜r—ry for extr—™ting — proof of R from — proof of R ∧ S F End forall andF efter our su™™ess on this ex—mpleD we might get more —m˜itious —nd seek to gener—lize the hint to —ll possi˜le predi™—tes P F Hint Extern I @c€ cˆA ⇒ match goal with | ‘ H X ∀ xD P x ∧ endF “ ⇒ apply @proj1 @H X AA User error X Bound head variable goq9s auto hint d—t—˜—ses work —s t—˜les m—pping head symbols to lists of t—™ti™s to tryF fe™—use of thisD the ™onst—nt he—d of —n Extern p—ttern must ˜e determin—˜le st—ti™—llyF sn our (rst Extern hintD the he—d sym˜ol w—s notD sin™e x = y desug—rs to not @eq x y AY —ndD in the se™ond ex—mpleD the he—d sym˜ol w—s P F „his restri™tion on Extern hints is the m—in limit—tion of the auto me™h—nismD preventing us from using it for gener—l ™ontext simpli(™—tions th—t —re not keyed o' of the form of the ™on™lusionF „his is perh—ps just —s wellD sin™e we ™—n often ™ode more e0™ient t—™ti™s with spe™i—lized vt—™ progr—msD —nd we will see how in l—ter se™tions of the ™h—pterF ‡e h—ve used Hint Rewrite in m—ny ex—mples so f—rF crush uses these hints ˜y ™—lling autorewriteF yur rewrite hints h—ve t—ken the form Hint Rewrite lemma X cpdtD —dding them to the cpdt rewrite d—t—˜—seF „his is ˜e™—useD in ™ontr—st to autoD autorewrite h—s no def—ult d—t—˜—seF „husD we set the ™onvention th—t crush uses the cpdt d—t—˜—seF „his ex—mple shows — dire™t use of autorewriteF Section autorewriteF PIQ Variable Variable A f Hypothesis Hint X SetF X A→ ff AF X ∀ xD Rewrite f f X f @f xA a f xF my dbF Lemma f f f X ∀ xD f @f @f x AA a introsY autorewrite with my QedF f xF db Y reflexivityF „here —re — few w—ys in whi™h autorewrite ™—n le—d to trou˜le when insu0™ient ™—re is t—ken in ™hoosing hintsF pirstD the set of hints m—y de(ne — nontermin—ting rewrite systemD in whi™h ™—se invo™—tions to autorewrite m—y not termin—teF ƒe™ondD we m—y —dd hints th—t 4le—d autorewrite down the wrong p—thF4 por inst—n™eX Section garden pathF Variable g X A → AF Hypothesis f g X ∀ xD f x a Hint Rewrite f g X my dbF g xF Lemma f f f ' X ∀ xD f @f @f x AA a f xF introsY autorewrite with my dbF aaaaaaaaaaaaaaaaaaaaaaaaaaaa g @g @g x AA a g x AbortF yur new hint w—s used to rewrite the go—l into — form where the old hint ™ould no longer ˜e —ppliedF „his 4nonEmonotoni™ity4 of rewrite hints ™ontr—sts with the situ—tion for autoD where new hints m—y slow down proof se—r™h ˜ut ™—n never 4˜re—k4 old proofsF Reset garden pathF works with qu—nti(ed equ—lities th—t in™lude —ddition—l premisesD ˜ut we must ˜e ™—reful to —void simil—r in™orre™t rewritingsF autorewrite Section garden pathF Variable P X A → PropF Variable g X A → AF Hypothesis f g X ∀ xD P x → Hint Rewrite f g X my dbF fx a g xF Lemma f f f ' X ∀ xD f @f @f x AA a f xF introsY autorewrite with my dbF aaaaaaaaaaaaaaaaaaaaaaaaaaaa g @g @g x AA a g x PIR subgoal P is X Px subgoal Q P @f x A subgoal R P @f x A is X is X AbortF „he in—ppropri—te rule (red the s—me three times —s ˜eforeD even though we know we will not ˜e —˜le to prove the premisesF Reset garden pathF yur (n—lD su™™essfulD —ttempt uses —n extr— —rgument to Hint t—™ti™ to —pply to gener—ted premisesF Section garden pathF Variable P X A → PropF Variable g X A → AF Hypothesis f g X ∀ xD P x → f x a g xF Hint Rewrite f g using assumption X my Rewrite th—t spe™i(es — dbF Lemma f f f ' X ∀ xD f @f @f x AA a f xF introsY autorewrite with my db Y reflexivityF QedF autorewrite will still use fg when the gener—ted premise is —mong our —ssumptionsF Lemma f f f g X ∀ xD P x → f @f introsY autorewrite with my QedF End garden pathF xA db Y a g xF reflexivityF st ™—n —lso ˜e useful to use the autorewrite with hypothesesD —s well —s in the ™on™lusionF Lemma in star X ∀ x yD f @f @f @f → f x a f @f @f y AAF introsY autorewrite with my QedF End x AAA db a f @f db in B formD whi™h does rewriting in yA in ∗Y assumptionF autorewriteF 12.3 Ltac Programming Basics ‡e h—ve —lre—dy seen m—ny ex—mples of vt—™ progr—msF sn the rest of this ™h—pterD we —ttempt to give — more prin™ipled introdu™tion to the import—nt fe—tures —nd design p—tternsF PIS yne ™ommon use for match t—™ti™s is identi(™—tion of su˜je™ts for ™—se —n—lysisD —s we see in this t—™ti™ de(nitionF Ltac nd if Xa match goal with | ‘ if cˆ then else “ ⇒ destruct X endF „he t—™ti™ ™he™ks if the ™on™lusion is —n ifD destructing the test expression if soF gert—in ™l—sses of theorem —re trivi—l to prove —utom—ti™—lly with su™h — t—™ti™F Theorem hmm X ∀ @a b c X boolAD if a then if b then True else True else if c then True else TrueF introsY repeat nd if Y constructorF QedF „he repeat th—t we use here is ™—lled — tacticalD or t—™ti™ ™om˜in—torF „he ˜eh—vior of repeat t is to loop through running t D running t on —ll gener—ted su˜go—lsD running t on their gener—ted su˜go—lsD —nd so onF ‡hen t f—ils —t —ny point in this se—r™h treeD th—t p—rti™ul—r su˜go—l is left to ˜e h—ndled ˜y l—ter t—™ti™sF „husD it is import—nt never to use repeat with — t—™ti™ th—t —lw—ys su™™eedsF enother very useful vt—™ ˜uilding ˜lo™k is context patternsF Ltac nd if inside Xa match goal with | ‘ context ‘if cˆ then else “ “ ⇒ destruct X endF „he ˜eh—vior of this t—™ti™ is to (nd —ny su˜term of the ™on™lusion th—t is —n if —nd then destruct the test expressionF „his version su˜sumes nd ifF Theorem hmm' X ∀ @a b c X boolAD if a then if b then True else True else if c then True else TrueF introsY repeat nd if inside Y constructorF QedF ‡e ™—n —lso use nd if inside to prove go—ls th—t nd if does not simplify su0™ientlyF PIT Theorem hmm2 X ∀ @a b X boolAD @if a then RP else RPA a @if b then RP else RPAF introsY repeat nd if inside Y reflexivityF QedF w—ny de™ision pro™edures ™—n ˜e ™oded in vt—™ vi— 4repeat match loopsF4 por inst—n™eD we ™—n implement — su˜set of the fun™tion—lity of tautoF Ltac my tauto Xa repeat match goal with | ‘ H X c€ c€ “ ⇒ exact True “ ⇒ constructor |‘ |‘ |‘ |‘ |‘ |‘ |‘ endF H ∧ “ ⇒ constructor → “ ⇒ intro H H H X X X False ∧ ∨ “ ⇒ destruct “ ⇒ destruct “ ⇒ destruct H H H H1 X c€ → cD H2 X c€ “⇒ let H Xa fresh 4r4 in generalize @H1 H2 AY clear H1 Y intro H ƒin™e match p—tterns ™—n sh—re uni(™—tion v—ri—˜les ˜etween hypothesis —nd ™on™lusion p—tternsD it is e—sy to (gure out when the ™on™lusion m—t™hes — hypothesisF „he exact t—™ti™ solves — go—l ™ompletely when given — proof term of the proper typeF st is —lso trivi—l to implement the 4introdu™tion rules4 for — few of the ™onne™tivesF smplementing elimin—tion rules is only — little more workD sin™e we must give — n—me for — hypothesis to destructF „he l—st rule implements modus ponensF „he most interesting p—rt is the use of the vt—™Elevel let with — fresh expressionF fresh t—kes in — n—me ˜—se —nd returns — fresh hypothesis v—ri—˜le ˜—sed on th—t n—meF ‡e use the new n—me v—ri—˜le H —s the n—me we —ssign to the result of modus ponensF „he use of generalize ™h—nges our ™on™lusion to ˜e —n impli™—tion from Q F ‡e ™le—r the origin—l hypothesis —nd move Q into the ™ontext with n—me HF Section propositionalF Variables P Q R X PropF Theorem propositional my tautoF X @P ∨ Q ∨ FalseA ∧ @P → Q A → True ∧ QF QedF End propositionalF st w—s rel—tively e—sy to implement modus ponensD ˜e™—use we do not lose inform—tion PIU ˜y ™le—ring every impli™—tion th—t we useF sf we w—nt to implement — simil—rlyE™omplete pro™edure for qu—nti(er inst—nti—tionD we need — w—y to ensure th—t — p—rti™ul—r proposition is not —lre—dy in™luded —mong our hypothesesF „o do th—t e'e™tivelyD we (rst need to le—rn — ˜it more —˜out the sem—nti™s of matchF st is tempting to —ssume th—t match works like it does in wvF sn f—™tD there —re — few ™riti™—l di'eren™es in its ˜eh—viorF yne is th—t we m—y in™lude —r˜itr—ry expressions in p—tternsD inste—d of ˜eing restri™ted to v—ri—˜les —nd ™onstru™torsF enother is th—t the s—me v—ri—˜le m—y —ppe—r multiple timesD indu™ing —n impli™it equ—lity ™onstr—intF „here is — rel—ted p—ir of two other di'eren™es th—t —re mu™h more import—nt th—n the othersF match h—s — backtracking semantics for failureF sn wvD p—ttern m—t™hing works ˜y (nding the (rst p—ttern to m—t™h —nd then exe™uting its ˜odyF sf the ˜ody r—ises —n ex™eptionD then the over—ll m—t™h r—ises the s—me ex™eptionF sn goqD f—ilures in ™—se ˜odies inste—d trigger ™ontinued se—r™h through the list of ™—sesF por inst—n™eD this @unne™ess—rily ver˜oseA proof s™ript worksX Theorem m1 X TrueF match goal with “ ⇒ intro |‘ | ‘ True “ ⇒ constructor endF QedF „he (rst ™—se m—t™hes trivi—llyD ˜ut its ˜ody t—™ti™ f—ilsD sin™e the ™on™lusion does not ˜egin with — qu—nti(er or impli™—tionF sn — simil—r wv m—t™hD th—t would me—n th—t the whole p—tternEm—t™h f—ilsF sn goqD we ˜—™ktr—™k —nd try the next p—tternD whi™h —lso m—t™hesF sts ˜ody t—™ti™ su™™eedsD so the over—ll t—™ti™ su™™eeds —s wellF „he ex—mple shows how f—ilure ™—n move to — di'erent p—ttern within — matchF p—ilure ™—n —lso trigger —n —ttempt to (nd a dierent way of matching a single patternF gonsider —nother ex—mpleX Theorem m2 X ∀ P Q R X PropD P → Q → introsY match goal with “ ⇒ idtac H |‘H X endF R → QF goq prints 4H1 4F fy —pplying idtac with —n —rgumentD — ™onvenient de˜ugging tool for 4le—king inform—tion out of matchesD4 we see th—t this match (rst tries ˜inding H to H1 D whi™h ™—nnot ˜e used to prove Q F xonethelessD the following v—ri—tion on the t—™ti™ su™™eeds —t proving the go—lX match goal with |‘H X “ ⇒ exact endF QedF H „he t—™ti™ (rst uni(es H with H1 D —s ˜eforeD ˜ut exact H f—ils in th—t ™—seD so the t—™ti™ engine se—r™hes for more possi˜le v—lues of HF iventu—llyD it —rrives —t the ™orre™t v—lueD so PIV th—t exact H —nd the over—ll t—™ti™ su™™eedF xow we —re equipped to implement — t—™ti™ for ™he™king th—t — proposition is not —mong our hypothesesX Ltac notHyp P Xa match goal with |‘ X P “ ⇒ fail I |⇒ match P with | c€I ∧ c€P ⇒ rst ‘ | ⇒ idtac end endF notHyp P1 | notHyp P2 | fail P “ ‡e use the equ—lity ™he™king th—t is ˜uilt into p—tternEm—t™hing to see if there is — hypothesis th—t m—t™hes the proposition ex—™tlyF sf soD we use the fail t—™ti™F ‡ithout —rgumentsD fail sign—ls norm—l t—™ti™ f—ilureD —s you might expe™tF ‡hen fail is p—ssed —n —rgument nD n is used to ™ount outw—rds through the en™losing ™—ses of ˜—™ktr—™king se—r™hF sn this ™—seD fail I s—ys 4f—il not just in this p—tternEm—t™hing ˜r—n™hD ˜ut for the whole matchF4 „he se™ond ™—se will never ˜e tried when the fail I is re—™hedF „his se™ond ™—seD used when P m—t™hes no hypothesisD ™he™ks if P is — ™onjun™tionF yther simpli(™—tions m—y h—ve split ™onjun™tions into their ™omponent formul—sD so we need to ™he™k th—t —t le—st one of those ™omponents is —lso not representedF „o —™hieve thisD we —pply the rst t—™ti™—lD whi™h t—kes — list of t—™ti™s —nd ™ontinues down the list until one of them does not f—ilF „he fail P —t the end s—ys to fail ˜oth the rst —nd the match wr—pped —round itF „he ˜ody of the c€I ∧ c€P ™—se gu—r—ntees th—tD if it is re—™hedD we either su™™eed ™ompletely or f—il ™ompletelyF „husD if we re—™h the wild™—rd ™—seD P is not — ™onjun™tionF ‡e use idtacD — t—™ti™ th—t would ˜e silly to —pply on its ownD sin™e its e'e™t is to su™™eed —t doing nothingF xonethelessD idtac is — useful pl—™eholder for ™—ses like wh—t we see hereF ‡ith the nonEpresen™e ™he™k implementedD it is e—sy to ˜uild — t—™ti™ th—t t—kes —s input — proof term —nd —dds its ™on™lusion —s — new hypothesisD only if th—t ™on™lusion is not —lre—dy presentD f—iling otherwiseF Ltac extend pf Xa let t Xa type of pf in notHyp t Y generalize pf Y introF ‡e see the useful type of oper—tor of vt—™F „his oper—tor ™ould not ˜e implemented in q—llin—D ˜ut it is e—sy to support in vt—™F ‡e end up with t ˜ound to the type of pfF ‡e ™he™k th—t t is not —lre—dy presentF sf soD we use — generalizeGintro ™om˜o to —dd — new hypothesis proved ˜y pfF ‡ith these t—™ti™s de(nedD we ™—n write — t—™ti™ completer for —dding to the ™ontext —ll ™onsequen™es of — set of simple (rstEorder formul—sF Ltac completer Xa PIW repeat match goal with ∧ “ ⇒ constructor |‘ |‘H X ∧ “ ⇒ destruct H | ‘ H X c€ → cD H' X c€ “⇒ generalize @H H' AY clear H Y intro | ‘ ∀ xD “ ⇒ intro |‘ endF H X ∀ xD c€ x → D @H X H' A H' X c€ cˆ H “⇒ extend ‡e use the s—me kind of ™onjun™tion —nd impli™—tion h—ndling —s previouslyF xote th—tD sin™e → is the spe™i—l nonEdependent ™—se of ∀D the fourth rule h—ndles intro for impli™—tionsD tooF sn the (fth ruleD when we (nd — ∀ f—™t H with — premise m—t™hing one of our hypothesesD we —dd the —ppropri—te inst—nti—tion of H 9s ™on™lusionD if we h—ve not —lre—dy —dded itF ‡e ™—n ™he™k th—t completer is working properlyX Section rstorderF Variable A X SetF Variables P Q R Hypothesis Hypothesis Theorem H1 H2 X x H X X ∀ xD X ∀ xD X ∀ xD completerF fo S Px A → PropF Px Rx → → → Qx S xF ∧ R xF S xF A X Px XQx H3 X R x H4 X S x aaaaaaaaaaaaaaaaaaaaaaaaaaaa H0 Sx assumptionF QedF End rstorderF ‡e n—rrowly —voided — su˜tle pitf—ll in our de(nition of completerF vet us try —nother de(nition th—t even seems prefer—˜le to the origin—lD to the untr—ined eyeF Ltac completer' Xa repeat match goal with ∧ “ ⇒ constructor |‘ |‘H X ∧ “ ⇒ destruct H | ‘ H X c€ → D H' X c€ “⇒ PPH generalize @H H' AY clear | ‘ ∀ xD “ ⇒ intro |‘ endF X ∀ xD c€ x → D extend @H X H' A H H' HY intro X c€ cˆ H “⇒ „he only di'eren™e is in the modus ponens ruleD where we h—ve repl—™ed —n unused uni(™—tion v—ri—˜le c with — wild™—rdF vet us try our ex—mple —g—in with this versionX Section rstorder'F Variable A X SetF Variables P Q R Hypothesis Hypothesis H2 Theorem X ∀ xD fo' S X X ∀ xD X ∀ xD H1 Px A → PropF Px Rx → → → Qx S xF ∧ R xF S xF completer'F goq loops forever —t this pointF ‡h—t went wrongc AbortF End rstorder'F e few ex—mples should illustr—te the issueF rere we see — matchE˜—sed proof th—t works (neX Theorem t1 X ∀ x X natD x a xF match goal with | ‘ ∀ xD “ ⇒ trivial endF QedF „his one f—ilsF Theorem t1' X∀ x X natD x a xF match goal with | ‘ ∀ x D c€ “ ⇒ trivial endF User error X No matching clauses for match goal AbortF „he pro˜lem is th—t uni(™—tion v—ri—˜les m—y not ™ont—in lo™—llyE˜ound v—ri—˜lesF sn this ™—seD c€ would need to ˜e ˜ound to x a x D whi™h ™ont—ins the lo™—l qu—nti(ed v—ri—˜le x F fy using — wild™—rd in the e—rlier versionD we —voided this restri™tionF PPI „he goq VFP rele—se in™ludes — spe™i—l p—ttern form for — uni(™—tion v—ri—˜le with —n expli™it set of free v—ri—˜lesF „h—t uni(™—tion v—ri—˜le is then ˜ound to — fun™tion from the free v—ri—˜les to the 4re—l4 v—lueF sn goq VFI —nd e—rlierD there is no su™h work—roundF xo m—tter whi™h version you useD it is import—nt to ˜e —w—re of this restri™tionF es we h—ve —lluded toD the restri™tion is the ™ulprit ˜ehind the in(niteElooping ˜eh—vior of completer'F ‡e unintention—lly m—t™h qu—nti(ed f—™ts with the modus ponens ruleD ™ir™umE venting the 4—lre—dy present4 ™he™k —nd le—ding to di'erent ˜eh—viorF 12.4 Functional Programming in Ltac vt—™ supports quite ™onvenient fun™tion—l progr—mmingD with — vispEwithEsynt—x kind of )—vorF roweverD there —re — few synt—™ti™ ™onventions involved in getting progr—ms to ˜e —™™eptedF „he vt—™ synt—x is optimized for t—™ti™EwritingD so one h—s to de—l with some in™onvenien™es in writing more st—nd—rd fun™tion—l progr—msF „o illustr—teD let us try to write — simple list length fun™tionF ‡e st—rt out writing it just like in q—llin—D simply repl—™ing Fixpoint @—nd its —nnot—tionsA with LtacF Ltac length ls Xa match ls with | nil ⇒ O | XX ls' ⇒ S @length endF ls' A Error X The reference ls' was not found in the current environment et this pointD we hopefully remem˜er th—t p—ttern v—ri—˜le n—mes must ˜e pre(xed ˜y question m—rks in vt—™F Ltac length ls Xa match ls with | nil ⇒ O | XX cls9 ⇒ S @length endF ls' A Error X The reference S was not found in the current environment „he pro˜lem is th—t vt—™ tre—ts the expression S @length ls' A —s —n invo™—tion of — t—™ti™ S with —rgument length ls'F ‡e need to use — spe™i—l —nnot—tion to 4es™—pe into4 the q—llin— p—rsing nontermin—lF Ltac length ls Xa match ls with PPP | nil ⇒ O | XX cls9 ⇒ endF constr X@ƒ @length ls' AA „his de(nition is —™™eptedF st ™—n ˜e — little —wkw—rd to test vt—™ de(nitions like thisF rere is one methodF Goal FalseF let n Xa length @I XX P XX Q XX pose nF nilA in Xa S @length @P XX Q XX nilAA X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa n False ‡e use the pose t—™ti™D whi™h extends the proof ™ontext with — new v—ri—˜le th—t is set equ—l to p—rti™ul—r — termF ‡e ™ould —lso h—ve used idtac n in pl—™e of pose nD whi™h would h—ve printed the result without ™h—nging the ™ontextF n only h—s the length ™—l™ul—tion unrolled one stepF ‡h—t h—s h—ppened here is th—tD ˜y es™—ping into the constr nontermin—lD we referred to the length fun™tion of q—llin—D r—ther th—n the length vt—™ fun™tion th—t we —re de(ningF AbortF Reset lengthF „he thing to remem˜er is th—t q—llin— terms ˜uilt ˜y t—™ti™s must ˜e ˜ound expli™itly vi— let or — simil—r te™hniqueD r—ther th—n inserting vt—™ ™—lls dire™tly in other q—llin— termsF Ltac length ls Xa match ls with | nil ⇒ O | XX cls9 ⇒ let ls Xa length constr X@ƒ ls A endF ls' in Goal FalseF let n Xa length @I XX P XX Q XX pose nF nilA in n Xa Q X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa False AbortF ‡e ™—n —lso use —nonymous fun™tion expressions —nd lo™—l fun™tion de(nitions in vt—™D —s this ex—mple of — st—nd—rd list map fun™tion showsF PPQ Ltac map T f Xa let rec map' ls Xa match ls with | nil ⇒ constr X@dnil T A | cx XX cls9 ⇒ let x' Xa f x in let ls Xa map' ls' in constr X@x9 XX ls A end in map'F vt—™ fun™tions ™—n h—ve no impli™it —rgumentsF st m—y seem surprising th—t we need to p—ss T D the ™—rried type of the output listD expli™itlyF ‡e ™—nnot just use type of f D ˜e™—use f is —n vt—™ termD not — q—llin— termD —nd vt—™ progr—ms —re dyn—mi™—lly typedF f ™ould use very synt—™ti™ methods to de™ide to return di'erently typed terms for di'erent inputsF ‡e —lso ™ould not repl—™e constr X@dnil T A with constr XnilD ˜e™—use we h—ve no stronglyEtyped ™ontext to use to infer the p—r—meter to nilF vu™kilyD we do h—ve su0™ient ™ontext within constr X@x9 XX ls AF ƒometimes we need to employ the opposite dire™tion of 4nontermin—l es™—peD4 when we w—nt to p—ss — ™ompli™—ted t—™ti™ expression —s —n —rgument to —nother t—™ti™D —s we might w—nt to do in invoking mapF Goal FalseF let ls Xa map @nat ∗ natA7type pose lsF ltac X@fun x ⇒ constr X@xD x AA @I XX P XX Q XX nilA in Xa @ID IA XX @PD PA XX @QD QA XX nil X list @nat ∗ natA aaaaaaaaaaaaaaaaaaaaaaaaaaaa l False AbortF 12.5 Recursive Proof Search he™iding how to inst—nti—te qu—nti(ers is one of the h—rdest p—rts of —utom—ted (rstEorder theorem provingF por — given pro˜lemD we ™—n ™onsider —ll possi˜le ˜oundedElength sequen™es of qu—nti(er inst—nti—tionsD —pplying only proposition—l re—soning —t the endF „his is pro˜—E ˜ly — ˜—d ide— for —lmost —ll go—lsD ˜ut it m—kes for — ni™e ex—mple of re™ursive proof se—r™h pro™edures in vt—™F ‡e ™—n ™onsider the m—ximum 4dependen™y ™h—in4 length for — (rstEorder proofF ‡e de(ne the ™h—in length for — hypothesis to ˜e HD —nd the ™h—in length for —n inst—nti—tion of — qu—nti(ed f—™t to ˜e one gre—ter th—n the length for th—t f—™tF „he t—™ti™ inster n is me—nt to try —ll possi˜le proofs with ™h—in length —t most nF Ltac inster n Xa PPR intuitionY match n with | S cn9 ⇒ match goal with | ‘ H X ∀ x X c„D D end endF x “ ⇒ generalize @H X c„ x AY inster n' inster ˜egins ˜y —pplying proposition—l simpli(™—tionF xextD it ™he™ks if —ny ™h—in length rem—insF sf soD it tries —ll possi˜le w—ys of inst—nti—ting qu—nti(ed hypotheses with properlyE typed lo™—l v—ri—˜lesF st is ™riti™—l to re—lize th—tD if the re™ursive ™—ll inster n' f—ilsD then the match goal just seeks out —nother w—y of unifying its p—ttern —g—inst proof st—teF „husD this sm—ll —mount of ™ode provides —n eleg—nt demonstr—tion of how ˜—™ktr—™king match en—˜les exh—ustive se—r™hF ‡e ™—n verify the e0™—™y of inster with two short ex—mplesF „he ˜uiltEin firstorder t—™ti™ @with no extr— —rgumentsA is —˜le to prove the (rst ˜ut not the se™ondF Section test insterF Variable A X SetF Variables P Q X A → PropF Variable f X A → AF Variable g X A → A → AF Hypothesis Theorem inster QedF inster QedF End test X∀ test inster PF Hypothesis Hypothesis Theorem H1 H3 H4 x yD P X∀ x yD P x yA @g → x yA Q @f x AF → Q @f x AF X ∀ u vD P u ∧ P v ∧ u = v → P @g X ∀ uD Q @f u A → P u ∧ P @f u AF test inster2 QF @g X∀ x yD x = y → Px → Q @f u v AF yA → Q @f x AF insterF „he style employed in the de(nition of inster ™—n seem very ™ounterintuitive to fun™tion—l progr—mmersF …su—llyD fun™tion—l progr—ms —™™umul—te st—te ™h—nges in expli™it —rguments to re™ursive fun™tionsF sn vt—™D the st—te of the ™urrent su˜go—l is —lw—ys impli™itF xonetheE lessD in ™ontr—st to gener—l imper—tive progr—mmingD it is e—sy to undo —ny ™h—nges to this st—teD —nd indeed su™h 4undoing4 h—ppens —utom—ti™—lly —t f—ilures within matchesF sn this w—yD vt—™ progr—mming is simil—r to progr—mming in r—skell with — st—teful f—ilure mon—d th—t supports — ™omposition oper—tor —long the lines of the rst t—™ti™—lF pun™tion—l progr—mming purists m—y re—™t indign—ntly to the suggestion of progr—mming this w—yF xonethelessD —s with other kinds of 4mon—di™ progr—mmingD4 m—ny pro˜lems —re mu™h simpler to solve with vt—™ th—n they would ˜e with expli™itD pure proof m—nipul—tion in wv or r—skellF „o demonstr—teD we will write — ˜—si™ simpli(™—tion pro™edure for logi™—l PPS impli™—tionsF „his pro™edure is inspired ˜y one for sep—r—tion logi™D where ™onjun™ts in formul—s —re thought of —s 4resour™esD4 su™h th—t we lose no ™ompleteness ˜y 4™rossing out4 equ—l ™onE jun™ts on the two sides of —n impli™—tionF „his pro™ess is ™ompli™—ted ˜y the f—™t th—tD for re—sons of modul—rityD our formul—s ™—n h—ve —r˜itr—ry nested tree stru™ture @˜r—n™hing —t ™onjun™tionsA —nd m—y in™lude existenti—l qu—nti(ersF st is helpful for the m—t™hing pro™ess to 4go under4 qu—nti(ers —nd in f—™t de™ide how to inst—nti—te existenti—l qu—nti(ers in the ™on™lusionF „o distinguish the impli™—tions th—t our t—™ti™ h—ndles from the impli™—tions th—t will show up —s 4plum˜ing4 in v—rious lemm—sD we de(ne — wr—pper de(nitionD — not—tionD —nd — t—™ti™F Definition imp @P1 P2 X PropA Xa P1 → P2F Infix 4!b4 Xa imp @no associativityD at level WSAF Ltac imp Xa unfold imp Y firstorderF „hese lemm—s —˜out imp will ˜e useful in the t—™ti™ th—t we will writeF Theorem and True prem X ∀ P QD @P ∧ True !b Q A → @P !b Q AF impF QedF Theorem and True conc X ∀ P QD @P !b Q ∧ TrueA → @P !b Q AF impF QedF Theorem assoc prem1 X ∀ P Q R SD @P ∧ @Q ∧ R A !b S A → @@P ∧ Q A ∧ R !b S AF impF QedF Theorem assoc prem2 X ∀ P Q R SD @Q ∧ @P ∧ R A !b S A → @@P ∧ Q A ∧ R !b S AF impF QedF Theorem comm prem X ∀ P Q RD @P ∧ Q !b R A → @Q ∧ P !b R AF impF QedF Theorem assoc conc1 X ∀ P Q R SD PPT @S !b P ∧ @Q ∧ R AA → @S !b @P ∧ Q A ∧ R AF impF QedF Theorem assoc conc2 X ∀ P Q @S !b Q ∧ @P ∧ R AA → @S !b @P ∧ Q A ∧ R AF impF QedF Theorem comm conc X ∀ @R !b P ∧ Q A → @R !b Q ∧ P AF impF QedF R SD P Q RD „he (rst order of ˜usiness in ™r—fting our matcher t—™ti™ will ˜e —uxili—ry support for se—r™hing through formul— treesF „he search prem t—™ti™ implements running its t—™ti™ —rgument tac on every su˜formul— of —n imp premiseF es it tr—verses — treeD search prem —pplies some of the —˜ove lemm—s to rewrite the go—l to ˜ring di'erent su˜formul—s to the he—d of the go—lF „h—t isD for every su˜formul— P of the impli™—tion premiseD we w—nt P to 4h—ve — turnD4 where the premise is re—rr—nged into the form P ∧ Q for some Q F „he t—™ti™ tac should expe™t to see — go—l in this form —nd fo™us its —ttention on the (rst ™onjun™t of the premiseF Ltac search prem tac Xa let rec search P Xa tac || @apply and True premY tac A || match P with | c€I ∧ c€P ⇒ @apply assoc prem1Y search P1 A || @apply assoc prem2Y search P2 A end in match goal with | ‘ c€ ∧ !b “ ⇒ search P |‘ ∧ c€ !b “ ⇒ apply comm premY search P |‘ !b “ ⇒ progress @tac || @apply and True endF premY tac AA „o underst—nd how search prem worksD we turn (rst to the (n—l matchF sf the premise ˜egins with — ™onjun™tionD we ™—ll the search pro™edure on e—™h of the ™onjun™tsD or only the (rst ™onjun™tD if th—t —lre—dy yields — ™—se where tac does not f—ilF search P expe™ts —nd m—int—ins the inv—ri—nt th—t the premise is of the form P ∧ Q for some Q F ‡e p—ss P expli™itly —s — kind of de™re—sing indu™tion me—sureD to —void looping forever when tac PPU —lw—ys f—ilsF „he se™ond match ™—se ™—lls — ™ommut—tivity lemm— to re—lize this inv—ri—ntD ˜efore p—ssing ™ontrol to searchF „he (n—l match ™—se tries —pplying tac dire™tly —nd thenD if th—t f—ilsD ™h—nges the form of the go—l ˜y —dding —n extr—neous True ™onjun™t —nd ™—lls tac —g—inF search itself tries the s—me tri™ks —s in the l—st ™—se of the (n—l matchF eddition—llyD if neither worksD it ™he™ks if P is — ™onjun™tionF sf soD it ™—lls itself re™ursively on e—™h ™onjun™tD (rst —pplying —sso™i—tivity lemm—s to m—int—in the go—lEform inv—ri—ntF ‡e will —lso w—nt — du—l fun™tion search concD whi™h does tree se—r™h through —n imp ™on™lusionF Ltac search conc tac Xa let rec search P Xa tac || @apply and True concY tac A || match P with | c€I ∧ c€P ⇒ @apply assoc conc1Y search P1 A || @apply assoc conc2Y search P2 A end in match goal with !b c€ ∧ “ ⇒ search P |‘ !b ∧ c€ “ ⇒ apply comm concY search P |‘ |‘ !b “ ⇒ progress @tac || @apply and True endF concY tac AA xow we ™—n prove — num˜er of lemm—s th—t —re suit—˜le for —ppli™—tion ˜y our se—r™h t—™ti™sF e lemm— th—t is me—nt to h—ndle — premise should h—ve the form P ∧ Q !b R for some interesting P D —nd — lemm— th—t is me—nt to h—ndle — ™on™lusion should h—ve the form P !b Q ∧ R for some interesting Q F Theorem False prem False ∧ P !b QF X∀ P QD impF QedF Theorem True conc X ∀ P @P !b Q A → @P !b True ∧ Q AF impF QedF Q X PropD Theorem Match X ∀ P Q R X PropD @Q !b R A → @P ∧ Q !b P ∧ R AF impF QedF PPV Theorem ex prem X ∀ @T X TypeA @P X @∀ xD P x ∧ Q !b R A → @ex P ∧ Q !b R AF impF QedF T → PropA @Q R X PropAD Theorem ex conc X ∀ @T X TypeA @P X @Q !b P x ∧ R A → @Q !b ex P ∧ R AF impF QedF T → PropA @Q R X PropA xD ‡e will —lso w—nt — 4˜—se ™—se4 lemm— for (nishing proofs where ™—n™el—tion h—s removed every ™onstituent of the ™on™lusionF Theorem imp True X ∀ PD P !b TrueF impF QedF yur (n—l matcher t—™ti™ is now str—ightforw—rdF pirstD we intros —ll v—ri—˜les into s™opeF „hen we —ttempt simple premise simpli(™—tionsD (nishing the proof upon (nding False —nd elimin—ting —ny existenti—l qu—nti(ers th—t we (ndF efter th—tD we se—r™h through the ™on™lusionF ‡e remove True ™onjun™tsD remove existenti—l qu—nti(ers ˜y introdu™ing uni(™—tion v—ri—˜les for their ˜ound v—ri—˜lesD —nd se—r™h for m—t™hing premises to ™—n™elF pin—llyD when no more progress is m—deD we see if the go—l h—s ˜e™ome trivi—l —nd ™—n ˜e solved ˜y imp TrueF sn e—™h ™—seD we use the t—™ti™ simple apply in pl—™e of apply to use — simplerD less expensive uni(™—tion —lgorithmF Ltac matcher Xa introsY repeat search prem ltac X@simple apply False prem || @simple apply ex premY introAAY repeat search conc ltac X@simple apply True conc || simple eapply ex conc || search prem ltac X@simple apply MatchAAY try simple apply imp TrueF yur t—™ti™ su™™eeds —t proving — simple ex—mpleF Theorem t2 X ∀ P Q X PropD Q ∧ @P ∧ FalseA ∧ P !b matcherF QedF P ∧ QF sn the gener—ted proofD we (nd — tr—™e of the workings of the se—r™h t—™ti™sF Print t2 a fun P comm t2F X Prop ⇒ prem @assoc prem1 @assoc Q prem2 @False prem PPW @P Xa€ ∧ P ∧ QA @P ∧ Q AAAA X∀ PQ X PropD Q ∧ @P ∧ FalseA ∧ P !b P ∧ Q ‡e ™—n —lso see th—t matcher is wellEsuited for ™—ses where some hum—n intervention is needed —fter the —utom—tion (nishesF Theorem t3 X ∀ P Q R X PropD P ∧ Q !b Q ∧ R ∧ PF matcherF aaaaaaaaaaaaaaaaaaaaaaaaaaaa True !b R ™—n™eled those ™onjun™ts th—t it w—s —˜le to ™—n™elD le—ving — simpli(ed su˜go—l for usD mu™h —s intuition doesF matcher AbortF matcher even su™™eeds —t guessing qu—nti(er inst—nti—tionsF st is the uni(™—tion th—t o™™urs in uses of the Match lemm— th—t does the re—l work hereF Theorem t4 matcherF X ∀ @P X nat → PropA QD @∃ xD P x ∧ QA !b Q ∧ @∃ xD P x AF QedF Print t4F t4 a fun @P X nat → PropA @Q X PropA ⇒ and True prem @ex @P Xafun x X @fun x X nat ⇒ prem nat ⇒ P x ∧ QA assoc prem2 @Match @P XaA @and True conc @ex conc @fun x0 X nat ⇒ P x0 A x @Match @P Xa€ x A @imp True @P Xa„rueAAAAAAAA X ∀ @P X nat → PropA @Q X PropAD @∃ x X natD P x ∧ Q A !b Q ∧ @∃ x X natD P x A 12.6 Creating Unication Variables e (n—l useful ingredient in t—™ti™ ™r—fting is the —˜ility to —llo™—te new uni(™—tion v—ri—˜les expli™itlyF „—™ti™s like eauto introdu™e uni(™—tion v—ri—˜le intern—lly to support )exi˜le proof se—r™hF ‡hile eauto —nd its rel—tives do backward re—soningD we often w—nt to do simil—r forward re—soningD where uni(™—tion v—ri—les ™—n ˜e useful for simil—r re—sonsF PQH por ex—mpleD we ™—n write — t—™ti™ th—t inst—nti—tes the qu—nti(ers of — univers—llyE qu—nti(ed hypothesisF „he t—™ti™ should not need to know wh—t the —ppropri—te inst—nE ti—nti—tions —reY r—therD we w—nt these ™hoi™es (lled with pl—™eholdersF ‡e hope th—tD when we —pply the spe™i—lized hypothesis l—terD synt—™ti™ uni(™—tion will determine ™on™rete v—luesF fefore we —re re—dy to write — t—™ti™D we ™—n try out its ingredients one —t — timeF Theorem t5 X @∀ introsF natD S x b x A → P b IF X x H X ∀ x X natD S x b x aaaaaaaaaaaaaaaaaaaaaaaaaaaa PbI „o inst—nti—te evar @y X H generi™—llyD we (rst need to n—me the v—lue to ˜e used for x F natAF X ∀ x X natD S x b x y Xa cPUW X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa PbI H „he proof ™ontext is extended with — new v—ri—˜le yD whi™h h—s ˜een —ssigned to ˜e equ—l to — fresh uni(™—tion v—ri—˜le cPUWF ‡e w—nt to inst—nti—te H with cPUWF „o get —hold of the new uni(™—tion v—ri—˜leD r—ther th—n just its —li—s yD we perform — trivi—l ™—llE˜yEv—lue redu™tion in the expression yF sn p—rti™ul—rD we only request the use of one redu™tion ruleD deltaD whi™h de—ls with de(nition unfoldingF ‡e p—ss — )—g further stipul—ting th—t only the de(nition of y ˜e unfoldedF „his is — simple tri™k for getting —t the v—lue of — synonym v—ri—˜leF let y' Xa eval cbv delta ‘y “ in y in clear y Y generalize @H y' AF H X ∀ x X natD S x b x aaaaaaaaaaaaaaaaaaaaaaaaaaaa S cPUW b cPUW → P b I yur inst—nti—tion w—s su™™essfulF ‡e ™—n (nish ˜y using the re(ned formul— to repl—™e the origin—lF clear HY intro HF X S cPVI b cPVI aaaaaaaaaaaaaaaaaaaaaaaaaaaa H PQI PbI ‡e ™—n (nish the proof ˜y using apply9s uni(™—tion to (gure out the proper v—lue of cPVIF @„he origin—l uni(™—tion v—ri—˜le w—s repl—™ed ˜y —notherD —s often h—ppens in the intern—ls of the v—rious t—™ti™s9 implement—tionsFA apply QedF HF xow we ™—n write — t—™ti™ th—t en™—psul—tes the p—ttern we just employedD inst—nti—ting —ll qu—nti(ers of — p—rti™ul—r hypothesisF Ltac insterU H Xa repeat match type of H with | ∀ x X c„D ⇒ let x Xa fresh 4x4 in evar @x X T AY let x' Xa eval cbv delta ‘x “ in x in clear x Y generalize @H x' AY clear endF HY intro H Theorem t5' X @∀ x X natD S x b x A → P b IF intro H Y insterU H Y apply HF QedF „his p—rti™ul—r ex—mple is somewh—t sillyD sin™e apply ˜y itself would h—ve solved the go—l origin—llyF ƒep—r—te forw—rd re—soning is more useful on hypotheses th—t end in existenti—l qu—nti(™—tionsF fefore we go through —n ex—mpleD it is useful to de(ne — v—ri—nt of insterU th—t does not ™le—r the ˜—se hypothesis we p—ss to itF Ltac insterKeep H Xa let H' Xa fresh 4r94 in generalize H Y intro H' Y insterU H'F Section t6F Variables A B X TypeF Variable P X A → B → PropF Variable f X A → A → AF Variable g X B → B → BF Hypothesis Hypothesis H1 H2 X ∀ vD ∃ uD P X ∀ v1 u1 v2 v uF u2D P v1 u1 → → P v2 u2 P @f v1 v2 A Theorem t6 X ∀ introsF @g u1 u2 AF v1 v2D ∃ u1D ∃ u2D P @f v1 v2 A PQP @g u1 u2 AF xeither eauto nor firstorder is ™lever enough to prove this go—lF ‡e ™—n help out ˜y doing some of the work with qu—nti(ers ourselvesF do P insterKeep H1F yur proof st—te is extended with two generi™ inst—n™es of H1 F X ∃ u X B D P cRPVW u X ∃ u X B D P cRPVV u aaaaaaaaaaaaaaaaaaaaaaaaaaaa ∃ u1 X B D ∃ u2 X B D P @f v1 v2 A @g u1 u2 A H' H'0 eauto still ™—nnot prove the go—lD so we elimin—te the two new existenti—l qu—nti(ersF repeat match goal with | ‘ H X ex “ ⇒ destruct endF H xow the go—l is simple enough to solve ˜y logi™ progr—mmingF eautoF QedF End t6F yur insterU t—™ti™ does not f—re so well with qu—nti(ed hypotheses th—t —lso ™ont—in impli™—tionsF ‡e ™—n see the pro˜lem in — slight modi(™—tion of the l—st ex—mpleF ‡e introdu™e — new un—ry predi™—te Q —nd use it to st—te —n —ddition—l requirement of our hypothesis H1 F Section t7F Variables A B X TypeF Variable Q X A → PropF Variable P X A → B → PropF Variable f X A → A → AF Variable g X B → B → BF Hypothesis Hypothesis H1 H2 X ∀ vD Q v → ∃ uD X ∀ v1 u1 v2 u2D P v uF P v1 u1 → → P v2 u2 P @f v1 v2 A @g u1 u2 AF Theorem t6 X ∀ v1 v2D Q v1 → Q v2 → ∃ u1D ∃ introsY do P insterKeep H1 Y repeat match goal with “ ⇒ destruct H | ‘ H X ex endY eautoF u2D P @f v1 v2 A @g u1 u2 AF „his proof s™ript does not hit —ny errors until the very endD when —n error mess—ge like this one is displ—yedF PQQ No more subgoals but non Einst—nti—ted existential variables Ia cRQVR X ‘A X Type B X Type Q X A → Prop P X A → B → Prop fX A→A→A gX B →B →B H1 X ∀ v X AD Q v → ∃ u X B D P v u H2 X ∀ @v1 X AA @u1 X B A @v2 X AA @u2 X B AD P v1 u1 → P v2 u2 → P @f v1 v2 A @g v1 X A v2 X A H X Q v1 H0 X Q v2 H' X Q v2 → ∃ u X B D P v2 u Q v2 “ X Existential u1 u2 A „here is —nother simil—r line —˜out — di'erent existenti—l v—ri—˜leF rereD 4existenti—l v—ri—˜le4 me—ns wh—t we h—ve —lso ™—lled 4uni(™—tion v—ri—˜leF4 sn the ™ourse of the proofD some uni(™—tion v—ri—˜le cRQVR w—s introdu™ed ˜ut never uni(edF …ni(™—tion v—ri—˜les —re just — devi™e to stru™ture proof se—r™hY the l—ngu—ge of q—llin— proof terms does not in™lude themF „husD we ™—nnot produ™e — proof term without inst—nti—ting the v—ri—˜leF „he error mess—ge shows th—t cRQVR is me—nt to ˜e — proof of Q v2 in — p—rti™ul—r proof st—teD whose v—ri—˜les —nd hypotheses —re displ—yedF st turns out th—t cRQVR w—s ™re—ted ˜y insterUD —s the v—lue of — proof to p—ss to H1 F ‚e™—ll th—tD in q—llin—D impli™—tion is just — degener—te ™—se of ∀ qu—nti(™—tionD so the insterU ™ode to m—t™h —g—inst ∀ —lso m—t™hed the impli™—tionF ƒin™e —ny proof of Q v2 is —s good —s —ny other in this ™ontextD there w—s never —ny opportunity to use uni(™—tion to determine ex—™tly whi™h proof is —ppropri—teF ‡e expe™t simil—r pro˜lems with —ny impli™—tions in —rguments to insterUF AbortF End t7F Reset insterUF ‡e ™—n rede(ne insterU to tre—t impli™—tions di'erentlyF sn p—rti™ul—rD we p—tternEm—t™h on the type of the type T in ∀ x X c„D FFFF sf T h—s type PropD then x 9s inst—nti—tion should ˜e thought of —s — proofF „husD inste—d of pi™king — new uni(™—tion v—ri—˜le for itD we inste—d —pply — userEsupplied t—™ti™ tacF st is import—nt th—t we end this spe™i—l Prop ™—se with || fail ID so th—tD if tac f—ils to prove T D we —˜ort the inst—nti—tionD r—ther th—n ™ontinuing on to the def—ult qu—nti(er h—ndlingF Ltac insterU tac H Xa repeat match type of H with PQR | ∀ x X c„D ⇒ match type of T with | Prop ⇒ @let H' Xa fresh 4r94 in assert @H' X T AY ‘ solve ‘ tac “ | generalize @H H' AY clear H H' Y intro H “A || fail I |⇒ let x Xa fresh 4x4 in evar @x X T AY let x' Xa eval cbv delta ‘x “ in x in clear x Y generalize @H x' AY clear H Y intro H end endF Ltac insterKeep tac H Xa let H' Xa fresh 4r94 in generalize H Y intro H' Y insterU tac H'F Section t7F Variables A B X TypeF Variable Q X A → PropF Variable P X A → B → PropF Variable f X A → A → AF Variable g X B → B → BF Hypothesis Hypothesis H1 H2 X ∀ vD Q v → ∃ uD X ∀ v1 u1 v2 u2D P v uF P v1 u1 → → P v2 u2 P @f Theorem v1 v2 A t6 X∀ @g u1 u2 AF v1 v2D Q v1 → Q v2 →∃ u1D ∃ u2D P @f v1 v2 A @g u1 u2 AF ‡e ™—n prove the go—l ˜y ™—lling insterKeep with — t—™ti™ th—t tries to (nd —nd —pply — Q hypothesis over — v—ri—˜le —˜out whi™h we do not yet know —ny P f—™tsF ‡e need to ˜egin this t—™ti™ ™ode with idtac Y to get —round — str—nge limit—tion in goq9s proof engineD where — (rstE™l—ss t—™ti™ —rgument m—y not ˜egin with — matchF introsY do P insterKeep ltac X@idt—™Y match with “⇒ | ‘ H X Q cv match goal with | ‘ X context ‘P v “ | ⇒ apply H end endA H1 Y PQS goal “ ⇒ fail I repeat match goal with “ ⇒ destruct | ‘ H X ex endY eautoF QedF End t7F H st is often useful to inst—nti—te existenti—l v—ri—˜les expli™itlyF e ˜uiltEin t—™ti™ provides one w—y of doing soF X ∃ p X nat ∗ natD fst p a QF econstructor Y instantiate @I Xa @QD PAAY reflexivityF QedF Theorem t8 „he I —˜ove is identifying —n existenti—l v—ri—˜le —ppe—ring in the ™urrent go—lD with the l—st existenti—l —ppe—ring —ssigned num˜er ID the se™ond l—st —ssigned num˜er PD —nd so onF „he n—med existenti—l is repl—™ed everywhere ˜y the term to the right of the XaF „he instantiate t—™ti™ ™—n ˜e ™onvenient for explor—tory provingD ˜ut it le—ds to very ˜rittle proof s™ripts th—t —re unlikely to —d—pt to ™h—nging theorem st—tementsF st is often more helpful to h—ve — t—™ti™ th—t ™—n ˜e used to —ssign — v—lue to — term th—t is known to ˜e —n existenti—lF fy employing — round—˜out implement—tion te™hniqueD we ™—n ˜uild — t—™ti™ th—t gener—lizes this fun™tion—lityF sn p—rti™ul—rD our t—™ti™ equate will —ssert th—t two terms —re equ—lF sf one of the terms h—ppens to ˜e —n existenti—lD then it will ˜e repl—™ed everywhere with the other termF Ltac equate x y Xa let H Xa fresh 4r4 in assert @H X x a y AY ‘ reflexivity | clear H “F f—ils if it is not possi˜le to prove x a y ˜y reflexivityF ‡e perform the proof only for its uni(™—tion side e'e™tsD ™le—ring the f—™t x a y —fterw—rdF ‡ith equateD we ™—n ˜uild — less ˜rittle version of the prior ex—mpleF equate X ∃ p X nat ∗ natD fst p a QF econstructor Y match goal with | ‘ fst cx a Q “ ⇒ equate endY reflexivityF QedF Theorem t9 PQT x @QD PA Chapter 13 Proof by Reection „he l—st ™h—pter highlighted — very heuristi™ —ppro—™h to provingF sn this ™h—pterD we will study —n —ltern—tive te™hniqueD proof by reectionF ‡e will writeD in q—llin—D de™ision pro™edures with proofs of ™orre™tnessD —nd we will —ppe—l to these pro™edures in writing very short proofsF ƒu™h — proof is ™he™ked ˜y running the de™ision pro™edureF „he term reection —pplies ˜e™—use we will need to tr—nsl—te q—llin— propositions into v—lues of indu™tive types representing synt—xD so th—t q—llin— progr—ms m—y —n—lyze themF 13.1 Proving Evenness €roving th—t p—rti™ul—r n—tur—l num˜er ™onst—nts —re even is ™ert—inly something we would r—ther h—ve h—ppen —utom—ti™—llyF „he vt—™Eprogr—mming te™hniques th—t we le—rned in the l—st ™h—pter m—ke it e—sy to implement su™h — pro™edureF Inductive isEven X nat → Prop Xa | Even O X isEven O | Even SS X ∀ nD isEven n → isEven @S @S n AAF Ltac prove even Xa repeat constructorF Theorem even 256 X isEven PSTF prove evenF QedF Print even 256F even 256 a Even SS @Even SS @Even SS @Even SS FFF—nd so onF „his pro™edure —lw—ys works @—t le—st on m—™hines with in(nite resour™esAD ˜ut it h—s — serious dr—w˜—™kD whi™h we see when we print the proof it gener—tes th—t PST PQU is evenF „he (n—l proof term h—s length line—r in the input v—lueF „his seems like — sh—meD sin™e we ™ould write — trivi—l —nd trustworthy progr—m to verify evenness of ™onst—ntsF „he proof ™he™ker ™ould simply ™—ll our progr—m where neededF st is —lso unfortun—te not to h—ve st—ti™ typing gu—r—ntees th—t our t—™ti™ —lw—ys ˜eh—ves —ppropri—telyF yther invo™—tions of simil—r t—™ti™s might f—il with dyn—mi™ type errorsD —nd we would not know —˜out the ˜ugs ˜ehind these errors until we h—ppened to —ttempt to prove ™omplex enough go—lsF „he te™hniques of proof ˜y re)e™tion —ddress ˜oth ™ompl—intsF ‡e will ˜e —˜le to write proofs like this with ™onst—nt size overhe—d ˜eyond the size of the inputD —nd we will do it with veri(ed de™ision pro™edures written in q—llin—F por this ex—mpleD we ˜egin ˜y using — type from the MoreSpecif module @in™luded in the ˜ook sour™eA to write — ™erti(ed evenness ™he™kerF Print partialF Inductive partial @P X PropA X Set Xa e partial P Proved v—lue is —n option—l proof of Local Open Scope X PF P → ‘P “ | Uncertain X ‘P “ „he not—tion ‘P “ st—nds for partial P F partial scopeF ‡e ˜ring into s™ope some not—tions for the partial typeF „hese overl—p with some of the not—tions we h—ve seen previously for spe™i(™—tion typesD so they were pl—™ed in — sep—r—te s™ope th—t needs sep—r—te openingF Definition check even @n X natA X ‘isEven n “F Hint Constructors isEvenF refine @x F @n X natA X ‘isEven n “ Xa match n with | H ⇒ Yes | I ⇒ No | S @S n' A ⇒ Reduce @F n' A endAY autoF DefinedF ‡e ™—n use dependent p—tternEm—t™hing to write — fun™tion th—t performs — surprising fe—tF ‡hen given — partial P D this fun™tion partialOut returns — proof of P if the partial v—lue ™ont—ins — proofD —nd it returns — @uselessA proof of True otherwiseF prom the st—ndpoint of wv —nd r—skell progr—mmingD it seems impossi˜le to write su™h — typeD ˜ut it is trivi—l with — return —nnot—tionF Definition partialOut @P X PropA @x X ‘P “A Xa match x return @match x with | Proved ⇒ P | Uncertain ⇒ True endA with | Proved pf ⇒ pf PQV | Uncertain ⇒ endF I st m—y seem str—nge to de(ne — fun™tion like thisF roweverD it turns out to ˜e very useful in writing — re)e™tive verison of our e—rlier prove even t—™ti™X Ltac prove even reective Xa match goal with | ‘ isEven cx“ ⇒ exact @partialOut @check endF even N AA ‡e identify whi™h n—tur—l num˜er we —re ™onsideringD —nd we 4prove4 its evenness ˜y pulling the proof out of the —ppropri—te check even ™—llF Theorem X even 256' isEven PSTF prove even reectiveF QedF Print even 256'F even 256' X a partialOut isEven PST @check even PSTA ‡e ™—n see — ™onst—nt wr—pper —round the o˜je™t of the proofF por —ny even num˜erD this form of proof will su0™eF ‡h—t h—ppens if we try the t—™ti™ with —n odd num˜erc Theorem even 255 X isEven PSSF prove even reectiveF User error X No matching clauses for match goal „h—nkfullyD the t—™ti™ f—ilsF „o see more pre™isely wh—t goes wrongD we ™—n run m—nu—lly the ˜ody of the matchF exact @partialOut @check even PSSAAF Error X The term 4p—rti—lyut @™he™k even PSSA4 has 4m—t™h ™he™k even PSS with | ‰es ⇒ isiven PSS | xo ⇒ „rue end4 while it is expected to have type 4isiven PSS4 type es usu—lD the typeE™he™ker performs no redu™tions to simplify error mess—gesF sf we redu™ed the (rst term ourselvesD we would see th—t check even PSS redu™es to — NoD so th—t the (rst term is equiv—lent to TrueD whi™h ™ert—inly does not unify with isEven PSSF AbortF PQW 13.2 Reecting the Syntax of a Trivial Tautology Language ‡e might —lso like to h—ve re)e™tive proofs of trivi—l t—utologies like this oneX Theorem true tautoF QedF Print X @True ∧ TrueA → @True ∨ @True ∧ @True → TrueAAAF true galoreF true galore fun galore a True ∧ True ⇒ @fun X True ⇒ or introl @True ∧ @True → TrueAA IA H X True ∧ True → True ∨ True ∧ @True → TrueA H X and ind es we might expe™tD the proof th—t tauto ˜uilds ™ont—ins expli™it —ppli™—tions of n—tur—l dedu™tion rulesF por l—rge formul—sD this ™—n —dd — line—r —mount of proof size overhe—dD ˜eyond the size of the inputF „o write — re)e™tive pro™edure for this ™l—ss of go—lsD we will need to get into the —™tu—l 4re)e™tion4 p—rt of 4proof ˜y re)e™tionF4 st is impossi˜le to ™—seE—n—lyze — Prop in —ny w—y in q—llin—F ‡e must reect Prop into some type th—t we can —n—lyzeF „his indu™tive type is — good ™—ndid—teX Inductive taut X Set Xa | TautTrue X taut | TautAnd X taut → taut → taut | TautOr X taut → taut → taut | TautImp X taut → taut → tautF ‡e write — re™ursive fun™tion to 4unre)e™t4 this synt—x ˜—™k to PropF Fixpoint tautDenote @t X tautA X Prop Xa match t with | TautTrue ⇒ True | TautAnd t1 t2 ⇒ tautDenote t1 ∧ tautDenote t2 | TautOr t1 t2 ⇒ tautDenote t1 ∨ tautDenote t2 | TautImp t1 t2 ⇒ tautDenote t1 → tautDenote t2 endF st is e—sy to prove th—t every formul— in the r—nge of Theorem tautTrue X ∀ tD induction t Y crushF QedF tautDenote is trueF tautDenote tF „o use tautTrue to prove p—rti™ul—r formul—sD we need to implement the synt—x re)e™tion pro™essF e re™ursive vt—™ fun™tion does the jo˜F PRH Ltac tautReect P Xa match P with | True ⇒ TautTrue | c€I ∧ c€P ⇒ let t1 Xa tautReect P1 in let t2 Xa tautReect P2 in constr X@„—utend t1 t2 A | c€I ∨ c€P ⇒ let t1 Xa tautReect P1 in let t2 Xa tautReect P2 in constr X@„—utyr t1 t2 A | c€I → c€P ⇒ let t1 Xa tautReect P1 in let t2 Xa tautReect P2 in constr X@„—utsmp t1 t2 A endF ‡ith tautReect —v—il—˜leD it is e—sy to (nish our re)e™tive t—™ti™F ‡e look —t the go—l formul—D re)e™t itD —nd —pply tautTrue to the re)e™ted formul—F Ltac obvious Xa match goal with | ‘ c€ “ ⇒ let t Xa tautReect P in exact @tautTrue t A endF ‡e ™—n verify th—t obvious solves our origin—l ex—mpleD with — proof term th—t does not mention det—ils of the proofF Theorem true galore' obviousF X @True ∧ TrueA → @True ∨ @True ∧ @True → TrueAAAF QedF Print true galore'F true galore' a tautTrue @TautImp @TautAnd TautTrue TautTrueA @TautOr TautTrue @TautAnd TautTrue @TautImp TautTrue X True ∧ True → True ∨ True ∧ @True → TrueA TautTrueAAAA st is worth ™onsidering how the re)e™tive t—™ti™ improves on — pureEvt—™ implement—tionF „he formul— re)e™tion pro™ess is just —s —dEho™ —s ˜eforeD so we g—in little thereF sn gener—lD proofs will ˜e more ™ompli™—ted th—n formul— tr—nsl—tionD —nd the 4generi™ proof rule4 th—t we —pply here is on mu™h ˜etter form—l footing th—n — re™ursive vt—™ fun™tionF „he dependent type of the proof gu—r—ntees th—t it 4works4 on —ny input formul—F „his is —ll in PRI —ddition to the proofEsize improvement th—t we h—ve —lre—dy seenF 13.3 A Monoid Expression Simplier €roof ˜y re)e™tion does not require en™oding of —ll of the synt—x in — go—lF ‡e ™—n insert 4v—ri—˜les4 in our synt—x types to —llow inje™tion of —r˜itr—ry pie™esD even if we ™—nnot —pply spe™i—lized re—soning to themF sn this se™tionD we explore th—t possi˜ility ˜y writing — t—™ti™ for norm—lizing monoid equ—tionsF Section monoidF Variable A X SetF Variable e X AF Variable f X A → A → AF Infix 4C4 Xa fF Hypothesis Hypothesis Hypothesis X ∀ a b cD @a C b A C identl X ∀ aD e C a a aF identr X ∀ aD a C e a aF assoc c a a C @b C c AF ‡e —dd v—ri—˜les —nd hypotheses ™h—r—™terizing —n —r˜itr—ry inst—n™e of the —lge˜r—i™ stru™ture of monoidsF ‡e h—ve —n —sso™i—tive ˜in—ry oper—tor —nd —n identity element for itF st is e—sy to de(ne —n expression tree type for monoid expressionsF e Var ™onstru™tor is — 4™—t™hE—ll4 ™—se for su˜expressions th—t we ™—nnot modelF „hese su˜expressions ™ould ˜e —™tu—l q—llin— v—ri—˜lesD or they ™ould just use fun™tions th—t our t—™ti™ is un—˜le to underst—ndF Inductive mexp X Set Xa | Ident X mexp | Var X A → mexp | Op X mexp → mexp → mexpF xextD we write —n 4unEre)e™t4 fun™tionF Fixpoint mdenote @me X mexpA X A Xa match me with | Ident ⇒ e | Var v ⇒ v | Op me1 me2 ⇒ mdenote me1 C mdenote endF me2 ‡e will norm—lize expressions ˜y )—ttening them into listsD vi— —sso™i—tivityD so it is helpful to h—ve — denot—tion fun™tion for lists of monoid v—luesF Fixpoint mldenote @ls X list AA X A Xa match ls with | nil ⇒ e | x XX ls' ⇒ x C mldenote ls' PRP endF „he )—ttening fun™tion itself is e—sy to implementF Fixpoint atten @me X mexpA X list A Xa match me with | Ident ⇒ nil | Var x ⇒ x XX nil | Op me1 me2 ⇒ atten me1 CC atten endF atten Lemma me2 h—s — str—ightforw—rd ™orre™tness proof in terms of our X ∀ ml2 ml1D C mldenote ml2 a induction ml1 Y crushF QedF denote fun™tionsF atten correct' mldenote ml1 mldenote Theorem atten correct X ∀ meD mdenote Hint Resolve atten correct'F induction QedF me @ml1 CC a ml2 AF mldenote @atten me AF me Y crushF xow it is e—sy to prove — theorem th—t will ˜e the m—in tool ˜ehind our simpli(™—tion t—™ti™F Theorem X ∀ me1 me2D mldenote @atten me1 A a mldenote @atten me2 A → mdenote me1 a mdenote me2F introsY repeat rewrite atten correctY assumptionF QedF monoid reect ‡e implement re)e™tion into the mexp typeF Ltac reect me Xa match me with | e ⇒ Ident | cmeI C cmeP ⇒ let r1 Xa reect me1 in let r2 Xa reect me2 in constr X@yp r1 r2 A | ⇒ constr X@†—r me A endF „he (n—l monoid t—™ti™ works on go—ls th—t equ—te two monoid termsF ‡e re)e™t e—™h —nd ™h—nge the go—l to refer to the re)e™ted versionsD (nishing o' ˜y —pplying monoid reect —nd simplifying uses of mldenoteF Ltac monoid Xa match goal with PRQ |‘ endF cmeI a cmeP “ ⇒ let r1 Xa reect me1 in let r2 Xa reect me2 in change @mdenote r1 a mdenote r2 AY apply monoid reectY simpl mldenote ‡e ™—n m—ke short work of theorems like this oneX Theorem t1 X ∀ a b introsY monoidF c dD a C b C c C d a a C @b C c A C dF aaaaaaaaaaaaaaaaaaaaaaaaaaaa a C @b C @c C @d C eAAA a a C @b C @c C @d C eAAA monoid re)exivityF h—s ™—noni™—lized ˜oth sides of the equ—lityD su™h th—t we ™—n (nish the proof ˜y reflexivityF QedF st is interesting to look —t the form of the proofF Print t1F t1 a fun a b c d X ⇒ @Op @Op @Op @Var a A @Var b AA @Var c AA @Var d AA @Op @Op @Var a A @Op @Var b A @Var c AAA @Var d AA @re equal @a C @b C @c C @d C eAAAAA X ∀ a b c d X AD a C b C c C d a a C @ b C c A C d A monoid reect „he proof term ™ont—ins only rest—tements of the equ—lity oper—nds in re)e™ted formD followed ˜y — use of re)exivity on the sh—red ™—noni™—l formF End monoidF ixtensions of this ˜—si™ —ppro—™h —re used in the implement—tions of the ring —nd t—™ti™s th—t ™ome p—™k—ged with goqF eld 13.4 A Smarter Tautology Solver xow we —re re—dy to revisit our e—rlier t—utology solver ex—mpleF ‡e w—nt to ˜ro—den the s™ope of the t—™ti™ to in™lude formul—s whose truth is not synt—™ti™—lly —pp—rentF ‡e will w—nt to —llow inje™tion of —r˜itr—ry formul—sD like we —llowed —r˜itr—ry monoid expressions in the l—st ex—mpleF ƒin™e we —re working in — ri™her theoryD it is import—nt to ˜e —˜le to use equ—lities ˜etween di'erent inje™ted formul—sF por inst—n™eD we ™—nnot prove P → P ˜y PRR tr—nsl—ting the formul— into — v—lue like Imp @Var P A @Var P AD ˜e™—use — q—llin— fun™tion h—s no w—y of ™omp—ring the two P s for equ—lityF „o —rrive —t — ni™e implement—tion s—tisfying these ™riteri—D we introdu™e the quote t—™ti™ —nd its —sso™i—ted li˜r—ryF Require Import QuoteF Inductive formula X Set Xa | Atomic X index → formula | Truth X formula | Falsehood X formula | And X formula → formula → formula | Or X formula → formula → formula | Imp X formula → formula → formulaF „he type index ™omes from the Quote li˜r—ry —nd represents — ™ount—˜le v—ri—˜le typeF „he rest of formula9s de(nition should ˜e old h—t ˜y nowF „he quote t—™ti™ will implement inje™tion from Prop into formula for usD ˜ut it is not quite —s sm—rt —s we might likeF sn p—rti™ul—rD it interprets impli™—tions in™orre™tlyD so we will need to de™l—re — wr—pper de(nition for impli™—tionD —s we did in the l—st ™h—pterF Definition imp @P1 P2 X PropA Xa P1 → P2F Infix 4!b4 Xa imp @no associativityD at level WSAF xow we ™—n de(ne our denot—tion fun™tionF Definition asgn Xa varmap PropF Fixpoint formulaDenote @atomics X asgnA @f X formulaA X Prop Xa match f with | Atomic v ⇒ varmap nd False v atomics | Truth ⇒ True | Falsehood ⇒ False | And f1 f2 ⇒ formulaDenote atomics f1 ∧ formulaDenote atomics f2 | Or f1 f2 ⇒ formulaDenote atomics f1 ∨ formulaDenote atomics f2 | Imp f1 f2 ⇒ formulaDenote atomics f1 !b formulaDenote atomics f2 endF „he varmap type f—mily implements m—ps from index v—luesF sn this ™—seD we de(ne —n —ssignment —s — m—p from v—ri—˜les to PropsF formulaDenote works with —n —ssignmentD —nd we use the varmap nd fun™tion to ™onsult the —ssignment in the Atomic ™—seF „he (rst —rgument to varmap nd is — def—ult v—lueD in ™—se the v—ri—˜le is not foundF Section my tautoF Variable atomics X asgnF Definition holds @v X indexA Xa varmap nd False v atomicsF ‡e de(ne some shorth—nd for — p—rti™ul—r v—ri—˜le ˜eing trueD —nd now we —re re—dy to de(ne some helpful fun™tions ˜—sed on the ListSet module of the st—nd—rd li˜r—ryD whi™h @unsurprisinglyA presents — view of lists —s setsF PRS Require Import Definition ListSetF index eq decide equalityF X∀ xy X indexD {x a y } C {x = y }F DefinedF Definition indexA @v X indexA Xa set add index eq v sF dec X ∀ v @s X set indexAD {In v s } C {¬ In v s }F add @s X set Definition In Local Open Scope specif scopeF introY refine @x F @s X set indexA X {In match s with | nil ⇒ No | v' XX s' ⇒ index eq v' v || F s' endAY crushF DefinedF v s} C {¬ In v s } Xa ‡e de(ne wh—t it me—ns for —ll mem˜ers of —n index set to represent true propositionsD —nd we prove some lemm—s —˜out this notionF Fixpoint allTrue @s X match s with | nil ⇒ True | v XX s' ⇒ holds endF Theorem allTrue add set ∧ v X∀ indexA X Prop Xa allTrue s' v sD allTrue s → holds v → allTrue @add s v AF induction s Y crush Y match goal with | ‘ context ‘if ci then endY crushF QedF Theorem allTrue In X∀ else “ “ ⇒ destruct E v sD allTrue s → set In v s → varmap nd False induction s Y crushF QedF Hint Resolve v atomicsF allTrue add allTrue InF Local Open Scope partial scopeF xow we ™—n write — fun™tion forward whi™h implements de™onstru™tion of hypothesesF st h—s — dependent typeD in the style of gh—pter TD gu—r—nteeing ™orre™tnessF „he —rguments PRT to forward —re — go—l formul— f D — set known of —tomi™ formul—s th—t we m—y —ssume —re trueD — hypothesis formul— hypD —nd — su™™ess ™ontinu—tion cont th—t we ™—ll when we h—ve extended known to hold new truths implied ˜y hypF Definition forward @f X formulaA @known X set indexA @hyp X formulaA @cont X ∀ known'D ‘allTrue known' → formulaDenote atomics f “A X ‘allTrue known → formulaDenote atomics hyp → formulaDenote atomics f “F refine @x F @f X formulaA @known X set indexA @hyp X formulaA @cont X ∀ known'D ‘allTrue known' → formulaDenote atomics f “A X ‘allTrue known → formulaDenote atomics hyp → formulaDenote atomics f “ Xa match hyp with | Atomic v ⇒ Reduce @cont @add known v AA | Truth ⇒ Reduce @cont known A | Falsehood ⇒ Yes | And h1 h2 ⇒ Reduce @F @Imp h2 f A known h1 @fun known' ⇒ Reduce @F f known' h2 cont AAA | Or h1 h2 ⇒ F f known h1 cont 88 F f known h2 cont ⇒ Reduce @cont known A | Imp endAY crushF DefinedF e backward fun™tion implements —n—lysis of the (n—l go—lF st ™—lls impli™—tionsF Definition backward @known X set indexA @f X formulaA X ‘allTrue known → formulaDenote atomics f “F refine @x F @known X set indexA @f X formulaA X ‘allTrue known → formulaDenote atomics f “ Xa match f with | Atomic v ⇒ Reduce @In dec v known A | Truth ⇒ Yes | Falsehood ⇒ No | And f1 f2 ⇒ F known f1 88 F known f2 | Or f1 f2 ⇒ F known f1 || F known f2 | Imp f1 f2 ⇒ forward f2 known f1 @fun known' ⇒ endAY crush Y eautoF DefinedF forward to h—ndle F known' f2 A e simple wr—pper —round backward gives us the usu—l type of — p—rti—l de™ision pro™edureF Definition my tauto @f X formulaA X ‘formulaDenote introY refine @Reduce @backward nil f AAY crushF DefinedF End my tautoF atomics f “F yur (n—l t—™ti™ implement—tion is now f—irly str—ightforw—rdF pirstD we intro —ll qu—ntiE PRU (ers th—t do not ˜ind PropsF „hen we ™—ll the quote t—™ti™D whi™h implements the re)e™tion for usF pin—llyD we —re —˜le to ™onstru™t —n ex—™t proof vi— partialOut —nd the my tauto q—llin— fun™tionF Ltac my tauto Xa repeat match goal with | ‘ ∀ x X c€D “ ⇒ match type of P with | Prop ⇒ fail I | ⇒ intro end endY quote formulaDenote Y match goal with | ‘ formulaDenote cm cf “ ⇒ exact @partialOut @my endF tauto m f AA e few ex—mples demonstr—te how the t—™ti™ worksF Theorem mt1 my tautoF X TrueF QedF Print mt1F mt1 a partialOut @my X True ‡e see my tauto formulaDenoteF Theorem mt2 my tautoF X∀ xy tauto @Empty vm PropA —pplied with —n empty X TruthA varmapD sin™e every su˜formul— is h—ndled ˜y natD x a y !b x a yF QedF Print mt2F mt2 a fun x y X nat ⇒ partialOut @my tauto @Node vm @x a y A @Empty vm PropA @Empty @Imp @Atomic End idx A @Atomic End idx AAA X ∀ x y X natD x a y !b x a y vm PropAA gru™i—llyD ˜oth inst—n™es of x a y —re represented with the s—me indexD End idxF „he v—lue of this index only needs to —ppe—r on™e in the varmapD whose form reve—ls th—t varmaps —re represented —s ˜in—ry treesD where index v—lues denote p—ths from tree roots to le—vesF PRV Theorem mt3 X ∀ x y zD @x ` y ∧ y b z A ∨ @y b z ∧ x ` !b y b z ∧ @x ` y ∨ x ` S y AF my tautoF QedF S yA Print mt3F fun x y z X nat ⇒ partialOut @my tauto @Node vm @x ` S y A @Node vm @x ` y A @Empty vm PropA @Empty vm PropAA @Node vm @y b z A @Empty vm PropA @Empty vm PropAAA @Imp @Or @And @Atomic @Left idx End idx AA @Atomic @Right idx End idx AAA @And @Atomic @Right idx End idx AA @Atomic End idx AAA @And @Atomic @Right idx End idx AA @Or @Atomic @Left idx End idx AA @Atomic End idx AAAAA X ∀ x y z X natD x ` y ∧ y b z ∨ y b z ∧ x ` S y !b y b z ∧ @x ` y ∨ x ` S y A yur go—l ™ont—ined three distin™t —tomi™ formul—sD —nd we see th—t — threeEelement varmap is gener—tedF st ™—n ˜e interesting to o˜serve di'eren™es ˜etween the level of repetition in proof terms gener—ted ˜y my tauto —nd tauto for espe™i—lly trivi—l theoremsF Theorem mt4 my tautoF X True ∧ True ∧ True ∧ True ∧ True ∧ True ∧ False !b FalseF QedF Print mt4F mt4 a partialOut @my tauto @Empty vm PropA @Imp @And Truth @And Truth @And Truth @And Truth @And Truth @And Truth FalsehoodAAAAAA FalsehoodAA X True ∧ True ∧ True ∧ True ∧ True ∧ True ∧ False !b False Theorem mt4' X True ∧ True ∧ True ∧ True ∧ True ∧ True ∧ False → FalseF tautoF QedF Print mt4'F PRW mt4' fun a H X True ∧ True ∧ True ∧ True ∧ True ∧ True ∧ False ⇒ and ind @fun @ X TrueA @H1 X True ∧ True ∧ True ∧ True ∧ True ∧ FalseA ⇒ and ind @fun @ X TrueA @H3 X True ∧ True ∧ True ∧ True ∧ FalseA ⇒ and ind @fun @ X TrueA @H5 X True ∧ True ∧ True ∧ FalseA ⇒ and ind @fun @ X and ind TrueA @H7 X True ∧ True ∧ FalseA ⇒ TrueA @H9 X True ∧ FalseA ⇒ ind @fun @ X TrueA @H11 X FalseA ⇒ False @fun @ X and X ind H9 A H7 A H5 A H3 A H1 A H False H11 A True ∧ True ∧ True ∧ True ∧ True ∧ True ∧ False → False 13.5 Exercises IF smplement — re)e™tive pro™edure for norm—lizing systems of line—r equ—tions over r—E tion—l num˜ersF sn p—rti™ul—rD the t—™ti™ should identify —ll hypotheses th—t —re line—r equ—tions over r—tion—ls where the equ—tion righth—nd sides —re ™onst—ntsF st should norm—lize e—™h hypothesis to h—ve — lefth—nd side th—t is — sum of produ™ts of ™onst—nts —nd v—ri—˜lesD with no v—ri—˜le —ppe—ring multiple timesF „henD your t—™ti™ should —dd together —ll of these equ—tions to form — single new equ—tionD possi˜ly ™le—ring the origE in—l equ—tionsF ƒome ™oe0™ients m—y ™—n™el in the —dditionD redu™ing the num˜er of v—ri—˜les th—t —ppe—rF „o work with r—tion—l num˜ersD import module QArith —nd use Local Open Scope Q scopeF ell of the usu—l —rithmeti™ oper—tor not—tions will then work with r—tion—lsD —nd there —re shorth—nds for ™onst—nts H —nd IF yther r—tion—ls must ˜e written —s num 5 den for numer—tor num —nd denomin—tor denF …se the in(x oper—tor aa in pl—™e of aD to de—l with di'erent w—ys of expressing the s—me num˜er —s — fr—™tionF por inst—n™eD — theorem —nd proof like this one should work with your t—™ti™X Theorem t2 X ∀ x y z D @P 5 IA B @x E @Q 5 PA B y A aa IS 5 I → z C @V 5 IA B x aa PH 5 I → @ET 5 PA B y C @IH 5 IA B x C z aa QS 5 IF introsY reectContext Y assumptionF QedF ‰our solution ™—n work in —ny w—y th—t involves re)e™ting synt—x —nd doing most ™—l™ul—tion with — q—llin— fun™tionF „hese hints outline — p—rti™ul—r possi˜le solutionF PSH „hroughoutD the ring t—™ti™ will ˜e helpful for proving m—ny simple f—™ts —˜out r—tioE n—lsD —nd t—™ti™s like rewrite —re ™orre™tly overlo—ded to work with r—tion—l equ—lity aaF @—A he(ne —n indu™tive type exp of expressions over r—tion—ls @whi™h inh—˜it the goq type Q AF sn™lude v—ri—˜les @represented —s n—tur—l num˜ersAD ™onst—ntsD —dditionD su˜tr—™tionD —nd multipli™—tionF @˜A he(ne — fun™tion lookup for re—ding —n element out of — list of r—tion—lsD ˜y its position in the listF @™A he(ne — fun™tion expDenote th—t tr—nsl—tes representing v—ri—˜le v—luesD to Q F @dA he(ne — re™ursive fun™tion of the equ—tions —re trueF eqsDenote over expsD —long with lists of r—tion—ls list @exp B Q AD ™h—r—™terizing when —ll @eA pix — represent—tion lhs of )—ttened expressionsF ‡here len is the num˜er of v—ri—˜lesD represent — )—ttened equ—tion —s ilist Q lenF i—™h position of the list gives the ™oe0™ient of the ™orresponding v—ri—˜leF @fA ‡rite — re™ursive fun™tion linearize th—t t—kes — ™onst—nt k —nd —n expression e —nd option—lly returns —n lhs equiv—lent to k B eF „his fun™tion returns None when it dis™overs th—t the input expression is not line—rF „he p—r—meter len of lhs should ˜e — p—r—meter of linearizeD tooF „he fun™tions singletonD everywhereD —nd map2 from DepList will pro˜—˜ly ˜e helpfulF st is —lso helpful to know th—t Qplus is the identi(er for r—tion—l —dditionF @gA ‡rite — re™ursive fun™tion linearizeEqs X list @exp B Q A → option @lhs B Q AF „his fun™tion line—rizes —ll of the equ—tions in the list in turnD ˜uilding up the sum of the equ—tionsF st returns None if the line—riz—tion of —ny ™onstituent equ—tion f—ilsF @hA he(ne — denot—tion fun™tion for lhsF @iA €rove th—tD when exp line—riz—tion su™™eeds on ™onst—nt line—rized version h—s the s—me me—ning —s k B eF k —nd expression eD the @jA €rove th—tD when linearizeEqs su™™eeds on —n equ—tion list eqsD then the (n—l summedEup equ—tion is true whenever the origin—l equ—tion list is trueF @kA ‡rite — t—™ti™ ndVarsHyps to se—r™h through —ll equ—lities on r—tion—ls in the ™ontextD re™ursing through —dditionD su˜tr—™tionD —nd multipli™—tion to (nd the list of expressions th—t should ˜e tre—ted —s v—ri—˜lesF „his list should ˜e suit—˜le —s —n —rgument to expDenote —nd eqsDenoteD —sso™i—ting — Q v—lue to e—™h n—tur—l num˜er th—t st—nds for — v—ri—˜leF @lA ‡rite — t—™ti™ reect to re)e™t — list of v—ri—˜le v—luesF Q expression into expD with respe™t to — given @mA ‡rite — t—™ti™ reectEqs to re)e™t — formul— th—t ˜egins with — sequen™e of impliE ™—tions from line—r equ—lities whose lefth—nd sides —re expressed with expDenoteF PSI „his t—™ti™ should ˜uild — list @exp B Q A representing the equ—tionsF ‚emem˜er to give —n expli™it type —nnot—tion when returning — nil listD —s in constr X@dnil @exp B Q AAF @nA xow this (n—l t—™ti™ should do the jo˜X Ltac reectContext Xa let ls Xa ndVarsHyps in repeat match goal with “⇒ | ‘ H X ce aa cnum 5 cden let r Xa reect ls e in change @expDenote ls r aa num 5 den A in H Y generalize H endY match goal with | ‘ cg “ ⇒ let re Xa reectEqs g in introsY let H Xa fresh 4r4 in assert @H X eqsDenote ls re AY ‘ simpl in BY tauto | repeat match goal with aa “ ⇒ clear H | ‘ H X expDenote endY generalize @linearizeEqsCorrect ls re H AY clear H Y simplY match goal with | ‘ cˆ aa c‰ → “ ⇒ ring simplify X Y Y intro end “ endF PSP Chapter 14 Proving in the Large st is somewh—t unfortun—te th—t the term 4theoremEproving4 looks so mu™h like the word 4theoryF4 wost rese—r™hers —nd pr—™titioners in softw—re —ssume th—t me™h—nized theoremE proving is profoundly impr—™ti™—lF sndeedD until re™entlyD most —dv—n™es in theoremEproving for higherEorder logi™s h—ve ˜een l—rgely theoreti™—lF roweverD st—rting —round the ˜eginning of the PIst ™enturyD there w—s — surge in the use of proof —ssist—nts in serious veri(™—tion e'ortsF „h—t line of work is still quite newD ˜ut s ˜elieve it is not too soon to distill some lessons on how to work e'e™tively with l—rge form—l proofsF „husD this ™h—pter gives some tips for stru™turing —nd m—int—ining l—rge goq developE mentsF 14.1 Ltac Anti-Patterns sn this ˜ookD s h—ve ˜een following —n unusu—l styleD where proofs —re not ™onsidered (nished until they —re 4fully —utom—tedD4 in — ™ert—in senseF ƒi—™h su™h theorem is proved ˜y — single t—™ti™F ƒin™e vt—™ is — „uringE™omplete progr—mming l—ngu—geD it is not h—rd to squeeze —r˜itr—ry heuristi™s into single t—™ti™sD using oper—tors like the semi™olon to ™om˜ine stepsF sn ™ontr—stD most vt—™ proofs 4in the wild4 ™onsist of m—ny stepsD performed ˜y individu—l t—™ti™s followed ˜y periodsF ss it re—lly worth dr—wing — distin™tion ˜etween proof steps termin—ted ˜y semi™olons —nd steps termin—ted ˜y periodsc s —rgue th—t this isD in f—™tD — very import—nt distin™tionD with serious ™onsequen™es for — m—jority of import—nt veri(™—tion dom—insF „he more uninteresting drudge work — proof dom—in involvesD the more import—nt it is to work to prove theorems with single t—™ti™sF prom —n —utom—tion st—ndpointD singleEt—™ti™ proofs ™—n ˜e extremely e'e™tiveD —nd —utom—tion ˜e™omes more —nd more ™riti™—l —s proofs —re popul—ted ˜y more uninteresting det—ilF sn this se™tionD s will give some ex—mples of the ™onsequen™es of more ™ommon proof stylesF es — running ex—mpleD ™onsider — ˜—si™ l—ngu—ge of —rithmeti™ expressionsD —n interpreter for itD —nd — tr—nsform—tion th—t s™—les up every ™onst—nt in —n expressionF Inductive exp X Set Xa PSQ nat → exp Plus X exp → exp → expF Fixpoint eval @e X expA X nat Xa | | Const X match e with | Const n ⇒ n | Plus e1 e2 ⇒ endF eval e1 C eval e2 Fixpoint times @k X natA @e X expA X exp Xa match e with | Const n ⇒ Const @k B n A | Plus e1 e2 ⇒ Plus @times k e1 A @times k endF ‡e ™—n write — very m—nu—l proof th—t e2 A double re—lly dou˜les —n expression9s v—lueF Theorem eval times X ∀ k eD eval @times k e A a k B eval eF induction eF trivialF simplF rewrite IHe1F rewrite IHe2F rewrite mult plus trivialF QedF distr lF ‡e use sp—™es to sep—r—te the two indu™tive ™—sesF „he se™ond ™—se mentions —utom—ti™—llyE gener—ted hypothesis n—mes expli™itlyF es — resultD inno™uous ™h—nges to the theorem st—teE ment ™—n inv—lid—te the proofF Reset eval timesF Theorem eval double X ∀ k xD eval @times k x A a k B eval xF induction xF trivialF simplF rewrite IHe1F Error X The reference IHe1 was not found „he indu™tive hypotheses —re n—med in IHx1 the current environmentF —nd AbortF PSR IHx2 nowD not IHe1 —nd IHe2F ‡e might de™ide to use — more expli™it invo™—tion of induction to give expli™it ˜inders for —ll of the n—mes th—t we will referen™e l—ter in the proofF Theorem eval times X ∀ k eD eval @times k e A a k B eval eF induction e as ‘ | c IHe1 c IHe2 “F trivialF simplF rewrite IHe1F rewrite IHe2F rewrite mult plus trivialF QedF distr lF ‡e p—ss induction —n intro patternD using — | ™h—r—™ter to sep—r—te out instru™tions for the di'erent indu™tive ™—sesF ‡ithin — ™—seD we write c to —sk goq to gener—te — n—me —utom—ti™—llyD —nd we write —n expli™it n—me to —ssign th—t n—me to the ™orresponding new v—ri—˜leF st is —pp—rent th—tD to use intro p—tterns to —void proof ˜rittlenessD one needs to keep tr—™k of the seemingly unimport—nt f—™ts of the orders in whi™h v—ri—˜les —re introdu™edF „husD the s™ript keeps working if we repl—™e e ˜y x D ˜ut it h—s ˜e™ome more ™lutteredF ergu—˜lyD neither proof is p—rti™ul—rly e—sy to followF „h—t ™—tegory of ™ompl—int h—s to do with underst—nding proofs —s st—ti™ —rtif—™tsF es with progr—mming in gener—lD with serious proje™tsD it tends to ˜e mu™h more import—nt to ˜e —˜le to support evolution of proofs —s spe™i(™—tions ™h—ngeF …nstru™tured proofs like the —˜ove ex—mples ™—n ˜e very h—rd to upd—te in ™on™ert with theorem st—tementsF por inst—n™eD ™onsider how the l—st proof s™ript pl—ys out when we modify times to introdu™e — ˜ugF Reset timesF Fixpoint times @k X natA @e X expA X exp Xa match e with | Const n ⇒ Const @I C k B n A | Plus e1 e2 ⇒ Plus @times k e1 A @times k endF Theorem eval times X ∀ k eD eval @times k e A a k B eval eF induction e as ‘ | c IHe1 c IHe2 e2 A “F trivialF simplF rewrite IHe1F Error X The reference IHe1 was not found in the current environmentF PSS AbortF g—n you spot wh—t went wrongD without stepping through the s™ript stepE˜yEstepc „he pro˜lem is th—t trivial never f—ilsF yrigin—llyD trivial h—d ˜een su™™eeding in proving —n equ—lity th—t follows ˜y re)exivityF yur ™h—nge to times le—ds to — ™—se where th—t equ—lity is no longer trueF trivial h—ppily le—ves the f—lse equ—lity in pl—™eD —nd we ™ontinue on to the sp—n of t—™ti™s intended for the se™ond indu™tive ™—seF …nfortun—telyD those t—™ti™s end up ˜eing —pplied to the rst ™—se inste—dF „he pro˜lem with trivial ™ould ˜e 4solved4 ˜y writing solve ‘trivial“ inste—dD so th—t —n error is sign—led e—rly on if something unexpe™ted h—ppensF roweverD the root pro˜lem is th—t the synt—x of — t—™ti™ invo™—tion does not imply how m—ny su˜go—ls it produ™esF wu™h more ™onfusing inst—n™es of this pro˜lem —re possi˜leF por ex—mpleD if — lemm— L is modi(ed to t—ke —n extr— hypothesisD then uses of apply L will gener—l more su˜go—ls th—n ˜eforeF yld unstru™tured proof s™ripts will ˜e™ome hopelessly jum˜ledD with t—™ti™s —pplied to in—ppropri—te su˜go—lsF fe™—use of the l—™k of stru™tureD there is usu—lly rel—tively little to ˜e gle—ned from knowledge of the pre™ise point in — proof s™ript where —n error is r—isedF Reset timesF Fixpoint times @k X natA @e X expA X exp Xa match e with | Const n ⇒ Const @k B n A | Plus e1 e2 ⇒ Plus @times k e1 A @times k e2 A endF w—ny re—l developments try to m—ke essenti—lly unstru™tured proofs look stru™tured ˜y —pplying ™—reful indent—tion ™onventionsD idempotent ™—seEm—rker t—™ti™s in™luded soley to serve —s do™ument—tionD —nd so onF ell of these str—tegies su'er from the s—me kind of f—ilure of —˜str—™tion th—t w—s just demonstr—tedF s like to s—y th—t if you (nd yourself ™—ring —˜out indent—tion in — proof s™riptD it is — sign th—t the s™ript is stru™tured poorlyF ‡e ™—n rewrite the ™urrent proof with — single t—™ti™F Theorem eval times X ∀ k eD eval @times k e A a k B eval eF induction e as ‘ | c IHe1 c IHe2 “Y ‘ trivial | simplY rewrite IHe1 Y rewrite IHe2 Y rewrite mult plus distr lY trivial “F QedF „his is —n improvement in ro˜ustness of the s™riptF ‡e no longer need to worry —˜out t—ti™s from one ™—se ˜eing —pplied to — di'erent ™—seF ƒtillD the proof s™ript is not espe™i—lly re—d—˜leF €ro˜—˜ly most re—ders would not (nd it helpful in expl—ining why the theorem is trueF „he situ—tion gets worse in ™onsidering extensions to the theorem we w—nt to proveF vet us —dd multipli™—tion nodes to our exp type —nd see how the proof f—resF Reset expF PST Inductive exp X Set Xa | Const X nat → exp | Plus X exp → exp → exp | Mult X exp → exp → expF Fixpoint eval @e X expA X nat Xa match e with | Const n ⇒ n | Plus e1 e2 ⇒ eval e1 C eval e2 | Mult e1 e2 ⇒ eval e1 B eval e2 endF Fixpoint times @k X natA @e X expA X exp Xa match e with | Const n ⇒ Const @k B n A | Plus e1 e2 ⇒ Plus @times k e1 A @times k | Mult e1 e2 ⇒ Mult @times k e1 A e2 endF Theorem eval times X ∀ k eD eval @times k e A a k B eval eF e2 A induction e as ‘ | c IHe1 c IHe2 “Y ‘ trivial | simplY rewrite IHe1 Y rewrite IHe2 Y rewrite Error X Expects a disjunctive pattern with Q mult plus distr lY trivial “F branchesF AbortF …nsurprisinglyD the old proof f—ilsD ˜e™—use it expli™itly s—ys th—t there —re two indu™tive ™—sesF „o upd—te the s™riptD we mustD —t — minimumD remem˜er the order in whi™h the indu™tive ™—ses —re gener—tedD so th—t we ™—n insert the new ™—se in the —ppropri—te pl—™eF iven thenD it will ˜e p—inful to —dd the ™—seD ˜e™—use we ™—nnot w—lk through proof steps inter—™tively when they o™™ur inside —n expli™it set of ™—sesF Theorem eval times X ∀ k eD eval @times k e A a k B eval eF induction e as ‘ | c IHe1 c IHe2 | c IHe1 c IHe2 “Y ‘ trivial | simplY rewrite IHe1 Y rewrite IHe2 Y rewrite mult plus distr lY trivial | simplY rewrite IHe1 Y rewrite mult assocY trivial “F QedF xow we —re in — position to see how mu™h ni™er is the style of proof th—t we h—ve followed in most of this ˜ookF Reset eval timesF PSU Hint X Rewrite mult plus distr l cpdtF Theorem eval times X ∀ k eD eval @times k e A a k B eval eF induction e Y crushF QedF „his style is motiv—ted ˜y — h—rd truthX one person9s m—nu—l proof s™ript is —lmost —lw—ys mostly ins™rut—˜le to most everyone elseF s ™l—im th—t stepE˜yEstep form—l proofs —re — poor w—y of ™onveying inform—tionF „husD we h—d might —s well ™ut out the steps —nd —utom—te —s mu™h —s possi˜leF ‡h—t —˜out the illustr—tive v—lue of proofsc wost inform—l proofs —re re—d to ™onvey the ˜ig ide—s of proofsF row ™—n re—ding induction eY crush ™onvey —ny ˜ig ide—sc wy position is th—t —ny ide—s th—t st—nd—rd —utom—tion ™—n (nd —re not very ˜ig —fter —llD —nd the real ˜ig ide—s should ˜e expressed through lemm—s th—t —re —dded —s hintsF en ex—mple should help illustr—te wh—t s me—nF gonsider this fun™tionD whi™h rewrites —n expression using —sso™i—tivity of —ddition —nd multipli™—tionF Fixpoint reassoc @e X expA X exp Xa match e with | Const ⇒ e | Plus e1 e2 ⇒ let e1' Xa reassoc e1 in let e2' Xa reassoc e2 in match e2' with | Plus e21 e22 ⇒ Plus @Plus e1' e21 A e22 | ⇒ Plus e1' e2' end | Mult e1 e2 ⇒ let e1' Xa reassoc e1 in let e2' Xa reassoc e2 in match e2' with | Mult e21 e22 ⇒ Mult @Mult e1' e21 A e22 | ⇒ Mult e1' e2' end endF Theorem reassoc correct X ∀ eD eval @reassoc e A a eval eF induction e Y crush Y match goal with | ‘ context ‘match ci with Const ⇒ | Plus destruct E Y crush endF yne su˜go—l rem—insX IHe2 X eval e3 B eval e4 a eval e2 PSV ⇒ | Mult ⇒ end“ “ ⇒ aaaaaaaaaaaaaaaaaaaaaaaaaaaa eval e1 B eval e3 B eval e4 a eval e1 B eval e2 crush does not know how to (nish this go—lF ‡e ™ould (nish the proof m—nu—llyF rewrite ← IHe2 Y crushF roweverD the proof would ˜e e—sier to underst—nd —nd m—int—in if we sep—r—ted this insight into — sep—r—te lemm—F AbortF Lemma rewr crushF X∀ a b c dD b B c a d → a B b B c a a B dF QedF Hint Resolve rewrF Theorem reassoc correct X ∀ eD eval @reassoc e A a eval eF induction e Y crush Y match goal with | ‘ context ‘match ci with Const ⇒ | Plus destruct E Y crush endF QedF ⇒ | Mult ⇒ end“ “ ⇒ sn the limitD — ™ompli™—ted indu™tive proof might rely on one hint for e—™h indu™tive ™—seF „he lemm— for e—™h hint ™ould rest—te the —sso™i—ted ™—seF gomp—red to m—nu—l proof s™riptsD we —rrive —t more re—d—˜le resultsF ƒ™ripts no longer need to depend on the order in whi™h ™—ses —re gener—tedF „he lemm—s —re e—sier to digest sep—r—tely th—n —re fr—gments of t—™ti™ ™odeD sin™e lemm— st—tements in™lude ™omplete proof ™ontextsF ƒu™h ™ontexts ™—n only ˜e extr—™ted from monolithi™ m—nu—l proofs ˜y stepping through s™ripts inter—™tivelyF „he more ™ommon situ—tion is th—t — l—rge indu™tion h—s sever—l e—sy ™—ses th—t —uE tom—tion m—kes short work ofF sn the rem—ining ™—sesD —utom—tion performs some st—nd—rd simpli(™—tionF emong these ™—sesD some m—y require quite involved proofsY su™h — ™—se m—y deserve — hint lemm— of its ownD where the lemm— st—tement m—y ™opy the simpli(ed version of the ™—seF eltern—tivelyD the proof s™ript for the m—in theorem m—y ˜e extended with some —utom—tion ™ode t—rgeted —t the spe™i(™ ™—seF iven su™h t—rgeted s™ripting is more desir—˜le th—n m—nu—l provingD ˜e™—use it m—y ˜e re—d —nd understood without knowledge of — proof9s hier—r™hi™—l stru™tureD ™—se orderingD or n—me ˜inding stru™tureF 14.2 Debugging and Maintaining Automation pullyE—utom—ted proofs —re desir—˜le ˜e™—use they open up possi˜ilities for —utom—ti™ —d—pE t—tion to ™h—nges of spe™i(™—tionF e wellEengineered s™ript within — n—rrow dom—in ™—n survive m—ny ™h—nges to the formul—tion of the pro˜lem it solvesF ƒtillD —s we —re workE PSW ing with higherEorder logi™D most theorems f—ll within no o˜vious de™id—˜le theoriesF st is inevit—˜le th—t most longElived —utom—ted proofs will need upd—tingF fefore we —re re—dy to upd—te our proofsD we need to write them in the (rst pl—™eF ‡hile fullyE—utom—ted s™ripts —re most ro˜ust to ™h—nges of spe™i(™—tionD it is h—rd to write every new proof dire™tly in th—t formF snste—dD it is useful to ˜egin — theorem with explor—tory proving —nd then gr—du—lly re(ne it into — suit—˜le —utom—ted formF gonsider this theorem from gh—pter UD whi™h we ˜egin ˜y proving in — mostly m—nu—l w—yD invoking crush —fter e—™h steop to dis™h—rge —ny lowEh—nging fruitF yur m—nu—l e'ort involves ™hoosing whi™h expressions to ™—seE—n—lyze onF Theorem cfold correct X ∀ induction e Y crushF dep destruct dep destruct dep destruct dep destruct dep destruct dep destruct t @e X exp t AD expDenote e a expDenote @cfold e AF @cfold @cfold e1 AY crushF @cfold @cfold e1 AY crushF @cfold @cfold e1 AY crushF e2 AY crushF e2 AY crushF e2 AY crushF dep destruct @cfold e1 AY crushF @expDenote e1 AY crushF dep destruct @cfold e AY crushF dep destruct @cfold e AY crushF dep destruct QedF sn this ™omplete proofD it is h—rd to —void noti™ing — p—tternF ‡e rework the proofD —˜str—™ting over the p—tterns we (ndF Reset cfold correctF Theorem cfold correct X ∀ induction e Y crushF t @e X exp t AD expDenote e a expDenote @cfold e AF „he expression we w—nt to destru™t here turns out to ˜e the dis™riminee of — matchD —nd we ™—n e—sily enough write — t—™ti™ th—t destru™ts —ll su™h expressionsF Ltac t Xa repeat @match |‘ endY with ⇒ | Plus ⇒ context ‘match ci with NConst | Eq ⇒ | BConst ⇒ | And ⇒ | If ⇒ | Pair ⇒ | Fst ⇒ | Snd ⇒ end“ “ ⇒ goal dep destruct E crush AF tF PTH „his t—™ti™ invo™—tion dis™h—rges the whole ™—seF st does the s—me on the next two ™—sesD ˜ut it gets stu™k on the fourth ™—seF tF tF tF „he su˜go—l9s ™on™lusion isX aaaaaaaaaaaaaaaaaaaaaaaaaaaa @if expDenote e1 then expDenote @cfold e2 A else expDenote @cfold expDenote @if expDenote e1 then cfold e2 else cfold e3 A ‡e need to exp—nd our Ltac t' Xa repeat @match |‘ goal t e3 AA a t—™ti™ to h—ndle this ™—seF with context ‘match dep destruct E | ‘ @if ci then endY crush AF ci with NConst ⇒ | Plus ⇒ | Eq ⇒ | BConst ⇒ | And ⇒ | If ⇒ | Pair ⇒ | Fst ⇒ | Snd ⇒ end“ “ ⇒ else A a “ ⇒ destruct E t'F xow the go—l is dis™h—rgedD ˜ut t' h—s no e'e™t on the next su˜go—lF t'F e (n—l revision of Ltac t Xa repeat @match |‘ t (nishes the proofF with ⇒ | Plus ⇒ context ‘match ci with NConst | Eq ⇒ | BConst ⇒ | And ⇒ | If ⇒ | Pair ⇒ | Fst ⇒ | Snd ⇒ end“ “ ⇒ goal dep destruct E |‘ |‘ endY @if ci then else A a “ ⇒ destruct context ‘match pairOut ci with Some ⇒ | None ⇒ end“ “ ⇒ dep destruct E crush AF t F t F QedF PTI E ‡e ™—n t—ke the (n—l t—™ti™ —nd move it into the initi—l p—rt of the proof s™riptD —rriving —t — ni™elyE—utom—ted proofF Reset tF Theorem cfold correct X ∀ t @e X exp t AD expDenote e a expDenote @cfold e AF induction e Y crush Y repeat @match goal with ⇒ | ‘ context ‘match ci with NConst ⇒ | Plus | Eq ⇒ | BConst ⇒ | And ⇒ | If ⇒ | Pair ⇒ | Fst ⇒ | Snd ⇒ end“ “ ⇒ dep destruct E @if ci then |‘ |‘ endY QedF else A a “ ⇒ destruct ci with Some ⇒ | None ⇒ end“ “ ⇒ context ‘match pairOut E dep destruct E crush AF iven —fter we put together ni™e —utom—ted proofsD we must de—l with spe™i(™—tion ™h—nges th—t ™—n inv—lid—te themF st is not gener—lly possi˜le to step through singleEt—™ti™ proofs inter—™tivelyF „here is — ™omm—nd Debug On th—t lets us step through points in t—™ti™ exe™utionD ˜ut the de˜ugger tends to m—ke ™ounterintuitive ™hoi™es of whi™h points we would like to stop —tD —nd perEpoint output is quite ver˜oseD so most goq users do not (nd this de˜ugging mode very helpfulF row —re we to underst—nd wh—t h—s ˜roken in — s™ript th—t used to workc en ex—mple helps demonstr—te — useful —ppro—™hF gonsider wh—t would h—ve h—ppened in our proof of reassoc correct if we h—d (rst —dded —n unfortun—te rewriting hintF Reset reassoc correctF Theorem eval e1 crushF confounder B eval e2 X ∀ e1 e2 e3D B eval e3 a eval e1 B @eval e2 C I E IA B eval e3F QedF Hint Rewrite confounder X cpdtF Theorem reassoc correct X ∀ eD eval @reassoc e A a eval eF induction e Y crush Y match goal with | ‘ context ‘match ci with Const ⇒ | Plus destruct E Y crush endF yne su˜go—l rem—insX PTP ⇒ | Mult ⇒ end“ “ ⇒ aaaaaaaaaaaaaaaaaaaaaaaaaaaa eval e1 B @eval e3 C I E IA B eval e4 a eval e1 B eval e2 „he poorlyE™hosen rewrite rule (redD ™h—nging the go—l to — form where —nother hint no longer —ppliesF sm—gine th—t we —re in the middle of — l—rge development with m—ny hintsF row would we di—gnose the pro˜lemc pirstD we might not ˜e sure whi™h ™—se of the indu™tive proof h—s gone wrongF st is useful to sep—r—te out our —utom—tion pro™edure —nd —pply it m—nu—llyF RestartF Ltac t Xa crush Y match goal with | ‘ context ‘match ci with Const ⇒ | Plus | Mult ⇒ end“ “ ⇒ destruct E Y crush endF ⇒ induction eF ƒin™e we see the su˜go—ls ˜efore —ny simpli(™—tion o™™ursD it is ™le—r th—t this is the ™—se for ™onst—ntsF t m—kes short work of itF tF „he next su˜go—lD for —dditionD is —lso dis™h—rged without trou˜leF tF „he (n—l su˜go—l is for multipli™—tionD —nd it is here th—t we get stu™k in the proof st—te summ—rized —˜oveF tF ‡h—t is t doing to get us to this pointc „he of questionF info ™omm—nd ™—n help us —nswer this kind UndoF info tF aa simpl in BY intuitionY substY autorewrite with cpdt in BY simpl in BY intuitionY substY autorewrite with cpdt in BY simpl in BY intuitionY substY destruct @reassoc e2 AF simpl in BY intuitionF simpl in BY intuitionF simpl in BY intuitionY substY autorewrite with cpdt in BY refine @eq ind r @fun n X nat ⇒ n B @eval e3 C I E IA B eval e4 a eval e1 B eval PTQ e2 A IHe1 AY with cpdt in BY simpl in BY intuitionY substY autorewrite with cpdt in BY simpl in BY intuitionY substF autorewrite e det—iled tr—™e of t 9s exe™ution —ppe—rsF ƒin™e we —re using the very gener—l crush t—™ti™D m—ny of these steps h—ve no e'e™t —nd only o™™ur —s inst—n™es of — more gener—l str—tegyF ‡e ™—n ™opyE—ndEp—ste the det—ils to see where things go wrongF UndoF ‡e —r˜itr—rily split the s™ript into ™hunksF „he (rst few seem not to do —ny h—rmF simpl simpl simpl simpl simpl in in in in in BY BY BY BY BY intuitionY substY autorewrite with cpdt in BF intuitionY substY autorewrite with cpdt in BF intuitionY substY destruct @reassoc e2 AF intuitionF intuitionF „he next step is reve—led —s the ™ulpritD ˜ringing us to the (n—l unproved su˜go—lF simpl in BY intuitionY substY autorewrite with cpdt in BF ‡e ™—n split the steps further to —ssign ˜l—meF UndoF simpl in BF intuitionF substF autorewrite with cpdt in BF st w—s the (n—l of these four t—™ti™s th—t m—de the rewriteF ‡e ™—n (nd out ex—™tly wh—t h—ppenedF „he info ™omm—nd presents hier—r™hi™—l views of proof stepsD —nd we ™—n zoom down to — lower level of det—il ˜y —pplying info to one of the steps th—t —ppe—red in the origin—l tr—™eF UndoF info autorewrite with cpdt in BF aa refine @eq ind r @fun n X nat ⇒ n a eval e1 B @confounder @reassoc e1 A e3 e4 AAF eval e2 A „he w—y — rewrite is displ—yed is somewh—t ˜—roqueD ˜ut we ™—n see th—t theorem confounder is the (n—l ™ulpritF et this pointD we ™ould remove th—t hintD prove —n —ltern—te version of the key lemm— rewrD or ™ome up with some other remedyF pixing this kind of pro˜lem tends to ˜e rel—tively e—sy on™e the pro˜lem is reve—ledF AbortF ƒometimes — ™h—nge to — development h—s undesir—˜le perform—n™e ™onsequen™esD even if PTR it does not prevent —ny old proof s™ripts from ™ompletingF sf the perform—n™e ™onsequen™es —re severe enoughD the proof s™ripts ™—n ˜e ™onsidered ˜roken for pr—™ti™—l purposesF rere is one ex—mple of — perform—n™e surpriseF Section slowF Hint Resolve trans eqF „he ™entr—l element of the pro˜lem is the —ddition of tr—nsitivity —s — hintF ‡ith tr—nE sitivity —v—il—˜leD it is e—sy for proof se—r™h to wind up exploring exponenti—l se—r™h sp—™esF ‡e —lso —dd — few other —r˜itr—ry v—ri—˜les —nd hypothesesD designed to le—d to trou˜le l—terF Variable A X SetF Variables P Q R S X Variable f X A → AF Hypothesis Hypothesis H1 H2 X∀ X∀ A → A x yD P x y x yD S x y → PropF →Qx y→ → R x yF Rxy → fx a f yF ‡e prove — simple lemm— very qui™klyD using the Time ™omm—nd to me—sure ex—™tly how qui™klyF Lemma slow Time X∀ x yD P x y → eauto TF Finished transaction in HF secs Qxy → Sxy → fx a f yF @HFHTVHHRuDHFs A QedF xow we —dd — di'erent hypothesisD whi™h is inno™ent enoughY in f—™tD it is even prov—˜le —s — theoremF Hypothesis Lemma X∀ x yD x a X ∀ x yD eauto TF Pxy → H3 slow' Time Finished transaction in PF y secs → fx Qxy a → f yF Sxy → fx a f yF @IFPTRHUWuDHFs A ‡hy h—s the se—r™h time gone up so mu™hc „he info ™omm—nd is not mu™h helpD sin™e it only shows the result of se—r™hD not —ll of the p—ths th—t turned out to ˜e worthlessF RestartF info eauto TF aa intro x Y intro y Y intro simple eapply trans apply re equalF simple eapply simple HY eqF intro H0 Y intro trans eqF PTS H4 Y simple apply simple simple eapply trans eqF apply re equalF simple apply eexact HF re equalF H1 F eexact H0F simple apply H2 Y eexact H4 F „his output does not tell us why proof se—r™h t—kes so longD ˜ut it does provide — ™lue th—t would ˜e useful if we h—d forgotten th—t we —dded tr—nsitivity —s — hintF „he eauto t—™ti™ is —pplying depthE(rst se—r™hD —nd the proof s™ript where the re—l —™tion is ends up ˜uried inside — ™h—in of pointless invo™—tions of tr—nsitivityD where e—™h invo™—tion uses re)exivity to dis™h—rge one su˜go—lF i—™h in™rement to the depth —rgument to eauto —dds —nother silly use of tr—nsitivityF „his w—sted proof e'ort only —dds line—r time overhe—dD —s long —s proof se—r™h never m—kes f—lse stepsF xo f—lse steps were m—de ˜efore we —dded the new hypothesisD ˜ut somehow the —ddition m—de possi˜le — new f—ulty p—thF „o underst—nd whi™h p—ths we en—˜ledD we ™—n use the debug ™omm—ndF RestartF debug eauto TF „he output is — l—rge proof treeF „he ˜eginning of the tree is enough to reve—l wh—t is h—ppeningX I depthaT IFI depthaT intro IFIFI depthaT intro IFIFIFI depthaT intro IFIFIFIFI depthaT intro IFIFIFIFIFI depthaT intro IFIFIFIFIFIFI depthaS apply H3 IFIFIFIFIFIFIFI depthaR eapply trans eq IFIFIFIFIFIFIFIFI depthaR apply re equal IFIFIFIFIFIFIFIFIFI depthaQ eapply trans eq IFIFIFIFIFIFIFIFIFIFI depthaQ apply re equal IFIFIFIFIFIFIFIFIFIFIFI depthaP eapply trans eq IFIFIFIFIFIFIFIFIFIFIFIFI depthaP apply re equal IFIFIFIFIFIFIFIFIFIFIFIFIFI depthaI eapply trans eq IFIFIFIFIFIFIFIFIFIFIFIFIFIFI depthaI apply re equal IFIFIFIFIFIFIFIFIFIFIFIFIFIFIFI depthaH eapply trans eq PTT IFIFIFIFIFIFIFIFIFIFIFIFIFIFP depthaI apply sym eq Y trivial IFIFIFIFIFIFIFIFIFIFIFIFIFIFPFI depthaH eapply trans eq IFIFIFIFIFIFIFIFIFIFIFIFIFIFQ depthaH eapply trans eq IFIFIFIFIFIFIFIFIFIFIFIFP depthaP apply sym eq Y trivial IFIFIFIFIFIFIFIFIFIFIFIFPFI depthaI eapply trans eq IFIFIFIFIFIFIFIFIFIFIFIFPFIFI depthaI apply re equal IFIFIFIFIFIFIFIFIFIFIFIFPFIFIFI depthaH eapply trans eq IFIFIFIFIFIFIFIFIFIFIFIFPFIFP depthaI apply sym eq Y trivial IFIFIFIFIFIFIFIFIFIFIFIFPFIFPFI depthaH eapply trans eq IFIFIFIFIFIFIFIFIFIFIFIFPFIFQ depthaH eapply trans eq „he (rst ™hoi™e eauto m—kes is to —pply H3 D sin™e H3 h—s the fewest hypotheses of —ll of the hypotheses —nd hints th—t m—t™hF roweverD it turns out th—t the single hypothE esis gener—ted is unprov—˜leF „h—t does not stop eauto from trying to prove it with —n exponenti—llyEsized tree of —ppli™—tions of tr—nsitivityD re)exivityD —nd symmetry of equ—lityF st is the ™hildren of the initi—l apply H3 th—t —™™ount for —ll of the noti™e—˜le time in proof exe™utionF sn — more re—listi™ developmentD we might use this output of info to re—lize th—t —dding tr—nsitivity —s — hint w—s — ˜—d ide—F QedF End slowF st is —lso e—sy to end up with — proof s™ript th—t uses too mu™h memoryF es t—™ti™s runD they —void gener—ting proof termsD sin™e serious proof se—r™h will ™onsider m—ny possi˜le —venuesD —nd we do not w—nt to ˜uilt proof terms for su˜proofs th—t end up unusedF snste—dD t—™ti™ exe™ution m—int—ins thunks @suspended ™omput—tionsD represented with ™losuresAD su™h th—t — t—™ti™9s proofEprodu™ing thunk is only exe™uted when we run QedF „hese thunks ™—n use up l—rge —mounts of sp—™eD su™h th—t — proof s™ript exh—usts —v—il—˜le memoryD even when we know th—t we ™ould h—ve used mu™h less memory ˜y for™ing some thunks e—rlierF „he abstract t—™ti™—l helps us for™e thunks ˜y proving some su˜go—ls —s their own lemm—sF por inst—n™eD — proof induction x Y crush ™—n in m—ny ™—ses ˜e m—de to use signi(™—ntly less pe—k memory ˜y ™h—nging it to induction x Y abstract crushF „he m—in limit—tion of abstract is th—t it ™—n only ˜e —pplied to su˜go—ls th—t —re proved ™ompletelyD with no undetermined uni(™—tion v—ri—˜les rem—iningF ƒtillD m—ny l—rge —utom—ted proofs ™—n re—lize v—st memory s—vings vi— abstractF 14.3 Modules v—st ™h—pter9s ex—mples of proof ˜y re)e™tion demonstr—te opportunities for implementing —˜str—™t proof str—tegies with stronger form—l gu—r—ntees th—n ™—n ˜e h—d with vt—™ s™riptE ingF goq9s module system provides —nother tool for more rigorous development of generi™ theoremsF „his fe—ture is inspired ˜y the module systems found in ƒt—nd—rd wv —nd y˜E je™tive g—mlD —nd the dis™ussion th—t follows —ssumes f—mili—rity with the ˜—si™s of one of PTU those systemsF wv modules f—™ilit—te the grouping of —˜str—™t types with oper—tions over those typesF woreoverD there is support for functorsD whi™h —re fun™tions from modules to modulesF e ™—noni™—l ex—mple of — fun™tor is one th—t ˜uilds — d—t— stru™ture implement—tion from — module th—t des™ri˜es — dom—in of keys —nd its —sso™i—ted ™omp—rison oper—tionsF ‡hen we —dd modules to — ˜—se l—ngu—ge with dependent typesD it ˜e™omes possi˜le to use modules —nd fun™tors to form—lize kinds of re—soning th—t —re ™ommon in —lge˜r—F por inst—n™eD this module sign—ture ™—ptures the essen™e of the —lge˜r—i™ stru™ture known —s — groupF e group ™onsists of — ™—rrier set GD —n —sso™i—tive ˜in—ry oper—tion f D — left identity element e for f D —nd —n oper—tion i th—t is — left inverse for f F Module Type GROUPF Parameter G X SetF Parameter f X G → G → Parameter e X G F Parameter i X G → G F G F Axiom assoc X ∀ a b cD f @f a b A c a Axiom ident X ∀ aD f e a a aF Axiom inverse X ∀ aD f @i a A a a e F End GROUPF f a @f b c AF w—ny useful theorems hold of —r˜itr—ry groupsF ‡e ™—pture some su™h theorem st—teE ments in —nother module sign—tureF Module Type GROUP THEOREMSF Declare Module M X GROUPF Axiom ident' Axiom inverse' X ∀ aD M.f X ∀ aD a M.f M.e a a aF @M.i Axiom unique ident X ∀ e'D @∀ aD End GROUP THEOREMSF aA M.f a M.e e' a F a aA → e' a M.e F ‡e implement generi™ proofs of these theorems with — fun™torD whose input is —n —r˜itr—ry group MF „he proofs —re ™ompletely m—nu—lD sin™e it would t—ke some e'ort to ˜uild suit—˜le generi™ —utom—tionY r—therD these theorems ™—n serve —s — ˜—sis for —n —utom—ted pro™edure for simplifying group expressionsD —long the lines of the pro™edure for monoids from the l—st ™h—pterF ‡e t—ke the proofs from the ‡ikipedi— p—ge on element—ry group theoryF Module Group @M X Module M Xa MF Import GROUPA X GROUP THEOREMS with Module M MF Theorem inverse' X ∀ aD f a @i a A a e F introF rewrite ← @ident @f a @i a AAAF rewrite ← @inverse @f a @i a AAA at IF PTV Xa MF rewrite assoc F rewrite assoc F rewrite ← @assoc @i a A a @i a AAF rewrite inverse F rewrite ident F apply inverse F QedF Theorem ident' X ∀ aD f a e a aF introF rewrite ← @inverse a AF rewrite ← assoc F rewrite inverse'F apply ident F QedF Theorem unique ident X ∀ e'D @∀ aD M.f e' a a a A → e' a M.e F introsF rewrite ← @H e AF symmetryF apply ident'F QedF End GroupF ‡e ™—n show th—t the integers with C form — groupF Require Import ZArithF Open Scope Z scopeF Module IntF Definition G Xa ZF Definition f x y Xa x C yF Definition e Xa HF Definition i x Xa ExF Theorem assoc X ∀ a b cD f @f a b A c a f a @f b c AF unfold f Y crushF QedF Theorem ident X ∀ aD f e a a aF unfold fD e Y crushF QedF Theorem inverse X ∀ aD f @i a A a a eF unfold fD iD e Y crushF QedF End IntF xextD we ™—n produ™e integerEspe™i(™ versions of the generi™ group theoremsF Module IntTheorems Xa Group@IntAF PTW Check IntTheorems.unique ident F IntTheorems.unique ident X∀ e' X Int.GD @∀ a X Int.GD Int.f e' a Theorem unique ident X ∀ e'D @∀ aD e' C exact IntTheorems.unique ident F QedF a a aA → a aA → e' e' a Int.e a HF es in wvD the module system provides —n e'e™tive w—y to stru™ture l—rge developmentsF …nlike in wvD goq modules —dd no expressivenessY we ™—n implement —ny module —s —n inh—˜it—nt of — dependent re™ord typeF st is the se™ondE™l—ss n—ture of modules th—t m—kes them e—sier to use th—n dependent re™ords in m—ny ™—seF fe™—use modules m—y only ˜e used in quite restri™ted w—ysD it is e—sier to support ™onvenient module ™oding through spe™i—l ™omm—nds —nd editing modesD —s the —˜ove ex—mple demonstr—tesF en isomorphi™ implement—tion with re™ords would h—ve su'ered from l—™k of su™h ™onvenien™es —s module su˜typing —nd import—tion of the (elds of — moduleF 14.4 Build Processes es in softw—re developmentD l—rge goq proje™ts —re mu™h more m—n—ge—˜le when split —™ross multiple (les —nd when de™omposed into li˜r—riesF goq —nd €roof qener—l provide very good support for these —™tivitiesF gonsider — li˜r—ry th—t we will n—me LibD housed in dire™tory LIB —nd split ˜etween (les A.vD B.vD —nd C.vF e simple w—ke(le will ™ompile the li˜r—ryD relying on the st—nd—rd goq tool coq makefile to do the h—rd workF MODULES := A B C VS := $(MODULES:%=%.v) .PHONY: coq clean coq: Makefile.coq make -f Makefile.coq Makefile.coq: Makefile $(VS) coq_makefile -R . Lib $(VS) -o Makefile.coq clean:: Makefile.coq make -f Makefile.coq clean rm -f Makefile.coq „he w—ke(le ˜egins ˜y de(ning — v—ri—˜le VS holding the list of (len—mes to ˜e in™luded in the proje™tF „he prim—ry t—rget is coqD whi™h depends on the ™onstru™tion of —n —uxilE i—ry w—ke(le ™—lled Makefile.coqF enother rule expl—ins how to ˜uild th—t (leF ‡e ™—ll PUH coq makefileD using the -R )—g to spe™ify th—t (les in the ™urrent dire™tory should ˜e ™onE sidered to ˜elong to the li˜r—ry LibF „his w—ke(le will ˜uild — ™ompiled version of e—™h moduleD su™h th—t X.v is ™ompiled into X.voF xow ™ode in B.v m—y refer to de(nitions in A.v —fter running Require Import Lib.AF vi˜r—ry Lib is presented —s — moduleD ™ont—ining — su˜module AD whi™h ™ont—ins the de(nitions from A.vF „hese —re genuine modules in the sense of goq9s module systemD —nd they m—y ˜e p—ssed to fun™tors —nd so onF Require Import is — ™onvenient ™om˜in—tion of two more primitive ™omm—ndsF Require (nds the .vo (le ™ont—ining the n—med moduleD ensuring th—t the module is lo—ded into memE oryF Import lo—ds —ll topElevel de(nitions of the n—med module into the ™urrent n—mesp—™eD —nd it m—y ˜e used with lo™—l modules th—t do not h—ve ™orresponding .vo (lesF enother ™omm—ndD LoadD is for inserting the ™ontents of — n—med (le ver˜—timF st is gener—lly ˜etE ter to use the moduleE˜—sed ™omm—ndsD sin™e they —void rerunning proof s™riptsD —nd they f—™ilit—te reorg—niz—tion of dire™tory stru™ture without the need to ™h—nge ™odeF xow we would like to use our li˜r—ry from — di'erent developmentD ™—lled Client —nd found in dire™tory CLIENTD whi™h h—s its own w—ke(leF MODULES := D E VS := $(MODULES:%=%.v) .PHONY: coq clean coq: Makefile.coq make -f Makefile.coq Makefile.coq: Makefile $(VS) coq_makefile -R LIB Lib -R . Client $(VS) -o Makefile.coq clean:: Makefile.coq make -f Makefile.coq clean rm -f Makefile.coq ‡e ™h—nge the coq makefile ™—ll to indi™—te where the li˜r—ry —nd E.v ™—n refer to de(nitions from Lib module A —fter running Require Import Lib.AF —nd E.v ™—n refer to de(nitions from D.v ˜y running Require Import Client.DF PUI Lib is foundF xow D.v st ™—n ˜e useful to split — li˜r—ry into sever—l (lesD ˜ut it is —lso in™onvenient for ™lient ™ode to import li˜r—ry modules individu—llyF ‡e ™—n get the ˜est of ˜oth worlds ˜yD for ex—mpleD —dding —n extr— sour™e (le Lib.v to Lib 9s dire™tory —nd w—ke(leF Require Export Lib.A Lib.B Lib.CF xow ™lient ™ode ™—n import —ll de(nitions from —ll of Require Import Lib 9s modules simply ˜y running LibF „he two w—ke(les —˜ove sh—re — lot of ™odeD soD in pr—™ti™eD it is useful to de(ne — ™ommon w—ke(le th—t is in™luded ˜y multiple li˜r—ryEspe™i(™ w—ke(lesF „he rem—ining ingredient is the proper w—y of editing li˜r—ry ™ode (les in €roof qener—lF ‚e™—ll this snippet of .emacs ™ode from gh—pter PD whi™h tells €roof qener—l where to (nd the li˜r—ry —sso™i—ted with this ˜ookF (custom-set-variables ... '(coq-prog-args '("-I" "/path/to/cpdt/src")) ... ) „o do inter—™tive editing of our ™urrent ex—mpleD we just need to ™h—nge the )—gs to point to the right pl—™esF (custom-set-variables ... ; '(coq-prog-args '("-I" "/path/to/cpdt/src")) '(coq-prog-args '("-R" "LIB" "Lib" "-R" "CLIENT" "Client")) ... ) ‡hen working on multiple proje™tsD it is useful to le—ve multiple versions of this setting in your .emacs (leD ™ommenting out —ll ˜ut one of them —t —ny moment in timeF „o swit™h ˜etween proje™tsD ™h—nge the ™ommenting stru™ture —nd rest—rt im—™sF PUP Part IV Formalizing Programming Languages and Compilers PUQ Chapter 15 First-Order Abstract Syntax w—ny people interested in inter—™tive theoremEproving w—nt to prove theorems —˜out proE gr—mming l—ngu—gesF „h—t dom—in —lso provides — good setting for demonstr—ting how to —pply the ide—s from the e—rlier p—rts of this ˜ookF „his p—rt introdu™es some te™hniques for en™oding the synt—x —nd sem—nti™s of progr—mming l—ngu—gesD —long with some ex—mple proofs designed to ˜e —s pr—™ti™—l —s possi˜leD r—ther th—n to illustr—te ˜—si™ goq te™hniqueF „o prove —nything —˜out — l—ngu—geD we must (rst form—lize the l—ngu—ge9s synt—xF ‡e h—ve — ˜ro—d design sp—™e to ™hoose fromD —nd it m—kes sense to st—rt with the simplest optionsD soE™—lled rst-order synt—x en™odings th—t do not use dependent typesF „hese en™odings —re (rstEorder ˜e™—use they do not use goq fun™tion types in — ™riti™—l w—yF sn this ™h—pterD we ™onsider the most popul—r (rstEorder en™odingsD using e—™h to prove — ˜—si™ type soundness theoremF 15.1 Concrete Binding „he most o˜vious en™oding of the synt—x of progr—mming l—ngu—ges follows usu—l ™ontextE free gr—mm—rs liter—llyF ‡e represent v—ri—˜les —s strings —nd in™lude — v—ri—˜le in our eƒ„ de(nition wherever — v—ri—˜le —ppe—rs in the inform—l gr—mm—rF gon™rete ˜inding turns out to involve — surprisingly l—rge —mount of meni—l ˜ookkeepingD espe™i—lly when we en™ode higherEorder l—ngu—ges with nested ˜inder s™opesF „his se™tion9s ex—mple should give — )—vor of wh—t is requiredF Module ConcreteF ‡e need our v—ri—˜le type —nd its de™id—˜le equ—lity oper—tionF Definition Definition var Xa var eq stringF Xa string decF ‡e will form—lize ˜—si™ simplyEtyped l—m˜d— ™—l™ulusF „he synt—x of expressions —nd types follows wh—t we would write in — ™ontextEfree gr—mm—rF Inductive exp X Set Xa PUR bool → exp Var X var → exp App X exp → exp → exp Abs X var → exp → expF Inductive type X Set Xa | Bool X type | Arrow X type → type → typeF | | | | Const X st is useful to de(ne — synt—x extension th—t lets us write fun™tion types in more st—nd—rd not—tionF Infix 4!b4 Xa Arrow @right at associativityD level THAF xow we turn to — typing judgmentF ‡e will need to de(ne it in terms of typing ™ontextsD whi™h we represent —s lists of p—irs of v—ri—˜les —nd typesF Definition ctx Xa list @var × typeAF „he de(nitions of our judgments will ˜e prettier if we write them using mix(x synt—xF „o de(ne — judgment for looking up the type of — v—ri—˜le in — ™ontextD we (rst reserve — not—tion for the judgmentF ‚eserved not—tions en—˜le mutu—llyEre™ursive de(nition of — judgment —nd its not—tionY in this senseD the reserv—tion is like — forw—rd de™l—r—tion in gF Reserved Notation 4q |Ev x X t4 @no associativityD at level WHD x at next level AF xow we de(ne the judgment itselfD for v—ri—˜le typingD using — where ™l—use to —sso™i—te — not—tion de(nitionF Inductive lookup X ctx → | First X ∀ x t GD @xD t A XX G |Ev x X t | Next X ∀ x t x' t' GD x = x' → G |Ev x X t → @x'D t' A XX G |Ev x X t var → where 4q |Ev x X t4 Xa @lookup Hint type → Prop Xa G x t AF Constructors lookupF „he s—me te™hnique —pplies to de(ning the m—in typing judgmentF ‡e use —n at next level ™l—use to ™—use the —rgument e of the not—tion to ˜e p—rsed —t — low enough pre™eden™e levelF Reserved Notation 4q |Ee e X t4 @no Inductive hasType X ctx → | TConst X ∀ G bD G |Ee Const b X Bool | TVar X ∀ G v tD G |Ev v X t associativityD at exp → type → Prop Xa PUS level WHD e at next level AF |Ee Var v X t | TApp X ∀ G e1 e2 dom ranD G |Ee e1 X dom !b ran → G |Ee e2 X dom → G |Ee App e1 e2 X ran | TAbs X ∀ G x e' dom ranD @xD dom A XX G |Ee e' X ran → G |Ee Abs x e' X dom !b → G ran where 4q |Ee e X t4 Xa @hasType Hint G e t AF Constructors hasTypeF st is useful to know th—t v—ri—˜le lookup results —re un™h—nged ˜y —dding extr— ˜indings to the end of — ™ontextF Lemma G1 weaken lookup |Ev Xt CC G' |Ev X∀ x t G' G1D x → G1 x X tF induction G1 as ‘ | ‘c c“ c “Y crush Y match goal with “ ⇒ inversion | ‘ H X |Ev X endF QedF Hint Resolve H Y crush weaken lookupF „he s—me property extends to the full typing judgmentF Theorem weaken hasType' X ∀ G' G |Ee e X t → G CC G' |Ee e X tF induction IY crush Y eautoF QedF G e tD Theorem weaken hasType X ∀ e tD nil |Ee e X t → ∀ G'D G' |Ee e X tF introsY change G' with @nil CC G' AY eapply weaken hasType'Y eautoF QedF Hint Resolve weaken hasTypeF wu™h of the in™onvenien™e of (rstEorder en™odings ™omes from the need to tre—t ™—ptureE —voiding su˜stitution expli™itlyF ‡e must st—rt ˜y de(ning — su˜stitution fun™tionF Section substF Variable x X varF Variable e1 X expF PUT ‡e —re su˜stituting expression e1 for every free o™™urren™e of x F xote th—t this de(nition is spe™i—lized to the ™—se where e1 is ™losedY su˜stitution is su˜st—nti—lly more ™ompli™—ted otherwiseD potenti—lly involving expli™it —lph—Ev—ri—tionF vu™kilyD our ex—mple of type s—fety for — ™—llE˜yEv—lue sem—nti™s only requires this restri™ted v—riety of su˜stitutionF Fixpoint subst @e2 X expA X exp Xa match e2 with | Const ⇒ e2 | Var x' ⇒ if var eq x' x then e1 else e2 | App e1 e2 ⇒ App @subst e1 A @subst e2 A | Abs x' e' ⇒ Abs x' @if var eq x' x then e' else endF subst e' A ‡e ™—n prove — few theorems —˜out su˜stitution in wellEtyped termsD where we —ssume th—t e1 is ™losed —nd h—s type xt F Variable xt X typeF Hypothesis Ht' X nil |Ee e1 X xtF st is helpful to est—˜lish — not—tion —sserting the freshness of — p—rti™ul—r v—ri—˜le in — ™ontextF Notation 4x 5 q4 Xa @∀ t' X typeD In @xD t' A G → FalseA @no associativityD at level WHAF „o prove type preserv—tionD we will need lemm—s proving ™onsequen™es of v—ri—˜le lookup proofsF Lemma subst lookup' X ∀ x' tD x = x' → ∀ G1D G1 CC @xD xt A XX nil |Ev x' X t → G1 |Ev x' X tF induction G1 as ‘ | ‘c c“ c “Y crush Y match goal with “ ⇒ inversion | ‘ H X |Ev X endY crushF QedF Hint Resolve H subst lookup'F Lemma subst lookup X ∀ x' t G1D x' 5 G1 → G1 CC @xD xt A XX nil |Ev x' X t → t a xtF induction G1 as ‘ | ‘c c“ c “Y crush Y eautoY match goal with | ‘ H X |Ev X “ ⇒ inversion H endY crush Y @elimtype FalseY eautoY match goal with | ‘ H X nil |Ev X “ ⇒ inversion PUU H QedF endA || match goal with “ ⇒ apply |‘H X endF Implicit Arguments H Y crush Y eauto subst lookup ‘x' t G1 “F enother set of lemm—s —llows us to remove prov—˜ly unused v—ri—˜les from the ends of typing ™ontextsF Lemma shadow lookup X∀ v t t' G1D |Ev x X t' → G1 CC @xD xt A XX nil |Ev v X t → G1 |Ev v X tF induction G1 as ‘ | ‘c c“ c “Y crush Y match goal with “ ⇒ inversion H | ‘ H X nil |Ev X “⇒ | ‘ H1 X |Ev X D H2 X |Ev X inversion H1 Y crush Y inversion H2 Y crush endF QedF G1 Lemma shadow hasType' X ∀ G e tD G |Ee e X t → ∀ G1D G a G1 CC @xD xt A XX → ∀ t D G1 |Ev x X t → G1 |Ee e X tF Hint Resolve shadow lookupF nil induction IY crush Y eautoY match goal with | ‘ H X @cxHD A XX CC @cxD A XX |Ee X destruct @var eq x0 x AY substY eauto endF QedF Lemma shadow hasType X ∀ G1 e |Ee e X t CC @xD xt A XX nil → G1 |Ev x X t → G1 |Ee e X tF introsY eapply shadow QedF G1 Hint Resolve “⇒ t t D hasType'Y eautoF shadow hasTypeF hisjointness f—™ts m—y ˜e extended to l—rger ™ontexts when the —ppropri—te o˜lig—tions —re metF PUV Lemma disjoint cons X ∀ x x' t @G X ctxAD x 5G → x' = x → x 5 @x'D t A XX GF firstorderY match goal with “ ⇒ injection |‘H X@ D Aa@ D A endY crushF QedF Hint Resolve H disjoint consF pin—llyD we —rrive —t the m—in theorem —˜out su˜stitutionX it preserves typingF Theorem subst hasType X ∀ G e2 tD G |Ee e2 X t → ∀ G1D G a G1 CC @xD xt A XX nil → x 5 G1 → G1 |Ee subst e2 X tF induction IY crush Y try match goal with | ‘ context ‘if ci then else “ “ ⇒ destruct endY crush Y eauto TY match goal with “⇒ | ‘ H1 X x 5 D H2 X |Ev x X rewrite @subst lookup H1 H2 A endY crushF QedF E ‡e wr—p the l—st theorem into —n e—sierEtoE—pply form spe™i—lized to ™losed expressionsF Theorem subst hasType closed X ∀ e2 tD @xD xt A XX nil |Ee e2 X t → nil |Ee subst e2 X tF introsY eapply subst hasTypeY eautoF QedF End substF Hint Resolve subst hasType closedF e not—tion for su˜stitution will m—ke the oper—tion—l sem—nti™s e—sier to re—dF Notation 4‘ x £b eI “ eP4 Xa @subst x e1 e2 A @no associativityD at level VHAF „o de(ne — ™—llE˜yEv—lue sm—llEstep sem—nti™sD we rely on — st—nd—rd judgment ™h—r—™E terizing whi™h expressions —re v—luesF Inductive val X exp → Prop Xa | VConst X ∀ bD val @Const b A | VAbs X ∀ x eD val @Abs x e AF PUW Hint Constructors valF xow the step rel—tion is e—sy to de(neF Reserved Notation 4eI aab eP4 @no associativityD at level WHAF Inductive step X exp → exp → Prop Xa | Beta X ∀ x e1 e2D val e2 @Abs x e1 A e2 aab ‘x X ∀ e1 e2 e1'D e1 aab e1' → App e1 e2 aab App e1' e2 | Cong2 X ∀ e1 e2 e2'D → | e2 “ e1 App Cong1 val e1 → → e2 aab e2' App e1 e2 aab App e1 e2' where 4eI aab eP4 Xa @step Hint e1 e2 AF Constructors stepF „he progress theorem s—ys th—t —ny wellEtyped expression ™—n t—ke — stepF „o de—l with limit—tions of the induction t—™ti™D we put most of the proof in — lemm— whose st—tement uses the usu—l tri™k of introdu™ing extr— equ—lity hypothesesF Lemma progress' X ∀ G e tD G |Ee e X t → G a nil → val e ∨ ∃ e'D e aab e'F induction IY crush Y eautoY try match goal with “ ⇒ inversion H | ‘ H X |Ee X !b endY match goal with |‘H X “ ⇒ solve ‘ inversion H Y crush Y eauto “ endF QedF Theorem progress X ∀ e tD nil |Ee e X t → val e ∨ ∃ e'D e aab e'F introsY eapply progress'Y eautoF QedF e simil—r p—ttern works for the preserv—tion theoremD whi™h s—ys th—t —ny step of exe™uE tion preserves —n expression9s typeF Lemma preservation' X ∀ → G a nil → ∀ e'D e aab e' G e tD G |Ee e X t PVH → nil |Ee e' X tF induction IY inversion PY match goal with X | ‘ H X |Ee Abs endY eautoF QedF crush Y eautoY “ ⇒ inversion H Theorem preservation X ∀ e tD nil |Ee e X t → ∀ e'D e aab e' → nil |Ee e' X tF introsY eapply preservation'Y eautoF QedF End ConcreteF „his w—s — rel—tively simple ex—mpleD giving only — t—ste of the proof ˜urden —sso™i—ted with ™on™rete synt—xF ‡e were helped ˜y the f—™t th—tD with ™—llE˜yEv—lue sem—nti™sD we only need to re—son —˜out su˜stitution in ™losed expressionsF „here w—s —lso no need to —lph—Ev—ry —n expressionF 15.2 De Bruijn Indices he fruijn indi™es —re mu™h more popul—r th—n ™on™rete synt—xF „his te™hnique provides — canonical represent—tion of synt—xD where —ny two —lph—Eequiv—lent expressions h—ve synE t—™ti™—lly equ—l en™odingsD removing the need for expli™it re—soning —˜out —lph— ™onversionF †—ri—˜les —re represented —s n—tur—l num˜ersD where v—ri—˜le n denotes — referen™e to the n th ™losest en™losing ˜inderF fe™—use v—ri—˜le referen™es in e'e™t point to ˜indersD there is no need to l—˜el ˜indersD su™h —s fun™tion —˜str—™tionD with v—ri—˜lesF Module DeBruijnF Definition var Xa natF Definition var eq Xa eq nat decF Inductive exp X Set Xa | Const X bool → exp | Var X var → exp | App X exp → exp → exp | Abs X exp → expF Inductive type X Set Xa | Bool X type | Arrow X type → type → typeF Infix 4!b4 Xa Arrow @right associativityD at level THAF „he de(nition of typing pro™eeds mu™h the s—me —s in the l—st se™tionF ƒin™e v—ri—˜les —re num˜ersD ™ontexts ™—n ˜e simple lists of typesF „his m—kes it possi˜le to write the lookup judgment without mentioning inequ—lity of v—ri—˜lesF PVI Definition ctx Xa list typeF Reserved Notation 4q |Ev x X t4 @no Inductive lookup X ctx → | First X ∀ t GD t XX G |Ev O X t | Next X ∀ x t t' GD G |Ev x X t → t' XX G |Ev S x X t var → where 4q |Ev x X t4 Xa @lookup Hint associativityD at level WHD x at next level AF at level WHD e at next level AF type → Prop Xa G x t AF Constructors lookupF Reserved Notation 4q |Ee e X t4 @no Inductive hasType X ctx → exp → | TConst X ∀ G bD G |Ee Const b X Bool | TVar X ∀ G v tD G |Ev v X t → G |Ee Var v X t | TApp X ∀ G e1 e2 dom ranD G |Ee e1 X dom !b ran → G |Ee e2 X dom → G |Ee App e1 e2 X ran | TAbs X ∀ G e' dom ranD dom XX G |Ee e' X ran → G |Ee Abs e' X dom !b ran where 4q |Ee e X t4 Xa @hasType associativityD type → Prop Xa G e t AF sn the hasType ™—se for fun™tion —˜str—™tionD there is no need to ™hoose — v—ri—˜le n—meF ‡e simply push the fun™tion dom—in type onto the ™ontext GF Hint Constructors hasTypeF ‡e prove roughly the s—me we—kening theorems —s ˜eforeF Lemma weaken lookup X ∀ G |Ev v X t → G CC G' |Ev v X tF induction IY crushF QedF Hint Resolve G' v t GD weaken lookupF Theorem weaken G |Ee e X t hasType' X∀ G' G e tD PVP → G CC G' |Ee e X tF induction IY crush Y eautoF QedF Theorem weaken hasType X ∀ e tD nil |Ee e X t → ∀ G'D G' |Ee e X tF introsY change G' with @nil CC G' AY eapply weaken hasType'Y eautoF QedF Hint Resolve weaken hasTypeF Section substF Variable e1 X expF ƒu˜stitution is e—sier to de(ne th—n with ™on™rete synt—xF ‡hile our old de(nition needed to use two ™omp—risons for equ—lity of v—ri—˜lesD the de fruijn su˜stitution only needs one ™omp—risonF Fixpoint subst @x X varA @e2 X expA X exp Xa match e2 with | Const ⇒ e2 | Var x' ⇒ if var eq x' x then e1 else e2 | App e1 e2 ⇒ App @subst x e1 A @subst x e2 A | Abs e' ⇒ Abs @subst @S x A e' A endF Variable xt X typeF ‡e prove simil—r theorems —˜out inversion of v—ri—˜le lookupF Lemma subst eq X ∀ t G1D G1 CC xt XX nil |Ev length G1 X t → t a xtF induction G1 Y inversion IY crushF QedF Implicit Arguments subst eq ‘t G1 “F Lemma subst eq' X ∀ t G1 xD G1 CC xt XX nil |Ev x X t → x = length G1 → G1 |Ev x X tF induction G1 Y inversion IY crush Y match goal with | ‘ H X nil |Ev X “ ⇒ inversion H endF QedF Hint Resolve subst eq'F PVQ Lemma X ∀ v t G1D XX nil |Ev v X t subst neq CC xt → v = length → G1 |Ee Var G1 induction QedF v G1 Y Hint Resolve Hypothesis G1 X tF inversion IY crushF subst neqF Ht' X nil |Ee e1 X xtF „he next lemm— is in™luded solely to guide eautoD whi™h will not —pply ™omput—tion—l equiv—len™es —utom—ti™—llyF Lemma X ∀ dom G1 e' ranD dom XX G1 |Ee subst @length @dom XX G1 AA e' X ran → dom XX G1 |Ee subst @S @length G1 AA e' X ranF trivialF QedF hasType push Hint Resolve hasType pushF pin—llyD we —re re—dy for the m—in theorem —˜out su˜stitution —nd typingF Theorem subst hasType X ∀ G e2 tD G |Ee e2 X t → ∀ G1D G a G1 CC xt XX nil → G1 |Ee subst @length G1 A e2 X tF induction IY crush Y try match goal with | ‘ context ‘if ci then else “ “ ⇒ destruct endY crush Y eauto TY try match goal with “⇒ | ‘ H X |Ev X rewrite @subst eq H A endY crushF QedF Theorem subst hasType closed X ∀ e2 tD xt XX nil |Ee e2 X t → nil |Ee subst O e2 X tF introsY change O with @length @dnil typeAAY eapply QedF End substF Hint Resolve E subst hasTypeY eautoF subst hasType closedF ‡e de(ne the oper—tion—l sem—nti™s mu™h —s ˜eforeF Notation 4‘ x £b eI “ eP4 Xa @subst e1 x e2 A PVR @no associativityD at level VHAF Inductive val X exp → Prop Xa | VConst X ∀ bD val @Const b A | VAbs X ∀ eD val @Abs e AF Hint Constructors valF Reserved Notation 4eI aab eP4 @no associativityD at level WHAF Inductive step X exp → exp → Prop Xa | Beta X ∀ e1 e2D val e2 @Abs e1 A e2 aab ‘O | Cong1 X ∀ e1 e2 e1'D e1 aab e1' → App e1 e2 aab App e1' e2 | Cong2 X ∀ e1 e2 e2'D → App val e1 → → e2 aab e2' App e1 e2 aab App e1 e2' where 4eI aab eP4 Xa @step Hint e2 “ e1 e1 e2 AF Constructors stepF ƒin™e we h—ve —dded the right hintsD the progress —nd preserv—tion theorem st—tements —nd proofs —re ex—™tly the s—me —s in the ™on™rete en™oding ex—mpleF Lemma progress' X ∀ G e tD G |Ee e X t → G a nil → val e ∨ ∃ e'D e aab e'F induction IY crush Y eautoY try match goal with “ ⇒ inversion H | ‘ H X |Ee X !b endY repeat match goal with “ ⇒ solve ‘ inversion H Y crush Y eauto “ |‘H X endF QedF Theorem progress X ∀ e tD nil |Ee e X t → val e ∨ ∃ e'D e aab e'F introsY eapply progress'Y eautoF QedF Lemma preservation' X ∀ → G a nil → ∀ e'D e aab e' → nil |Ee e' X tF G e tD G |Ee e X t PVS induction IY inversion PY match goal with | ‘ H X |Ee Abs X endY eautoF QedF crush Y eautoY “ ⇒ inversion H Theorem preservation X ∀ e tD nil |Ee e X t → ∀ e'D e aab e' → nil |Ee e' X tF introsY eapply preservation'Y eautoF QedF End DeBruijnF 15.3 Locally Nameless Syntax „he most popul—r goq synt—x en™oding tod—y is the locally nameless styleD whi™h h—s ˜een —round for — while ˜ut w—s popul—rized re™ently ˜y eydemir et —lFD following — methodology summ—rized in their p—per 4ingineering porm—l wet—theoryF4 e spe™i—lized tutori—l ˜y th—t group1 expl—ins the —ppro—™hD ˜—sed on — li˜r—ryF sn this se™tionD we will ˜uild up —ll of the ne™ess—ry ingredients from s™r—t™hF „he oneEsenten™e summ—ry of lo™—lly n—meless en™oding is th—t we represent free v—ri—˜les —s ™on™rete synt—x doesD —nd we represent ˜ound v—ri—˜les with de fruijn indi™esF w—ny proofs involve re—soning —˜out terms tr—nspl—nted into di'erent free v—ri—˜le ™ontextsY ™onE ™rete en™oding of free v—ri—˜les me—ns th—tD to perform su™h — tr—nspl—ntingD we need no (xEup oper—tion to —djust de fruijn indi™esF et the s—me timeD use of de fruijn indi™es for lo™—l v—ri—˜les gives us ™—noni™—l represent—tions of expressionsD with respe™t to the usu—l ™onvention of —lph—Eequiv—len™eF „his m—kes m—ny oper—tionsD in™luding su˜stitution of open terms in open termsD e—sier to implementF „he 4ingineering porm—l wet—theory4 methodology involves — num˜er of su˜tle design de™isionsD whi™h we will des™ri˜e —s they —ppe—r in the l—test version of our running ex—mpleF Module LocallyNamelessF Definition Definition free var Xa stringF Xa natF bound var Inductive exp X Set Xa | Const X bool → exp | FreeVar X free var → exp | BoundVar X bound var → exp | App X exp → exp → exp | Abs X exp → expF 1 http://www.cis.upenn.edu/~plclub/oregon08/ PVT xote the di'erent ™onstru™tors for free vsF ˜ound v—ri—˜lesD —nd note th—t the l—™k of — v—ri—˜le —nnot—tion on Abs nodes is inherited from the de fruijn ™onventionF Inductive type X Set Xa | Bool X type | Arrow X type → type → Infix 4!b4 Xa Arrow typeF @right at associativityD level THAF es typing only depends on types of free v—ri—˜lesD our ™ontexts ˜orrow their form from the ™on™rete ˜inding ex—mpleF Definition ctx Xa list @free var × typeAF Reserved Notation 4q |Ev x X t4 @no Inductive lookup X ctx → | First X ∀ x t GD @xD t A XX G |Ev x X t | Next X ∀ x t x' t' GD x = x' → G |Ev x X t → @x'D t' A XX G |Ev x X t free var where 4q |Ev x X t4 Xa @lookup Hint → associativityD at level WHD x at next level AF type → Prop Xa G x t AF Constructors lookupF „he (rst unusu—l oper—tion we need is openingD where we repl—™e — p—rti™ul—r ˜ound v—ri—˜le with — p—rti™ul—r free v—ri—˜leF ‡henever we 4go under — ˜inderD4 in the typing judgment or elsewhereD we ™hoose — new free v—ri—˜le to repl—™e the old ˜ound v—ri—˜le of the ˜inderF ypening implements the repl—™ement of one ˜y the otherF st is like — spe™i—lized version of the su˜stitution fun™tion we used for pure de fruijn termsF Section openF Variable x X free varF Fixpoint open @n X bound varA @e X expA X exp Xa match e with | Const ⇒ e | FreeVar ⇒ e | BoundVar n' ⇒ if eq nat dec n' n then FreeVar x else if le lt dec n' n then e else BoundVar @pred n' A | App e1 e2 ⇒ App @open n e1 A @open n e2 A | Abs e1 ⇒ Abs @open @S n A e1 A endF PVU End openF ‡e will —lso need to re—son —˜out —n expression9s set of free v—ri—˜lesF „o keep things simpleD we represent sets —s lists th—t m—y ™ont—in dupli™—tesF xote how mu™h e—sier this oper—tion is to implement th—n over pure de fruijn termsD sin™e we do not need to m—int—in — sep—r—te numeri™ —rgument th—t keeps tr—™k of how deeply we h—ve des™ended into the input expressionF Fixpoint freeVars @e X expA X list free var Xa match e with | Const ⇒ nil | FreeVar x ⇒ x XX nil | BoundVar ⇒ nil | App e1 e2 ⇒ freeVars e1 CC freeVars e2 | Abs e1 ⇒ freeVars e1 endF st will ˜e useful to h—ve — wellEformedness judgment for our termsF „his notion is ™—lled en expression m—y ˜e de™l—red to ˜e ™losedD up to — p—rti™ul—r m—ximum de fruijn indexF local closureF Inductive lclosed X nat → exp → Prop Xa | CConst X ∀ n bD lclosed n @Const b A | CFreeVar X ∀ n vD lclosed n @FreeVar v A | CBoundVar X ∀ n vD v ` n → lclosed n @BoundVar v A | CApp X ∀ n e1 e2D lclosed n e1 → lclosed n e2 → lclosed | CAbs X ∀ n e1D lclosed @S n A e1 → lclosed n @Abs e1 AF Hint n @App e1 e2 A Constructors lclosedF xow we —re re—dy to de(ne the typing judgmentF Reserved Notation 4q |Ee e X t4 @no associativityD at level Inductive hasType X ctx → exp → type → Prop Xa | TConst X ∀ G bD G |Ee Const b X Bool | TFreeVar X ∀ G v tD G |Ev v X t → G |Ee FreeVar v X t | TApp X ∀ G e1 e2 dom ranD G |Ee e1 X dom !b ran → G |Ee e2 X dom → G |Ee App e1 e2 X ran | TAbs X ∀ G e' dom ran LD @∀ xD ¬ In x L → @xD dom A XX G |Ee open x O e' X ran A → G |Ee Abs e' X dom !b ran PVV WHD e at next level AF where 4q |Ee e X t4 Xa @hasType G e t AF gomp—red to the previous versionsD only the TAbs rule is surprisingF „he rule uses conite quantiifcationF „h—t isD the premise of the rule qu—nti(es over —ll x v—lues th—t —re not mem˜ers of — (nite set LF e proof m—y ™hoose —ny v—lue of L when —pplying TAbsF en —ltern—teD more intuitive version of the rule would (x L to ˜e freeVars e'F st turns out th—t the gre—ter )exi˜ility of the rule —˜ove simpli(es m—ny proofs signi(™—ntlyF „his typing judgment m—y ˜e proved equiv—lent to the more intuitive versionD though we will not ™—rry out the proof hereF ƒpe™i(—llyD wh—t our version of TAbs s—ys is th—tD to prove th—t Abs e' h—s — fun™tion typeD we must prove th—t —ny opening of e' with — v—ri—˜le not in L h—s the proper typeF por e—™h x ™hoi™eD we extend the ™ontext G in the usu—l w—yF Hint Constructors hasTypeF ‡e prove — st—nd—rd we—kening theorem for typingD —dopting — more gener—l form th—n in the previous se™tionsF Lemma lookup push X ∀ G G' x t x' t'D @∀ x tD G |Ev x X t → G' |Ev x X t A → @xD t A XX G |Ev x' X t' → @xD t A XX G' |Ev x' X t'F inversion PY crushF QedF Hint Resolve lookup pushF Theorem weaken hasType X ∀ G e tD G |Ee e X t → ∀ G'D @∀ x tD G |Ev x X t → G' |Ev → G' |Ee e X tF induction IY crush Y eautoF QedF Hint Resolve x X tA weaken hasTypeF ‡e de(ne — simple extension of crush to —pply in m—ny of the lemm—s th—t followF Ltac ln Xa crush Y repeat @match goal with | ‘ context ‘if ci then else “ “ ⇒ destruct E | ‘ X context ‘if ci then else “ “ ⇒ destruct endY crush AY eautoF „wo ˜—si™ properties of lo™—l ™losure will ˜e useful l—terF Lemma lclosed S X∀ x e nD lclosed n @open x n e A → lclosed @S n A eF induction e Y inversion IY lnF PVW E QedF Hint Resolve Lemma lclosed SF lclosed weaken lclosed n X∀ n eD e → ∀ n'D n' ≥ n → lclosed n' eF induction IY crushF QedF Hint Resolve lclosed weakenF Hint Extern I @ ≥ A ⇒ omegaF „o prove some further propertiesD we need the —˜ility to ™hoose — v—ri—˜le th—t is disjoint from — p—rti™ul—r (nite setF ‡e implement — spe™i(™ ™hoi™e fun™tion freshY its det—ils do not m—tterD —s —ll we need is the (n—l theorem —˜out itD freshOkF gon™retelyD to ™hoose — v—ri—˜le disjoint from set LD we sum the lengths of the v—ri—˜le n—mes in L —nd ™hoose — new v—ri—˜le n—me th—t is one longer th—n th—t sumF „his v—ri—˜le ™—n ˜e the string 4x 4D followed ˜y — num˜er of primes equ—l to the sumF Open Scope string scopeF Fixpoint primes @n X natA X string Xa match n with | O ⇒ 4x4 | S n' ⇒ primes n' CC 494 endF Fixpoint sumLengths @L X list free varA X nat Xa match L with | nil ⇒ O | x XX L' ⇒ String.length x C sumLengths L' endF Definition fresh @L X list free varA Xa primes @sumLengths LAF e few lemm—s su0™e to est—˜lish the ™orre™tness theorem Theorem freshOk' X ∀ x → ¬ In x LF induction LY crushF QedF Lemma LD String.length x X ∀ s2 s1D @s1 CC s2 A a induction s1 Y crushF QedF Rewrite length app Lemma sumLengths L length app String.length Hint b freshOk length primes X X ∀ nD String.length s1 C String.length s2F cpdtF String.length @primes n A a PWH S nF for freshF induction n Y QedF Hint crushF Rewrite length primes X cpdtF Theorem freshOk X ∀ LD ¬ In @fresh LA LF introsY apply freshOk'Y unfold freshY QedF Hint Resolve crushF freshOkF xow we ™—n prove th—t wellEtypedness implies lo™—l ™losureF fresh will ˜e used for us —utom—ti™—lly ˜y eauto in the Abs ™—seD driven ˜y the presen™e of freshOk —s — hintF Lemma hasType lclosed X ∀ G |Ee e X t → lclosed O eF induction IY eautoF QedF G e tD en import—nt ™onsequen™e of lo™—l ™losure is th—t ™ert—in openings —re idempotentF Lemma lclosed open X ∀ n eD lclosed → ∀ xD open x n e a eF induction IY lnF QedF Hint Resolve Open Scope ne lclosed open hasType lclosedF list scopeF ‡e —re now —lmost re—dy to get down to the det—ils of su˜stitutionF pirstD we prove six lemm—s rel—ted to tre—ting lists —s setsF Lemma In cons1 X ∀ T @x x a x' → In x @x' XX ls AF crushF QedF x' X T A lsD Lemma x' X T A lsD In cons2 X∀ T @x In x ls → In x crushF @x' XX ls AF QedF Lemma In app1 X∀ T @x X T A ls2 ls1D In x ls1 → In x @ls1 CC ls2 AF induction ls1 Y crushF QedF Lemma In app2 X∀ T @x X T A ls2 ls1D PWI In x ls2 → In x @ls1 CC ls2 AF induction ls1 Y crushF QedF Lemma freshOk app1 X ∀ L1 L2D ¬ In @fresh @L1 CC L2 AA L1F introsY generalize @freshOk @L1 CC L2 AAY crushF QedF Lemma freshOk app2 X ∀ L1 L2D ¬ In @fresh @L1 CC L2 AA L2F introsY generalize @freshOk @L1 CC L2 AAY crushF QedF Hint Resolve In cons1 In cons2 In app1 In app2F xow we ™—n de(ne our simplest su˜stitution fun™tion yetD th—nks to the f—™t th—t we only su˜situte for free v—ri—˜lesD whi™h —re distinguished synt—™ti™—lly from ˜ound v—ri—˜lesF Section substF Hint Resolve freshOk app1 freshOk app2F Variable x X free varF Variable e1 X expF Fixpoint subst @e2 X expA X exp Xa match e2 with | Const ⇒ e2 | FreeVar x' ⇒ if string dec x' x then e1 else e2 | BoundVar ⇒ e2 | App e1 e2 ⇒ App @subst e1 A @subst e2 A | Abs e' ⇒ Abs @subst e' A endF Variable xt X typeF st ™omes in h—ndy to de(ne disjointness of — v—ri—˜le —nd — ™ontext di'erently th—n in previous ex—mplesF ‡e use the st—nd—rd list fun™tion mapD —s well —s the fun™tion fst for proje™ting the (rst element of — p—irF ‡e write dfst r—ther th—n just fst to —sk th—t fst9s impli™it —rguments ˜e inst—nti—ted with inferred v—luesF Definition disj x @G X ctxA Xa In x @map @dfst A G A → FalseF Infix 454 Xa disj @no associativityD at level WHAF Ltac disj Xa crush Y match goal with | ‘ X XX a cqH CC “ ⇒ destruct G0 endY crush Y eautoF ƒome ˜—si™ properties of v—ri—˜le lookup will ˜e needed on the ro—d to our usu—l theorem ™onne™ting su˜stitution —nd typingF PWP Lemma lookup disj' X∀ t G1D |Ev x X t → ∀ GD x 5 G → G1 a G CC @xD xt A XX nil → t a xtF unfold disj Y induction IY disjF QedF G1 Lemma lookup disj X ∀ t GD x 5G → G CC @xD xt A XX nil |Ev x X t → t a xtF introsY eapply lookup disj'Y eautoF QedF Lemma lookup ne' X ∀ G1 v tD G1 |Ev v X t → ∀ GD G1 a G CC @xD xt A XX nil →v =x → G |Ev v X tF induction IY disjF QedF Lemma lookup ne X ∀ G v tD G CC @xD xt A XX nil |Ev v X t →v =x → G |Ev v X tF introsY eapply lookup ne'Y eautoF QedF Hint Extern I @ |Ee X A ⇒ match goal with “ ⇒ rewrite @lookup disj H1 H2 A | ‘ H1 X D H2 X endF Hint Resolve lookup neF A ⇒ f equalF Hint Extern I @deq exp ‡e need to know th—t su˜stitution —nd opening ™ommute under —ppropri—te ™ir™umE st—n™esF Lemma open subst X ∀ x0 e' nD lclosed n e1 → x = x0 → open x0 induction QedF @subst e' Y lnF n e' A a subst @open x0 n e' AF ‡e st—te — ™oroll—ry of the l—st result whi™h will work more smoothly with eautoF PWQ Lemma hasType open subst X ∀ G x0 e tD G |Ee subst @open x0 H e A X t → x = x0 → lclosed H e1 → G |Ee open x0 H @subst e A X tF introsY rewrite open substY eautoF QedF Hint Resolve hasType open substF enother lemm— est—˜lishes the v—lidity of we—kening v—ri—˜le lookup judgments with fresh v—ri—˜lesF Lemma disj push X ∀ x0 @t X typeA x 5G → x = x0 → x 5 @x0D t A XX GF unfold disj Y crushF QedF Hint Resolve GD disj pushF Lemma lookup cons X ∀ x0 dom G x1 tD G |Ev x1 X t A GA → ¬ In x0 @map @dfst → @x0D dom A XX G |Ev x1 X tF induction IY crush Y match goal with | ‘ H X |Ev X “ ⇒ inversion endY crushF QedF Hint Resolve lookup Hint Unfold disjF H consF pin—llyD it is useful to st—te — version of the is useful in our m—in su˜stitution proofF TAbs rule spe™i—lized to the ™hoi™e of Lemma TAbs specialized X ∀ G e' dom ran L x1D @∀ xD ¬ In x @x1 XX L CC map @dfst A G A → @xD → G |Ee Abs e' X dom !b ranF eautoF QedF dom A XX G |Ee open x O e' L X th—t ran A xow we ™—n prove the m—in indu™tive lemm— in — m—nner simil—r to wh—t worked for ™on™rete ˜indingF Lemma hasType subst' |Ee e X t → ∀ GD G1 a X∀ G1 e tD G1 G CC @xD xt A XX nil PWR →x 5G → G |Ee e1 X xt → G |Ee subst e X tF induction IY ln Y match goal with | ‘ L X list free varD X cx 5 apply TAbs specialized with endF QedF “⇒ L xY eauto PH „he m—in theorem —˜out su˜stitution of ™losed expressions follows e—silyF Theorem hasType subst X ∀ @xD xt A XX nil |Ee e X t → nil |Ee e1 X xt → nil |Ee subst e X tF introsY eapply hasType QedF End substF Hint Resolve e tD subst'Y eautoF hasType substF ‡e ™—n de(ne the oper—tion—l sem—nti™s in —lmost the s—me w—y —s in previous ex—mplesF Notation 4‘ x £b eI “ eP4 Xa @subst x e1 e2 A @no associativityD at Inductive val X exp → Prop Xa | VConst X ∀ bD val @Const b A | VAbs X ∀ eD val @Abs e AF Hint Constructors valF Reserved Notation 4eI aab eP4 @no associativityD Inductive step X exp → exp → Prop Xa | Beta X ∀ e1 e2 xD val e2 → ¬ In x @freeVars e1 A → App @Abs e1 A e2 aab ‘x | Cong1 X ∀ e1 e2 e1'D e1 aab e1' → App e1 e2 aab App e1' | Cong2 X ∀ e1 e2 e2'D val e1 → → e2 aab e2 “ x O e1 A e2 e2' App e1 e2 aab App e1 e2' where 4eI aab eP4 Xa @step Hint @open e1 e2 AF Constructors stepF PWS at level WHAF level THAF „he only interesting ™h—nge is th—t the Beta rule requires identifying — fresh v—ri—˜le x to use in opening the —˜str—™tion ˜odyF ‡e ™ould h—ve —voided this ˜y implementing — more gener—l open th—t —llows su˜stituting expressions for v—ri—˜lesD not just v—ri—˜les for v—ri—˜lesD ˜ut it simpli(es the proofs to h—ve just one gener—l su˜stitution fun™tionF xow we —re re—dy to prove progress —nd preserv—tionF „he s—me proof s™ript from the l—st ex—mples su0™es to prove progressD though signi(™—ntly di'erent lemm—s —re —pplied for us ˜y eautoF Lemma progress' X ∀ G e tD G |Ee e X t → G a nil → val e ∨ ∃ e'D e aab e'F induction IY crush Y eautoY try match goal with “ ⇒ inversion H | ‘ H X |Ee X !b endY repeat match goal with “ ⇒ solve ‘ inversion H Y crush Y eauto “ |‘H X endF QedF Theorem progress X ∀ e tD nil |Ee e X t → val e ∨ ∃ e'D e aab e'F introsY eapply progress'Y eautoF QedF „o est—˜lish preserv—tionD it is useful to form—lize — prin™iple of sound —lph—Ev—ri—tionF sn p—rti™ul—rD when we open —n expression with — p—rti™ul—r v—ri—˜le —nd then immedi—tely su˜stitute for the s—me v—ri—˜leD we ™—n repl—™e th—t v—ri—˜le with —ny other th—t is not free in the ˜ody of the opened expressionF Lemma alpha open X ∀ x1 x2 e1 e2 nD ¬ In x1 @freeVars e2 A → ¬ In x2 @freeVars e2 A → ‘x1 e1 “@open x1 n e2 A a ‘x2 e1 “@open x2 n e2 AF induction e2 Y lnF QedF Hint Resolve freshOk app1 freshOk app2F eg—in it is useful to st—te — dire™t ™oroll—ry whi™h is e—sier to —pply in proof se—r™hF Lemma hasType alpha open X ∀ G L e0 e2 x tD ¬ In x @freeVars e0 A → G |Ee ‘fresh @L CC freeVars e0 A e2 “@open @fresh @L CC freeVars e0 AA H e0 A X t → G |Ee ‘x e2 “@open x H e0 A X tF introsY rewrite @alpha open x @fresh @L CC freeVars e0 AAAY autoF QedF Hint Resolve hasType alpha openF PWT xow the previous se™tions9 preserv—tion proof s™ripts (nish the jo˜F Lemma preservation' X ∀ G e tD G |Ee e X t → G a nil → ∀ e'D e aab e' → nil |Ee e' X tF induction IY inversion PY crush Y eautoY match goal with “ ⇒ inversion | ‘ H X |Ee Abs X endY eautoF QedF Theorem preservation X ∀ e tD nil |Ee e X t → ∀ e'D e aab e' → nil |Ee e' X tF introsY eapply preservation'Y eautoF QedF End LocallyNamelessF PWU H Chapter 16 Dependent De Bruijn Indices „he previous ™h—pter introdu™ed the most ™ommon form of de fruijn indi™esD without esE senti—l use of dependent typesF sn e—rlier ™h—ptersD we used dependent de fruijn indi™es to illustr—te tri™ks for working with dependent typesF „his ™h—pter presents one ™omplete ™—se study with dependent de fruijn indi™esD fo™using on produ™ing the most m—int—in—˜le proof possi˜le of — ™l—ssi™ theorem —˜out l—m˜d— ™—l™ulusF „he proof th—t follows does not provide — ™omplete guide to —ll kinds of form—liz—tion with de fruijn indi™esF ‚—therD it is intended —s —n ex—mple of some simple design p—tterns th—t ™—n m—ke proving st—nd—rd theorems mu™h e—sierF ‡e will prove ™ommut—tivity of ™—ptureE—voiding su˜stitution for ˜—si™ untyped l—m˜d— ™—l™ulusX x1 = x2 ⇒ [e1 /x1 ][e2 /x2 ]e = [e2 /x2 ][[e2 /x2 ]e1 /x1 ]e 16.1 Dening Syntax and Its Associated Operations yur de(nition of expression synt—x should ˜e unsurprisingF en expression of type exp n m—y refer to n di'erent free v—ri—˜lesF Inductive exp X nat → Type Xa | Var X ∀ nD n n → exp n | App X ∀ nD exp n → exp n → exp | Abs X ∀ nD exp @S n A → exp nF n „he ™l—ssi™ implement—tion of su˜stitution in de fruijn terms requires —n —uxili—ry operE —tionD liftingD whi™h in™rements the indi™es of —ll free v—ri—˜les in —n expressionF ‡e need to lift whenever we go under — ˜inderF st is useful to write —n —uxili—ry fun™tion liftVar th—t lifts — v—ri—˜leY th—t isD liftVar x y will return y C I if y ≥ x D —nd it will return y otherwiseF „his simple des™ription uses num˜ers r—ther th—n our dependent n f—milyD so the —™tu—l spe™i(™—tion is more involvedF PWV gom˜ining — numer of dependent types tri™ksD we wind up with this ™on™rete re—liz—E tionF Fixpoint liftVar n @x X n n A X n @pred n A → n n Xa match x with | First ⇒ fun y ⇒ Next y | Next x' ⇒ fun y ⇒ match y in n n' return n n' → @n @pred n' A → n → n @S n' A with | First ⇒ fun x' ⇒ First | Next y' ⇒ fun fx' ⇒ Next @fx' y' A end x' @liftVar x' A endF n' A xow it is e—sy to implement the m—in lifting oper—tionF Fixpoint lift n @e X exp n A X n @S n A → exp @S n A Xa match e with | Var f ' ⇒ fun f ⇒ Var @liftVar f f ' A | App e1 e2 ⇒ fun f ⇒ App @lift e1 f A @lift e2 f A | Abs e1 ⇒ fun f ⇒ Abs @lift e1 @Next f AA endF „o de(ne su˜stitution itselfD we will need to —pply some expli™it type ™—stsD ˜—sed on equ—lities ˜etween typesF e single equ—lity will su0™e for —ll of our ™—stsF sts st—tement is somewh—t str—ngeX it qu—nti(es over — v—ri—˜le f of type n nD ˜ut then never mentions f F ‚—therD qu—ntifying over f is useful ˜e™—use n is — dependent type th—t is inh—˜ited or not depending on its indexF „he ˜ody of the theoremD S @pred nA a nD is true only for n > 0D ˜ut we ™—n prove it ˜y ™ontr—di™tion when n a HD ˜e™—use we h—ve —round — v—lue f of the uninh—˜ited type n HF Theorem nzf X ∀ n @f X n n AD destruct IY trivialF QedF S @pred n A a nF xow we de(ne — not—tion to stre—mline our ™—st expressionsF „he ™ode ‘f return nD r for e“ denotes — ™—st of expression e whose type ™—n ˜e o˜t—ined ˜y su˜stituting some num˜er n1 for n in rF f should ˜e — proof th—t n1 a n2D for —ny n2F sn th—t ™—seD the type of the ™—st expression is r with n2 su˜stituted for nF Notation 4‘ f 9return9 n D r 9for9 e “4 Xa match f in a n return r with | re equal ⇒ e endF „his not—tion is useful in de(ning — v—ri—˜le su˜stitution oper—tionF „he ide— is th—t substVar x y returns None if x a y Y otherwiseD it returns — squished version of y with — sm—ller n indexD re)e™ting th—t v—ri—˜le x h—s ˜een su˜stituted —w—yF ‡ithout dependent PWW typesD this would ˜e — simple de(nitionF ‡ith dependen™yD it is re—son—˜ly intri™—teD —nd our m—in t—sk in —utom—ting proofs —˜out it will ˜e hiding th—t intri™—™yF Fixpoint substVar n @x X n n A X n n → option @n @pred n AA Xa match x with | First ⇒ fun y ⇒ match y in n n' return option @n @pred n' AA with | First ⇒ None | Next f ' ⇒ Some f ' end | Next x' ⇒ fun y ⇒ match y in n n' return n @pred n' A → @n @pred n' A → option @n @pred @pred → option @n @pred n' AA with | First ⇒ fun x' ⇒ Some ‘nzf x' return nD n n for First“ | Next y' ⇒ fun fx' ⇒ match fx' y' with | None ⇒ None | Some f ⇒ Some ‘nzf y' return nD n n for Next f “ end end x' @substVar x' A endF n' AAAA st is now e—sy to de(ne our (n—l su˜stitution fun™tionF „he —˜str—™tion ™—se involves two ™—stsD where one uses the sym eq fun™tion to ™onvert — proof of n1 a n2 into — proof of n2 a n1F Fixpoint subst n @e X exp n A X n n → exp @pred n A → exp @pred n A Xa match e with | Var f ' ⇒ fun f v ⇒ match substVar f f ' with | None ⇒ v | Some f  ⇒ Var f  end | App e1 e2 ⇒ fun f v ⇒ App @subst e1 f v A @subst e2 f v A | Abs e1 ⇒ fun f v ⇒ Abs ‘sym eq @nzf f A return nD exp n for subst e1 @Next f A ‘nzf f return nD exp n for lift v First““ endF yur (n—l ™ommut—tivity theorem is —˜out substD ˜ut our proofs will rely on — few more —uxili—ry de(nitionsF pirstD we will w—nt —n oper—tion more th—t in™rements the index of — n while preserving its interpret—tion —s — num˜erF Fixpoint more n @f X n n A X n @S n A Xa match f with | First ⇒ First | Next f ' ⇒ Next @more f ' A QHH endF ƒe™ondD we will w—nt — kind of inverse to liftVarF Fixpoint unliftVar n @f X n n A X n @pred n A → n @pred n A Xa match f with | First ⇒ fun g ⇒ ‘nzf g return nD n n for First“ | Next f ' ⇒ fun g ⇒ match g in n n' return n n' → @n @pred n' A → n @pred n' AA → n n' with | First ⇒ fun f ' ⇒ f ' | Next g' ⇒ fun unlift ⇒ Next @unlift g' A end f ' @unliftVar f ' A endF 16.2 Custom Tactics vess th—n — p—ge of t—™ti™ ™ode will ˜e su0™ient to —utom—te our proof of ™ommu—tivityF ‡e st—rt ˜y de(ning — workhorse simpli(™—tion t—™ti™ simpD whi™h extends crush in — few w—ysF Ltac simp Xa repeat progress @crush Y try discriminateY ‡e enter —n inner loop of —pplying hints spe™i(™ to our dom—inF repeat match goal with yur (rst two hints (nd pl—™es where equ—lity proofs —re p—tternEm—t™hed onF „he (rst hint m—t™hes p—tternEm—t™hes in the ™on™lusionD while the se™ond hint m—t™hes p—tternE m—t™hes in hypothesesF sn e—™h ™—seD we —pply the li˜r—ry theorem UIP reD whi™h s—ys th—t —ny proof of — f—™t like e a e is itself equ—l to re equalF ‚ewriting with this f—™t en—˜les redu™tion of the p—tternEm—t™h th—t we foundF | ‘ context ‘match cpf with re equal ⇒ end“ “ ⇒ rewrite @UIP re pf A | ‘ X context ‘match cpf with re equal ⇒ end“ “⇒ rewrite @UIP re pf A in B „he next hint (nds —n opportunity to invert — |‘ H X Next a Next n equ—lity hypothesisF “ ⇒ injection HY clear H sf we h—ve two equ—lity hypotheses th—t sh—re — lefth—nd sideD we ™—n use one to rewrite the otherD ˜ringing the hypotheses9 righth—nd sides together in — single equ—tionF QHI |‘ H X ci a D H' “ ⇒ rewrite X ci a H in H' pin—llyD we would like —utom—ti™ use of qu—nti(ed equ—lity hypotheses to perform rewritE ingF ‡e p—tternEm—t™h — hypothesis H —sserting proposition P F ‡e try to use H to perform rewriting everywhere in our go—lF „he rewrite su™™eeds if it gener—tes no —ddition—l hypotheE sesD —ndD to prevent in(nite loops in proof se—r™hD we ™le—r H if it ˜egins with univers—l qu—nti(™—tionF |‘ H X c€ “ ⇒ rewrite H in BY ‘match endAF with | ∀ x D ⇒ clear | ⇒ idtac end“ P H sn implementing —nother level of —utom—tionD it will ˜e useful to m—rk whi™h free v—riE —˜les we gener—ted with t—™ti™sD —s opposed to whi™h were present in the origin—l theorem st—tementF ‡e use — dummy m—rker predi™—te Generated to re™ord th—t inform—tionF e t—™ti™ not generated f—ils if —nd only if its —rgument is — gener—ted v—ri—˜leD —nd — t—™ti™ generate re™ords th—t its —rgument is gener—tedF Definition Generated n @ X n n A Xa TrueF Ltac not generated x Xa match goal with | ‘ X Generated x “ ⇒ fail I | ⇒ idtac endF Ltac generate x Xa assert @Generated x AY ‘ constructor | “F e t—™ti™ destructG performs ™—se —n—lysis on n v—luesF „he ˜uiltEin ™—se —n—lysis t—™ti™s —re not sm—rt enough to h—ndle —ll situ—tionsD —nd we —lso w—nt to m—rk new v—ri—˜les —s gener—tedD to —void in(nite loops of ™—se —n—lysisF yur destructG t—™ti™ will only pro™eed if its —rgument is not gener—tedF Theorem n inv X ∀ n @f X n @S n AAD f a First ∨ ∃ f 'D f a Next f 'F introsY dep destruct f Y eautoF QedF Ltac destructG E Xa not generated E Y let x Xa fresh 4x4 in @destruct @n inv E A as ‘ | ‘x ““ || destruct E as ‘ | c x “AY ‘ | generate x “F yur most powerful workhorse t—™ti™ will ˜e desterD whi™h in™orpor—tes —ll of simp 9s simE pli(™—tions —nd —dds heuristi™s for —utom—ti™ ™—se —n—lysis —nd —utom—ti™ qu—nti(er inst—nE ti—tionF QHP Ltac dester Xa simp Y repeat @match goal with „he (rst hint expresses our m—in insight into qu—nti(er inst—nti—tionF ‡e identify — hypothesis IH th—t ˜egins with qu—nti(™—tion over n v—luesF ‡e —lso identify — free n v—ri—˜le x —nd —n —r˜itr—ry equ—lity hypothesis HF qiven theseD we try inst—nti—ting IH with x F ‡e know we ™hose ™orre™tly if the inst—nti—ted proposition in™ludes —n opportunity to rewrite using HF |‘ x X n D H X a D IH X ∀ f X n D generalize @IH x AY clear IH Y intro IH Y “⇒ rewrite H in IH „his ˜—si™ ide— su0™es for —ll of our expli™it qu—nti(er inst—nti—tionF ‡e —dd one more v—ri—nt th—t h—ndles ™—ses where —n opportunity for rewriting is only exposed if two di'erent qu—nti(ers —re inst—nti—ted —t on™eF |‘ x X n D y X n D H X a D X ∀ @f X n A @g X n AD IH generalize @IH x y AY ‡e w—nt to ™—seE—n—lyze on —ny sion or —n —rgument to moreF |‘ context ‘match destructG E |‘ X clear intro IH Y rewrite H in IH n expression th—t is the dis™riminee of — match expresE ci with context ‘match IH Y “⇒ First ci with ⇒ ⇒ First | Next | Next ⇒ ⇒ end“ “ ⇒ end“ “⇒ destructG E |‘ context ‘more ci“ “ ⇒ destructG E ‚e™—ll th—t simp will simplify equ—lity proof terms of f—™ts like e a eF „he proofs in question will either ˜e of n a S @pred nA or S @pred nA a nD for some nF „hese equ—tions do not h—ve synt—™ti™—lly equ—l sidesF ‡e ™—n get to the point where they do h—ve equ—l sides ˜y performing ™—se —n—lysis on nF ‡henever we do soD the n a H ™—se will ˜e ™ontr—di™toryD —llowing us to dis™h—rge it ˜y (nding — free v—ri—˜le of type n H —nd performing inversion on itF sn the n a S n' ™—seD the sides of these equ—lities will simplify to equ—l v—luesD —s neededF „he next two hints identify n v—lues th—t —re good ™—ndid—tes for su™h ™—se —n—lysisF |‘ x X n cn “⇒ match goal with | ‘ context ‘nzf x “ “ ⇒ destruct nY ‘ inversion x QHQ |“ end | ‘ x X n @pred cnAD y X n cn match goal with | ‘ context ‘nzf x “ “ ⇒ destruct nY ‘ inversion end “⇒ y |“ pin—llyD we (nd match dis™riminees of option typeD enfor™ing th—t we do not destru™t —ny dis™riminees th—t —re themselves match expressionsF gru™i—llyD we do these ™—se —n—lyses with case eq inste—d of destructF „he former —dds equ—lity hypotheses to re™ord the rel—tionships ˜etween old v—ri—˜les —nd their new dedu™ed formsF „hese equ—lities will ˜e used ˜y our qu—nti(er inst—nti—tion heuristi™F |‘ context ‘match ci with None ⇒ match E with | match with None ⇒ | Some | ⇒ case eq E Y firstorder end | Some ⇒ ⇒ end“ “ ⇒ end ⇒ fail I i—™h iter—tion of the loop ends ˜y ™—lling simp —g—inD —ndD —fter no more progress ™—n ˜e m—deD we (nish ˜y ™—lling eautoF endY simp AY eautoF 16.3 Theorems ‡e —re now re—dy to prove our m—in theoremD ˜y w—y of — progression of lemm—sF „he (rst p—ir of lemm—s ™h—r—™terizes the inter—™tion of su˜stitution —nd lifting —t the v—ri—˜le levelF Lemma substVar unliftVar X ∀ n @f0 X n n A f gD match substVar f0 fD substVar @liftVar f0 g A f with | Some f1D Some f2 ⇒ ∃ f 'D substVar g f1 a Some f ' ∧ substVar @unliftVar f0 g A f2 a Some f ' | Some f1D None ⇒ substVar g f1 a None | NoneD Some f2 ⇒ substVar @unliftVar f0 g A f2 a None | NoneD None ⇒ False endF induction f0 Y desterF QedF Lemma substVar liftVar X∀ n @f0 X n n A fD QHR @liftVar f0 f A a induction f0 Y desterF QedF substVar f0 Some fF xextD we de(ne — notion of gre—terEth—nEorEequ—l for theorem for itD —nd —dd th—t theorem —s — hintF Inductive n ge X ∀ n1D n n1 → ∀ n2D n | GeO X ∀ n1 @f1 X n n1 A n2D n ge f1 @First X n @S n2 AA | GeS X ∀ n1 @f1 X n n1 A n2 @f2 X n n2 AD n2 n v—luesD prove —n inversion → Prop Xa n ge f1 f2 → n ge @Next f1 A @Next f2 AF Hint Constructors n geF Lemma n ge inv' n ge f1 X∀ n1 n2 → match f1D f2 with | Next f1'D Next | D ⇒ True endF destruct IY desterF QedF Lemma @f1 X n n1 A @f2 X n n2 AD f2 n ge inv X∀ n1 n2 f2' @f1 X n ge @Next f1 A @Next f2 A → n ge f1 f2F introsY generalize @n QedF Hint Resolve ⇒ n ge f1' f2' n n1 A @f2 X n n2 AD ge inv' @f1 Xa Next f1 A @f2 Xa Next f2 AAY desterF n ge invF n ™onstru™tor Next is simil—rly usefulF X n n AD e ™ongruen™e lemm— for the Lemma Next cong X ∀ n @f1 f1 a f2 → Next f1 a Next f2F desterF QedF Hint Resolve f2 Next congF ‡e prove — ™ru™i—l lemm— —˜out Lemma liftVar more n ge g X∀ n @f X liftVar in terms of n geF n n A @f0 X n @S n AA gD f0 → match liftVar f0 f in n n' return n n' → @n @pred n' A → | First n0 ⇒ fun ⇒ First n n' A → n @S n' A with QHS | Next n0 y' ⇒ fun fx' ⇒ Next @fx' y' A end g @liftVar g A a liftVar @more f0 A @liftVar g f AF induction f Y inversion IY desterF QedF Hint Resolve liftVar moreF ‡e suggest — p—rti™ul—r w—y of ™h—nging the form of — go—lD so th—t other hints —re —˜le to m—t™hF Hint Extern I @ a lift @Next @more cfAAA ⇒ change @Next @more f AA with @more @Next f AAF ‡e suggest —pplying the f equal t—™ti™ to simplify equ—lities over expressionsF por inst—n™eD this would redu™e — go—l App f1 x1 a App f2 x2 to two go—ls f1 a f2 —nd x1 a x2F Hint Extern I @eq @A Xa exp A A ⇒ f equalF yur ™onsider—tion of lifting in isol—tion (nishes with —nother hint lemm—F „he —uxili—ry lemm— with — strengthened indu™tion hypothesis is where we put n ge to useD —nd we do not need to mention th—t predi™—te —g—in —ftew—rdF Lemma double lift' n ge g X∀ n @e X exp n A f gD f → lift @lift e f A @Next g A a induction e Y desterF QedF lift @lift e gA Lemma double lift X ∀ n @e X exp n A gD lift @lift e FirstA @Next g A a lift @lift e g A introsY apply double lift'Y desterF QedF Hint Resolve @more f AF FirstF double liftF xow we ™h—r—™terize the inter—™tion of su˜stitution —nd lifting on v—ri—˜lesF ‡e st—rt with — more gener—l form substVar lift' of the (n—l lemm— substVar liftD with the l—tter proved —s — dire™t ™oroll—ry of the formerF @f0 X n n A f gD substVar ‘nzf f0 return nD n @S n A for liftVar @more g A ‘sym eq @nzf f0 A return nD n n for f0 ““ @liftVar @liftVar @Next f0 A ‘nzf f0 return nD n n for g “A f A a match substVar f0 f with | Some f  ⇒ Some ‘nzf f0 return nD n n for liftVar g | None ⇒ None endF induction f0 Y desterF QedF Lemma substVar lift' X∀ n QHT f “ Lemma substVar lift substVar @liftVar X ∀ n @f0 f g X n @S n AAD @more g A f0 A @liftVar @liftVar @Next a match substVar f0 f with | Some f  ⇒ Some @liftVar | None ⇒ None endF introsY generalize @substVar QedF f0 A g A f A g f A lift' f0 f g AY desterF ‡e follow — simil—r de™omposition for the expressionElevel theorem —˜out su˜stitution —nd liftingF Lemma lift subst' X ∀ n @e1 X exp n A f g e2D lift @subst e1 f e2 A g a ‘sym eq @nzf f A return nD exp n for subst @liftVar @Next f A ‘nzf f return nD n n for g “AA f return nD n @S n A for liftVar @more g A ‘sym eq @nzf f A return nD n n for f ““ ‘nzf f return nD exp n for lift e2 g ““F induction e1 Y generalize substVar liftY desterF QedF @lift ‘nzf Lemma e1 lift subst X∀ ng @e2 X exp @S n AA e3D subst @lift e2 FirstA @Next g A @lift e3 FirstA a lift @n Xa n A @subst introsY generalize @lift subst' e2 g First e3 AY desterF QedF Hint Resolve e2 g e3 A FirstF lift substF yur l—st —uxili—ry lemm— ™h—r—™terizes — situ—tion where su˜stitution ™—n undo the e'e™ts of liftingF X ∀ n @e1 X exp n A e2 fD subst @lift e1 f A f e2 a e1F induction e1 Y generalize substVar liftVarY QedF Lemma undo lift' desterF Lemma undo lift X ∀ n e2 e3 @f0 X n @S @S n AAA gD e3 a subst @lift e3 @unliftVar f0 g AA @unliftVar f0 g A @subst @n Xa S n A e2 g e3 AF generalize undo lift'Y desterF QedF Hint Resolve undo liftF pin—llyD we —rrive —t the su˜stitution ™ommut—tivity theoremF Lemma subst comm' subst @subst e1 f X ∀ n @e1 X e2 A g e3 exp n A f g e2 e3D QHU a subst @subst e1 @liftVar f g A ‘nzf g return nD exp n for lift e3 ‘sym eq @nzf g A return nD n n for unliftVar f g ““A @unliftVar f g A @subst e2 g e3 AF induction e1 Y generalize @substVar unliftVar @n Xa n AAY desterF QedF Theorem subst comm X ∀ @e1 X exp PA e2 e3D subst @subst e1 First e2 A First e3 a subst @subst e1 @Next FirstA @lift e3 FirstAA First @subst e2 First introsY generalize @subst comm' e1 First First e2 e3 AY desterF QedF e3 AF „he (n—l theorem is spe™i—lized to the ™—se of su˜stituting in —n expression with ex—™tly two free v—ri—˜lesD whi™h yields — st—tement th—t is re—d—˜le enoughD —s st—tements —˜out de fruijn indi™es goF „his proof s™ript is resilient to spe™i(™—tion ™h—ngesF st is e—sy to —dd new ™onstru™tors to the l—ngu—ge ˜eing tre—tedF „he proofs —d—pt —utom—ti™—lly to the —ddition of —ny ™onE stru™tor whose su˜terms e—™h involve zero or one new ˜ound v—ri—˜lesF „h—t isD to —dd su™h — ™onstru™torD we only need to —dd it to the de(nition of exp —nd —dd @quite o˜viousA ™—ses for it in the de(nitions of lift —nd substF QHV Chapter 17 Higher-Order Abstract Syntax sn m—ny ™—sesD det—iled re—soning —˜out v—ri—˜le ˜inders —nd su˜stitution is — sm—ll —nnoyE —n™eY in other ™—sesD it ˜e™omes the domin—nt ™ost of proving — theorem form—llyF xo m—tter whi™h of these possi˜ilities prev—ilsD it is ™le—r th—t it would ˜e very pr—gm—ti™ to (nd — w—y to —void re—soning —˜out v—ri—˜le identity or freshnessF e wellEest—˜lished —ltern—tive to (rstEorder en™odings is higher-order abstract syntaxD or ryeƒF sn me™h—nized theoremE provingD ryeƒ is most ™losely —sso™i—ted with the vp met— logi™ —nd the tools ˜—sed on itD in™luding „welfF sn this ™h—pterD we will see th—t ryeƒ ™—nnot ˜e implemented dire™tly in goqF roweverD — few very simil—r en™odings —re possi˜le —nd —re in f—™t very e'e™tive in some import—nt dom—insF 17.1 Classic HOAS „he motto of ryeƒ is simpleX represent o˜je™t l—ngu—ge ˜inders using met— l—ngu—ge ˜indersF rereD 4o˜je™t l—ngu—ge4 refers to the l—ngu—ge ˜eing form—lizedD while the met— l—ngu—ge is the l—ngu—ge in whi™h the form—liz—tion is doneF yur usu—l met— l—ngu—geD goq9s q—llin—D ™ont—ins the st—nd—rd ˜inding f—™ilities of fun™tion—l progr—mmingD m—king it — promising ˜—se for higherEorder en™odingsF ‚e™—ll the ™on™rete en™oding of ˜—si™ untyped l—m˜d— ™—l™ulus expressionsF Inductive uexp X Set Xa | UVar X string → uexp | UApp X uexp → uexp → uexp | UAbs X string → uexp → uexpF „he expli™it presen™e of v—ri—˜le n—mes for™es us to think —˜out issues of freshness —nd v—ri—˜le ™—ptureF „he ryeƒ —ltern—tive would look like thisF Reset uexpF Inductive uexp X Set Xa QHW | | UApp UAbs X uexp → uexp → uexp X @uexp → uexpA → uexpF ‡e h—ve —voided —ny mention of v—ri—˜lesF snste—dD we en™ode the ˜inding done ˜y —˜str—™tion using the ˜inding f—™ilities —sso™i—ted with q—llin— fun™tionsF por inst—n™eD we might represent the term λx. x x —s UAbs @fun x ⇒ UApp x x AF goq h—s ˜uiltEin support for m—t™hing ˜inders in —nonymous fun expressions to their usesD so we —void needing to implement our own ˜inderEm—t™hing logi™F „his de(nition is not quite ryeƒD ˜e™—use of the ˜ro—d v—riety of fun™tions th—t goq would —llow us to p—ss —s —rguments to UAbsF ‡e ™—n thus ™onstru™t m—ny uexps th—t do not ™orrespond to norm—l l—m˜d— termsF „hese devi—nts —re ™—lled exotic termsF sn vpD fun™tions m—y only ˜e written in — very restri™tive ™omput—tion—l l—ngu—geD l—™kingD —mong other thingsD p—ttern m—t™hing —nd re™ursive fun™tion de(nitionsF „husD th—nks to — ™—reful ˜—l—n™ing —™t of design de™isionsD exoti™ terms —re not possi˜le with usu—l ryeƒ en™odings in vpF yur de(nition of uexp h—s — more fund—ment—l pro˜lemX it is inv—lid in q—llin—F Error X Non strictly positive occurrence of 4@uexp → uexpA → uexp4F 4uexp4 in ‡e h—ve viol—ted — rule th—t we ™onsidered ˜eforeX —n indu™tive type m—y not ˜e de(ned in terms of fun™tions over itselfF ‡—y ˜—™k in gh—pter QD we ™onsidered this ex—mple —nd the re—sons why we should ˜e gl—d th—t goq reje™ts itF „husD we will need to use more ™leverness to re—p simil—r ˜ene(tsF „he root pro˜lem is th—t our expressions ™ont—in v—ri—˜les representing expressions of the s—me kindF w—ny useful kinds of synt—x involve no su™h ™y™lesF por inst—n™eD it is e—sy to use ryeƒ to en™ode st—nd—rd (rstEorder logi™ in goqF Inductive prop X Type Xa | Eq X ∀ TD T → T → prop | Not X prop → prop | And X prop → prop → prop | Or X prop → prop → prop | Forall X ∀ TD @T → propA → prop | Exists X ∀ TD @T → propA → propF Fixpoint propDenote @p X propA X Prop Xa match p with | Eq x y ⇒ x a y | Not p ⇒ ¬ @propDenote p A | And p1 p2 ⇒ propDenote p1 ∧ propDenote p2 | Or p1 p2 ⇒ propDenote p1 ∨ propDenote p2 | Forall f ⇒ ∀ xD propDenote @f x A | Exists f ⇒ ∃ xD propDenote @f x A QIH endF …nfortun—telyD there —re other re™ursive fun™tions th—t we might like to write ˜ut ™—nnotF yne simple ex—mple is — fun™tion to ™ount the num˜er of ™onstru™tors used to ˜uild — propF „o look inside — Forall or ExistsD we need to look inside the qu—nti(er9s ˜odyD whi™h is represented —s — fun™tionF sn q—llin—D —s in most st—ti™—llyEtyped fun™tion—l l—ngu—gesD the only w—y to inter—™t with — fun™tion is to ™—ll itF ‡e h—ve no hope of doing th—t hereY the dom—in of the fun™tion in question h—s —n —r˜it—ry type T D so T m—y even ˜e uninh—˜itedF sf we h—d — univers—l w—y of ™onstru™ting v—lues to look inside fun™tionsD we would h—ve un™overed — ™onsisten™y ˜ug in goq3 ‡e —re still su'ering from the possi˜ility of writing exoti™ termsD su™h —s this ex—mpleX Example Example Example Xa Eq I IF false prop Xa Not true propF exotic prop Xa Forall @fun b X true prop bool ⇒ if b then true prop else false propAF „husD the ide— of — uniform w—y of looking inside — ˜inder to (nd —nother wellEde(ned prop is hopelessly doomedF e ™lever ryeƒ v—ri—nt ™—lled weak HOAS m—n—ges to rule out exoti™ terms in goqF rere is — we—k ryeƒ version of untyped l—m˜d— termsF Parameter var X SetF Inductive uexp X Set Xa | UVar X var → uexp | UApp X uexp → uexp → uexp | UAbs X @var → uexpA → uexpF ‡e postul—te the existen™e of some set var of v—ri—˜lesD —nd v—ri—˜le nodes —ppe—r exE pli™itly in our synt—xF e ˜inder is represented —s — fun™tion over variablesD r—ther th—n —s — fun™tion over expressionsF „his ˜re—ks the ™y™le th—t led goq to reje™t the liter—l ryeƒ de(nitionF st is e—sy to en™ode our previous ex—mpleD λx. x xX Example self app Xa UAbs @fun x ⇒ UApp @UVar x A @UVar x AAF ‡h—t —˜out exoti™ termsc „he pro˜lems they ™—used e—rlier ™—me from the f—™t th—t q—llin— is expressive enough to —llow us to perform ™—se —n—lysis on the types we used —s the dom—ins of ˜inder fun™tionsF ‡ith we—k ryeƒD we use —n —˜str—™t type var —s the dom—inF ƒin™e we —ssume the existen™e of no fun™tions for de™onstru™ting var sD goq9s type soundness enfor™es th—t no q—llin— term of type uexp ™—n t—ke di'erent v—lues depending on the v—lue of — var —v—il—˜le in the typing ™ontextD except ˜y in™orpor—ting those v—ri—˜les into — uexp v—lue in — leg—l w—yF ‡e—k ryeƒ ret—ins the other dis—dv—nt—ge of our previous ex—mpleX it is h—rd to write re™ursive fun™tions th—t de™onstru™t termsF es with the previous ex—mpleD some fun™tions are implement—˜leF por inst—n™eD we ™—n write — fun™tion to reverse the fun™tion —nd —rgument positions of every UApp nodeF Fixpoint swap @e X uexpA X uexp Xa match e with QII | UVar ⇒ e | UApp e1 e2 ⇒ UApp @swap e2 A @swap e1 A | UAbs e1 ⇒ UAbs @fun x ⇒ swap @e1 x AA endF roweverD it is still impossi˜le to write — fun™tion to ™ompute the size of —n expressionF ‡e would still need to m—nuf—™ture — v—lue of type var to peer under — ˜inderD —nd th—t is impossi˜leD ˜e™—use var is —n —˜str—™t typeF 17.2 Parametric HOAS sn the ™ontext of r—skellD ‡—sh˜urn —nd ‡eiri™h introdu™ed — te™hnique ™—lled parametric HOASD or €ryeƒF fy m—king — slight —lter—tion in the spirit of we—k ryeƒD we —rrive —t —n en™oding th—t —ddresses —ll three of the ™ompl—ints —˜oveX the en™oding is leg—l in goqD exoti™ terms —re impossi˜leD —nd it is possi˜le to write —ny synt—xEde™onstru™ting fun™tion th—t we ™—n write with (rstEorder en™odingsF „he l—st of these —dv—nt—ges is not even present with ryeƒ in „welfF sn — senseD we re™eive it in ex™h—nge for giving up — free implement—tion of ™—ptureE—voiding su˜stitutionF „he (rst step is to ™h—nge the we—k ryeƒ type so th—t var is — v—ri—˜le inside — se™tionD r—ther th—n — glo˜—l p—r—meterF Reset uexpF Section uexpF Variable var X SetF Inductive uexp X Set Xa | UVar X var → uexp | UApp X uexp → uexp → uexp | UAbs X @var → uexpA → uexpF End uexpF xextD we ™—n en™—psul—te ™hoi™es of Definition Uexp Xa ∀ varD var inside — polymorphi™ fun™tion typeF uexp varF „his type Uexp is our (n—lD exoti™EtermEfree represent—tion of l—m˜d— termsF snside the ˜ody of — Uexp fun™tionD var v—lues m—y not ˜e de™onstru™ted illeg—lyD for mu™h the s—me re—son —s with we—k ryeƒF ‡e simply tr—de —n —˜str—™t type for p—r—metri™ polymorphismF yur running ex—mple λx. x x is e—sily expressedX Example self app X Uexp Xa fun var ⇒ UAbs @var Xa var A @fun x X var ⇒ UApp @var Xa var A @UVar @var Xa var A x A @UVar @var Xa var A x AAF sn™luding —ll mentions of var expli™itly helps ™l—rify wh—t is h—ppening hereD ˜ut it is ™onvenient to let goq9s lo™—l type inferen™e (ll in these o™™urren™es for usF Example self app' X Uexp Xa fun ⇒ UAbs @fun QIP x ⇒ UApp @UVar x A @UVar x AAF ‡e ™—n go further —nd —pply the €ryeƒ te™hnique to dependentlyEtyped eƒ„sD where q—llin— typing gu—r—ntees th—t only wellEtyped terms ™—n ˜e representedF por the rest of this ™h—pterD we ™onsider the ex—mple of simplyEtyped l—m˜d— ™—l™ulus with n—tur—l num˜ers —nd —dditionF ‡e st—rt with — ™onvention—l de(nition of the type l—ngu—geF Inductive type X Type Xa | Nat X type | Arrow X type → type → typeF Infix 4!b4 Xa Arrow @right associativityD at level THAF yur de(nition of the expression type follows the de(nition for untyped l—m˜d— ™—l™ulusD with one import—nt ™h—ngeF xow our se™tion v—ri—˜le var is not just — typeF ‚—therD it is — function returning typesF „he ide— is th—t — v—ri—˜le of o˜je™t l—ngu—ge type t is represented ˜y — var t F xote how this en—˜les us to —void indexing the exp type with — represent—tion of typing ™ontextsF Section expF Variable var X type → TypeF Inductive exp X type → Type Xa | Const' X nat → exp Nat | Plus' X exp Nat → exp Nat → exp Nat | Var X ∀ tD var t → exp t | App' X ∀ dom ranD exp @dom !b ran A → exp dom → exp ran | Abs' X ∀ dom ranD @var dom → exp ran A → exp @dom !b ran AF End expF Implicit Arguments Implicit Arguments Implicit Arguments Const' ‘var “F Var ‘var t “F Abs' ‘var dom ran “F yur (n—l represent—tion type wr—ps Definition Exp t Xa ∀ varD exp —s ˜eforeF exp var tF ‡e ™—n de(ne some sm—rt ™onstru™tors to m—ke it e—sier to ˜uild polymorphism expli™itlyF Definition Const @n X natA X Exp Nat Xa fun ⇒ Const' nF Definition Plus @E1 E2 X Exp NatA X Exp Nat Xa fun ⇒ Plus' @E1 A @E2 AF Definition App dom ran @F X Exp @dom !b ran AA @X X fun ⇒ App' @F A @X AF Exp dom A X Exps Exp ran without using Xa e ™—se for fun™tion —˜str—™tion is not —s n—tur—lD ˜ut we ™—n implement one ™—ndid—te in terms of — type f—mily Exp1D su™h th—t Exp1 free result represents —n expression of type result with one free v—ri—˜le of type freeF QIQ Definition Exp1 t1 t2 Xa ∀ varD var t1 → exp var t2F Definition Abs dom ran @B X Exp1 dom ran A X Exp @dom !b fun ⇒ Abs' @B AF ran A Xa xow it is e—sy to en™ode — num˜er of ex—mple progr—msF Example zero Xa Const HF Example one Xa Const IF Example one again Xa Plus zero oneF Example ident X Exp @Nat !b NatA Xa Abs @fun X ⇒ Var X AF Example app ident Xa App ident one againF Example app X Exp @@Nat !b NatA !b Nat !b NatA Xa fun ⇒ Abs' @fun f ⇒ Abs' @fun x ⇒ App' @Var f A @Var x AAAF Example app ident' Xa App @App app identA one againF ‡e ™—n write synt—xEde™onstru™ting fun™tionsD su™h —s CountVarsD whi™h ™ounts how m—ny nodes —ppe—r in —n ExpF pirstD we write — version countVars for expsF „he m—in tri™k is to spe™i—lize countVars to work over expressions where var is inst—nti—ted —s fun ⇒ unitF „h—t isD every v—ri—˜le is just — v—lue of type unitD su™h th—t v—ri—˜les ™—rry no inform—tionF „he import—nt thing is th—t we h—ve — v—lue tt of type unit —v—il—˜leD to use in des™ending into ˜indersF Var Fixpoint countVars t @e X exp @fun ⇒ unitA t A X nat Xa match e with | Const' ⇒ H | Plus' e1 e2 ⇒ countVars e1 C countVars e2 ⇒I | Var | App' e1 e2 ⇒ countVars e1 C countVars e2 | Abs' e' ⇒ countVars @e' ttA endF ‡e turn countVars into CountVars with expli™it inst—nti—tion of — polymorphi™ Exp v—lue ‡e ™—n write —n unders™ore for the p—r—mter to ED ˜e™—use lo™—l type inferen™e is —˜le to infer the proper v—lueF EF Definition CountVars t @E X Exp t A e few ev—lu—tions est—˜lish th—t X nat Xa countVars @E AF CountVars Eval compute in aH X nat CountVars zeroF Eval compute in aH X nat CountVars oneF Eval compute in ˜eh—ves pl—usi˜lyF CountVars one againF QIR aH X nat Eval compute in aI X nat CountVars identF Eval compute in aI X nat CountVars app identF Eval compute in aP X nat CountVars appF Eval compute in aQ X nat CountVars app ident'F ‡e might w—nt to go further —nd ™ount o™™urren™es of — single distinguished free v—ri—˜le in —n expressionF sn this ™—seD it is useful to inst—nti—te var —s fun ⇒ boolF ‡e will represent the distinguished v—ri—˜le with true —nd —ll other v—ri—˜les with falseF Fixpoint countOne t @e X exp @fun ⇒ boolA t A X nat Xa match e with | Const' ⇒ H | Plus' e1 e2 ⇒ countOne e1 C countOne e2 | Var true ⇒ I | Var false ⇒ H | App' e1 e2 ⇒ countOne e1 C countOne e2 | Abs' e' ⇒ countOne @e' falseA endF ‡e wr—p countOne into CountOneD whi™h we type using the Exp1 de(nition from ˜eforeF CountOne oper—tes on —n expression E with — single free v—ri—˜leF ‡e —pply —n inst—nti—ted E to true to m—rk this v—ri—˜le —s the one countOne should look forF countOne itself is ™—reful to inst—nti—te —ll other v—ri—˜les with falseF Definition countOne CountOne t1 t2 @E trueAF @E X ‡e ™—n ™he™k the ˜eh—vior of Exp1 t1 t2 A CountOne X nat Xa on — few ex—mplesF Example ident1 X Exp1 Nat Nat Xa fun X ⇒ Var XF Example add self X Exp1 Nat Nat Xa fun X ⇒ Plus' @Var Example app zero X Exp1 @Nat !b NatA Nat Xa fun X ⇒ Example app ident1 X Exp1 Nat Nat Xa fun X ⇒ App' @Abs' @fun Y ⇒ Var Y AA @Var X AF QIS XA @Var X AF @Var X A @Const' HAF App' Eval compute in aI X nat CountOne ident1F Eval compute in aP X nat CountOne add self F Eval compute in aI X nat CountOne app zeroF Eval compute in aI X nat CountOne app ident1F „he €ryeƒ en™oding turns out to ˜e just —s gener—l —s the (rstEorder en™odings we s—w previouslyF „o provide — t—ste of th—t gener—lityD we implement — tr—nsl—tion into ™on™rete synt—xD rendered in hum—nEre—d—˜le stringsF „his is —s e—sy —s representing v—ri—˜les —s stringsF Section ToStringF Open Scope string scopeF Fixpoint natToString @n X natA X string Xa match n with | O ⇒ 4y4 | S n' ⇒ 4ƒ@4 CC natToString n' CC 4A4 endF pun™tion toString t—kes —n extr— —rgument curD whi™h holds the l—st v—ri—˜le n—me —sE signed to — ˜inderF ‡e ˜uild new v—ri—˜le n—mes ˜y extending cur with primesF „he fun™tion returns — p—ir of the next —v—il—˜le v—ri—˜le n—me —nd of the —™tu—l expression renderingF Fixpoint toString t @e X exp @fun ⇒ stringA t A @cur X stringA X string B string Xa match e with | Const' n ⇒ @curD natToString n A | Plus' e1 e2 ⇒ let @cur'D s1 A Xa toString e1 cur in let @cur D s2 A Xa toString e2 cur' in @cur D 4@4 CC s1 CC 4A C @4 CC s2 CC 4A4A | Var s ⇒ @curD s A | App' e1 e2 ⇒ let @cur'D s1 A Xa toString e1 cur in let @cur D s2 A Xa toString e2 cur' in @cur D 4@4 CC s1 CC 4A @4 CC s2 CC 4A4A | Abs' e' ⇒ QIT endF let @cur'D s A Xa toString @e' cur A @cur CC 494A in @cur'D 4@’4 CC cur CC 4D 4 CC s CC 4A4A Definition End ToStringF ToString t @E X Exp t A Eval compute in ToString a 4y47string X string string Xa snd @toString @E A 4x4AF zeroF Eval compute in ToString a 4ƒ@yA47string X string X oneF Eval compute in ToString one againF a 4@yA C @ƒ@yAA47string X string Eval compute in ToString a 4@’xD xA47string X string identF Eval compute in ToString app identF a 4@@’xD xAA @@yA C @ƒ@yAAA47string X string Eval compute in ToString appF a 4@’xD @’x9D @xA @x9AAA47string X string Eval compute in ToString app ident'F a 4@@@’xD @’x9D @xA @x9AAAA @@’xD xAAA @@yA C @ƒ@yAAA47string X string yur (n—l ex—mple is ™ru™i—l to using €ryeƒ to en™ode st—nd—rd oper—tion—l sem—nti™sF ‡e de(ne ™—ptureE—voiding su˜stitutionD in terms of — fun™tion atten whi™h t—kes in —n expression th—t represents v—ri—˜les —s expressionsF atten repl—™es every node Var e with eF Section attenF Variable var X type → TypeF Fixpoint atten t @e X exp @exp var A t A X exp var t Xa match e with | Const' n ⇒ Const' n | Plus' e1 e2 ⇒ Plus' @atten e1 A @atten e2 A | Var e' ⇒ e' | App' e1 e2 ⇒ App' @atten e1 A @atten e2 A QIU | Abs' endF End attenF e' ⇒ Abs' @fun x ⇒ atten @e' @Var x AAA pl—ttening turns out to implement the he—rt of su˜stitutionF ‡e —pply E2D whi™h h—s one free v—ri—˜leD to E1D repl—™ing the o™™urren™es of the free v—ri—˜le ˜y ™opies of E1F atten t—kes ™—re of removing the extr— Var —ppli™—tions —round these ™opiesF Definition Subst t1 t2 @E1 X atten @E2 @E1 AAF Exp t1 A Eval compute in Subst one ident1F a fun var X type → Type ⇒ X Exp Nat @E2 X Const' Exp1 t1 t2 A X Exp t2 Xa fun ⇒ I Eval compute in Subst one add self F a fun var X type → Type ⇒ Plus' @Const' IA @Const' IA X Exp Nat Eval compute in Subst ident app zeroF a fun var X type → Type ⇒ App' @Abs' @fun X X var Nat ⇒ X Exp Nat Var X AA @Const' HA Eval compute in Subst one app ident1F a fun var X type → Type ⇒ App' @Abs' @fun x X var Nat ⇒ Var x AA @Const' IA X Exp Nat 17.3 A Type Soundness Proof ‡ith Subst de(nedD there —re few surprises en™ountered in de(ning — st—nd—rd sm—llEstepD ™—llE˜yEv—lue sem—nti™s for our o˜je™t l—ngu—geF ‡e ˜egin ˜y ™l—ssifying — su˜set of expresE sions —s v—luesF Inductive Val X ∀ tD Exp t → Prop Xa | VConst X ∀ nD Val @Const n A | VAbs X ∀ dom ran @B X Exp1 dom ran AD Val @Abs Hint B AF Constructors ValF ƒin™e this l—ngu—ge is more ™ompli™—ted th—n the one we ™onsidered in the ™h—pter on (rstEorder en™odingsD we will use expli™it ev—lu—tion ™ontexts to de(ne the sem—nti™sF e v—lue of type Ctx t u is — ™ontext th—t yields —n expression of type u when (lled ˜y —n expression of type t F ‡e h—ve one ™ontext for e—™h position of the App —nd Plus ™onstru™torsF Inductive Ctx X type → type → Type Xa | AppCong1 X ∀ @dom ran X typeAD QIV → Ctx @dom !b ran A ran | AppCong2 X ∀ @dom ran X typeAD Exp @dom !b ran A → Ctx dom ran | PlusCong1 X Exp Nat → Ctx Nat Nat | PlusCong2 X Exp Nat → Ctx Nat NatF Exp dom e judgment ™h—r—™terizes when ™ontexts —re v—lidD enfor™ing the st—nd—rd ™—llE˜yEv—lue restri™tion th—t ™ert—in positions must hold v—luesF Inductive isCtx X ∀ t1 t2D Ctx t1 t2 → Prop Xa | IsApp1 X ∀ dom ran @X X Exp dom AD isCtx @AppCong1 ran X A | IsApp2 X ∀ dom ran @F X Exp @dom !b ran AAD Val F → isCtx @AppCong2 F A | IsPlus1 X ∀ E2D isCtx @PlusCong1 E2 A | IsPlus2 X ∀ E1D Val E1 → isCtx @PlusCong2 E1 AF e simple de(nition implements plugging — ™ontext with — spe™i(™ expressionF Definition plug t1 t2 @C X Ctx t1 t2 A X Exp t1 → Exp t2 Xa match C with X ⇒ fun F ⇒ App F X | AppCong1 F ⇒ fun X ⇒ App F X | AppCong2 | PlusCong1 E2 ⇒ fun E1 ⇒ Plus E1 E2 | PlusCong2 E1 ⇒ fun E2 ⇒ Plus E1 E2 endF Infix 4d4 Xa plug @no associativityD at level THAF pin—llyD we h—ve the step rel—tion itselfD whi™h ™om˜ines our ingredients in the st—nd—rd w—yF sn the ™ongruen™e ruleD we introdu™e the extr— v—ri—˜le E1 —nd its —sso™i—ted equ—lity to m—ke the rule e—sier for eauto to —pplyF Reserved Notation 4iI aab iP4 @no associativityD at level WHAF Inductive Step X ∀ tD Exp t → Exp t → Prop Xa | Beta X ∀ dom ran @B X Exp1 dom ran A @X X Exp dom AD Val X → App @Abs BA X aab Subst X B X ∀ n1 n2D Plus @Const n1 A @Const n2 A aab Const @n1 C | Cong X ∀ t t' @C X Ctx t t' A E E' E1D | Sum n2 A isCtx C → → → aC dE E aab E' E1 aab C d E1 E' where 4iI aab iP4 Xa @Step Hint Constructors isCtx StepF E1 E2 AF „o prove type soundness for this sem—nti™sD we need to over™ome one ™ru™i—l o˜st—™leF QIW ƒt—nd—rd proofs use indu™tion on the stru™ture of typing deriv—tionsF yur en™oding mixes typing deriv—tions with expression synt—xD so we w—nt to indu™t over expression stru™tureF yur expressions —re represented —s fun™tionsD whi™h do notD in gener—lD —dmit indu™tion in goqF roweverD ˜e™—use of our use of p—r—metri™ polymorphismD we know th—t our expressions doD in f—™tD h—ve indu™tive stru™tureF sn p—rti™ul—rD every ™losed v—lue of Exp type must ˜elong to the following rel—tionF Inductive Closed X ∀ tD | CConst X ∀ nD Closed @Const n A | CPlus X ∀ E1 E2D Exp t Closed E1 → Closed E2 → Closed @Plus E1 | | CApp X∀ dom ran E2 A @E1 X Exp @dom !b Closed E1 → Closed E2 → Closed @App E1 CAbs X∀ dom ran Closed @Abs E1 AF → Prop Xa E2 A @E1 X ran AA E2D Exp1 dom ran AD row ™—n we prove su™h — f—™tc st pro˜—˜ly ™—nnot ˜e est—˜lished in goq without —xiomsF ‚—therD one would h—ve to est—˜lish it met—theoreti™—llyD re—soning inform—lly outside of goqF por nowD we —ssert the f—™t —s —n —xiomF „he l—ter ™h—pter on intension—l tr—nsform—tions shows one —ppro—™h to removing the need for —n —xiomF Axiom closed X ∀ t @E X Exp t AD Closed EF „he usu—l progress —nd preserv—tion theorems —re now very e—sy to proveF sn f—™tD preserv—tion is impli™it in our dependentlyEtyped de(nition of StepF „his is — huge winD ˜e™—use we —void ™ompletely the theorem —˜out su˜stitution —nd typing th—t m—de up the ˜ulk of e—™h proof in the ™h—pter on (rstEorder en™odingsF „he progress theorem yields to — few lines of —utom—tionF ‡e de(ne — slight v—ri—nt of crush whi™h —lso looks for ™h—n™es to use the theorem inj pair2 on hypothesesF „his theorem de—ls with —n —rtif—™t of the w—y th—t inversion works on dependentlyEtyped hypothesesF Ltac my crush' Xa crush Y repeat @match goal with |‘H X “ ⇒ generalize @inj pair2 H AY clear H endY crush AF Hint Extern I @ a d A ⇒ simplF „his is the point where we need to do indu™tion over fun™tionsD in the form of expressions EF „he judgment Closed provides the perfe™t fr—meworkY we indu™t over Closed deriv—tionsF Lemma progress' X ∀ t @E X Exp t AD QPH Closed E → Val E ∨ ∃ E'D E aab E'F induction IY crush Y repeat match goal with | ‘ H X Val endY eauto TF QedF “ ⇒ inversion HY ‘“Y clear H Y my crush' yur (n—l proof of progress m—kes one topElevel use of the —xiom —˜oveF Theorem closed th—t we —sserted X ∀ t @E X Exp t AD Val E ∨ ∃ E'D E aab E'F introsY apply progress'Y apply closed F QedF progress 17.4 Big-Step Semantics enother st—nd—rd exer™ise in oper—tion—l sem—nti™s is proving the equiv—len™e of sm—llEstep —nd ˜igEstep sem—nti™sF ‡e ™—n ™—rry out this exer™ise for our €ryeƒ l—m˜d— ™—l™ulusF wost of the steps —re just —s ple—s—nt —s in the previous se™tionD ˜ut things get ™ompli™—ted ne—r to the endF ‡e must st—rt ˜y de(ning the ˜igEstep sem—nti™s itselfF „he de(nition is ™ompletely st—nd—rdF Reserved Notation 4iI aaab iP4 @no associativityD at level Inductive BigStep X ∀ tD Exp t → Exp t → Prop Xa | SConst X ∀ nD Const n aaab Const n | SPlus X ∀ E1 E2 n1 n2D E1 aaab Const n1 → E2 aaab Const n2 → Plus E1 E2 aaab Const @n1 C n2 A X ∀ dom ran @E1 X Exp @dom !b ran AA E1 aaab Abs B → E2 aaab V2 → Subst V2 B aaab V → App E1 E2 aaab V | SAbs X ∀ dom ran @B X Exp1 dom ran AD Abs B aaab Abs B | SApp where 4iI aaab iP4 Xa @BigStep E2 B V2 VD E1 E2 AF QPI WHAF Hint Constructors BigStepF „o prove — ™ru™i—l intermedi—te lemm—D we will w—nt to n—me the tr—nsitiveEre)exive ™losure of the sm—llEstep rel—tionF Reserved Notation 4iI aabB iP4 @no Inductive MultiStep X ∀ tD Exp t → | Done X ∀ t @E X Exp t AD E aabB E | OneStep X ∀ t @E E' E X Exp t AD E aab E' → E' aabB E → E aabB E Exp t where 4iI aabB iP4 Xa @MultiStep Hint associativityD at level WHAF → Prop Xa E1 E2 AF Constructors MultiStepF e few ˜—si™ properties of ev—lu—tion —nd v—lues —dmit e—sy proofsF Theorem MultiStep trans X ∀ E1 aabB E2 → E2 aabB E3 → E1 aabB E3F induction IY eautoF QedF t @E1 Theorem Big Val X ∀ t @E E aaab V → Val VF induction IY crushF QedF X Exp t AD Theorem Val V Val Big X∀ t V @V X E2 E3 X Exp t AD Exp t AD → V aaab VF destruct IY crushF QedF Hint Resolve Big Val Val BigF enother useful property de—ls with pushing multiEstep ev—lu—tion inside of ™ontextsF Lemma Multi Cong isCtx C X∀ t t' @C X Ctx t t' AD → ∀ E E'D E aabB E' → C d E aabB C d E'F induction PY crush Y eautoF QedF Lemma Multi Cong' X∀ t t' @C X Ctx t t' A E1 E2 E E'D QPP isCtx C aC dE E2 a C d E' E aabB E' E1 aabB E2F crush Y apply Multi QedF → → → → E1 Hint Resolve CongY autoF Multi Cong'F …nrestri™ted use of tr—nsitivity of aabB ™—n le—d to very l—rge eauto se—r™h sp—™esD whi™h h—s very in™onvenient e0™ien™y ™onsequen™esF snste—dD we de(ne — spe™i—l t—™ti™ mtrans th—t tries —pplying tr—nsitivity with — p—rti™ul—r intermedi—te expressionF Ltac mtrans E Xa match goal with | ‘ E aabB “ ⇒ fail I | ⇒ apply MultiStep trans with endF EY ‘ solve ‘ eauto “ | eauto “ ‡ith mtransD we ™—n give — re—son—˜ly short proof of one dire™tion of the equiv—len™e ˜etween ˜igEstep —nd sm—llEstep sem—nti™sF ‡e in™lude proof ™—ses spe™i(™ to rules of the ˜igEstep sem—nti™sD sin™e le—ving the det—ils to eauto would le—d to — very slow proof s™riptF „he use of solve in mtrans 9s de(nition keeps us from going down unfruitful p—thsF Theorem Big Multi X ∀ t @E V X E aaab V → E aabB VF induction IY crush Y eautoY repeat match goal with | ‘ n1 X D E2 X | ‘ n1 X D n2 X | ‘ B X D E2 X endF QedF Exp t AD “ ⇒ mtrans @Plus @Const n1 A E2 A “ ⇒ mtrans @Plus @Const n1 A @Const “ ⇒ mtrans @App @Abs B A E2 A n2 AA ‡e —re —lmost re—dy to prove the other dire™tion of the equiv—len™eF pirstD we wr—p —n e—rlier lemm— in — form th—t will work ˜etter with eautoF Lemma Big Val' Val V2 → → V1 V1 crushF X∀ a V2 aaab t @V1 V2 X Exp t AD V2F QedF Hint Resolve Big Val'F xow we ˜uild some quite involved t—™ti™ support for re—soning —˜out equ—lities over QPQ €ryeƒ termsF pirstD we will ™—ll equate conj F G to determine the ™onsequen™es of —n equ—lity F a GF ‡hen F a f e 1 FFF e n —nd G a f e' 1 FFF e' nD equate conj will return — ™onjun™tion e 1 a e' 1 ∧ FFF ∧ e n a e' nF ‡e h—rd™ode — p—ttern for e—™h v—lue of n from I to SF Ltac equate conj F G Xa match constr X@pD G A with | @ cxID cxPA ⇒ constr X@xI a x2 A | @ cxI cyID cxP cyPA ⇒ constr X@xI a x2 ∧ y1 a y2 A | @ cxI cyI czID cxP cyP czPA ⇒ constr X@xI a x2 ∧ y1 a y2 ∧ | @ cxI cyI czI cuID cxP cyP czP cuPA ⇒ constr X@xI a x2 ∧ y1 a y2 ∧ z1 a z2 ∧ u1 a u2 A | @ cxI cyI czI cuI cvID cxP cyP czP cuP cvPA ⇒ constr X@xI a x2 ∧ y1 a y2 ∧ z1 a z2 ∧ u1 a u2 ∧ v1 a v2 A endF z1 a z2 A „he m—in t—™ti™ is my crushD whi™h gener—lizes our e—rlier my crush' ˜y performing inE version on hypotheses th—t equ—te €ryeƒ termsF goq9s ˜uiltEin inversion is only designed to ˜e useful on equ—lities over indu™tive typesF €ryeƒ terms —re fun™tionsD so inversion is not very helpful on themF „o perform the equiv—lent of discriminateD we inst—nti—te the terms with var —s fun ⇒ unit —nd then —ppe—l to norm—l discriminateF „his elimin—tes some ™ontr—di™tory ™—sesF „o perform the equiv—lent of injectionD we must ™onsider —ll possi˜le var inst—nti—tionsF ƒome f—irly intri™—te logi™ strings together these elementsF „he det—ils —re not worth dis™ussingD sin™e our ™on™lusion will ˜e th—t one should —void de—ling with proofs of f—™ts like this oneF Ltac my crush Xa my crush' Y repeat @match goal with “⇒ | ‘ H X cp a cq @let H' Xa fresh 4r94 in assert @H' X F @fun ⇒ unitA a G @fun ⇒ unitAAY ‘ congruence | discriminate || injection H' Y clear H' “Y my crush' Y repeat match goal with | ‘ H X context ‘fun ⇒ unit“ “ ⇒ clear H endY match type of H with | cp a cq ⇒ let ec Xa equate conj F G in let var Xa fresh 4v—r4 in assert ec Y ‘ intuitionY unfold Exp Y apply ext eq Y intro var Y assert @H' X F var a G var AY try congruenceY match type of H' with | cˆ a c‰ ⇒ QPR endY my crush'F endAY clear H let X Xa eval hnf in X in let Y Xa eval hnf in Y in change @X a Y A in H' endY injection H' Y my crush' Y tauto | intuitionY subst “ my crush' AY ‡ith th—t ™ompli™—ted t—™ti™ —v—il—˜leD the proof of the m—in lemm— is str—ightforw—rdF Lemma Multi Big' X ∀ t @E E' X Exp t AD E aab E' → ∀ E D E' aaab E → E aaab E F induction IY crush Y eautoY match goal with “ ⇒ inversion H Y my crush Y eauto | ‘ H X aaab endY match goal with | ‘ H X isCtx “ ⇒ inversion H Y my crush Y eauto endF QedF Hint Resolve Multi Big'F „he other dire™tion of the over—ll equiv—len™e follows —s —n e—sy ™oroll—ryF Theorem Multi Big X ∀ t @E V X E aabB V → Val V → E aaab VF induction IY crush Y eautoF QedF Exp t AD „he lesson here is th—t working dire™tly with €ryeƒ terms ™—n e—sily le—d to extremely intri™—te proofsF st is usu—lly — ˜etter ide— to sti™k to indu™tive proofs —˜out instantiated €ryeƒ termsY in the ™—se of this ex—mpleD th—t me—ns proofs —˜out exp inste—d of ExpF ƒu™h results ™—n usu—lly ˜e wr—pped into results —˜out Exp without further indu™tionF hi'erent theorems dem—nd di'erent v—ri—nts of this underlying —dvi™eD —nd we will ™onsider sever—l of them in the ™h—pters to ™omeF QPS Chapter 18 Type-Theoretic Interpreters „hroughout this ˜ookD we h—ve given sem—nti™s for progr—mming l—ngu—ges vi— exe™ut—˜le interpreters written in q—llin—F €ryeƒ is quite ™omp—ti˜le with th—t modelD when we w—nt to form—lize m—ny of the wide v—riety of interesting nonE„uringE™omplete progr—mming l—ngu—gesF wost su™h l—ngu—ges h—ve very str—ightforw—rd el—˜or—tions into q—llin—F sn this ™h—pterD we show how to extend our p—st —ppro—™h to higherEorder l—ngu—ges en™oded with €ryeƒD —nd we show how simple progr—m tr—nsform—tions m—y ˜e proved ™orre™t with respe™t to these el—˜or—tive sem—nti™sF 18.1 Simply-Typed Lambda Calculus ‡e ˜egin with — ™opy of l—st ™h—pter9s en™oding of the synt—x of simplyEtyped l—m˜d— ™—l™ulus with n—tur—l num˜ers —nd —dditionF „he primes —t the ends of ™onstru™tor n—mes —re goneD sin™e here our prim—ry su˜je™t is exps inste—d of ExpsF Module STLCF Inductive type X Type Xa | Nat X type | Arrow X type → type → typeF Infix 4!b4 Xa Arrow @right at associativityD Section varsF Variable var X type → TypeF Inductive exp X type → Type Xa | Var X ∀ tD var t → | | exp t Const Plus X nat → exp Nat exp Nat → exp Nat → exp Nat X QPT level THAF X ∀ t1 t2D exp @t1 !b t2 A → exp t1 → exp t2 | Abs X ∀ t1 t2D @var t1 → exp t2 A → exp @t1 !b t2 AF End varsF | App Definition Implicit Implicit Implicit Implicit Implicit Exp t Xa ∀ Arguments Arguments Arguments Arguments Arguments varD exp var tF Var ‘var t “F Const ‘var “F Plus ‘var “F App ‘var t1 t2 “F Abs ‘var t1 t2 “F „he de(nitions th—t follow will ˜e e—sier to re—d if we de(ne some p—rsing not—tions for the ™onstru™torsF Notation 45 v4 Xa @Var v A @at level UHAF Notation 4BA n4 Xa @Const n A @at level UHAF Infix 4C¢4 Xa Plus @left associativityD at level UWAF Infix 4d4 Xa App @left associativityD at level UUAF Notation 4’ x D e4 Xa @Abs @fun x ⇒ e AA @at level UVAF Notation 4’ 3 D e4 Xa @Abs @fun ⇒ e AA @at level UVAF e few ex—mples will ˜e useful for testing the fun™tions we will writeF Example Example Example Example Example Example Example X Exp Nat Xa fun ⇒ BAHF one X Exp Nat Xa fun ⇒ BAIF ⇒ zero C¢ one F zpo X Exp Nat Xa fun ident X Exp @Nat !b NatA Xa fun ⇒ ’xD 5xF app ident X Exp Nat Xa fun ⇒ ident d zpo F ⇒ ’fD ’xD 5f d 5xF app X Exp @@Nat !b NatA !b Nat !b NatA Xa fun app ident' X Exp Nat Xa fun ⇒ app d ident d zpo F zero „o write our interpreterD we must (rst interpret o˜je™t l—ngu—ge types —s met— l—ngu—ge typesF Fixpoint typeDenote @t X typeA X Set Xa match t with | Nat ⇒ nat | t1 !b t2 ⇒ typeDenote t1 → typeDenote endF t2 „he ™ru™i—l tri™k of the expression interpreter is to represent v—ri—˜les using the typeDenote fun™tionF hue to limit—tions in goq9s synt—x extension systemD we ™—nnot t—ke —dv—nt—ge QPU of some of our not—tions when they —ppe—r in p—tternsD soD to ˜e ™onsistentD in p—tterns we —void not—tions —ltogetherF Fixpoint expDenote match e with | Var v ⇒ v | | Const n ⇒ Plus e1 e2 | App | Abs endF t @e X exp typeDenote t A X Xa n ⇒ expDenote e1 C expDenote e2 ⇒ @expDenote e1 A @expDenote ⇒ fun x ⇒ expDenote @e' x A e1 e2 e' typeDenote t e2 A Definition ExpDenote t @e X Exp t A Xa expDenote @e AF ƒome tests est—˜lish th—t ExpDenote produ™es q—llin— terms like we might write m—nuE —llyF Eval compute in ExpDenote zeroF aH X typeDenote Nat Eval compute in ExpDenote oneF aI X typeDenote Nat Eval compute in ExpDenote zpoF aI X typeDenote Nat Eval compute in ExpDenote identF a fun x X nat ⇒ x X typeDenote @Nat !b NatA Eval compute in ExpDenote app identF aI X typeDenote Nat Eval compute in ExpDenote appF a fun @x X nat → natA @x0 X natA ⇒ x x0 X typeDenote @@Nat !b NatA !b Nat !b NatA Eval compute in ExpDenote app ident'F aI X typeDenote Nat ‡e ™—n upd—te to the higherEorder ™—se our ™ommon ex—mple of — ™onst—nt folding fun™tionF „he workhorse fun™tion cfold is p—r—meterized to —pply to —n exp th—t uses —ny QPV typeF en output of cfold uses the s—me var type —s the inputF es in the de(nition of expDenoteD we ™—nnot use most of our not—tions in p—tternsD ˜ut we use them freely to m—ke the ˜odies of match ™—ses e—sier to re—dF var Section cfoldF Variable var X type → TypeF Fixpoint cfold t @e X exp match e with | Var v ⇒ 5v | | var t A X exp var t Xa ⇒ ¢n Plus e1 e2 ⇒ let e1' Xa cfold e1 in let e2' Xa cfold e2 in match e1'D e2' return with | Const n1D Const n2 ⇒ ¢@nI C | D ⇒ e1' C¢ e2' end Const n | App | Abs endF End cfoldF Definition ⇒ cfold e1 d cfold ⇒ ’xD cfold @e' x A e1 e2 e' Cfold t @E X Exp t A X Exp t n2 A e2 Xa fun ⇒ cfold @E AF xow we would like to prove the ™orre™tness of CfoldD whi™h follows from — simple indu™tive lemm— —˜out cfoldF X ∀ t @e X exp t AD @cfold e A a expDenote eF induction e Y crush Y try @ext eq Y crush AY repeat @match goal with | ‘ context ‘cfold ci“ “ ⇒ dep endY crush AF QedF Lemma cfold correct expDenote Theorem X ∀ t @E X Exp t AD ExpDenote @Cfold E A a ExpDenote EF unfold ExpDenoteD Cfold Y introsY apply QedF End STLCF destruct @cfold Cfold correct cfold correctF QPW EA 18.2 Adding Products and Sums „he ex—mple is e—sily —d—pted to support produ™ts —nd sumsD the ˜—sis of nonEre™ursive d—t—types in wv —nd r—skellF Module PSLCF Inductive type X Type Xa | Nat X type | Arrow X type → type → type | Prod X type → type → type | Sum X type → type → typeF Infix 4!b4 Xa Arrow @right associativityD at level TPAF Infix 4BB4 Xa Prod @right associativityD at level TIAF Infix 4CC4 Xa Sum @right associativityD at level THAF Section varsF Variable var X type → TypeF Inductive exp X type → Type Xa | Var X ∀ tD var t → | | exp t nat → exp Nat Plus X exp Nat → exp Nat → exp Nat Const X X ∀ t1 t2D exp @t1 !b t2 A → exp t1 → exp t2 | Abs X ∀ t1 t2D @var t1 → exp t2 A → exp @t1 !b t2 A | App | Pair X∀ t1 t2D exp t1 → exp t2 → exp @t1 BB t2 A X ∀ t1 t2D exp @t1 BB t2 A → exp t1 | Snd X ∀ t1 t2D exp @t1 BB t2 A → exp t2 | Fst QQH | Inl X∀ t1 t2D | Inr X∀ t1 t2D | SumCase End exp t1 → exp @t1 CC t2 A exp t2 → exp @t1 CC t2 A X∀ t1 t2 tD exp @t1 CC t2 A → @var t1 → exp t A → @var t2 → exp t A → exp tF varsF Definition Implicit Implicit Implicit Implicit Implicit Exp t Xa ∀ Arguments Arguments Arguments Arguments Arguments varD exp var tF Var ‘var t “F Const ‘var “F Abs ‘var t1 t2 “F Inl ‘var t1 t2 “F Inr ‘var t1 t2 “F Notation 45 v4 Xa @Var v A @at level UHAF Notation 4BA n4 Xa @Const n A @at level UHAF Infix 4C¢4 Xa Plus @left associativityD at level UVAF Infix 4d4 Xa App @left associativityD at level UUAF Notation 4’ x D e4 Xa @Abs @fun x ⇒ e AA @at level UVAF Notation 4’ 3 D e4 Xa @Abs @fun ⇒ e AA @at level UVAF Notation 4‘ eI D eP “4 Xa @Pair e1 e2 AF Notation 45I e4 Xa @Fst e A @at level USAF Notation 45P e4 Xa @Snd e A @at level USAF Notation 49™—se9 e 9of9 x ⇒ eI | y ⇒ eP4 Xa @SumCase @at level UWAF e @fun x ⇒ e1 A @fun y ⇒ e2 AA e few ex—mples ™—n ˜e de(ned e—silyD using the not—tions —˜oveF Example Example Example @Nat BB Nat !b Nat BB NatA Xa fun ⇒ ’pD ‘5P 5pD 5I 5p“F zo X Exp @Nat BB NatA Xa fun ⇒ ‘BAHD BAI“F swap zo X Exp @Nat BB NatA Xa fun ⇒ swap d zo F swap X Exp Example natOut X Exp @Nat CC Nat !b NatA Xa fun ⇒ ’sD case 5s of x ⇒ 5x | y ⇒ 5y C¢ 5yF Example ns1 X Exp @Nat CC NatA Xa fun ⇒ Inl @BAQAF Example ns2 X Exp @Nat CC NatA Xa fun ⇒ Inr @BASAF Example natOut ns1 X Exp Nat Xa fun ⇒ natOut d ns1 F Example natOut ns2 X Exp Nat Xa fun ⇒ natOut d ns2 F QQI „he sem—nti™s —d—pts without in™identF Fixpoint typeDenote @t X typeA X Set Xa match t with | Nat ⇒ nat | t1 !b t2 ⇒ typeDenote t1 → typeDenote t2 | t1 BB t2 ⇒ typeDenote t1 B typeDenote t2 | t1 CC t2 ⇒ typeDenote t1 C typeDenote t2 end7typeF Fixpoint expDenote match e with | Var v ⇒ v | | Const n ⇒ Plus e1 e2 t @e X exp typeDenote t A X typeDenote t n ⇒ expDenote e1 C expDenote e2 ⇒ @expDenote e1 A @expDenote ⇒ fun x ⇒ expDenote @e' x A | | App e1 e2 Abs e' | | | Pair Fst Snd Xa ⇒ @expDenote e1D ⇒ fst @expDenote e' A e' ⇒ snd @expDenote e' A e1 e2 e2 A expDenote e2 A e' ⇒ inl @expDenote e' A Inr e' ⇒ inr @expDenote e' A SumCase e' e1 e2 ⇒ match expDenote e' with | inl v ⇒ expDenote @e1 v A | inr v ⇒ expDenote @e2 v A end endF | | | Inl Definition e' ExpDenote t @e X Exp t A Xa expDenote @e AF Eval compute in ExpDenote swapF a fun x X nat B nat ⇒ @let @ D y A Xa x in yD let @x0D A Xa X typeDenote @Nat BB Nat !b Nat BB NatA Eval compute in ExpDenote zoF a @HD IA X typeDenote @Nat BB NatA Eval compute in ExpDenote swap a @ID HA X typeDenote @Nat BB NatA zoF QQP x in x0 A Eval cbv beta iota delta E‘plus “ in ExpDenote natOutF a fun x X nat C nat ⇒ match x with | inl v ⇒ v | inr v ⇒ v C v end X typeDenote @Nat CC Nat !b NatA Eval compute in ExpDenote ns1F a inl nat Q X typeDenote @Nat CC NatA Eval compute in ExpDenote ns2F a inr nat S X typeDenote @Nat CC NatA Eval compute in ExpDenote natOut ns1F aQ X typeDenote Nat Eval compute in ExpDenote natOut ns2F a IH X typeDenote Nat ‡e —d—pt the cfold fun™tion using the s—me ˜—si™ dependentEtypes tri™k th—t we —pplied in —n e—rlier ™h—pter to — very simil—r fun™tion for — l—ngu—ge without v—ri—˜lesF Section cfoldF Variable var X type → TypeF Definition pairOutType t Xa match t return Type with | t1 BB t2 ⇒ option @exp var t1 B exp var t2 A | ⇒ unit endF Definition pairOutDefault @t X typeA X pairOutType t Xa match t with | BB ⇒ None | ⇒ tt endF Definition pairOut t1 t2 @e X exp var @t1 BB t2 AA X option @exp var t1 B exp var t2 A Xa match e in exp t return pairOutType t with | Pair e1 e2 ⇒ Some @e1D e2 A | ⇒ pairOutDefault endF Fixpoint cfold t @e X exp var t A X exp var t Xa QQQ match e with | Var v ⇒ 5v | | | | | | ⇒ ¢n Plus e1 e2 ⇒ let e1' Xa cfold e1 in let e2' Xa cfold e2 in match e1'D e2' return with | Const n1D Const n2 ⇒ ¢@nI C | D ⇒ e1' C¢ e2' end Const n ⇒ cfold e1 d cfold ⇒ ’xD cfold @e' x A App e1 e2 Abs e' Pair e1 e2 Fst t1 e' ⇒ ‘cfold n2 A e2 e1D cfold e2 “ ⇒ let e Xa cfold e' in match pairOut e with | None ⇒ 5I e | Some @e1D A ⇒ e1 end | Snd e' ⇒ let e Xa cfold e' in match pairOut e with | None ⇒ 5P e | Some @ D e2 A ⇒ e2 end | | | End Inl e' Inr e' SumCase endF ⇒ Inl @cfold e' A ⇒ Inr @cfold e' A e' e1 e2 ⇒ case cfold e' of x ⇒ cfold @e1 x A | y ⇒ cfold @e2 y A cfoldF Definition Cfold t @E X Exp t A X Exp t Xa fun ⇒ cfold @E AF „he proofs —re —lmost —s str—ightforw—rd —s ˜eforeF ‡e (rst est—˜lish two simple theorems —˜out p—irs —nd their proje™tionsF Section pairsF Variables A B X TypeF QQR Variable Variable Variable v1 v2 v X X X AF BF A B BF Theorem pair eta1 X @v1D destruct v Y crushF QedF v2 A a v → v1 a fst vF Theorem pair eta2 X @v1D destruct v Y crushF QedF End pairsF v2 A a v → v2 a snd vF Hint Resolve pair eta1 pair eta2F „o the proof s™ript for the m—in lemm—D we —dd just one more match ™—seD dete™ting when ™—se —n—lysis is —ppropri—te on dis™riminees of m—t™hes over sum typesF X ∀ t @e X exp t AD expDenote @cfold e A a expDenote eF induction e Y crush Y try @ext eq Y crush AY repeat @match goal with | ‘ context ‘cfold ci“ “ ⇒ dep destruct @cfold E A | ‘ match ci with inl ⇒ | inr ⇒ end a “ ⇒ destruct endY crush AY eautoF QedF Lemma cfold correct Theorem X ∀ t @E X Exp t AD ExpDenote @Cfold E A a ExpDenote EF unfold ExpDenoteD Cfold Y introsY apply QedF End PSLCF Cfold correct cfold correctF QQS E Chapter 19 Extensional Transformations v—st ™h—pter9s ™onst—nt folding ex—mple w—s p—rti™ul—rly e—sy to verifyD ˜e™—use th—t tr—nsE form—tion used the s—me sour™e —nd t—rget l—ngu—geF sn this ™h—pterD we verify — di'erent tr—nsl—tionD illustr—ting the —dded ™omplexities in tr—nsl—ting ˜etween l—ngu—gesF €rogr—m tr—nsform—tions ™—n ˜e ™l—ssi(ed —s intensionalD when they require some noE tion of inequ—lity ˜etween v—ri—˜lesY or extensionalD otherwiseF „his ™h—pter9s ex—mple is extension—lD —nd the next ™h—pter de—ls with the tri™kier intension—l ™—seF 19.1 CPS Conversion for Simply-Typed Lambda Calculus e ™onvenient method for ™ompiling fun™tion—l progr—ms ˜egins with ™onversion to continuationpassing styleD or g€ƒF sn this restri™ted formD fun™tion ™—lls never returnY inste—dD we p—ss expli™it return pointersD mu™h —s in —ssem˜ly l—ngu—geF eddition—llyD we m—ke order of ev—lu—tion expli™itD ˜re—king ™omplex expressions into sequen™es of primitive oper—tionsF yur tr—nsl—tion will oper—te over the s—me sour™e l—ngu—ge th—t we used in the (rst p—rt of l—st ™h—pterD so we omit most of the l—ngu—ge de(nitionF roweverD we do m—ke one signi(™—nt ™h—ngeX sin™e we will ˜e working with multiple l—ngu—ges th—t involve simil—r ™onstru™tsD we use goq9s notation scope me™h—nism to dis—m˜igu—teF por inst—n™eD the sp—n of ™ode de—ling with type not—tions looks like thisX Notation 49x—t94 Xa TNat X Infix 4!b4 Xa Arrow @right source scopeF associativityD at level THA X source scopeF Open Scope source scopeF Bind Scope source scope with typeF Delimit Scope source scope with sourceF ‡e expli™itly pl—™e our not—tions inside — s™ope n—med source scopeD —nd we —sso™i—te — delimiting key source with source scopeF ‡ithout further ™omm—ndsD our not—tions would only ˜e used in expressions like @FFFA7sour™eF ‡e —lso open our s™ope lo™—lly within this QQT moduleD so th—t we —void repe—ting 7sour™e in m—ny pl—™esF purtherD we bind our s™ope to typeF sn some ™ir™umst—n™es where goq is —˜le to infer th—t some su˜expression h—s type typeD th—t su˜expression will —utom—ti™—lly ˜e p—rsed in source scopeF „he other ™riti™—l new ingredient is — gener—liz—tion of the Closed rel—tion from two ™h—pters —goF „he new rel—tion exp equiv ™h—r—™ters when two expressions m—y ˜e ™onE sidered synt—™ti™—lly equ—lF ‡e need to ˜e —˜le to h—ndle ™—ses where e—™h expression uses — di'erent var typeF sntuitivelyD we will w—nt to ™omp—re expressions th—t use their v—riE —˜les to store sour™eElevel —nd t—rgetElevel v—luesF ‡e express p—irs of equiv—lent v—ri—˜les using — list p—r—meter to the rel—tionY v—ri—˜le expressions will ˜e ™onsidered equiv—lent if —nd only if their v—ri—˜les ˜elong to this listF „he rule for fun™tion —˜str—™tion extends the list in — higherEorder w—yF „he rem—ining rules just implement the o˜vious ™ongruen™e over expressionsF Section exp equivF Variables var1 var2 X type → TypeF Inductive exp equiv X list { t X type 8 var1 t B → ∀ tD exp var1 t → exp var2 t → Prop Xa | EqVar X ∀ G t @v1 X var1 t A v2D t @v1D v2 AA G In @existT → exp equiv G @5vIA @5vPA | EqConst | EqPlus X∀ var2 t }7type G nD exp equiv G @¢nA @¢nA X∀ G x1 y1 x2 y2D exp equiv G x1 x2 → exp equiv G y1 y2 → exp equiv G @x1 C¢ y1 A @x2 C¢ y2 A X ∀ G t1 t2 @f1 X exp @t1 !b t2 AA @x1 X exp t1 A f2 x2D exp equiv G f1 f2 → exp equiv G x1 x2 → exp equiv G @f1 d x1 A @f2 d x2 A | EqAbs X ∀ G t1 t2 @f1 X var1 t1 → exp var1 t2 A f2D @∀ v1 v2D exp equiv @existT t1 @v1D v2 A XX G A @f1 v1 A @f2 v2 AA → exp equiv G @Abs f1 A @Abs f2 AF | End EqApp exp equivF st turns out th—tD for —ny p—r—metri™ expression ED —ny two inst—nti—tions of E with p—rti™ul—r var types must ˜e equiv—lentD with respe™t to —n empty v—ri—˜le listF „he p—r—E metri™ity of q—llin— gu—r—ntees thisD in mu™h the s—me w—y th—t it gu—r—nteed the truth of the —xiom —˜out ClosedF „husD we —ssert —n —n—logous —xiom hereF Axiom Exp equiv exp equiv nil X ∀ t @E X Exp t A var1 @E var1 A @E var2 AF var2D QQU End SourceF xow we need to de(ne the g€ƒ l—ngu—geD where ˜in—ry fun™tion types —re repl—™ed with un—ry ™ontinu—tion typesD —nd we —dd produ™t types ˜e™—use they will ˜e useful in our tr—nsl—tionF Module CPSF Inductive type X Type Xa | TNat X type | Cont X type → type | Prod X type → type → typeF Notation 49x—t94 Xa TNat X cps scopeF Notation 4t "b4 Xa @Cont t A @at level TIA X cps scopeF Infix 4BB4 Xa Prod @right associativityD at level THA X cps scopeF Bind Scope cps scope with typeF Delimit Scope cps scope with cpsF Section varsF Variable var X type → TypeF e g€ƒ progr—m is — series of ˜indings of primitive oper—tions @primopsAD followed ˜y either — h—lt with — (n—l progr—m result or ˜y — ™—ll to — ™ontinu—tionF „he —rguments to these progr—mEending oper—tions —re enfor™ed to ˜e v—ri—˜lesF „o use the v—lues of ™ompound expressions inste—dD those expressions must ˜e de™omposed into ˜indings of primopsF „he primop l—ngu—ge itself simil—rly for™es v—ri—˜les for —ll —rguments ˜esides ˜odies of fun™tion —˜str—™tionsF Inductive prog X Type Xa | PHalt X var Nat → prog X ∀ tD var @t "bA → var t → prog | Bind X ∀ tD | App primop t → @var t → → prog progA with primop X type → Type Xa | Const X nat → primop Nat | Plus X var Nat → var Nat → primop | X ∀ tD @var t → Abs Nat progA QQV → | Pair primop @t "bA X∀ t1 t2D var t1 → → var t2 primop @t1 BB X ∀ t1 t2D var @t1 BB t2 A → primop t1 | Snd X ∀ t1 t2D var @t1 BB t2 A → primop t2F End varsF | t2 A Fst Implicit Arguments Implicit Arguments PHalt ‘var “F Implicit Implicit Implicit Implicit Implicit Implicit Const ‘var “F Arguments Arguments Arguments Arguments Arguments Arguments App ‘var t “F Plus ‘var “F Abs ‘var t “F Pair ‘var t1 t2 “F Fst ‘var t1 t2 “F Snd ‘var t1 t2 “F Notation 49r—lt9 x4 Xa @PHalt x A @no associativityD at level USA X Infix 4dd4 Xa App @no associativityD at level USA X cps scopeF Notation 4x ← p Y e4 Xa @Bind p @fun x ⇒ e AA @right associativityD at level UTD p at next level A X cps scopeF Notation 43 ← p Y e4 Xa @Bind p @fun ⇒ e AA @right associativityD at level UTD p at next level A X cps scopeF Notation 4BA n4 Xa @Const n A @at level UHA X cps scopeF Infix 4C¢4 Xa Plus @left associativityD at level UWA X cps cps scopeF scopeF Notation 4’ x D e4 Xa @Abs @fun x ⇒ e AA @at level UVA X cps Notation 4’ 3 D e4 Xa @Abs @fun ⇒ e AA @at level UVA X cps scopeF scopeF Notation 4‘ xI D xP “4 Xa @Pair x1 x2 A X cps scopeF Notation 45I x4 Xa @Fst x A @at level UPA X cps scopeF Notation 45P x4 Xa @Snd x A @at level UPA X cps scopeF Bind Scope cps scope Open Scope with cps scopeF prog primopF sn interpreting typesD we tre—t ™ontinu—tions —s fun™tions with ™odom—in nat —s our —r˜itr—ry progr—m result typeF Fixpoint typeDenote @t X typeA X Set Xa match t with QQW natD ™hoosing | Nat ⇒ nat | t' "b ⇒ typeDenote t' → nat | t1 BB t2 ⇒ @typeDenote t1 B typeDenote endF t2 A7type e mutu—llyEre™ursive de(nition est—˜lishes the me—nings of progr—ms —nd primopsF Fixpoint progDenote @e X prog typeDenoteA X nat Xa match e with | PHalt n ⇒ n | App f x ⇒ f x | Bind p x ⇒ progDenote @x @primopDenote p AA end with primopDenote t @p X primop match p with | Const n ⇒ n | Plus n1 n2 ⇒ n1 C n2 | Abs | Pair | Fst | Snd endF e ⇒ fun x ⇒ progDenote ⇒ @v1D ⇒ fst v v ⇒ snd v v1 v2 typeDenote t A X typeDenote t Xa @e x A v2 A v Definition Prog Xa ∀ varD prog varF Definition Primop t Xa ∀ varD primop var tF Definition ProgDenote @E X ProgA Xa progDenote @E AF Definition PrimopDenote t @P X Primop t A Xa primopDenote @P AF End CPSF Import Source CPSF „he tr—nsl—tion itself ˜egins with — typeElevel ™ompil—tion fun™tionF ‡e ™h—nge every fun™tion into — ™ontinu—tion whose —rgument is — p—irD ™onsisting of the tr—nsl—tion of the origin—l —rgument —nd of —n expli™it return pointerF Fixpoint cpsType @t X Source.typeA X CPS.type Xa match t with | Nat ⇒ Nat 7™ps | t1 !b t2 ⇒ @cpsType t1 BB @cpsType t2 "bA "bA7™ps end7sour™eF xow we ™—n de(ne the expression tr—nsl—tionF „he not—tion x ←− e1 Y e2 st—nds for tr—nsl—ting sour™eElevel expression e1 D ˜inding x to the g€ƒElevel result of running the tr—nsl—ted progr—mD —nd then ev—lu—ting g€ƒElevel expression e2 in th—t ™ontextF Reserved Notation 4x ←− eI Y eP4 @right associativityD at level UTD e1 at next level AF QRH Section cpsExpF Variable var X CPS.type → TypeF Import SourceF Open Scope cps scopeF ‡e implement — wellEknown v—riety of higherEorderD oneEp—ss g€ƒ tr—nsl—tionF „he tr—nsl—tion cpsExp is p—r—meterized not only ˜y the expression e to tr—nsl—teD ˜ut —lso ˜y — met—Elevel ™ontinu—tionF „he ide— is th—t cpsExp ev—lu—tes the tr—nsl—tion of e —nd ™—lls the ™ontinu—tion on the resultF ‡ith this ™onventionD cpsExp itself is — n—tur—l m—t™h for the not—tion we just reservedF Fixpoint cpsExp t @e X exp @fun t ⇒ var @cpsType t AA t A X @var @cpsType t A → prog var A → prog var Xa match e with | Var v ⇒ fun k ⇒ k v | ⇒ fun ← ¢nY Const n x k ⇒ kx | ⇒ fun x1 ←− e1 Y x2 ←− e2 Y x ← x1 C¢ x2 Y Plus e1 e2 k ⇒ kx | App e1 e2 ⇒ fun k ⇒ ←− e1 Y ←− e2 Y kf ← ’rD k r Y p ← ‘xD kf “Y f dd p e' ⇒ fun k ⇒ | Abs f ← CPS.Abs @var Xa var A @fun x ← 5I p Y kf ← 5P p Y r ←− e' x Y kf dd r AY f x end p ⇒ kf where 4x ←− eI Y eP4 Xa @cpsExp End cpsExpF e1 @fun x ⇒ e2 AAF ƒin™e not—tions do not survive the ™losing of se™tionsD we rede(ne the not—tion —sso™i—ted QRI with cpsExpF Notation 4x ←− eI Y eP4 Xa @cpsExp Implicit Arguments e1 @fun x ⇒ e2 AA X cps scopeF cpsExp ‘var t “F ‡e wr—p cpsExp into the p—r—metri™ version CpsExpD p—ssing —n —lw—ysEh—lt ™ontinu—tion —t the root of the re™ursionF Definition CpsExp @E X Exp Nat A X Prog Xa fun ⇒ cpsExp @E A @PHalt @var Xa AAF Eval compute in CpsExp zeroF a fun var X type → Type ⇒ X Prog x ← BAHY Halt x Eval compute in CpsExp oneF a fun var X type → Type ⇒ X Prog x ← BAIY Halt x Eval compute in CpsExp zpoF a fun var X type → Type ⇒ X Prog x ← BAHY x0 ← BAIY Eval compute in CpsExp app identF a fun var X type → Type ⇒ f ← @’ pD x ← 5I p Y kf ← 5P p Y kf dd x AY x ← BAHY x0 ← BAIY x1 ← @x C¢ x0 AY kf ← @’ rD Halt r AY X Prog x1 p ← @x C¢ ← ‘x1D kf “Y x0 AY Halt x1 f dd Eval compute in CpsExp app ident'F a fun var X type → Type ⇒ f← @’ pD x ← 5I p Y kf ← 5P p Y f← @’ p0D x0 ← 5I p0 Y kf0 ← 5P p0 Y kf1 ← @’ rD kf0 dd r AY p1 ← ‘x0D kf1 “Y x dd p1 AY kf dd f AY f0 ← @’ pD x ← 5I p Y kf ← 5P p Y kf dd x AY kf ← @’ rD x ← BAHY x0 ← BAIY x1 ← @x C¢ x0 AY kf ← @’ r0D Halt r0 AY p ← ‘x1D kf “Y r dd p AY QRP p p X ← ‘f0D kf “Y f dd p Prog Eval compute in aH X nat Eval compute in aI X nat Eval compute in aI X nat Eval compute in aI X nat Eval compute in aI X nat ProgDenote @CpsExp zeroAF ProgDenote @CpsExp oneAF ProgDenote @CpsExp zpoAF ProgDenote @CpsExp app identAF ProgDenote @CpsExp app ident'AF yur m—in indu™tive lemm— —˜out cpsExp needs — notion of ™omp—ti˜ility ˜etween sour™eE level —nd g€ƒElevel v—luesF ‡e express ™omp—ti˜ility with — logical relation Y th—t isD we de(ne — ˜in—ry rel—tion ˜y re™ursion on type stru™tureD —nd the fun™tion ™—se of the rel—tion ™onsiders fun™tions rel—ted if they m—p rel—ted —rguments to rel—ted resultsF sn det—ilD the fun™tion ™—se is slightly more ™ompli™—tedD sin™e it must de—l with our ™ontinu—tionE˜—sed ™—lling ™onventionF Fixpoint lr @t X Source.typeA X Source.typeDenote t → CPS.typeDenote @cpsType t A → Prop Xa match t with | Nat ⇒ fun n1 n2 ⇒ n1 a n2 | t1 !b t2 ⇒ fun f1 f2 ⇒ ∀ x1 x2D lr x1 x2 → ∀ k D ∃ rD f2 @x2D k A a k r ∧ lr @f1 x1 A r end7sour™eF „he m—in lemm— is now e—sily st—ted —nd provedF „he most surprising —spe™t of the st—tement is the presen™e of two versions of the expression to ˜e ™ompiledF „he (rstD e1 D uses — var ™hoi™e th—t m—kes it — suit—˜le —rgument to expDenoteF „he se™ond expressionD e2D uses — var ™hoi™e th—t m—kes its ™ompil—tionD cpsExp e2 kD — suit—˜le —rgument to progDenoteF ‡e use exp equiv to —ssert th—t e1 —nd e2 h—ve the s—me underlying stru™tureD up to — v—ri—˜le ™orresponden™e list GF e hypothesis —˜out G ensures th—t —ll of its p—irs of v—ri—˜les QRQ ˜elong to the logi™—l rel—tion lrF ‡e —lso use lrD in ™on™ert with some qu—nti(™—tion over ™ontinu—tions —nd progr—m resultsD in the ™on™lusion of the lemm—F „he lemm—9s proof should ˜e unsurprising ˜y nowF st uses our st—nd—rd ˜—g of vt—™ tri™ks to help out with qu—nti(er inst—nti—tionY crush —nd eauto ™—n h—ndle the restF Lemma cpsExp correct exp equiv G → @∀ t v1 v2D → ∀ kD ∃ rD X∀ @e1 X Gt exp tA @e2 X exp t AD e1 e2 In @existT t @v1D v2 AA G → lr t v1 v2 A progDenote @cpsExp e2 k A a progDenote @k r A ∧ lr t @expDenote e1 A rF induction IY crush Y repeat @match goal with | ‘ H X ∀ kD ∃ rD progDenote @cpsExp ci k A a ∧ context ‘cpsExp ci cu“ “ ⇒ generalize @H K AY clear H | ‘ ∃ rD progDenote @ c‚A a progDenote @ r A ∧ “ ⇒ ∃R | ‘ t1 X Source.type “⇒ match goal with “⇒ | ‘ Hlr X lr t1 cˆI cˆPD IH X ∀ v1 v2D generalize @IH X1 X2 AY clear IH Y intro IH Y match type of IH with | c€ → ⇒ assert P end end endY crush AY eautoF QedF e simple lemm— est—˜lishes the degener—te ™—se of Lemma vars easy X ∀ t v1 v2D In @existT @fun t0 ⇒ @Source.typeDenote @v1D v2 AA nil → lr t v1 v2F crushF QedF e m—nu—l —ppli™—tion of where we use the —xiom Exp Theorem t0 cpsExp correct equiv F B cpsExp correct9s typeDenote @cpsType hypothesis —˜out GF t0 AA7typeA t proves — version —ppli™—˜le to X ∀ @E X Exp Nat AD @CpsExp E A a ExpDenote EF unfold ProgDenoteD CpsExpD ExpDenote Y introsY generalize @cpsExp correct @e1 Xa E A @e2 Xa E A @Exp equiv A vars easy @PHalt @var Xa AAAY crushF QedF CpsExp correct ProgDenote QRR CpsExpF „his is 19.2 Exercises IF ‡hen in the l—st ™h—pter we implemented ™onst—nt folding for simplyEtyped l—m˜d— ™—l™ulusD it m—y h—ve seemed n—tur—l to try —pplying ˜et— redu™tionsF „his would h—ve ˜een — lot more trou˜le th—n is —pp—rent —t (rstD ˜e™—use we would h—ve needed to ™onvin™e goq th—t our norm—lizing fun™tion —lw—ys termin—tedF st might —lso seem th—t ˜et— redu™tion is — lost ™—use ˜e™—use we h—ve no e'e™tive w—y of su˜stituting in the exp typeY we only m—n—ged to write — su˜stitution fun™tion for the p—r—metri™ Exp typeF „his is not —s ˜ig of — pro˜lem —s it seemsF por inst—n™eD for the l—ngu—ge we ˜uilt ˜y extending simplyEtyped l—m˜d— ™—l™ulus with produ™ts —nd sumsD it —lso —ppe—rs th—t we need su˜stitution for simplifying case expressions whose dis™riminees —re known to ˜e inl or inrD ˜ut the fun™tion is still implement—˜leF por this exer™iseD extend the produ™ts —nd sums ™onst—nt folder from the l—st ™h—pter so th—t it simpli(es case expressions —s wellD ˜y ™he™king if the dis™riminee is — known inl or known inrF elso extend the ™orre™tness theorem to —pply to your new de(nitionF ‰ou will pro˜—˜ly w—nt to —ssert —n —xiom rel—ting to —n expression equiv—len™e rel—tion like the one de(ned in this ™h—pterF eny su™h —xiom should only mention synt—xY it should not mention —ny ™ompil—tion or denot—tion fun™tionsF pollowing the form—t of the —xiom from the l—st ™h—pter is the s—fest ˜et to —void proving — worthless theoremF QRS Chapter 20 Intensional Transformations „he essenti—l ˜ene(t of higherEorder en™odings is th—t v—ri—˜le ™ontexts —re impli™itF ‡e repE resent the o˜je™t l—ngu—ge9s ™ontexts within the met— l—ngu—ge9s ™ontextsF por tr—nsl—tions like g€ƒ ™onversionD this is — ™le—r winD sin™e su™h tr—nsl—tions do not need to keep tr—™k of det—ils of whi™h v—ri—˜les —re —v—il—˜leF yther import—nt tr—nsl—tionsD in™luding ™losure ™onversionD need to work with v—ri—˜les —s (rstE™l—ssD —n—lyz—˜le v—luesF enother ex—mple is ™onversion from €ryeƒ terms to de fruijn termsF „he output form—t m—kes the stru™ture of v—ri—˜les expli™itD so the tr—nsl—tion requires expli™it re—soning —˜out v—ri—˜le identityF sn this ™h—pterD we implement veri(ed tr—nsl—tions in ˜oth dire™tions ˜etween l—st ™h—pter9s €ryeƒ l—ngu—ge —nd — de fruijn version of itF elong the w—yD we show one —ppro—™h to —voiding the use of —xioms with €ryeƒF „he de fruijn version of simplyEtyped l—m˜d— ™—l™ulus is de(ned in — m—nner th—t should ˜e old h—t ˜y nowF Module DeBruijnF Inductive exp X list type → type → Type Xa | Var X ∀ G tD member t G → exp G t | | Const Plus X ∀ GD nat → exp G Nat X ∀ GD exp G Nat → exp G | App X∀ | Abs Nat → exp G G t1 t2D exp G @t1 !b t2 A → exp G t1 → exp G t2 X ∀ G t1 t2D exp @t1 XX G A t2 → exp G @t1 !b Implicit Arguments t2 AF Const ‘G “F QRT Nat Fixpoint expDenote G t @e X exp G t A X hlist match e with v ⇒ fun s ⇒ hget s v | Var | | Const Plus n e1 | App | Abs endF ⇒ fun ⇒ n e2 ⇒ fun s ⇒ typeDenote G expDenote e1 s C → typeDenote t expDenote e2 s ⇒ fun s ⇒ @expDenote e1 s A @expDenote ⇒ fun s x ⇒ expDenote e' @x XXX s A e1 e2 e' Xa e2 s A End DeBruijnF Import Phoas DeBruijnF 20.1 From De Bruijn to PHOAS „he he—rt of the tr—nsl—tion into €ryeƒ is this fun™tion phoasifyD whi™h is p—r—meterized ˜y —n hlist th—t represents — m—pping from de fruijn v—ri—˜les to €ryeƒ v—ri—˜lesF Section phoasifyF Variable var X type → TypeF Fixpoint phoasify G t @e X DeBruijn.exp match e with v ⇒ fun s ⇒ 5@hget s v A | Var | | Const Plus | App | Abs endF n e1 ⇒ fun ⇒ ¢n e2 ⇒ fun s ⇒ phoasify G tA e1 s C¢ hlist var G → Phoas.exp var t Xa phoasify e2 s ⇒ fun s ⇒ phoasify e1 s d phoasify ⇒ fun s ⇒ ’xD phoasify e' @x XXX s A e1 e2 e' X e2 s End phoasifyF Definition Phoasify t @e X DeBruijn.exp nil t A X Phoas.Exp t Xa fun ⇒ phoasify e HNilF st turns out to ˜e trivi—l to est—˜lish the tr—nsl—tion9s soundnessF Theorem phoasify sound X ∀ G t @e X DeBruijn.exp G t A sD Phoas.expDenote @phoasify e s A a DeBruijn.expDenote e sF induction e Y crush Y ext eq Y crushF QedF ‡e ™—n prove th—t —ny output of Phoasify is wellEformedD in — sense strong enough to let us —void —sserting l—st ™h—pter9s —xiomF Print WfF QRU a fun @t X typeA @E X Exp t A ⇒ ∀ var1 var2 X type → TypeD exp X ∀ t X typeD Exp t → Prop Wf Section varsF Variables var1 X var2 equiv nil @E var1 A @E var2 A type → TypeF sn the ™ourse of proving wellEformednessD we will need to tr—nsl—te ˜—™k —nd forth ˜etween the de fruijn —nd €ryeƒ represent—tions of free v—ri—˜le inform—tionF „he fun™tion zip ™om˜ines two de fruijn su˜stitutions into — single €ryeƒ ™ontextF Fixpoint zip G @s1 X hlist var1 G A X hlist var2 G → list {t X type 8 var1 t B match s1 with | HNil ⇒ fun ⇒ nil | HCons v1 s1' ⇒ fun s2 ⇒ existT endF „wo simple lemm—s —˜out zip var2 t }7type @v1D hhd s2 A Xa XX zip s1' @htl s2 A will m—ke useful hintsF Lemma In zip X ∀ t G @s1 X hlist G A s2 @m X member t G AD t @hget s1 mD hget s2 m AA @zip s1 s2 AF In @existT induction s1 Y intro s2 Y dep destruct s2 Y intro m Y dep destruct QedF m Y crushF Lemma unsimpl zip X ∀ t @v1 X var1 t A @v2 X var2 t A G A s2 t' @e1 X Phoas.exp t' A e2D G @s1 X hlist exp equiv @zip @v1 XXX s1 A @v2 XXX s2 AA e1 e2 → exp equiv @existT @v1D v2 A XX zip s1 s2 A e1 e2F trivialF QedF Hint Resolve In zip unsimpl zipF xow it is trivi—l to prove the m—in indu™tive lemm— —˜out wellEformednessF Lemma phoasify wf Hint Constructors induction e Y QedF End varsF ‡e —pply @e X DeBruijn.exp G t A s1 s2D @phoasify e s1 A @phoasify e s2 AF exp equivF X∀ exp equiv @zip s1 Gt s2 A crushF phoasify wf m—nu—lly to prove the (n—l theoremF Theorem Phoasify wf X ∀ t @e X DeBruijn.exp Wf @Phoasify e AF unfold WfD Phoasify Y introsY nil t AD QRV QedF apply @phoasify wf e @HNil @B Xa var1 AA @HNil @B Xa var2 AAAF xowD if we ™ompose Phoasify with —ny tr—nsl—tion over €ryeƒ termsD we ™—n verify the ™omposed tr—nsl—tion without relying on —xiomsF „he ™on™lusion of Phoasify wf is ro˜ustly useful in verifying — wide v—riety of tr—nsl—tions th—t use — wide v—riety of var inst—nti—tionsF 20.2 From PHOAS to De Bruijn „he tr—nsl—tion to de fruijn terms is more involvedF ‡e will essenti—lly ˜e inst—nti—ting —nd using — €ryeƒ term following — ™onvention isomorphi™ to de Bruijn levelsD whi™h —re di'erent from the de fruijn indi™es th—t we h—ve tre—ted so f—rF ‡ith levelsD — given ˜ound v—ri—˜le is referred to ˜y the s—me num˜er —t e—™h of its o™™urren™esF sn —ny expressionD the ˜inders th—t —re not en™losed ˜y other ˜inders —re —ssigned level HD — ˜inder with just one en™losing ˜inder is —ssigned level ID —nd so onF „he uniformity of referen™es to —ny ˜inder will ˜e ™riti™—l to our tr—nsl—tionD sin™e it is ™omp—ti˜le with the p—ttern of (lling in —ll of — €ryeƒ v—ri—˜le9s lo™—tions —t on™e ˜y —pplying — fun™tionF ‡e implement — spe™i—l lookup fun™tionD for re—ding — num˜ered v—ri—˜le9s type out of — de fruijn level typing ™ontextF „he l—st v—ri—˜le in the list is t—ken to h—ve level HD the nextEtoEl—st level ID —nd so onF Fixpoint lookup @ts X list typeA @n X natA X option type Xa match ts with | nil ⇒ None | t XX ts' ⇒ if eq nat dec n @length ts' A then Some t else endF Infix 4554 Xa lookup @left associativityD at level lookup ts' n IAF ‡ith lookupD we ™—n de(ne — notion of wellEformedness for €ryeƒ expressions th—t we —re tre—ting —™™ording to the de fruijn level ™onventionF Fixpoint wf @ts X list typeA t @e X Phoas.exp @fun match e with | Phoas.Var t n ⇒ ts 55 n a Some t | Phoas.Const ⇒ True | Phoas.Plus e1 e2 ⇒ wf ts e1 ∧ wf ts e2 | Phoas.App e1 e2 ⇒ wf ts e1 ∧ wf ts e2 | Phoas.Abs t1 e1 ⇒ wf @t1 XX ts A @e1 @length endF ⇒ natA t A X Prop Xa ts AA 20.2.1 Connecting Notions of Well-Formedness yur (rst order of ˜usiness now is to prove th—t —ny wellEformed Exp inst—nti—tes to — wellE formed de fruijn level expressionF ‡e st—rt ˜y ™h—r—™terizingD —s — fun™tion of de fruijn QRW level ™ontextsD the set of €ryeƒ ™ontexts th—t will o™™ur in the proofD where we will ˜e indu™ting over —n exp equiv deriv—tionF Fixpoint makeG @ts X list typeA X list { t X type 8 nat B nat }7type Xa match ts with | nil ⇒ nil | t XX ts' ⇒ existT t @length ts'D length ts' A XX makeG ts' endF xow we prove — ™onne™tion ˜etween lookup —nd makeGD ˜y w—y of — lemm— —˜out lookupF Opaque eq nat decF Hint Extern I @ ≥ A ⇒ omegaF Lemma lookup contra' X ∀ t ts nD ts 55 n a Some t → n ≥ length ts → FalseF induction ts Y crush Y match goal with | ‘ X context ‘if ci then endY eautoF QedF else “ “ ⇒ destruct E Y crush Lemma lookup contra X ∀ t tsD ts 55 @length ts A a Some t → FalseF introsY eapply lookup contra'Y eautoF QedF Hint Resolve lookup contraF Lemma lookup In X ∀ t v1 v2 tsD X type ⇒ @nat B natA7typeA t @v1D v2 AA @makeG In @existT @fun → ts 55 v1 a Some tF induction ts Y crush Y match goal with | ‘ context ‘if ci then else “ “ ⇒ destruct E Y crush endY elimtype FalseY eautoF QedF Hint Resolve lookup InF ‡e ™—n prove the m—in indu™tive lemm— ˜y indu™tion over Hint Extern I @ XX Lemma Wf wf ' X∀ exp equiv G →∀ tsD G ts A a a G t e1 makeG @e2 X @ XX AA ⇒ reflexivityF Phoas.exp @fun ⇒ natA t AD e1 e2 makeG ts QSH exp equiv deriv—tionsF → wf ts e1F induction IY crush Y eautoF QedF Lemma Wf wf X∀ t @E X Exp t AD Wf E → wf nil @E @fun ⇒ natAAF introsY eapply Wf wf 'Y eautoF QedF 20.2.2 The Translation smplementing the tr—nsl—tion itself will require some proofsF yur m—in fun™tion dbify will t—ke wf proofs —s —rgumentsD —nd these proofs will ˜e ™riti™—l to ™onstru™ting de fruijn index termsF pirstD we use congruence to prove two ˜—si™ theorems —˜out optionsF Theorem None Some X ∀ None a Some x → FalseF congruenceF QedF T @x X Theorem T @x Some Some a a yF Some x X∀ T AD y X T AD Some y →x congruenceF QedF ‡e ™—n use these theorems to implement makeVarD whi™h tr—nsl—tes — proof —˜out into — de fruijn index v—ri—˜le with — ™losely rel—ted typeF Fixpoint makeVar {ts n t } X ts 55 n a Some t → member t ts Xa match ts with | nil ⇒ fun Heq ⇒ match None Some Heq with end | t' XX ts' ⇒ if eq nat dec n @length ts' A as b return @if b then else A a then fun Heq ⇒ match Some Some Heq with re equal ⇒ HFirst end else fun Heq ⇒ HNext @makeVar Heq A endF lookup → xow dbify is str—ightforw—rd to de(neF ‡e use the fun™tions proj1 —nd proj2 to de™ompose proofs of ™onjun™tionsF Fixpoint dbify {ts } t @e X Phoas.exp @fun ⇒ natA t A X wf ts e → DeBruijn.exp match e in Phoas.exp t return wf ts e → DeBruijn.exp ts t with | Phoas.Var n ⇒ fun wf ⇒ DeBruijn.Var @makeVar wfA | Phoas.Const n ⇒ fun ⇒ DeBruijn.Const n QSI ts t Xa | DeBruijn.Plus | ⇒ fun wf ⇒ @dbify e1 @proj1 wfAA @dbify Phoas.Plus e1 e2 e2 @proj2 wfAA ⇒ fun wf ⇒ @dbify e1 @proj1 wfAA @dbify e2 @proj2 wfAA e1 ⇒ fun wf ⇒ DeBruijn.Abs @dbify @e1 @length e1 e2 Phoas.App DeBruijn.App | Phoas.Abs endF ts AA wfA ‡e de(ne the p—r—metri™ tr—nsl—tion Dbify ˜y —ppe—ling to the wellEformedness tr—nsl—E tion theorem Wf wf th—t we proved e—rlierF Definition Dbify dbify @E A @Wf t @E X Phoas.Exp t A wf W AF @W X Wf E A X DeBruijn.exp nil t Xa „o prove soundnessD it is helpful to ™l—ssify — set of ™ontexts whi™h depends on — de fruijn index su˜stitutionF Fixpoint makeG' ts @s X hlist typeDenote ts A X list { t X type 8 nat B typeDenote t }7type Xa match s with | HNil ⇒ nil | HCons ts' v s' ⇒ existT @length ts'D v A XX endF makeG' s' ‡e prove —n —n—logous lemm— to the one we proved ™onne™ting timeD we ™onne™t makeG' —nd hgetF Lemma In makeG' contra' X ∀ t v2 ts @s X hlist t @nD v2 AA @makeG' s A In @existT → n ≥ length ts → FalseF induction s Y crush Y eautoF QedF Lemma In makeG' contra X ∀ t v2 ts @s X hlist In @existT t @length tsD v2 AA @makeG' s A → FalseF introsY eapply In makeG' contra'Y eautoF QedF Hint Resolve ts A nD ts AD In makeG' contraF Lemma In makeG' X ∀ t v1 v2 ts s @w X ts 55 v1 a Some t AD In @existT t @v1D v2 AA @makeG' s A → hget s @makeVar w A a v2F induction s Y crush Y match goal with | ‘ context ‘if ci then else “ “ ⇒ destruct E Y crush endY QSP makeG —nd lookupF „his QedF repeat match goal with | ‘ context ‘match cpf with re equal ⇒ rewrite @UIP re pf A endY crush Y elimtype FalseY eautoF Hint Resolve end“ “ ⇒ In makeG'F xow the m—in indu™tive lemm— ™—n ˜e st—ted —nd proved simplyF Lemma X∀ dbify sound exp equiv G →∀ ts G a Gt @e1 X Phoas.exp tA @e2 X Phoas.exp t AD e1 e2 @w X wf ts e1 A sD makeG' s → DeBruijn.expDenote @dbify e1 w A induction IY crush Y ext eq Y crushF QedF s a Phoas.expDenote e2F sn the usu—l w—yD we wr—p dbify sound into the (n—l soundness theoremD form—lly est—˜E lishing the expressive equiv—len™e of €ryeƒ —nd de fruijn index termsF Theorem X ∀ t @E X Exp t A @W X Wf E AD DeBruijn.expDenote @Dbify W A HNil a Phoas.ExpDenote EF unfold DbifyD Phoas.ExpDenote Y introsY eapply dbify soundY eautoF QedF Dbify sound QSQ Chapter 21 Higher-Order Operational Semantics „he l—st few ™h—pters h—ve shown how €ryeƒ ™—n m—ke it rel—tively p—inless to re—son —˜out progr—m tr—nsform—tionsF i—™h of our ex—mple l—ngu—ges so f—r h—s h—d — sem—nti™s th—t is e—sy to implement with —n interpreter in q—llin—F ƒin™e q—llin— is designed to rule out nonEtermin—tionD we ™—nnot hope to give interpreterE˜—sed sem—nti™s to „uringE™omplete progr—mming l—ngu—gesF p—lling ˜—™k on st—nd—rd oper—tion—l sem—nti™s le—ves us with the old ˜ure—u™r—ti™ ™on™erns —˜out ™—ptureE—voiding su˜stitutionF g—n we en™ode „uringE ™ompleteD higherEorder l—ngu—ges in goq without s—™ri(™ing the —dv—nt—ges of higherEorder en™odingc eny —ppro—™h th—t —pplies to ˜—si™ untyped l—m˜d— ™—l™ulus is likely to extend to most o˜je™t l—ngu—ges of interestF ‡e ™—n —ttempt the 4o˜vious4 w—y of equipping — €ryeƒ de(nition for use in —n oper—tion—l sem—nti™sD without mentioning su˜stitution expli™itlyF ƒpe™i(™—llyD we try to work with expressions with var inst—nti—ted with — type of v—luesF Section expF Variable var X TypeF Inductive exp X Type Xa | Var X var → exp | App X exp → exp → exp | Abs X @var → expA → expF End expF Inductive val X Type Xa | VAbs X @val → exp valA → valF Error X Non strictly positive 4@v—l → exp v—lA → v—l4F occurrence of 4v—l4 in ‡e would like to represent v—lues @whi™h —re —ll fun™tion —˜str—™tionsA —s fun™tions from v—ri—˜les to expressionsD where we represent v—ri—˜les —s the s—me v—lue type th—t we —re de(ningF „h—t w—yD — v—lue ™—n ˜e su˜stituted in — fun™tion ˜ody simply ˜y —pplying the QSR ˜ody to the v—lueF …nfortun—telyD the positivity restri™tion reje™ts this de(nitionD for mu™h the s—me re—son th—t we ™ould not use the ™l—ssi™—l ryeƒ en™odingF ‡e ™—n try —n —ltern—te —ppro—™h ˜—sed on de(ning val like — usu—l ™l—ss of synt—xF Section valF Variable var X TypeF Inductive val X Type Xa | VAbs X @var → exp var A → valF End valF xow the puzzle is how to write the type of —n expression whose v—ri—˜les —re represented —s v—luesF ‡e would like to ˜e —˜le to write — re™ursive de(nition like this oneX Fixpoint expV Xa exp @val expV AF yf ™ourseD this kind of de(nition is not stru™tur—lly re™ursiveD so goq will not —llow itF qetting 4su˜stitution for free4 seems to require some simil—r kind of selfEreferen™eF sn this ™h—pterD we will ™onsider —n —ltern—te t—ke on the pro˜lemF ‡e —dd — level of indiE re™tionD introdu™ing more expli™it synt—x to ˜re—k the ™y™le in type de(nitionsF ƒpe™i(™—llyD we represent fun™tion v—lues —s num˜ers th—t index into — closure heap th—t our oper—tion—l sem—nti™s m—int—ins —longside the expression ˜eing ev—lu—tedF 21.1 Closure Heaps „he essen™e of the te™hnique is to store fun™tion ˜odies in lists th—t —re extended monotonE i™—lly —s fun™tion —˜str—™tions —re ev—lu—tedF ‡e ™—n de(ne — set of fun™tions —nd theorems th—t implement the ™ore fun™tion—lity generi™—llyF Section lookupF Variable A X TypeF ‡e st—rt with — lookup fun™tion th—t gener—lizes l—st ™h—pter9s fun™tion of the s—me n—meF st sele™ts the element —t — p—rti™ul—r position in — listD where we num˜er the elements st—rting from the end of the listD so th—t prepending new elements does not ™h—nge the indi™es of old elementsF Fixpoint lookup @ls X list AA @n X natA X option A Xa match ls with | nil ⇒ None | v XX ls' ⇒ if eq nat dec n @length ls' A then Some endF Infix 4554 Xa ls1 lookup @left associativityD at level v else lookup ls' n IAF „he se™ond of our two de(nitions expresses when one list extends —notherF ‡e will write ls2 to indi™—te th—t ls1 ™ould evolve into ls2 Y th—t isD ls1 is — su0x of ls2F QSS Definition extends @ls1 ls2 X list AA Xa ∃ lsD ls2 a ls CC Infix 4 4 Xa extends @no associativityD at level VHAF ‡e prove —nd —dd —s hints — few ˜—si™ theorems —˜out Theorem lookup1 X ∀ x lsD @x XX ls A 55 @length ls A a Some xF crush Y match goal with | ‘ context ‘if ci then endY crushF QedF Theorem extends re X ∀ lsD ∃ nilY reflexivityF QedF ls ls1F lookup else “ “ ⇒ destruct —nd E lsF Theorem extends1 X ∀ v lsD ls v XX lsF introsY ∃ @v XX nilAY reflexivityF QedF Theorem ls1 extends trans X∀ ls1 ls2 ls3D ls2 → ls2 ls3 → ls1 ls3F intros c c c ‘l1 c“ ‘l2 c“Y ∃ @l2 CC QedF Lemma lookup contra X ∀ n v lsD ls 55 n a Some v → n ≥ length ls → FalseF induction ls Y crush Y match goal with | ‘ X context ‘if ci then endY crushF QedF Hint Resolve Theorem ls1 l1 AY crushF else “ “ ⇒ destruct lookup contraF extends lookup X∀ ls1 ls2 n vD ls2 → ls1 55 n a Some v → ls2 55 n a Some vF intros c c c c ‘l c“Y crush Y induction l Y crush Y match goal with | ‘ context ‘if ci then else “ “ ⇒ destruct endY crush Y elimtype FalseY eautoF QedF QST E E extendsF End lookupF Infix 4554 Xa lookup @left associativityD at level IAF Infix 4 4 Xa extends @no associativityD at level VHAF Hint Resolve lookup1 extends re extends1 extends trans extends lookupF ‡e —re de—ling expli™itly with the nittyEgritty of ™losure he—psF ‡hy is this ˜etter th—n de—ling with the nittyEgritty of v—ri—˜lesc „he in™onvenien™e of modeling l—m˜d— ™—l™ulusE style ˜inders ™omes from the presen™e of nested s™opesF €rogr—m ev—lu—tion will only involve one global ™losure he—pF elsoD the short development th—t we just (nished ™—n ˜e reused for m—ny di'erent o˜je™t l—ngu—gesF xone of these de(nitions or theorems needs to ˜e redone to h—ndle spe™i(™ o˜je™t l—ngu—ge fe—turesF fy —dding the theorems —s hintsD no perEo˜je™tE l—ngu—ge e'ort is required to —pply the ™riti™—l f—™ts —s neededF 21.2 Languages and Translation por the rest of this ™h—pterD we will ™onsider the ex—mple of g€ƒ tr—nsl—tion for untyped l—m˜d— ™—l™ulus with ˜oole—n ™onst—ntsF st is ™onvenient to in™lude these ™onst—ntsD ˜e™—use their presen™e m—kes it e—sy to st—te — (n—l tr—nsl—tion ™orre™tness theoremF Module SourceF ‡e de(ne the synt—x of sour™e expressions in our usu—l w—yF Section expF Variable var X TypeF Inductive exp X Type Xa | Var X var → exp | App X exp → exp → exp | Abs X @var → expA → exp | Bool X bool → expF End expF Implicit Arguments Bool ‘var “F Definition varD Exp Xa ∀ exp varF ‡e will implement — ˜igEstep oper—tion—l sem—nti™sD where expressions —re m—pped to v—luesF e v—lue is either — fun™tion or — ˜oole—nF ‡e represent — fun™tion —s — num˜er th—t will ˜e interpreted —s —n index into the glo˜—l ™losure he—pF Inductive val X Set Xa | VFun X nat → val | VBool X bool → valF e ™losureD thenD follows the usu—l represent—tion of fun™tion —˜str—™tion ˜odiesD where we represent v—ri—˜les —s v—luesF Definition closure Xa val → exp valF QSU Definition closures list closureF Xa yur ev—lu—tion rel—tion h—s four pl—™esF ‡e m—p —n initi—l ™losure he—p —nd —n expression into — (n—l ™losure he—p —nd — v—lueF „he interesting ™—ses —re for AbsD where we push the ˜ody onto the ™losure he—pY —nd for AppD where we perform — lookup in — ™losure he—pD to (nd the proper fun™tion ˜ody to exe™ute nextF Inductive eval X | EvVar X ∀ cs vD eval cs @Var v A | EvApp | cs2 → exp val → closures → val → Prop Xa cs v cs1 e1 e2 cs2 v1 c cs3 v2 cs4 v3D eval cs1 e1 → eval cs2 → → → | X∀ closures 55 cs2 @VFun v1 A e2 cs3 v2 v1 a Some c eval cs3 @c v2 A cs4 v3 eval cs1 @App e1 e2 A cs4 X ∀ cs cD cs @Abs c A @c XX v3 EvAbs eval X ∀ cs bD cs @Bool b A cs A @VFun @length cs AA EvBool eval cs @VBool b AF e simple wr—pper produ™es —n ev—lu—tion rel—tion suit—˜le for use on the m—in expression type ExpF Definition Eval @cs1 X eval cs1 @E A cs2 vF closuresA @E X ExpA @cs2 X closuresA @v X valA Xa „o prove our tr—nsl—tion9s ™orre™tnessD we will need the usu—l notions of expression equivE —len™e —nd wellEformednessF Section exp equivF Variables var1 var2 X TypeF Inductive exp equiv X list @var1 B var2 A → exp | EqVar X ∀ G v1 v2D In @v1D v2 A G → exp equiv G @Var v1 A @Var v2 A | | EqApp X∀ var1 G f1 x1 f2 x2D exp equiv G f1 f2 → exp equiv G x1 x2 → exp equiv G @App f1 x1 A @App f2 x2 A X ∀ G f1 f2D @∀ v1 v2D exp equiv @@v1D v2 A XX G A @f1 → exp equiv G @Abs f1 A @Abs f2 A EqAbs QSV v1 A @f2 v2 AA → exp var2 → Prop Xa | End EqBool X∀ G bD exp equiv G @Bool b A @Bool b AF exp equivF Definition End SourceF Wf @E X ExpA Xa ∀ var1 var2D exp equiv nil @E var1 A @E var2 AF yur t—rget l—ngu—ge ™—n ˜e de(ned without introdu™ing —ny —ddition—l tri™ksF Module CPSF Section expF Variable var X TypeF Inductive prog X Type Xa | Halt X var → prog | App X var → var → prog | Bind X primop → @var → progA → prog with primop X Type Xa | Abs X @var → progA → primop | Bool X bool → primop | Pair X var → var → primop | Fst X var → primop | Snd X var → primopF End expF Implicit Arguments Bool ‘var “F Notation 4x ← p Y e4 Xa @Bind p @fun x ⇒ e AA @right associativityD at level UTD p at next level AF Definition Definition Xa ∀ varD prog varF Primop Xa ∀ varD primop Prog varF Inductive val X Type Xa | VFun X nat → val | VBool X bool → val | VPair X val → val → valF Definition closure Xa val → prog valF Definition closures Xa list closureF Inductive eval X closures → prog val → val → Prop Xa | EvHalt X ∀ cs vD eval cs @Halt v A v | EvApp X∀ cs n v2 c v3D QSW 55 cs → → | eval eval EvBind a Some c cs @c v2 A v3 cs @App @VFun n A n X∀ v2 A v3 cs1 p e cs2 v1 v2D evalP cs1 p cs2 v1 → eval cs2 @e v1 A v2 → eval cs1 @Bind p e A v2 with evalP X closures → primop val → closures → val → Prop Xa | EvAbs X ∀ cs cD evalP cs @Abs c A @c XX cs A @VFun @length cs AA | | | | X∀ EvPair cs v1 v2D evalP cs @Pair v1 X∀ EvFst cs v1 v2D v2 A cs evalP cs @Fst @VPair v1 EvSnd X∀ cs v1 v2D evalP cs @Snd @VPair v1 EvBool X∀ @VPair v1 v2 A v2 AA cs v1 v2 AA cs v2 cs bD evalP cs @Bool b A cs @VBool b AF Definition Eval @cs X End CPSF Import closuresA @P X ProgA @v X valA Xa eval cs @P A vF Source CPSF pin—llyD we de(ne — g€ƒ tr—nsl—tion in the s—me w—y —s in our previous ex—mple for simplyEtyped l—m˜d— ™—l™ulusF Reserved Notation 4x ←− eI Y eP4 @right associativityD Section cpsExpF Variable var X TypeF Import SourceF Fixpoint cpsExp @e X exp var A X @var → prog var A → prog var Xa match e with | Var v ⇒ fun k ⇒ k v | ⇒ fun k ⇒ ←− e1 Y x ←− e2 Y kf ← CPS.Abs k Y p ← Pair x kf Y App e1 e2 f QTH at level UTD e1 at next level AF CPS.App f p | Abs e' f ⇒ fun ⇒ k CPS.Abs @var Xa ← Fst p Y kf ← Snd p Y r ←− e' x Y CPS.App kf r AY ← var A @fun p ⇒ x kf | Bool b x end ← ⇒ fun k CPS.Bool ⇒ bY kx where 4x ←− eI Y eP4 Xa @cpsExp End cpsExpF e1 @fun Notation 4x ←− eI Y eP4 Xa @cpsExp e1 Definition Xa fun CpsExp @E X ExpA X Prog @fun x x ⇒ ⇒ ⇒ e2 AAF e2 AAF cpsExp @E A @Halt @var Xa AAF 21.3 Correctness Proof yur proof for simplyEtyped l—m˜d— ™—l™ulus relied on — logi™—l rel—tion to st—te the key indu™tion hypothesisF ƒin™e logi™—l rel—tions pro™eed ˜y re™ursion on type stru™tureD we ™—nnot —pply them dire™tly in —n untyped settingF snste—dD we will use —n indu™tive judgment to rel—te sour™eElevel —nd g€ƒElevel v—luesF pirstD it is helpful to de(ne —n —˜˜revi—tion for the ™ompiled version of — fun™tion ˜odyF Definition cpsFunc fun p X var ⇒ x ← Fst p Y kf ← Snd p Y r ←− e' x Y CPS.App kf rF var @e' X var → Source.exp var A Xa xow we ™—n de(ne our ™orre™tness rel—tion crD whi™h is p—r—meterized ˜y sour™eElevel —nd g€ƒElevel ™losure he—psF Section crF Variable Variable Import s1 s2 X X Source.closuresF CPS.closuresF SourceF ynly equ—l ˜oole—ns —re rel—tedF por two fun™tion —ddresses l1 —nd l2 to ˜e rel—tedD they must point to v—lid fun™tions in their respe™tive ™losure he—psF „he —ddress l1 must point QTI to — fun™tion f1D —nd l2 must point to the result of ™ompiling fun™tion f2F purtherD f1 —nd f2 must ˜e equiv—lent synt—™ti™—lly in some v—ri—˜le environment GD —nd every v—ri—˜le p—ir in G must itself ˜elong to the rel—tion we —re de(ningF Inductive cr X Source.val → CPS.val → Prop Xa | CrBool X ∀ bD cr @Source.VBool b A @CPS.VBool b A X ∀ l1 l2 G f1 f2D @∀ x1 x2D exp equiv @@x1D x2 A XX G A @f1 → @∀ x1 x2D In @x1D x2 A G → cr x1 x2 A → s1 55 l1 a Some f1 → s2 55 l2 a Some @cpsFunc f2 A → cr @Source.VFun l1 A @CPS.VFun l2 AF End crF | CrFun Notation 4sI 8 sP |! vI ££ vP4 Xa @cr Hint x1 A @f2 s1 s2 v1 v2 A x2 AA @no associativityD at level UHAF Constructors crF „o prove our m—in lemm—D it will ˜e useful to know th—t sour™eElevel ev—lu—tion never removes old ™losures from — ™losure he—pF Lemma eval monotone Source.eval cs1 X∀ cs1 e cs2 vD e cs2 v → cs1 cs2F induction IY crush Y eautoF QedF purtherD cr ™ontinues to hold when its ™losure he—p —rguments —re evolved in leg—l w—ysF Lemma cs1 cr monotone X∀ cs1 cs2 cs1' cs2'D cs1' → cs2 cs2' → ∀ v1 v2D cs1 8 cs2 |! v1 ££ → cs1' 8 cs2' |! v1 ££ v2F induction QY crush Y eautoF QedF Hint Resolve v2 eval monotone cr monotoneF ‡e st—te — trivi—l f—™t —˜out the v—lidity of v—ri—˜le environmentsD so th—t we m—y —dd this f—™t —s — hint th—t eauto will —pplyF Lemma push X ∀ G s1 s2 v1' v2'D @∀ v1 v2D In @v1D v2 A G → s1 8 s2 |! v1 ££ v2 A → s1 8 s2 |! v1' ££ v2' → @∀ v1 v2D @v1'D v2' A a @v1D v2 A ∨ In @v1D v2 A G → crushF QedF QTP s1 8 s2 |! v1 ££ v2 AF Hint Resolve pushF yur (n—l prep—r—tion for the m—in lemm— involves —dding e'e™tive hints —˜out the g€ƒ l—ngu—ge9s oper—tion—l sem—nti™sF „he following t—™ti™ performs one step of ev—lu—tionF st uses the vt—™ ™ode eval hnf in e to ™ompute the head normal form of eD where the he—d norm—l form of —n expression in —n indu™tive type is —n —ppli™—tion of one of th—t indu™tive type9s ™onstru™torsF „he (n—l line ˜elow uses solve to ensure th—t we only t—ke — Bind step if — full ev—lu—tion deriv—tion for the —sso™i—ted primop m—y ˜e found ˜efore pro™eedingF Ltac evalOne Xa match goal with | ‘ CPS.eval c™s ce cv “ ⇒ let e Xa eval hnf in e in change @CPS.eval cs e v AY econstructor Y ‘ solve ‘ eauto “ | “ endF por primopsD we rely on eauto9s usu—l —ppro—™hF por go—ls th—t ev—lu—te progr—msD we inste—d —sk to tre—t one or more —ppli™—tions of evalOne —s — single stepD whi™h helps us —void p—ssing eauto —n ex™essively l—rge ˜ound on proof tree depthF Hint Constructors evalPF Hint Extern I @CPS.eval A⇒ evalOne Y repeat evalOneF „he (n—l lemm— pro™eeds ˜y indu™tion on —n ev—lu—tion deriv—tion for —n expression e1 th—t is equiv—lent to some e2 in some environment GF en initi—l ™losure he—p for e—™h l—ngu—ge is qu—nti(ed overD su™h th—t —ll v—ri—˜le p—irs in G —re ™omp—ti˜leF „he lemm—9s ™on™lusion —pplies to —n —r˜itr—ry ™ontinu—tion kD —sserting th—t — (n—l g€ƒElevel ™losure he—p s2 —nd — g€ƒElevel progr—m result v—lue r2 existF „hree ™onditions est—˜lish th—t s2 —nd r2 —re ™hosen properlyX iv—lu—tion of e2 9s ™omE pil—tion with ™ontinu—tion k must ˜e equiv—lent to ev—lu—tion of k r2F „he origin—l progr—m result r1 must ˜e ™omp—ti˜le with r2 in the (n—l ™losure he—psF pin—llyD s2' must ˜e — proper evolution of the origin—l g€ƒElevel he—p s2 F Lemma cpsExp correct X∀ s1 e1 s1' r1D Source.eval s1 e1 s1' r1 → ∀ G @e2 X exp CPS.valAD exp equiv G e1 e2 → ∀ s2D @∀ v1 v2D In @v1D v2 A G → s1 8 → ∀ kD ∃ s2'D ∃ r2D @∀ rD CPS.eval s2' @k r2 A r → CPS.eval s2 @cpsExp e2 ∧ s1' 8 s2' |! r1 ££ r2 ∧ s2 s2'F s2 |! v1 ££ v2 A kA rA „he proof s™ript follows our st—nd—rd —ppro—™hF sts m—in loop —pplies three hintsF pirstD we perform inversion on —ny deriv—tion of equiv—len™e ˜etween — sour™eElevel fun™tion v—lue QTQ —nd some other v—lueF ƒe™ondD we elimin—te redund—nt equ—lity hypothesesF pin—llyD we look for opportunities to inst—nti—te indu™tive hypothesesF ‡e identify —n sr ˜y its synt—™ti™ formD noting the expression E th—t it —pplies toF st is import—nt to inst—nti—te sres in the right orderD sin™e existenti—llyEqu—nti(ed v—ri—˜les in the ™on™lusion of one sr m—y need to ˜e used in inst—nti—ting the univers—l qu—nti(ers of — di'erent srF „husD we perform — qui™k ™he™k to fail I if the sr we found —pplies to —n expression th—t w—s ev—lu—ted —fter —nother expression E' whose sr we did not yet inst—nti—teF „he )ow of ™losure he—ps through sour™eElevel ev—lu—tion is used to implement the ™he™kF sf the hypothesis H is indeed the right sr to h—ndle nextD we use the guess t—™ti™ to guess v—lues for its univers—l qu—nti(ers —nd prove its hypotheses with eautoF „his t—™ti™ is very simil—r to inster from gh—pter IPF st t—kes two —rgumentsX the (rst is — v—lue to use for —ny properlyEtyped univers—l qu—nti(erD —nd the se™ond is the hypothesis to inst—nti—teF „he (n—l inner match dedu™es if we —re —t the point of exe™uting the ˜ody of — ™—lled fun™tionF sf soD we help guess ˜y s—ying th—t the initi—l ™losure he—p will ˜e the ™urrent ™losure he—p cs extended with the ™urrent ™ontinu—tion kF sn —ll other ™—sesD guess is sm—rt enough to oper—te —loneF induction IY inversion IY crush Y repeat @match goal with “ ⇒ inversion H Y clear H | ‘ H X 8 |! Source.VFun ££ “ ⇒ rewrite H1 in H2 Y clear H1 | ‘ H1 X ci a D H2 X ci a | ‘ H X ∀ G e2D exp equiv G ci e2 → “⇒ match goal with D X Source.eval ci9 cgƒ D | ‘ X Source.eval cgƒ E X ∀ G e2D exp equiv G ci9 e2 → “ ⇒ fail I | ⇒ match goal with | ‘ k X val → prog valD X 8 c™s |! ££ D X context ‘VFun“ “⇒ guess @k XX cs A H | ⇒ guess tt H end end endY crush AY eauto IQF QedF „he (n—l theorem follows e—sily from this lemm—F Theorem CpsExp correct Source.Eval nil E cs X∀ E cs bD @Source.VBool b A → Wf E → CPS.Eval nil @CpsExp E A @CPS.VBool b AF Hint Constructors CPS.evalF unfold Source.EvalD CPS.EvalD CpsExp Y intros c c c QTR H1 H2 Y QedF generalize @cpsExp correct H1 @H2 A @s2 Xa nilA pf ⇒ match pf with endA @Halt @var Xa AAAY @fun match goal with | ‘ H X 8 |! ££ “ ⇒ inversion H endY crushF QTS crush Y ...
View Full Document

Ask a homework question - tutors are online