Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Adam Chlipala
February 3, 2010
gopyright edm ghlipl PHHVEPHHWF his work is liensed under gretive gommons ettriutionExonommerilExo herivtive orks QFH nported vienseF he liense text is ville tX
http://creativecommons.org/licenses/by-nc-nd/3.0/
Contents
1 Introduction
IFI IFP hene 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 fsed on righerEyrder puntionl rogrmming vnguge 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 isyEtoEghek uernel roof vnguge F F F F F F F F F F IFPFR gonvenient rogrmmle roof eutomtion F F F F F F F F IFPFS roof y e)etion 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 hependentlyEyped vngugec F F F F F F F F ingineering with roof essistnt 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 ghpter oure 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 erithmeti ixpressions yver xturl xumers PFIFI oure vnguge F F F F F F F F F F F F PFIFP rget vnguge F F F F F F F F F F F F PFIFQ rnsltion F F F F F F F F F F F F F F F PFIFR rnsltion gorretness 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 oure vnguge F F F F F F F F F F F F PFPFP rget vnguge F F F F F F F F F F F F PFPFQ rnsltion F F F F F F F F F F F F F F F PFPFR rnsltion gorretness F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F U V V V W W W IH II II IP IQ
14
PFP
IS IS IU IW IW PT PT QH QP QR
36
37
QU RH RR
QFR QFS QFT QFU QFV QFW RFI RFP RFQ RFR RFS RFT SFI SFP SFQ SFR
wutully sndutive 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 sndutive ypes F F F F F F F wnul roofs eout gonstrutors ixerises F F F F F F F F F F F F F F F
F F F F F F
F F F F F F
F F F F F F
F F F F F F F F F F F F
F F F F F F F F F F F F
F F F F F F F F F F F F
F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F
F F F F F F F F 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
4 Inductive Predicates
ropositionl vogi F F F F F F F F F F F F ht hoes st wen to fe gonstrutivec pirstEyrder vogi F F F F F F F F F F F F F redites with smpliit iqulity F F F F eursive redites F F F F F F F F F F F ixerises F F F F F F F F F F F F F F F F F F
62
TQ TV TW UH UP UV VQ VT WH WP
gomputing with sn(nite ht 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 xonEerminting rogrms ixerises F F F F F F F F F F F F F F F F F F F F F F
82
93
WR IHH IHP IHQ IHR IHV
94
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 hependentlyEyped edEflk rees F F e gerti(ed egulr ixpression wther ixerises F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F snterpreter F F F F F F F Q F F F F
110
wore vengthEsndexed vists reterogeneous vists F F F F VFPFI e vmd glulus eursive ype he(nitions
135
VFR VFS VFT WFI WFP WFQ WFR WFS WFT WFU
ht trutures s sndex puntions F VFRFI enother snterpreter ixmple ghoosing fetween epresenttions F ixerises F F F F F F F F F F F F F F F F he he(nitionl iqulity F F F F F reterogeneous vists evisited F F F ypeEgsts in heorem ttements reterogeneous iqulity F F F F F F F iquivlene of iqulity exioms F F iqulity of puntions F F F F F F F F ixerises F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F
F F F F F F F F F F F
F F F F F F F F F F F
F F F F F F F F F F F
F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F F F F F F F F F F F F F F F
155
ISS ISU ITP ITU ITW IUI IUP
10 Generic Programming
IHFI e)eting httype he(nitions F F F F F F F F IHFP eursive he(nitions F F F F F F F F F F F F F F IHFPFI rettyErinting F F F F F F F F F F F F F IHFPFP wpping F F F F F F F F F F F F F F F F F IHFQ roving heorems out eursive 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
175
IIFI he Type rierrhy F F F F F F F F IIFIFI sndutive 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 fsis F F F F F F F F F IIFQFP exioms of ghoie F F F F F IIFQFQ exioms nd gomputtion
191
210
211
PII PIP PIS PPP PPR PQH
13 Proof by Reection
IQFI IQFP IQFQ IQFR IQFS IRFI IRFP IRFQ IRFR
roving ivenness F F F F F F F F F F F F F F F F F F F F F e)eting the yntx of rivil utology vnguge e wonoid ixpression impli(er F F F F F F F F F F F F F e mrter utology olver F F F F F F F F F F F F F F F ixerises F F F F F F F F F F F F F F F F F F F F F F F F F F vt entiEtterns F F F F F F F F F F F F heugging nd wintining eutomtion wodules F F F F F F F F F F F F F F F F F F fuild roesses F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
F F F F F F F F F
F F F F F F F F F
F F F F F F F F F
F F F F F F F F F
F F F F F F F F F
F F F F F F F F F
F F F F F F F F F
F F F F F F F F F
F F F F F F F F F
F F F 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
253
273
274
ISFI gonrete 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 sndies F F F F F F F F F 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 volly xmeless yntx F F F F F 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 yntx nd sts essoited ypertions F F F F F F F F F F F F F F F F F PWV ITFP gustom tis F F F F F F F F F F 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 glssi rye F F F F F F rmetri rye F F F F e ype oundness roof figEtep emntis F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F
298
309
18 Type-Theoretic Interpreters
IVFI implyEyped vmd glulus F 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 roduts 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
326
IWFI g gonversion for implyEyped vmd glulus F F F F F F F F F F F F F QQT IWFP ixerises F F F F F F F F F F F F F F 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 gonneting xotions of ellEpormedness F F F F F F F F F F F F F F F F QRW S
336
346
PIFI glosure reps F F F F F F F F F F F 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 vnguges nd rnsltion F F F F 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 gorretness 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
354
Chapter 1 Introduction
1.1 Whence This Book?
e would ll like to hve progrms hek tht our progrms re orretF hue in no smll prt to some old ut unful(lled promises in the history of omputer sieneD tody most people who write softwreD prtitioners nd demis likeD ssume tht the osts of forml progrm veri(tion outweigh the ene(tsF he purpose of this ook is to onvine you tht the tehnology of progrm veri(tion is mture enough tody tht it mkes sense to use it in support role in mny kinds of reserh projets in omputer sieneF feyond the onviningD s lso wnt to provide hndook on prtil engineering of erti(ed progrms with the goq proof ssistntF here re good numer of @though de(nitely not 4mny4A tools tht re in wide use tody for uilding mhineEheked mthemtil proofs nd mhineEerti(ed progrmsF his is my ttempt t n exhustive list of intertive 4proof ssistnts4 stisfying few riteriF pirstD the uthors of eh tool must intend for it to e put to use for softwreE relted pplitionsF eondD there must hve een enough engineering e'ort put into the tool tht someone not doing reserh on the tool itself would feel his time ws well spent using itF e third riterion is more of n empiril vlidtion of the seondX the tool must hve signi(nt user ommunity outside of its own development temF
sselleGryvD implemented with the 4proof ssistnt development frmework4 sselleD is the most populr proof ssistnt for the ryv logiF he other implementtions of ryv n e onsidered equivlent for purposes of the disussion hereF
typesD suh progrms re certied decision proceduresF sn suh sesD these erti(ed proeE dures n e put to good use without ever running them 3 heir types gurntee thtD if we did other to run themD we would reeive proper 4ground4 proofsF he ritil ingredient for this tehniqueD mny of whose instnes re referred to s proof by reectionD is wy of induing nonEtrivil omputtion inside of logil propositions during proof hekingF purtherD most of these instnes require dependent types to mke it possile to stte the pproprite theoremsF yf the proof ssistnts s listedD only goq relly provides this supportF
IH
those feturesF
1.5 Prerequisites
s try to keep the required kground knowledge to minimum in this ookF s will ssume fmilirity with the mteril from usul disrete mth nd logi ourses tken y ll underE grdute omputer siene mjorsD nd s will ssume tht reders hve signi(nt experiene progrmming in one of the wv diletsD in rskellD or in some otherD loselyErelted lngugeF
II
ixperiene with only dynmillyEtyped funtionl lnguges might led to efuddlement in some plesD ut reder who hs ome to grok heme deeply will proly e (neF e good portion of the ook is out how to formlize progrmming lngugesD ompilE ersD nd proofs out themF o understnd those prtsD it will e helpful to hve si knowledge of forml type systemsD opertionl semntisD nd the theorems usully proved out suh systemsF es referene on these topisD s reommend Types and Programming LanguagesD y fenjmin gF iereF
http://adam.chlipala.net/cpdt/cpdt.pdf
here is lso n online rwv version villeD with hyperlink from eh use of n identi(er to tht identi(er9s de(nitionX
http://adam.chlipala.net/cpdt/html/toc.html
he soure ode to the ook is lso freely ville tX
http://adam.chlipala.net/cpdt/cpdt.tgz
hereD you n (nd ll of the ode ppering in this ookD with prose interspersed in ommentsD in extly the order tht you (nd in this doumentF ou n step through the ode intertively with your hosen grphil goq interfeF he ode lso hs speil omments inditing whih prts of the hpters mke suitle strting points for intertive lss sessionsD where the lss works together to onstrut the progrms nd proofsF he inluded wke(le hs trget templates for uilding fresh set of lss templte (les utomtilly from the ook soureF s elieve tht good grphil interfe to goq is ruil for using it produtivelyF s use the roof qenerl3 mode for imsD whih supports numer of other proof ssistnts esides goqF here is lso the stndlone goqshi progrm developed y the goq temF s like eing le to omine erti(ed progrmming nd proving with other kinds of work inside the sme fullEfetured editorD nd goqshi hs hd good numer of rshes nd other nnoying ugs in reent historyD though s her tht it is improvingF sn the initil prt of this ookD s will referene roof qenerl proedures expliitlyD in introduing how to use goqD ut most of the ook will e interfeEgnostiD so feel free to use goqshi if you prefer itF
3 http://proofgeneral.inf.ed.ac.uk/
IP
Chapter Source
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
IQ
ith roof qenerlD the portion of u'er tht goq hs proessed is highlighted in some wyD like eing given lue kgroundF ou step through goq soure (les y positioning the point t the position you wnt goq to run to nd pressing gEg gEiF his n e used oth for norml stepEyEstep odingD y pling the point inside some ommnd pst the end of the highlighted regionY nd for undoingD y pling the point inside the highlighted regionF
Plus
TimesF
yur (rst line of goq ode should e unsurprising to wv nd rskell progrmmersF e de(ne n lgeri dttype binop to stnd for the inry opertors of our soure lnE gugeF here re just two wrinkles ompred to wv nd rskellF pirstD we use the keyword InductiveD in ple of dataD datatypeD or typeF his is not just trivil surfe syntx di'ereneY indutive types in goq re muh more expressive thn grden vriety lgeri dttypesD essentilly enling us to enode ll of mthemtisD though we egin humly in this hpterF eondD there is the X Set frgmentD whih delres tht we re de(ning dttype tht should e thought of s onstituent of progrmsF vterD we will see other options for de(ning dttypes in the universe of proofs or in n in(nite hierrhy of universesD enompssing oth progrms nd proofsD tht is useful in higherEorder onstrutionsF
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 tht onstnt my e uilt from one rgumentD nturl numerY nd inry opertion my e uilt from hoie of opertor nd two opernd expressionsF e note for reders following long in the hp versionX oqdo supports prettyEprinting of tokens in ve or rwvF here you see right rrow hrterD the soure ontins the egss text ->F yther exmples of this sustitution ppering in this hpter re doule right rrow for => nd the inverted 9e9 symol for forallF hen in dout out the egss version of symolD you n onsult the hpter soure odeF xow we re redy to sy wht these progrms menF e will do this y writing n interpreter tht n e thought of s trivil opertionl or denottionl semntisF @sf you
IS
re not fmilir with these semnti tehniquesD no need to worryY we will stik to 4ommon sense4 onstrutionsFA
Definition binopDenote @b X binopA X nat nat nat Xa match b with | Plus plus | Times mult endF
he mening of inry opertor is inry funtion over nturlsD de(ned with ptternE mthing nottion nlogous to the case nd match of wv nd rskellD nd referring to the funtions plus nd mult from the goq stndrd lirryF he keyword Definition is goq9s llEpurpose nottion for inding term of the progrmming lnguge to nmeD with some ssoited syntti sugrD like the nottion we see here for de(ning funtionF ht sugr ould e expnded 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 exmpleD we ould lso omit ll of the type nnottionsD rriving tX
Definition binopDenote Xa fun match b with | Plus plus | Times mult endF
vnguges like rskell nd wv hve onvenient principal typing propertyD whih gives us strong gurntees out how e'etive type inferene will eF nfortuntelyD goq9s type system is so expressive tht ny kind of 4omplete4 type inferene is impossileD nd the tsk even seems to e hrd heuristilly in prtieF xonethelessD goq inludes some very helpful heuristisD mny of them opying the workings of rskell nd wv typeEhekers for progrms tht fll in simple frgments of goq9s lngugeF his is s good time s ny to mention the preponderne of di'erent lnguges ssoiE ted with goqF he theoretil foundtion of goq is forml system lled the Calculus of Inductive Constructions (CIC)D whih is n extension of the older Calculus of Constructions (CoC)F gsg is quite sprtn foundtionD whih is helpful for proving mettheory ut not so helpful for rel developmentF tillD it is nie to know tht it hs een proved tht gsg enjoys properties like strong normalizationD mening tht every progrm @ndD more importntlyD every proof termA termintesY nd relative consistency with systems like versions of ermelo prenkel set theoryD whih roughly mens tht you n elieve tht goq proofs men tht IT
the orresponding propositions re 4relly trueD4 if you elieve in set theoryF goq is tully sed on n extension of gsg lled GallinaF he text fter the Xa nd efore the period in the lst ode exmple is term of qllinF qllin dds mny useful fetures tht re not ompiled internlly to more primitive gsg feturesF he importnt mettheorems out gsg hve not een extended to the full redth of these feturesD ut most goq users do not seem to lose muh sleep over this omissionF gommnds like Inductive nd Definition re prt of the vernacularD whih inludes ll sorts of useful queries nd requests to the goq systemF pinllyD there is LtacD goq9s dominEspei( lnguge for writing proofs nd deision proeduresF e will see some si exmples of vt lter in this hpterD nd muh of this ook is devoted to more involved vt exmplesF e n give simple de(nition of the mening 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 delre expliitly tht this is reursive de(nitionD using the keyword FixpointF he rest should e old ht for funtionl progrmmersF st is onvenient to e le to test de(nitions efore strting to prove things out themF e n verify tht our semntis is sensile y evluting some smple usesF
expDenote
expDenote
expDenote
Times
Inductive instr X Set Xa | IConst X nat instr | IBinop X binop instrF Definition Definition
Xa list instrF stack Xa list natF
prog
en instrution either pushes onstnt onto the stk or pops two rgumentsD pplies inry opertor to themD nd pushes the result onto the stkF e progrm is list of instrutionsD nd stk is list of nturl numersF IU
e n give instrutions menings s funtions from stks to optionl stksD where running n instrution results in None in se of stk under)ow nd results in Some s' when the result of exeution is the new stk s'F XX is the 4list ons4 opertor from the goq stndrd lirryF
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 esy to de(ne funtion tion of instrDenote through whole progrmF
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
here is one interesting di'erene ompred to our previous exmple of FixpointF his reursive funtion tkes two rgumentsD p nd s F st is ritil for the soundness of goq tht every progrm terminteD so shllow syntti termintion hek is imposed on every reursive funtion de(nitionF yne of the funtion prmeters must e designted to derese monotonilly ross reursive llsF ht isD every reursive ll must use version of tht rgument tht hs een pulled out of the urrent rgument y some numer of match expressionsF expDenote hs only one rgumentD so we did not need to speify whih of its rguments deresesF por progDenoteD we resolve the miguity y writing {struct p } to indite tht rgument p dereses struturllyF eent versions of goq will lso infer termintion rgumentD so tht we my write simplyX
Fixpoint progDenote @p X progA @s X match p with | nil Some s | i XX p' match instrDenote i s with
stackA
option stack Xa
IV
endF
p' s'
2.1.3 Translation
yur ompiler itself is now unsurprisingF CC is the list ontention opertor from the goq stndrd lirryF
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 tht this ompiler is orretD we n try few test runsD using our smple progrms from erlierF
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 progrms nd hek tht they give the right resultsF
Eval simpl in progDenote @compile @Const RPAA a Some @RP XX nilA X option stack Eval simpl in progDenote @compile @Binop a Some @R XX nilA X option stack
Plus
nilF
nilF
Eval simpl in progDenote @compile @Binop UAAA nilF a Some @PV XX nilA X option stack
Times
Theorem
compile correct
X eD
progDenote
@compile e A
nil
Some
@expDenote
XX
nilAF
hough penilEndEpper proof might lok out t this pointD writing 4y routine indution on eD4 it turns out not to mke sense to ttk this proof diretlyF e need to IW
e do tht y proving n
Lemma
compile correct'
progDenote
@compile
X e p sD CC p A s a
progDenote p
@expDenote
XX s AF e
efter the period in the Lemma ommndD we re in the (nd ourselves string t this ominous sreen of textX I subgoal
XX s A
goq seems to e restting the lemm for usF ht we re seeing is limited se of more generl protool for desriing where we re in proofF e re told tht we hve single sugolF sn generlD during proofD we n hve mny pending sugolsD eh of whih is logil proposition to proveF ugols n e proved in ny orderD ut it usully works est to prove them in the order tht goq hoosesF xext in the outputD we see our single sugol desried in full detilF here is douleE dshed lineD ove whih would e our free vriles nd hypothesesD if we hd nyF felow the line is the onlusionD whihD in generlD is to e proved from the hypothesesF e mnipulte the proof stte y running ommnds lled tacticsF vet us strt out y running one of the most importnt ttisX
induction eF
e delre tht this proof will proeed y indution on the struture of the expression eF his swps out our initil sugol for two new sugolsD one for eh se of the indutive 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 sugol is displyed with the douleEdshed line elow free vriles nd hypothesesD while lter sugols re only summrized with their onlusionsF e see n exmple of free vrile in the (rst sugolY n is free vrile of type natF he onlusion is the originl theorem sttement where e hs een repled y Const nF sn similr mnnerD the seond se hs e repled y generlized invotion of the Binop expression onstrutorF e n see tht proving oth ses orresponds to stndrd proof y struturl indutionF e egin the (rst se with nother very ommon ttiF
introsF
he urrent sugol hnges 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
e see tht intros hnges Eound vriles t the eginning of gol into free vriE lesF o progress furtherD we need to use the de(nitions of some of the funtions ppering in the golF he unfold tti reples n identi(er with its de(nitionF
unfold
n
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
s
unfold
n
expDenoteF
X nat s X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote @@IConst n XX nilA CC p A s a progDenote e only need to unfold the (rst ourrene of
progDenote
unfold
progDenote
at IF
PI
X nat X stack p X list instr aaaaaaaaaaaaaaaaaaaaaaaaaaaa @x progDenote @p0 X progA @s0 X stackA {struct option stack Xa
s
p0 }
match p0 with | nil Some s0 | i XX p' match instrDenote i s0 with | Some s' progDenote p' s' | None None @AXastkA end endA @@IConst n XX nilA CC p A s a progDenote p @n XX s A
his lst unfold hs left us with n nonymous (xpoint version of progDenoteD whih will generlly hppen when unfolding reursive de(nitionsF portuntelyD in this seD we n eliminte suh omplitions right wyD sine the struture of the rgument @IConst n XX nilA CC p is knownD llowing us to simplify the internl pttern mth with the simpl ttiX
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 @AXastkA end endA p @n XX s A a progDenote p @n XX s A
progDenoteX
PP
st looks like we re t the end of this seD sine we hve trivil equlityF sndeedD single tti (nishes us o'X
reflexivityF
yn to the seond indutive seX
b
e1
X X
binop
exp
IHe1 e2
X @s X
exp
stackA
progDenote
progDenote p
@expDenote @expDenote
e1
XX s A XX s A
@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
X @s X
stackA
e2
e see our (rst exmple of hypotheses ove the douleEdshed lineF hey re the indutive hypotheses IHe1 nd IHe2 orresponding to the suterms e1 nd e2D respetivelyF e strt out the sme wy s eforeD introduing new free vriles nd unfolding nd folding the pproprite de(nitionsF he seemingly frivolous unfoldGfold pirs re tully omplishing useful workD euse unfold will sometimes perform esy simpli(tionsF
e1
binop
exp
IHe1
X @s X
stackA
progDenote
progDenote p
@expDenote
e1
XX s A
PQ
e2
exp
IHe2 s
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
X @s X
stackA
ht we need is the ssoitive lw of list ontentionD ville s theorem in the stndrd lirryF
app ass
Check
app assF
app ass
X @A X TypeA @l
list AAD @l CC m A CC n a l CC m CC n
rewrite
app assF
xow we n notie tht the lefthnd side of the equlity mthes the lefthnd side of the seond indutive hypothesisD so we n rewrite with tht hypothesisD tooX
rewrite
IHe2F
progDenote
progDenote p
rewrite rewrite
IHe1F
app assF
progDenote progDenote
xow we n pply similr sequene of ttis to tht tht ended the proof of the (rst seF
unfold simplF
progDenote
at IF
PR
fold progDenoteF
reflexivityF
Proof
completedF
end there lies our (rst proofF elredyD even for simple theorems like thisD the (nl proof sript is unstrutured nd not very enlightening to redersF sf we extend this pproh to more serious theoremsD we rrive t the unredle proof sripts tht re the fvorite omplints of opponents of ttiEsed provingF portuntelyD goq hs rih support for sripted utomtionD nd we n tke dvntge of suh sripted tti @de(ned elsewhereA to mke short work of this lemmF e ort the old proof ttempt nd strt ginF
AbortF Lemma
compile correct' progDenote p
induction e Y QedF
@expDenote crushF
e s pD progDenote e
XX s AF
@compile
CC p A
e need only to stte the si indutive proof sheme nd ll tti tht utomtes the tedious resoning in etweenF sn ontrst to the period tti termintor from our lst proofD the semiolon tti seprtor supports struturedD ompositionl proofsF he tti t1Y t2 hs the e'et of running t1 nd then running t2 on eh remining sugolF he semiolon is one of the most fundmentl uilding loks of e'etive proof utomtionF he period termintor is very useful for explortory provingD where you need to see intermeE dite proof sttesD ut (nl proofs of ny serious omplexity should hve just one periodD terminting single ompound tti tht proly uses semiolonsF he crush tti omes from the lirry ssoited with this ook nd is not prt of the goq stndrd lirryF he ook9s lirry ontins numer of other ttis tht re espeilly helpful in highlyEutomted proofsF he proof of our min theorem is now esyF e prove it with four periodEterminted ttisD though seprting them with semiolons would work s wellY the version here is esier to step throughF
correct
X eD
progDenote
@compile e A
nil
Some
@expDenote
XX
nilAF
nilA com-
et this pointD we wnt to mssge the lefthnd side to mth the sttement of e theorem from the stndrd lirry is usefulX
app nil endF
Check
PS
X @A X TypeA @l X
rewrite @app
nil end
his timeD we expliitly speify the vlue of the vrile l from the theorem sttementD sine multiple expressions of list type pper in the onlusionF rewrite might hoose the wrong ple to rewrite if we did not speify whih we wntF X exp aaaaaaaaaaaaaaaaaaaaaaaaaaaa progDenote @compile e CC nilA nil a Some @expDenote
e
XX
nilA
rewrite
e
compile correct'F
XX
nilA
e re lmost doneF he lefthnd nd righthnd sides n e seen to mth y simple symoli evlutionF ht mens we re in lukD euse goq identi(es ny pir of terms s equl whenever they normlize to the sme result y symoli evlutionF fy the de(nition of progDenoteD tht is the se hereD ut we do not need to worry out suh detilsF e simple invotion of reflexivity does the normliztion nd heks tht the two results re synttilly equlF
reflexivityF QedF
Nat
BoolF
| | | |
of goq9s expressive powerY lmost everything else of interest is de(ned in terms of themF wv nd rskell hve indexed lgeri dttypesF por instneD their list types re indexed y the type of dt tht the list rriesF roweverD ompred to goqD wv nd rskell WV ple two importnt restritions on dttype de(nitionsF pirstD the indies of the rnge of eh dt onstrutor must e type vriles ound t the top level of the dttype de(nitionF here is no wy to do wht we did hereD where weD for instneD sy tht TPlus is onstrutor uilding tbinop whose indies re ll (xed t NatF Generalized algebraic datatypes (GADTs) re populr feture in qrg rskell nd other lnguges tht removes this (rst restritionF he seond restrition is not lifted y qehsF sn wv nd rskellD indies of types must e types nd my not e expressionsF sn goqD types my e indexed y ritrry qllin termsF ype indies n live in the sme universe s progrmsD nd we n ompute with them just like regulr progrmsF rskell supports holed form of omputtion in type indies sed on multiEprmeter type lssesD nd reent extensions like type funtions ring rskell progrmming even loser to 4rel4 funtionl progrmming with typesD utD without dependent typingD there must lwys e gp etween how one progrms with types nd how one progrms normllyF e n de(ne similr type fmily for typed expressionsF
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 importnt wyF here we delred tht binop hs type SetD here we delre tht tbinop hs type type type type SetF e de(ne tbinop s n indexed type familyF sndexed indutive types re t the hert
TPlus
Inductive texp X type Set Xa | TNConst X nat texp Nat | TBConst X bool texp Bool | TBinop X arg1 arg2 resD tbinop
soure expressionD y onstrutionF his turns out to e very onvenient for mny things we might wnt to do with expressionsF por instneD it is esy to dpt our interpreter pproh to de(ning semntisF e strt y de(ning funtion mpping the types of our lnguges into goq typesX
texp arg1 texp arg2 texp resF hnks to our use of dependent typesD every wellEtyped texp represents wellEtyped
arg1 arg2 res
Definition typeDenote @t X typeA X Set Xa match t with | Nat nat | Bool bool endF
st n tke few moments to ome to terms with the ft tht SetD the type of types of progrmsD is itself (rstElss typeD nd tht we n write funtions tht return SetsF st PU
tht wrinkleD the de(nition of typeDenote is trivilD relying on the nat nd bool types from the goq stndrd lirryF e need to de(ne few uxiliry funtionsD implementing our oolen inry opertors tht do not pper with the right types in the stndrd lirryF hey re entirely stndrd nd wvElikeD with the one vet eing tht the goq nat type uses unry representtionD where O is zero nd S n is the suessor of nF
Definition eq bool @b1 match b1D b2 with | trueD true true | falseD false true | D false endF
b2
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 inry opertorsX
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 funtion hs just few di'erenes from the denottion funtions we sw erlierF pirstD tbinop is n indexed typeD so its indies eome dditionl rguments to tbinopDenoteF eondD we need to perform genuine dependent pattern match to ome up with de(nition of this funtion tht typeEheksF sn eh rnh of the matchD we need to use rnhEspei( informtion out the indies to tbinopF qenerl type inferene tht tkes suh informtion into ount is undeidleD so it is often neessry to write nnottionsD like we see ove PV
on the line with matchF he in nnottion resttes the type of the term eing seEnlyzedF hough we use the sme nmes for the indies s we use in the type of the originl rgument inderD these re tully fresh vrilesD nd they re binding occurrencesF heir sope is the return luseF ht isD arg1D arg2D nd arg3 re new ound vriles ound only within the return luse typeDenote arg1 typeDenote arg2 typeDenote resF fy eing expliit out the funtionl reltionship etween the type indies nd the mth resultD we regin deidle type infereneF sn ftD reent goq versions use some heuristis tht n sve us the troule of writing match nnottionsD nd those heuristis get the jo done in this seF e n get wy 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
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 evlute few exmple progrms to onvine ourselves tht this semntis is orretF
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
@TBinop
TPlus
PW
Eval simpl in texpDenote @TBinop TLt @TBinop TPlus @TNConst PA @TNConst PAA @TNConst UAAF a true X typeDenote Bool
Definition
tstack
Xa
list typeF
eny stk lssi(ed y tstack must hve extly s mny elementsD nd eh stk element must hve the type found in the sme position of the stk typeF e n de(ne instrutions in terms of stk typesD where every instrution9s type tells us wht initil stk type it expets nd wht (nl stk type it will produeF
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
res arg2
XX s A @res XX s AF
tk mhine progrms must e similr indutive fmilyD sineD if we gin used the list type fmilyD we would not e le to gurntee tht intermedite stk types mth within progrmF
tstack
Set Xa
s3 s3F
xowD to de(ne the semntis of our new trget lngugeD we need representtion for stks t runtimeF e will gin tke dvntge of type informtion to de(ne types of vlue stks thtD y onstrutionD ontin the right numer nd types of elementsF
tstackA
X Set Xa
QH
vstack ts'
his is nother SetEvlued funtionF his time it is reursiveD whih is perfetly vlidD sine Set is not treted speilly in determining whih funtions my e writtenF e sy tht the vlue stk of n empty stk type is ny vlue of type unitD whih hs just single vlueD ttF e nonempty stk type leds to vlue stk tht is pirD whose (rst element hs the proper type nd whose seond element follows the representtion for the reminder of the stk typeF e write 7type so tht goq knows to interpret s grtesin produt rther thn multiplitionF his ide of progrmming with types n tke while to internlizeD ut it enles very simple de(nition of instrution denottionF yur de(nition is like wht you might expet from vispElike version of wv tht ignored type informtionF xonethelessD the ft tht tinstrDenote psses the typeEheker gurntees tht our stk mhine progrms 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 funtion to ind the initil stk in every se of the matchc gonsider this wellEintentioned ut invlid lterntive 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
he goq typeEheker omplins thtX
The term
vstack ts A
vstack ts'
Xa
arg2D s' A
4@nD sA4
has
he text cIIW stnds for uni(tion vrileF e n try to help goq (gure out the vlue of this vrile with n expliit nnottion 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
xow the error messge hngesF
The term
vstack ts A
vstack ts'
Xa
arg2D s' A
4@nD sA4
has
ell from our erlier disussion of match nnottions tht we write the nnottions to express to the typeEheker the reltionship etween the type indies of the se ojet nd the result type of the matchF goq hooses to ssign to the wildrd fter TINConst the nme t D nd the type error is telling us tht the type heker nnot prove tht t is the sme s tsF fy moving s out of the matchD we lose the ility to expressD with in nd return lusesD the reltionship etween the shred index ts of s nd iF here are resonly generl wys of getting round this prolem without pushing inders inside matchesF roweverD the lterntives re signi(ntly more involvedD nd the tehnique we use here is lmost ertinly the est hoieD whenever it ppliesF e (nish the semntis with strightforwrd de(nition of progrm denottionF
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 ompiltionD it is useful to hve n uxiliry funtion for ontenting two stk mhine progrmsF
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 tht funtion in pleD the ompiltion is de(ned very similrly to how it ws 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 feture of the de(nition is the undersores ppering to the right of rrowsF rskell nd wv progrmmers re quite fmilir with ompilers tht infer type prmeters to polymorphi vluesF sn goqD it is possile to go even further nd sk the system to infer ritrry termsD y writing undersores in ple of spei( vluesF ou my hve notied tht we hve een lling funtions without speifying ll of their rgumentsF por instneD the reursive lls here to tcompile omit the t rgumentF goq9s implicit argument mehnism utomtilly inserts undersores for rguments tht it will proly e le to inferF snferene of suh vlues is fr from ompleteD thoughY generllyD it only works in ses similr to those enountered with polymorphi type instntition in rskell nd wvF he undersores here re eing (lled in with stk typesF ht isD the goq type inferener isD in senseD inferring something out the )ow of ontrol in the trnslted progrmsF e n tke look t extly whih vlues re (lled inX
tcompileF
tcompile
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
@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
e n hek tht the ompiler genertes progrms tht ehve ppropritely on our smple progrms from oveX
tprogDenote vstack
nilA ttF
tprogDenote
a @trueD
ttA
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
Theorem
tcompile correct
tprogDenote
@tcompile
e nilA tt
@e X texp t AD a @texpDenote eD
ttAF
eginD we need to strengthen the theorem sttement so tht the indution will go throughF his timeD s will develop n lterntive pproh to this kind of proofD stting the key lemm sX
Lemma
tcompile correct'
tprogDenote
@tcompile
e ts A s
ts AD
hile lemm compile correct' qunti(ed over progrm tht is the 4ontinution4 for the expression we re onsideringD here we void drwing in ny extr syntti elementsF sn ddition to the soure expression nd its typeD we lso quntify over n initil stk type nd stk omptile with itF unning the ompiltion of the progrm strting from tht stkD we should rrive t stk tht di'ers only in hving the progrm9s denottion pushed onto itF vet us try to prove this theorem in the sme wy tht we settled on in the lst setionF
induction e Y
crushF
@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 nlogue to the app ass theorem tht we used to rewrite the gol in the lst setionF e n ort this proof nd prove suh 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'
ts A
his one goes through ompletely utomtillyF ome ode ehind the senes registers app ass for use y cat correct similrly to get the sme e'etX
crushF
e must register
tcon-
Hint
cpdtF
e sk tht the lemm e used for leftEtoEright rewritingD nd we sk for the hint to e dded to the hint dtse lled cpdtD whih is the dtse used y crushF xow we re redy to return to tcompile correct'D proving it utomtilly this timeF
Lemma
tcompile correct'
X
e
ts AD
e n register this min lemm s nother hintD llowing us to prove the (nl theorem trivillyF
Hint
cpdtF
ttAF
Theorem QedF
crushF
tprogDenote
@tcompile
QS
QT
3.1 Enumerations
goq indutive types generlize the lgeri dttypes found in rskell nd wvF gonfusingly enoughD indutive types lso generlize generlized lgeri dttypes @qehsAD y dding the possiility for type dependenyF iven soD it is worth king up from the exmples of the lst hpter nd going over siD lgeri dttype uses of indutive dttypesD euse the hne to prove things out the vlues of these types dds new wrinkles eyond usul prtie in rskell nd wvF he singleton type unit is n indutive typeX
Theorem
unit
he importnt thing out n indutive type isD unsurprisinglyD tht you n do indution over its vluesD nd indution is the key to proving this theoremF e sk to proeed y indution on the vrile x F QU
induction xF he gol hnges toX tt a tt FFFwhih we n dishrge trivillyF reflexivityF QedF st seems kind of odd to write proof y indution with no indutive hypothesesF e ould hve rrived t the sme result y eginning the proof withX destruct x F
FFFwhih orresponds to 4proof y se nlysis4 in lssil mthF por nonEreursive indutive typesD the two ttis will lwys hve identil ehviorF yften se nlysis is su0ientD even in proofs out reursive typesD nd it is nie to void introduing unneeded indution hypothesesF ht extly is the indution priniple for unitc e n sk goqX
Check
unit indF
unit ind
unit PropD P
tt
unitD P
ivery Inductive ommnd de(ning type T lso de(nes n indution priniple nmed T indF goq follows the gurryErowrd orrespondene nd inludes the ingredients of proE grmming nd proving in the sme single syntti lssF husD our typeD opertions over itD nd priniples for resoning out it ll live in the sme lnguge nd re desried y the sme type systemF he key to telling wht is progrm nd wht is proof lies in the distintion etween the type PropD whih ppers in our indution prinipleY nd the type SetD whih we hve seen few times lredyF he onvention goes like thisX Set is the type of norml typesD nd the vlues of suh types re progrmsF Prop is the type of logil propositionsD nd the vlues of suh types re proofsF husD n indution priniple hs type tht shows us tht it is funtion for uilding proofsF pei(llyD unit ind qunti(es over predite P over unit vluesF sf we n present proof tht P holds of ttD then we re rewrded with proof tht P holds for ny vlue u of type unitF sn our lst proofD the predite ws @fun u X unit u a ttAF e n de(ne n indutive type even simpler thn
Inductive Empty set X Set Xa F Empty set hs 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 feuse Empty set hs no elementsD the ft of hving n element of this type implies nythingF e use destruct I insted of destruct x in the proof euse unused qunti(ed
QV
unitX
vriles re relegted to eing referred to y numerF @here is good reson for thisD relted to the unity of qunti(ers nd implitionF en implition is just qunti(tion over proofD where the qunti(ed vrile is never usedF st generlly mkes more sense to refer to implition hypotheses y numer thn y nmeD nd goq trets our qunti(er over n unused vrile s n implition in determining the proper ehviorFA e n see the indution priniple tht mde this proof so esyX
Check
X @P X
sn other wordsD ny predite over vlues from the empty set holds vuously of every suh elementF sn the lst proofD we hose the predite @fun X Empty set P C P a SAF e n lso pply this getEoutEofEjilEfree rd progrmmtillyF rere is lzy wy of onverting vlues of Empty set to vlues of unitX
Definition
e2u
@e X
e employ match pttern mthing s in the lst hpterF ine we mth on vlue whose type hs no onstrutorsD there is no need to provide ny rnhesF woving up the ldder of omplexityD we n de(ne the oolensX
Definition not @b X boolA X bool Xa match b with | true false | false true endF
en lterntive de(nition desugrs to the oveX
subgoal P
is X
QW
not
@not
falseA
false
reflexivityF
vikewise for the seond sugolD so we n restrt the proof nd give very ompt justi(tionF
RestartF
not b
= bF
discriminate is used to prove tht two vlues of n indutive type re not equlD whenE ever the vlues re formed with di'erent onstrutorsF sn this seD the di'erent onstrutors re true nd falseF et this pointD it is proly not hrd to guess wht the underlying indution priniple for bool isF Check
bool indF bool ind
bool PropD P
true
P false
boolD P
I for
S OD
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
isZero
@pred @S @S n AAA a
falseF
e n lso now get into genuine indutive theoremsF pirstD we will need reursive funtionD to mke things interestingF
Fixpoint plus @n m X natA X nat Xa match n with |Om | S n' S @plus n' m A endF
ell tht Fixpoint is goq9s mehnism for reursive funtion de(nitionsF ome theoE rems out plus n e proved without indutionF
plus O n
a nF
goq9s omputtion rules utomtilly simplify the pplition of plusD euse unfolding the de(nition of plus gives us match expression where the rnh to e tken is ovious from syntx loneF sf we just reverse the order of the rgumentsD thoughD this no longer worksD nd we need indutionF
natD plus n
a
OD
a nF
is
plus O O
whih
trivil y omputtionF
yur seond sugol is more work nd lso demonstrtes our (rst indutive hypothesisF
n
nat
simplF
xow the onlusion is
S
@plus
OA
rewrite
IHnF
RI
F
crush
reflexivityF
xot muh relly went on in this proofD so the prove this theorem utomtillyF tti from the
Tactics
module n
RestartF
crushF
P O
@S nAA
natD P
nat indF
ih of the two ses of our lst 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 seond se to @ n X natD P n P @S nAAF he free vrile n nd indutive hypothesis IHn me from the rgument types given hereF ine nat hs onstrutor tht tkes n rgumentD we my sometimes need to know tht tht onstrutor is injetiveF
S n
S m
mF
injection refers to premise y numerD dding new equlities etween the orreE sponding rguments of equted terms tht re formed with the sme onstrutorF e end up needing to prove n a m n a mD so it is unsurprising tht tti nmed trivial is le to (nish the proofF here is lso very useful tti lled congruence tht n prove this theorem immeE ditelyF congruence generlizes discriminate nd injectionD nd it lso dds resoning out the generl properties of equlityD suh s tht funtion returns equl results on equl rgumentsF ht isD congruence is complete decision procedure for the theory of equality and uninterpreted functionsD plus some smrts out indutive typesF
e n de(ne type of lists of nturl numersF
Inductive nat list X Set Xa | NNil X nat list | NCons X nat nat list nat listF
eursive de(nitions re strightforwrd extensions of wht we hve 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
sndutive theorem proving n gin e utomted quite e'etivelyF
Theorem nlength napp X ls1 ls2 X nat listD a plus @nlength ls1 A @nlength ls2 AF induction ls1 Y crushF QedF Check
nat list indF nat list ind
nlength
@napp
ls1 ls2 A
P NNil
@NCons
n0 AA
sn generlD we n implement ny 4tree4 types s indutive typesF por exmpleD here re inry trees of nturlsF
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
n1 Y crushF
n1 n2 n3
n2 A n3
plus n1
@plus
n2 n3 AF
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
@nsplice
tr1 tr2 A
RQ
QedF Check
nat btree indF nat btree ind
P NLeaf
@NNode
n0 n1 AA
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 shorthnd for writing mny de(nitions tht shre the sme prmeterD sed on goq9s section mehnismF he following lok of ode is equivlent 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
@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 setionD the Variables we used re dded s extr funtion prmeters for eh de(ned identi(erD s neededF e verify tht this hs hppened using the Print ommndD ousin of Check whih shows the de(nition of symolD rther thn 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 (nl de(nition is the sme s wht we wrote mnully eforeF he other elements of the setion re ltered similrlyD turning out extly s they were eforeD though we mnged to write their de(nitions more suintlyF
Check
lengthF
length
X T X SetD list T nat he prmeter T is treted s new rgument to the indution prinipleD tooF
list indF
Check
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 sw tht T is dded s n extr rgument to the onstrutor ConsD there is no qunti(er for T in the type of the indutive se like there is for eh of the other rgumentsF
list ind
RS
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 sme s in pst exmplesD until we try to prove theorem similr to those tht me eforeF
Theorem
X el1 el2 X even listD elength @eapp el1 el2 A a plus @elength el1 A @elength induction el1 Y crushF
elength eapp
el2 AF
el2 AA
e hve no indution hypothesisD so we nnot prove this gol without strting nother indutionD whih would reh similr pointD sending us into futile in(nite hin of induE tionsF he prolem is tht goq9s genertion of T ind priniples is inompleteF e only get nonEmutul indution priniples generted y defultF
list indF
P ENil
listAD P @ECons n o AA
e see tht no indutive hypotheses re inluded nywhere in the typeF o get themD we must sk for mutul priniples s we need themD using the Scheme ommndF
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
P ENil
his is the priniple we wnted in the (rst pleF here is one more wrinkle left in using itX the induction tti will not pply it for us utomtillyF st will e helpful to look t how to prove one of our pst exmples without using inductionD so tht we n then generlize the tehnique to mutul indutive 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 exmpleD we n see tht induction is not mgiF st only does some ookE keeping for us to mke it esy to pply theoremD whih we n do diretly with the apply ttiF e pply not just n identi(er ut prtil pplition of itD speifying the predite we men to prove holds for ll nturlsF his tehnique generlizes to our mutul exmpleX
Theorem
elength
elength eapp
@eapp
el1
el2 AF
even listD
RU
elength
@fun
ol
odd list
@oapp
ol
@eapp
el1 el2 A
olength
QedF
@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 speify two preditesD one for eh of the mutully indutive typesF sn generlD it would not e good ide to ssume tht proof ssistnt ould infer extr preditesD so this wy of pplying mutul indution is out s strightforwrd s we ould hope forF
Inductive formula X Set Xa | Eq X nat nat formula | And X formula formula formula | Forall X @nat formulaA formulaF
yur kinds of formuls re equlities etween nturlsD onjuntionD nd universl qunE ti(tion over nturl numersF e void needing to inlude notion of 4vriles4 in our typeD y using goq funtions to enode qunti(tionF por instneD here is the enoding of x X natD x a x X
Example
forall re
e n write reursive funtions over re)exive types quite nturllyF rere is one trnsE lting our formuls into ntive 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 enode trivil formul trnsformtion tht swps the order of equlity nd onjuntion operndsF
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 tht this trnsformtion does not mke true formuls flseF
truth
X fD
formulaDenote f
formulaDenote
@swapper f AF
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
pousing on the Forall seD whih omes thirdD we see tht we re llowed to ssume tht the theorem holds for any application of the argument function f1F ht isD goq indution priniples do not follow simple rule tht the textul representtions of indution vriles must get shorter in ppels to indution hypothesesF vukily for usD the people ehind the mettheory of goq hve veri(ed tht this )exiility does not introdue unsoundnessF p to this pointD we hve seen how to enode in goq more nd more of wht is possile with lgeri dttypes in rskell nd wvF his my hve given the inurte impression tht indutive types re strit extension of lgeri dttypesF sn ftD goq must rule out some types llowed y rskell nd wvD for resons of soundnessF e)exive types provide our (rst good exmple of suh seF qiven our lst exmple of n indutive typeD mny reders re proly eger to try enoding the syntx of lmd lulusF sndeedD the funtionEsed representtion tehnique tht we just usedD lled higher-order abstract syntax (HOAS)D is the representtion of hoie for lmd luli in welf nd in mny pplitions implemented in rskell nd wvF vet us try to import tht hoie 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
e hve run foul of the strict positivity requirement for indutive de(nitionsD whih sys tht the type eing de(ned my not our to the left of n rrow in the type of onstrutor rgumentF st is importnt tht the type of onstrutor is viewed in terms of series of rguments nd resultD sine oviously we need reursive ourrenes to the lefts of the RW
outermost rrows if we re to hve reursive ourrenes t llF hy must goq enfore this restritionc smgine tht our lst de(nition hd een E eptedD llowing us to write this funtionX
term A
term
Xa
sing n informl ide of goq9s semntisD it is esy to verify tht the pplition uhoh @Abs uhohA will run foreverF his would e mere uriosity in ygml nd rskellD where nonEtermintion is ommonpleD though the ft tht we hve nonEterminting progrm without expliit reursive funtion de(nitions is unusulF por goqD howeverD this would e dissterF he possiility of writing suh funtion would destroy ll our on(dene tht proving theorem mens nythingF ine goq omines progrms nd proofs in one lngugeD 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 wys to relize most ene(ts of rye in goqF e will study prtiulr tehnique of this kind in the lter hpters on progrmming lnguge syntx nd semntisF
unit indF
unit ind
P u
e see tht this indution priniple is de(ned in terms of more generl prinipleD
unit rectF
Check
unit rect
unit TypeD P
gives
P
tt
unitD P
type unit Type insted of unit PropF Type is nother universeD like Set nd PropF sn ftD it is ommon supertype of othF vter onD we will disuss
unit rect
SH
extly wht the signi(nes of the di'erent universes reF por nowD it is just importnt tht we n use Type s sort of metEuniverse tht my turn out to e either Set or PropF e n see the symmetry inherent in the sutyping reltionship y printing the de(nition of nother priniple tht ws generted for unit utomtillyX
unit recF
P u
his is identil to the de(nition for unit indD exept tht we hve sustituted Set for PropF por most indutive types T D thenD we get not just indution priniples T indD ut lso reursion priniples T recF e n use T rec to write reursive de(nitions without expliit Fixpoint reursionF por instneD the following two de(nitions re equivlentX
@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 rit holeD unit funtionl progrm tht we n write mnullyF
rect
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
he only new feture we see is n as luse for matchD whih is used in onert with the return luse tht we sw in the introdutionF ine the type of the match is dependent on the vlue of the ojet eing nlyzedD we must give tht ojet nme so tht we n refer to it in the return luseF o prove tht unit rect is nothing speilD we n reimplement it mnullyF
rect'
@P X
unit TypeA @f X
P ttA
@u X
unitA Xa
e rely on goq9s heuristis for inferring match nnottionsF e n hek the implementtion of nat rect s wellX SI
nat rectF
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 |Of | 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 hve n tul reursive de(nitionF x expressions re n nonymous form of FixpointD just s fun expressions stnd for nonymous nonEreursive funtionsF feyond thtD the syntx of x mirrors tht of FixpointF e n understnd the de(nition of nat rect etter y reimplementing nat ind using setionsF
x F
nat rect
Section nat ind'F pirstD we hve the property of nturl numers tht we im to proveF Variable
P
nat PropF
O
seF
Hypothesis Hypothesis
O case
P OF S
natD P
@S n AF
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 setion dds the Variables nd Hypothesises s new funEound rguments to nat ind'D ndD modulo the use of Prop insted of TypeD we end up with the ext sme de(nition tht ws generted utomtilly for nat rectF e n lso exmine the de(nition of even mutullyEreursive typeF
list mutD
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 SP
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 mutullyEreursive xD with the di'erent funtions seprted y with in the sme wy tht they would e seprted y and in wvF e (nl for luse identi(es whih of the mutullyEreursive funtions should e the (nl vlue of the x expressionF sing this de(nition s templteD we n reimplement even list mut diretlyF Section even list mut'F pirstD we need the properties tht we re provingF Variable Variable
Peven Podd
ENil case
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
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 indution priniples for re)exive types re esy to implement diretlyF por our formula typeD we n use reursive de(nition muh 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
Inductive nat tree X Set Xa | NLeaf ' X nat tree | NNode' X nat list nat tree nat treeF
his is n exmple of nested indutive type de(nitionD euse we use the type we re de(ning s n rgument to prmetrized type fmilyF goq will not llow ll suh de(nitionsY it e'etively pretends tht we re de(ning nat tree mutully with version of list speilized to nat treeD heking tht the resulting expnded de(nition stis(es the usul rulesF por instneD if we repled list with type fmily tht used its prmeter s funtion rgumentD then the de(nition would e rejeted s violting the positivity restritionF vike we enountered for mutul indutive typesD we (nd tht the utomtillyEgenerted indution priniple for nat tree is too wekF
Check
here is no ommnd like Scheme tht will implement n improved priniple for usF sn generlD it tkes retivity to (gure out how to inorporte nested uses to di'erent type fmiliesF xow tht we know how to implement indution priniples mnullyD we re in SR
position to pply just suh retivity to this prolemF pirstD we will need n uxiliry de(nitionD hrterizing wht it mens 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 mnul proofs of them elowF
44F
A B
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
sn ddition to the de(nition of and itselfD we get informtion on impliit rguments nd prsing rules for and nd its onstrutor conjF e will ignore the prsing informtion for nowF he impliit rgument informtion tells us tht we uild proof of onjuntion y lling the onstrutor conj on proofs of the onjuntsD with no need to inlude the types of those proofs s expliit rgumentsF xow we rete setion for our indution prinipleD following the sme si pln s in the lst setion of this hpterF 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 indution priniple itself follows the intuition tht nested indutive type de(nitions re expnded into mutul indutive 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 rejets this de(nitionD sying 4eursive ll to nt tree ind9 hs prinipl rgument equl to 4tr4 insted of restF4 he term 4nested indutive type4 hints t the solution to the prolemF tust like true mutullyEindutive types require mutullyEreursive indution priniplesD nested types require nested reursionF
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 inlude n nonymous x version of list nat tree ind tht is literlly nested inside the de(nition of the reursive funtion orresponding to the indutive de(nition tht hd the nested use of listF
End
e n try our indution priniple out y de(ning some reursive funtions on nat trees nd proving theorem out themF pirstD we de(ne some helper funtions tht operte on listsF ST
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 funtion 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
xotie tht goq ws smrt enough to expnd the de(nition of map to verify tht we re using proper nested reursionD even through use of higherEorder funtionF
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 hve de(ned nother ritrry notion of tree spliingD similr to eforeD nd we n prove n nlogous theorem out its reltionship with tree sizeF e strt with useful lemm out dditionF
Lemma
@S
n2 A
n1 n2
n2 AF
plus S
s hintF
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
tr1 tr2 A
e know tht the stndrd indution priniple is insu0ient for the tskD so we need to provide using luse for the induction tti to speify our lternte prinipleF
induction
n
tr1
using
yne sugol reminsX 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
ntsize
tr1 AA ls
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
ls AAA
tr2 A trs A
efter few moments of squinting t this golD it eomes pprent tht we need to do se nlysis on the struture of lsF he rest is routineF
destruct
ls Y crushF
Cons
endA a A
e will go into gret detil on hints in lter hpterD ut the only importnt thing to note here is tht we register pttern tht desries onlusion we expet to enounter during the proofF he pttern my ontin uni(tion vrilesD whose nmes re pre(xed with question mrksD nd we my refer to those ound vriles in tti tht we sk to hve run whenever the pttern mthesF he dvntge of using the hint is not very ler hereD euse the originl proof ws so shortF roweverD the hint hs fundmentlly improved the redility of our proofF feforeD the proof referred to the lol vrile lsD whih hs n utomtillyEgenerted nmeF o humn reding the proof sript without stepping through it intertivelyD it ws not ler where ls me fromF he hint explins to the reder the proess for hoosing whih vriles to se nlyze onD nd the hint n ontinue working even if the rest of the proof struture hnges signi(ntlyF
SV
Theorem
true
falseF
e egin with the tti redD whih is short for 4one step of redutionD4 to unfold the de(nition of logil negtionF
redF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa true a false False he negtion is repled with n implition of flsehoodF e use the tti intro hnge the ssumption of the implition into hypothesis nmed HF
H
to
intro
H
HF
False
his is the point in the proof where we pply some retivityF e de(ne funtion whose utility will eome ler soonF
Definition f @b X boolA Xa if
st is worth relling the di'erene etween the lowerse nd upperse versions of truth nd flsehoodX True nd False re logil propositionsD while true nd false re oolen vlues tht we n seEnlyzeF e hve de(ned f suh tht our onlusion of False is omE puttionlly equivlent to f falseF husD the change tti will let us hnge the onlusion to f falseF
change H
@f
falseAF
xow the righthnd side of H 9s equlity ppers in the onlusionD so we n rewriteD using the nottion to request to reple the righthnd side the equlity with the lefthnd sideF
rewrite
HF
SW
e re lmost doneF tust how lose we re to done is reveled y omputtionl simpliE (tionF
simplF
X true a false aaaaaaaaaaaaaaaaaaaaaaaaaaaa
H
True
trivialF QedF
s hve no trivil utomted version of this proof to suggestD eyond using discriminate or congruence in the (rst pleF e n perform similr mnul proof of injetivity of the onstrutor S F s leve wlkE through of the detils to urious reders who wnt to run the proof sript intertivelyF
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
S m
mF
3.9 Exercises
IF he(ne n indutive type truth with three onstrutorsD YesD NoD nd MaybeF Yes stnds for ertin truthD No for ertin flsehoodD nd Maybe for n unknown situtionF he(ne 4notD4 4ndD4 nd 4or4 for this replement oolen lgerF rove tht your implementtion of 4nd4 is ommuttive nd distriutes over your implementtion of 4orF4 PF wodify the (rst exmple lnguge of ghpter P to inlude vrilesD where vriles re represented with natF ixtend the syntx nd semntis of expressions to ommodte the hngeF our new expDenote funtion should tke s new extr (rst rgument vlue of type var natD where var is synonym for nturlsEsEvrilesD nd the funtion ssigns vlue to eh vrileF he(ne onstnt folding funtion whih does ottomEup pss over n expressionD t eh stge repling every inry opertion on onstnts with n equivlent onstntF rove tht onstnt folding preserves the menings of expressionsF TH
QF eimplement the seond exmple lnguge of ghpter P to use mutullyEindutive types insted of dependent typesF ht isD de(ne two seprte @nonEdependentA induE tive types nat exp nd bool exp for expressions of the two di'erent typesD rther thn single indexed typeF o keep things simpleD you my onsider only the inry opertors tht tke nturls s operndsF edd nturl numer vriles to the lngugeD s in the lst exeriseD nd dd n 4if4 expression form tking s rguments one oolen exE pression nd two nturl numer expressionsF he(ne semntis nd onstntEfolding funtions for this new lngugeF our onstnt folding should simplify not just iE nry opertions @returning nturls or oolensA with known rgumentsD ut lso 4if4 expressions with known vlues for their test expressions ut possily undetermined 4then4 nd 4else4 sesF rove tht onstntEfolding nturl numer expression preserves its meningF RF sing re)exive indutive de(nitionD de(ne type nat tree of in(nitry treesD with nturl numers t their leves nd ountle in(nity of new trees rnhing out of eh internl nodeF he(ne funtion increment tht inrements the numer in every lef of nat treeF he(ne funtion leapfrog over nturl i nd tree ntF leapfrog should reurse into the ith hild of ntD the iCIst hild of tht nodeD the iCPnd hild of the next nodeD nd so onD until rehing lefD in whih se leapfrog should return the numer t tht lefF rove tht the result of ny ll to leapfrog is inremented y one y lling increment on the treeF SF he(ne type of trees of trees of trees of @repet to in(nityAF ht isD de(ne n indutive type trexpD whose memers re either se ses ontining nturl numers or inry trees of trexp sF fse your de(nition on prmeterized inry tree type btree tht you will lso de(neD so tht trexp is de(ned s nested indutive typeF he(ne funtion total tht sums ll of the nturls t the leves of trexpF he(ne funtion increment tht inrements every lef of trexp y oneF rove thtD for ll trD total @increment tr A total trF yn the wy to (nishing this proofD you will proly wnt to prove lemm nd dd it s hint using the syntx Hint Resolve name of lemmaFF TF rove disrimintion nd injetivity theorems for the nat btree type de(ned erlier in this hpterF sn prtiulrD without using the ttis discriminateD injectionD or congruenceD prove tht no lef equls ny nodeD nd prove tht two equl nodes rry the sme nturl numerF
TI
tt
unit
qllinF eprt from this theoretil onernD s will rgue tht it is most e'etive to do engineering with goq y employing di'erent tehniques for progrms versus proofsF wost of this ook is orgnized round tht distintionD desriing how to progrmD y pplying stndrd funtionl progrmming tehniques in the presene of dependent typesY nd how to proveD y writing ustom vt deision proeduresF ith tht perspetive in mindD this hpter is sort of mirror imge of the lst hpterD introduing how to de(ne predites with indutive de(nitionsF e will point out similrities in plesD ut muh of the e'etive goq user9s g of triks is disjoint for predites versus 4dttypesF4 his hpter is lso overt introdution to dependent typesD whih re the foundtion on whih interesting indutive predites re uiltD though we will rely on ttis to uild dependentlyEtyped proof terms for us for nowF e future hpter introdues more mnul pplition of dependent typesF
Theorem QedF
obvious'
constructorF
TQ
e n onlude nything from FalseD doing se nlysis on proof of False in the sme wy we might do se nlysis onD syD nturl numerF ine there re no ses to onsiderD ny suh se nlysis sueeds immeditely in proving the golF
neq
X P C P a S W C W a VQSF
et this pointD we hve n inonsistent hypothesis P C P a SD so the spei( onlusion is not importntF e use the elimtype tti to stte propositionD telling goq tht we wish to onstrut proof of the new proposition nd then prove the originl gol y se nlysis on the struture of the new uxiliry proofF ine False hs no onstrutorsD elimtype False simply leves us with the oligtion to prove FalseF
elimtype FalseF
XPCPaS aaaaaaaaaaaaaaaaaaaaaaaaaaaa
H
False
por nowD we will leve the detils of this proof out rithmeti to
crushF
QedF
crushF
e relted notion to
Print
not
notF
False
e see tht not is just shorthnd for implition of FalseF e n use tht ft expliitly in proofsF he syntx expnds to not P F
QedF
crushF
TR
conj
he interested reder n hek tht and hs gurryErowrd doppelgnger lled prodD the type of pirsF roweverD it is generlly most onvenient to reson out onjuntion using ttisF en expliit proof of ommuttivity of and illustrtes the usul suspets for suh tsksF is n in(x shorthnd for andF
Theorem
and comm
PF
P
QF
destruct IF
H
X Q aaaaaaaaaaaaaaaaaaaaaaaaaaaa Q P
H0
ivery proof of onjuntion provides proofs for oth onjuntsD so we get single sugol re)eting thtF e n proeed y splitting this sugol into se for eh onjunt of Q PF
splitF
P
subgoals H
X Q aaaaaaaaaaaaaaaaaaaaaaaaaaaa
H0 Q
subgoal P
P
is X
sn eh seD the onlusion is mong our hypothesesD so the assumption tti (nishes the proessF
or
or introl
or intror
e see tht there re two wys to prove disjuntionX prove the (rst disjunt or prove the seondF he gurryErowrd nlogue of this is the goq sum typeF e n demonstrte the min ttis here with nother proof of ommuttivityF
Theorem
or comm
PF
andD
destruct IF
P
subgoals
XP aaaaaaaaaaaaaaaaaaaaaaaaaaaa Q P
H
subgoal P Q P
is X
e n see thtD in the (rst sugolD we wnt to prove the disjuntion y proving its seond disjuntF he right tti telegrphs this intentF
right Y
assumptionF
QedF
left Y
assumptionF
st would e shme to hve to plod mnully through ll proofs out propositionl logiF vukilyD there is no needF yne of the most si goq utomtion ttis is tautoD whih is omplete deision proedure for onstrutive propositionl logiF @wore on wht 4onstrutive4 mens in the next setionFA e n use tauto to dispth ll of the purely propositionl theorems we hve proved so frF
comm'
PF
ometimes propositionl resoning forms importnt pluming for the proof of theoremD TT
ut we still need to pply some other smrts outD syD rithmetiF intuition is generE liztion of tauto tht proves everything it n using propositionl resoningF hen some gols reminD it uses propositionl lws to simplify them s fr s possileF gonsider this exmpleD whih uses the list ontention opertor CC from the stndrd lirryF
Theorem
arith comm
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
ls1 ls2
list natD
e lot of the proof struture hs een generted for us y intuitionD ut the (nl proof depends on ft out listsF he remining sugol hints t wht leverness we need to injetF 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 tht we need theorem out lengths of ontented listsD whih we proved lst hpter nd is lso in the stndrd lirryF
rewrite
ls1 ls2
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
ls2
xow the sugol follows y purely propositionl resoningF ht isD we ould reple length ls1 C length ls2 a T with P nd length ls1 a length ls2 with Q nd rrive t tutology of propositionl logiF
tautoF QedF intuition is one of the min its of glue in the implementtion of crushD soD with little helpD we n get short utomted proof of the theoremF Theorem
arith comm'
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
ls1 ls2
list natD
crushF
TU
QedF End
PropositionalF
TV
Theorem
exist1
natD x C I a PF
e n strt this proof with tti existsD whih should not e onfused with the formul onstrutor shorthnd of the sme nmeF @sn the hp version of this doumentD the reverse 9i9 ppers insted of the text 4exists4 in formulsFA
exists
IF
he onlusion is repled with version using the existentil witness tht we nnounedF aaaaaaaaaaaaaaaaaaaaaaaaaaaa ICIaP
reflexivityF QedF
e n lso use ttis to reson out existentil hypothesesF
Theorem exist2 X n m X natD @ x X natD n C x a m A n mF e strt y se nlysis on the proof of the existentil ftF destruct IF
XnCx am aaaaaaaaaaaaaaaaaaaaaaaaaaaa TW
he gol hs een repled y form where there is new free vrile x D nd where we hve new hypothesis tht the ody of the existentil holds with x sustituted for the old ound vrileF prom hereD the proof is just out rithmeti nd is esy to utomteF
QedF
crushF
he tti intuition hs (rstEorder ousin lled firstorderF firstorder proves mny formuls when only (rstEorder resoning is neededD nd it tries to perform (rstEorder simpli(tions in ny seF pirstEorder resoning is muh hrder thn propositionl resonE ingD so firstorder is muh more likely thn intuition to get stuk in wy tht mkes it run for long enough to e uselessF
constructorF
isZero HF
e n ll isZero judgmentD in the sense often used in the semntis of progrmming lngugesF tudgments re typilly de(ned in the style of natural deductionD where we write numer of inference rules with premises ppering ove solid line nd onlusion ppering elow the lineF sn this exmpleD the sole onstrutor IsZero of isZero n e thought of s the single inferene rule for deduing isZeroD with nothing ove the line nd isZero H elow itF he proof of isZero zero demonstrtes how we n pply n inferene ruleF he de(nition of isZero di'ers in n importnt wy from ll of the other indutive de(nitions tht we hve seen in this nd the previous hpterF snsted of writing just Set or Prop fter the olonD here we write nat PropF e sw exmples of prmeterized types like listD ut there the prmeters ppered with nmes before the olonF ivery onstrutor of prmeterized indutive type must hve rnge type tht uses the sme prmeterD wheres the form we use here enles us to use di'erent rguments to the type for di'erent onstrutorsF por instneD isZero fores its rgument to e HF e n see tht the onept of equlity is somehow impliit in the indutive de(nition mehnismF he wy this is omplished is similr to the wy tht logi vriles re used in rologD nd it is very powerful mehnism tht forms foundtion for formlizing ll of mthemtisF sn ftD though it is nturl to UH
think of indutive types s folding in the funtionlity of equlityD in goqD the true sitution is reversedD with equlity de(ned s just nother indutive type3
AA
Prop Xa
re equal
exmining the type of equlity9s sole onstrutor re equalD we see tht we n only prove equlity when its two rguments re synttilly equlF his de(nition turns out to pture ll of the si properties of equlityD nd the equlityEmnipulting ttis tht we hve seen so frD like reflexivity nd rewriteD re implemented treting eq s just nother indutive type with wellEhosen de(nitionF eturning to the exmple of isZeroD we n see how to mke use of hypotheses tht use this prediteF
eq is the type we get ehind the senes when uses of in(x a re expndedF e see tht eq hs oth prmeter x tht is (xed nd n extr unnmed rgument of the sme typeF he type of eq llows us to stte ny equlitiesD even those tht re provly flseF roweverD
Theorem isZero plus X n m X natD isZero m n C m a nF e wnt to proeed y ses on the proof of the ssumption out isZeroF destruct IF
n X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa n C H a n
ine isZero hs only one onstrutorD we re presented with only one sugolF he rgument m to isZero is repled with tht type9s rgument from the single onstrutor IsZeroF prom this pointD the proof is trivilF
QedF
crushF
enother exmple seems t (rst like it should dmit n nlogous proofD ut in ft provides demonstrtion of one of the most si goths of goq provingF
Theorem isZero contra X isZero I FalseF vet us try proof y ses on the ssumptionD s in the lst proofF destruct IF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa
False
st seems tht se nlysis hs not helped us muh t ll3 yur sole hypothesis disppersD leving usD if nythingD worse o' thn we were eforeF ht went wrongc e hve met n importnt restrition in ttis like destruct nd induction when pplied to types with UI
rgumentsF sf the rguments re not lredy free vrilesD they will e repled y new free vriles internlly efore doing the se nlysis or indutionF ine the rgument I to isZero is repled y fresh vrileD we lose the ruil ft tht it is not equl to HF hy does goq use this restritionc e will disuss the issue in detil in future hpterD when we see the dependentlyEtyped progrmming tehniques tht would llow us to write this proof term mnullyF por nowD we just sy tht the lgorithmi prolem of 4logilly omplete se nlysis4 is undeidle when phrsed in goq9s logiF e few ttis nd design ptterns tht we will present in this hpter su0e in lmost ll sesF por the urrent exmpleD wht we wnt is tti lled inversionD whih orresponds to the onept of inversion tht is frequently used with nturl dedution proof systemsF
contra'
isZero I P C P a SF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa ICIaR ht on erth hppened herec snternllyD destruct repled I with fresh vrileD ndD trying to e helpfulD it lso repled the ourrene of I within the unry representtion of eh numer in the golF his hs the net e'et of derementing eh of these numersF sf you re doing proof nd enounter strnge trnsmuttion like thisD there is good hne tht you should go k nd reple use of destruct with inversionF
AbortF
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 nturl dedution 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 tehniques of the lst setion re esily dptedF
Theorem QedF
even 0
constructorF
even HF even RF
Theorem QedF
even 4
st is not hrd to see tht sequenes of onstrutor pplitions like the ove n get tediousF e n void them using goq9s hint filityF
Hint
Constructors evenF
even 4'
contra
contra
X naI aaaaaaaaaaaaaaaaaaaaaaaaaaaa
H0
False
inversion n e little overzelous t timesD s we n see here with the introdution of the unused vrile n nd n equlity hypothesis out itF por more omplited preditesD thoughD dding suh ssumptions is ritil to deling with the undeidility of generl inversionF inversion QedF
H1F
Theorem even plus X n mD even n st seems resonle (rst hoie to proeed y indution on nF induction n Y
crushF
UQ
X X X
nat
IHn m H
H0
nd
H0
inversion
n
HF
X X X
nat
IHn m H
H1 X S n0 a n aaaaaaaaaaaaaaaaaaaaaaaaaaaa even @S @S n0 C m AA
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 indutive hypothesisD whih isX X X
IHn
nfortuntelyD the gol mentions n0 where it would need to mention n to mth IHnF e ould keep looking for wy to (nish this proof from hereD ut it turns out tht we n mke our lives muh esier y hnging our si strtegyF snsted of induting on the UR
struture of nD we should indut on the structure of one of the even proofsF his tehnique is ommonly lled rule induction in progrmming lnguge semntisF sn the setting of goqD we hve lredy seen how predites re de(ned using the sme indutive type mehnism s dttypesD so the fundmentl unity of rule indution with 4norml4 indution is pprentF
RestartF
induction IF
X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa even m even @H C m A
m
mA crushD
introF
simplY
constructorF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa even @n C m A xow we hve n ext mth with our indutive hypothesisD nd the reminder of the proof is trivilF
apply
IHeven Y crush
assumptionF
n hndle ll of the detils of the proof one we delre the indution
sn ftD strtegyF
RestartF
US
induction IY crushF QedF sndution on reursive predites hs similr pitflls to those we enountered with inverE sion in the lst setionF 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 lredy sunk trying to prove the (rst sugolD sine the rgument to even ws repled y fresh vrile internllyF his timeD we (nd it esiest to prove this theorem y wy of lemmF snsted of trusting induction to reple expressions with fresh vrilesD we do it ourselvesD expliitly dding the pproprite equlities 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 hs ny trikiness to itF destruct n Y destruct n0 Y crushF
n
IHeven n0
nat even @S nA
False
et this point it is useful to use theorem from the stndrd lirryD whih we lso proved with di'erent nme in the lst hpterF
Check
X
plus n SmF
plus n Sm
n
natD S @n C m A a n C S
apply
IHeven
with
n0 Y
assumptionF
es usulD we n rewrite the proof to void referening ny lollyEgenerted nmesD whih mkes our proof sript more redle nd more roust to hnges in the theorem sttementF e use the nottion to request hint tht does rightEtoEleft rewritingD just like we n with the rewrite ttiF
RestartF
Hint
Rewrite
plus n Sm
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 wy tht voids the use of lol vrile or hypothesis nmesD using the match tti form to do ptternEmthing on the golF e use uni(tion vriles pre(xed y question mrks in the ptternD nd we tke dvntge of the possiility to mention uni(tion vrile twie in one ptternD to enfore equlity etween ourrenesF he hint to rewrite with plus n Sm in prtiulr diretion sves us from hving to (gure out the right ple to pply tht theoremD nd we lso tke ritil dvntge of new ttiD eautoF crush uses the tti intuitionD whihD when it runs out of triks to try using only propositionl logiD y defult tries the tti autoD whih we sw in n erlier exmpleF auto ttempts rologEstyle logi progrmmingD serhing through ll proof trees up to erE tin depth tht re uilt only out of hints tht hve een registered with Hint ommndsF gompred to rologD auto ples n importnt restritionX it never introdues new uni(E tion vriles during serhF ht isD every time rule is pplied during proof serhD ll of its rguments must e deduile y studying the form of the golF eauto relxes this restritionD t the ost of possily exponentilly greter running timeF sn this prtiulr seD we know tht eauto hs only smll spe of proofs to serhD so it mkes sense to run itF st is ommon in e'etivelyEutomted goq proofs to see g of stndrd ttis pplied to pik o' the 4esy4 sugolsD (nishing with eauto to hndle the triky prts tht n ene(t from dEho exhustive serhF he originl theorem now follows trivilly from our lemmF
Theorem even contra X nD even @S @n C n AA FalseF introsY eapply even contra'Y eautoF QedF
e use vrint eapply of apply whih hs the sme reltionship to apply s eauto hs to autoF apply only sueeds if ll rguments to the rule eing used n e determined from the form of the golD wheres eapply will introdue uni(tion vriles for undetermined rgumentsF eauto is le to determine the right vlues for those uni(tion vrilesF fy onsidering n lternte ttempt t proving the lemmD we n see nother ommon pitfll of indutive proofs in goqF smgine tht we hd tried to prove even contra' with ll of the qunti(ers moved to the front of the lemm sttementF 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
yne sugol reminsX
n
n'
n'
@n C n A
NY
FalseF
N0
destruct
destruct
IHeven
False
e re out of luk hereF he indutive hypothesis is trivilly trueD sine its ssumption is flseF sn the version of this proof tht sueededD IHeven hd n expliit qunti(tion over nF his is euse the qunti(tion of n appeared after the thing we are inducting on in the theorem sttementF sn generlD qunti(ed vriles nd hypotheses tht pper efore the indution ojet in the theorem sttement sty (xed throughout the indutive proofF riles nd hypotheses tht re qunti(ed fter the indution ojet my e vried expliitly in uses of indutive hypothesesF hy should goq implement induction this wyc yne nswer is tht it voids urdening this si tti with dditionl heuristi smrtsD ut tht is not the whole pitureF smgine tht induction nlyzed dependenies mong vriles nd reordered qunti(ers to preE serve s muh freedom s possile in lter uses of indutive hypothesesF his ould mke the indutive hypotheses more omplexD whih ould in turn use prtiulr utomtion mhinery to fil when it would hve sueeded eforeF sn generlD we wnt to void qunE ti(ers in our proofs whenever we nD nd tht gol is furthered y the reftoring tht the induction tti fores us to doF
AbortF
4.6 Exercises
IF rove these tutologies of propositionl logiD using only the ttis applyD assumptionD constructorD destructD introD introsD leftD rightD splitD nd unfoldF @A @True @A @A
P P
@Q
@P
QA
@P
RA
PF rove the following tutology of (rstEorder logiD using only the ttis applyD assertD assumptionD destructD eapplyD eassumptionD nd existsF ou will proly (nd UV
assert useful for stting nd proving n intermedite lemmD enling kind of 4forE wrd resoningD4 in ontrst to the 4kwrd resoning4 tht is the defult for goq ttisF eassumption is version of assumption tht will do mthing of uni(tion vrilesF vet some vrile T of type Set e the set of individulsF x is onstnt symolD p is unry predite symolD q is inry predite symolD nd f is unry funtion symolF
@A
p x
@ x D
p x
yD
q x yA
x yD q x y
q y
@f y AA z D
q z
@f z A
QF he(ne n indutive predite pturing when nturl numer is n integer multiple of either T or IHF rove tht IQ does not stisfy your prediteD nd prove tht ny numer stisfying the predite is not oddF st is proly esiest to prove the seond theorem y inditing 4oddEness4 s equlity to P n C I for some nF RF he(ne simple progrmming lngugeD its semntisD nd its typing rulesD nd then prove tht wellEtyped progrms nnot go wrongF pei(llyX @A he(ne
var
@A he(ne n indutive type exp of expressionsD ontining nturl numer onstntsD nturl numer dditionD piring of two other expressionsD extrtion of the (rst omponent of pirD extrtion of the seond omponent of pirD nd vriles @sed on the var type you de(nedAF @A he(ne n indutive type cmd of ommndsD ontining expressions nd vrile ssignmentsF e vrile ssignment node should ontin the vrile eing sE signedD the expression eing ssigned to itD nd the ommnd to run fterwrdF @dA he(ne n indutive type pirings of vluesF
@eA he(ne type of vrile ssignmentsD whih ssign vlue to eh vrileF @fA he(ne igEstep evlution reltion evalD pturing wht it mens for n expresE sion to evlute to vlue under prtiulr vrile ssignmentF 4fig step4 mens tht the evlution of every expression should e proved with single inE stne of the indutive predite you will de(neF por instneD 4I C I evlutes to P under ssignment va 4 should e derivle for ny ssignment vaF @gA he(ne igEstep evlution reltion runD pturing wht it mens for ommnd to run to vlue under prtiulr vrile ssignmentF he vlue of ommnd is the result of evluting its (nl expressionF @hA he(ne type of vrile typingsD whih re like vrile ssignmentsD ut mp vriles to types insted of vluesF ou might use polymorphism to shre some ode with your vrile ssignmentsF @iA he(ne typing judgments for expressionsD vluesD nd ommndsF he expression nd ommnd ses will e in terms of typing ssignmentF UW
@jA he(ne predite varsType to express when vrile ssignment nd vrile typing gree on the types of vrilesF @kA rove tht ny expression tht hs type t under vrile typing vt evlutes under vrile ssignment va to some vlue tht lso hs type t in vtD s long s va nd vt greeF @lA rove tht ny ommnd tht hs type t under vrile typing vt evlutes under vrile ssignment va to some vlue tht lso hs type t in vtD s long s va nd vt greeF e few hints tht my e helpfulX @A yne esy wy of de(ning vrile ssignments nd typings is to de(ne oth s inE stnes of polymorphi mp typeF he mp type t prmeter T n e de(ned to e the type of ritrry funtions from vriles to T F e helpful funtion for implementing insertion into suh funtionl mp is eq nat decD whih you n mke ville with Require Import ArithFF eq nat dec hs dependent type tht tells you tht it mkes urte deisions on whether two nturl numers re equlD ut you n use it s if it returned oolenD eFgFD if eq nat dec n m then E1 else E2F @A sf you follow the lst hintD you my (nd yourself writing proof tht involves n expression with eq nat dec tht you would like to simplifyF unning destruct on the prtiulr ll to eq nat dec should do the trikF ou n utomte this dvie with piee of vtX
match goal with | context eq nat dec c c destruct @eq nat dec X Y A end @A ou proly do not wnt to use n indutive de(nition for omptiility of vrile ssignments nd typingsF @dA he Tactics module from this ook ontins vrint crush' of crushF crush' tkes two rgumentsF he (rst rgument is list of lemms nd other funtions to e tried utomtilly in 4forwrd resoning4 styleD where we dd new fts without eing sure yet tht they link into proof of the onlusionF he seond rgument is list of predites on whih inverison should e ttempted utomtillyF por instneD running crush' @lemma1D lemma2A pred will serh for hnes to pply lemma1 nd lemma2 to hypotheses tht re lredy villeD dding the new onluded ft if suitle hypotheses n e foundF snversion will e ttempted on ny hypothesis using predD ut only those inversions tht nrrow the (eld of possiilities to one possile rule will e keptF he formt of the list rguments to crush' is tht you n pss n empty list s ttD singleton list s the undorned single elementD nd multipleEelement list s tuple of the elementsF
VH
@eA sf you wnt crush' to pply polymorphi lemmsD you my hve to do little extr workD if the type prmeter is not free vrile of your proof ontext @so tht crush' does not know to try itAF por instneD if you de(ne polymorphi mp insert funtion assign of some type T X SetD FFFD nd you wnt prtiulr pplitions of assign dded utomtilly with type prmeter UD you would need to inlude assign in the lemm list s assign U @if you hve impliit rguments o'A or assign @T Xa U A or dassign U @if you hve impliit rguments onAF
VI
Fixpoint
bad
@u X
unitA X
Xa
bad uF
his would leve us with bad tt s proof of P F here re lso lgorithmi onsidertions tht mke universl termintion very desirleF e hve seen how ttis like reflexivity ompre terms up to equivlene under ompuE ttionl rulesF glls to reursiveD ptternEmthing funtions re simpli(ed utomtillyD with no need for expliit proof stepsF st would e very hrd to hold onto tht kind of ene(t if it eme possile to write nonEterminting progrmsY we would e running smk into the hlting prolemF yne solution is to use types to ontin the possiility of nonEtermintionF por instneD we n rete 4nonEtermintion mondD4 inside whih we must write ll of our generlE reursive progrmsF his is hevyweight solutionD nd so we would like to void it whenever possileF VP
vukilyD goq hs speil support for lss of lzy dt strutures tht hppens to ontin most exmples found in rskellF ht mehnismD co-inductive typesD is the sujet of this hpterF
or lzy listsF
he de(nition is surprisingly simpleF trting from the de(nition of listD we just need to hnge the keyword Inductive to CoInductiveF e ould hve left Nil onstrutor in our de(nitionD ut we will leve it out to fore ll of our strems to e in(niteF row do we write down strem onstntc yviously simple pplition of onstrutors is not good enoughD sine we ould only denote (nite ojets tht wyF therD wheres reursive de(nitions were neessry to use vlues of reursive indutive types e'etivelyD here we (nd tht we need co-recursive denitions to build vlues of oEindutive types e'etivelyF e n de(ne strem onsisting only of zeroesF
CoFixpoint
zeroes
nd
falseF
CoFixpoint trues X stream bool Xa Cons true with falses X stream bool Xa Cons false truesF
falses
goEindutive vlues re fir gme s rguments to reursive funtionsD nd we n use tht ft to write funtion to tke (nite pproximtion of stremF
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
Xa
nil
IHF VQ
true
XX
false
XX
true
XX
false
list bool
XX
true
XX
false
XX
true
XX
false
XX
true
XX
false
XX
nil
o frD it looks like oEindutive types might e mgi ulletD llowing us to import ll of the rskeller9s usul triksF roweverD there re importnt restritions tht re dul to the restritions on the use of indutive typesF pixpoints consume vlues of indutive typesD with restritions on whih arguments my e pssed in reursive llsF hullyD oE(xpoints produce vlues of oEindutive typesD with restritions on wht my e done with the results of oEreursive llsF he restrition for oEindutive types shows up s the guardedness conditionD nd it n e roken into two prtsF pirstD onsider this strem de(nitionD whih would e legl in rskellF
CoFixpoint
Error X
looper
Recursive
looper
In environment
stream nat
in 4looper4
he rule we hve run foul of here is tht every co-recursive call must be guarded by a constructor Y tht isD every oEreursive ll must e diret rgument to onstrutor of the oEindutive type we re genertingF st is good thing tht this rule is enforedF sf the de(nition of looper were eptedD our approx funtion would run forever when pssed looperD nd we would hve fllen into inonsistenyF he seond rule of gurdedness is esiest to see y (rst introduing more omplitedD ut leglD 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 literl opy of tht for the list map funtionD with the Nil se removed nd VR
Fixpoint hnged to CoFixpointF wny other stndrd funtions on lzy dt strutures n e implemented just s esilyF omeD like lterD nnot e implementedF ine the predite pssed to lter my rejet every element of the stremD we nnot stisfy even the (rst gurdedness onditionF he seond ondition is sutlerF o illustrte itD we strt o' with nother oEreursive funtion de(nition tht is leglF he funtion interleave tkes two strems nd produes new strem tht lterntes etween their elementsF Section interleaveF Variable A X SetF CoFixpoint interleave @s1 match s1D s2 with | Cons h1 t1D Cons h2 endF End interleaveF
s2 t2
stream AA X stream A Xa
Cons h1
@Cons
h2
@interleave
t1 t2 AA
xow sy we wnt to write weird stuttering version of prtiulr wyD sed on interlevingF
map
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 messge out n ungurded reursive llF his is euse we re violting the seond gurdedness onditionD whih sys thtD not only must oEreursive lls e rguments to onstrutorsD there must lso not be anything but matches and calls to constructors of the same co-inductive type wrpped round these immedite uses of oE reursive llsF he tul implemented rule for gurdedness is little more lenient thn wht we hve just sttedD ut you n ount on the illeglity of ny exeption tht would enhne the expressive power of oEreursionF hy enfore rule like thisc smgine thtD insted of interleaveD we hd lled some otherD less wellEehved funtion on stremsF erhps this other funtion might e de(ned mutully with map'F st might deonstrut its (rst rgumentD retrieving map' s from within Cons @f h A @map' s AF xext it might try match on this retrieved vlueD whih mounts to deonstruting map' s F o (gure out how this match turns outD we need to know the topElevel struture of map' s D ut this is extly wht we strted out trying to determine3 e run into loop in the evlution proessD nd we hve rehed witness of inonsisteny if we re evluting approx @map' s A I for ny s F
End
map'F
VS
ones ones'
onesF
ones'F
roweverD fed with the initil sugolD it is not t ll ler how this theorem n e provedF sn ftD it is unprovleF he eq predite tht we use is fundmentlly limited to equlities tht n e demonstrted y (niteD syntti rgumentsF o prove this equivleneD we will need to introdue new reltionF
AbortF
goEindutive dttypes mke sense y nlogy from rskellF ht we need now is co-inductive propositionF ht isD we wnt to de(ne proposition whose proofs my e in(niteD sujet to the gurdedness onditionF he ide of in(nite proofs does not show up in usul mthemtisD ut it n e very useful @unsurprisinglyA for resoning out in(nite dt struturesF fesides exmples from rskellD in(nite dt nd proofs will lso turn out to e useful for modelling inherently in(nite mthemtil ojetsD like progrm exeutionsF e re redy for our (rst oEindutive prediteF
Section stream eqF Variable A X SetF CoInductive stream eq X stream | Stream eq X h t1 t2D End
stream eqF
stream A Prop Xa
t1 A
@Cons
h t2 AF
e sy tht two strems re equl if nd only if they hve the sme heds nd their tils re equlF e use the norml (niteEsyntti equlity for the hedsD nd we refer to our new equlity reursively for the tilsF e n try restting the theorem with stream eqF
Theorem ones eq X stream eq ones ones'F goq does not support ttil oEindutive proofs s well s it supports ttil indutive proofsF he usul strting point is the cox ttiD whih sks to struture this proof s oE(xpointF
coxF
ones eq
assumptionF Proof
completedF
QedF
Error X
Recursive
X
In environment ones eq
i the gurryErowrd orrespondeneD the sme gurdedness ondition pplies to our oEindutive proofs s to our oEindutive dt struturesF e should e grteful tht this proof is rejetedD euseD if it were notD the sme proof struture ould e used to prove ny oEindutive theorem vuouslyD y diret ppel to itself3 hinking out how goq would generte proof term from the proof sript oveD we see tht the prolem is tht we re violting the (rst prt of the gurdedness onditionF huring our proofsD goq n help us hek whether we hve yet gone wrong in this wyF e n run the ommnd Guarded in ny ontext to see if it is possile to (nish the proof in wy tht will yield properly gurded proof termF
GuardedF
unning Guarded here gives us the sme error messge tht we got when we tried to run QedF sn lrger proofsD Guarded n e helpful in deteting prolems before we think we re redy to run QedF e need to strt the oEindution y pplying one of stream eq9s onstrutorsF o do thtD we need to know tht oth rguments to the predite re ConsesF snformllyD this is trivilD ut simpl is not le to help usF
UndoF simplF
ones eq
AbortF
pirstD we need to de(ne funtion tht seems pointless on (rst glneF
AA
stream A Xa
AAD s
frob sF
eq onesAF
eq ones'AF
X stream eq ones ones' aaaaaaaaaaaaaaaaaaaaaaaaaaaa stream eq @frob onesA @frob ones'A xow simpl is le to redue the stremsF
simplF
ones eq
X stream eq ones ones' aaaaaaaaaaaaaaaaaaaaaaaaaaaa stream eq @Cons I onesA @Cons I @@cox map @s X stream natA X stream nat Xa
VV
stream eq ones
@@cox
map
@s X
@map t A
mapD
assumptionF QedF
hy did this sillyElooking trik helpc he nswer hs to do with the onstrints pled on goq9s evlution rules y the need for termintionF he cox Erelted restrition tht foiled our (rst ttempt t using simpl is dul to restrition for xF sn prtiulrD n pplition of n nonymous x only redues when the topElevel struture of the reursive rgument is knownF ytherwiseD we would e unfolding the reursive de(nition d in(nitumF pixpoints only redue when enough is known out the denitions of their rgumentsF hullyD oE(xpoints only redue when enough is known out how their results will be usedF sn prtiulrD cox is only expnded when it is the disriminee of matchF ewriting with our super(illy silly lemm wrpped new matches round the two cox esD triggering redutionF sf cox es redued hphzrdlyD it would e esy to run into in(nite loops in evlutionD sine we reD fter llD uilding in(nite ojetsF yne ommon soure of di0ulty with oEindutive proofs is d intertion with stndrd goq utomtion mhineryF sf we try to prove ones eq' with utomtionD like we hve in previous indutive proofsD we get n invlid proofF
ones ones'F
he stndrd auto mhinery sees tht our gol mthes n ssumption nd so pplies tht ssumptionD even though this violtes gurdednessF yne usully strts proof like this y destructing some prmeter nd running ustom tti to (gure out the (rst proof rule to pply for eh seF elterntivelyD there re triks tht n e plyed with 4hiding4 the oEindutive hypothesisF
VW
Definition Definition
yur instrutions re loding of onstnt into registerD opying from one register to notherD unonditionl jumpD nd onditionl jump sed on whether the vlue 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 mps from registers to vluesF o de(ne funtion set for setting register9s vlue in mpD we import the Arith module from goq9s stndrd lirryD nd we use its funtion eq nat dec for ompring nturl numersF
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 indutive exec judgment ptures the e'et of n instrution on the progrm 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 tht exec represents totl funtionF sn our proof sriptD we use match tti with context ptternF his prtiulr exmple (nds n ourrene of pttern Jnz cr nywhere in the urrent sugol9s onlusionF e use goq lirry tti case eq to do se nlysis on whether the urrent vlue rs r of the register r is zero or notF case eq di'ers from destruct in sving n equlity relting the old vrile to the new form we dedue 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 redy to de(ne oEindutive judgment pturing the ide tht progrm runs foreverF e de(ne the judgment in terms of progrm progD represented s funtion mpping eh lel to the instrution found thereF
label
instrF
regs
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
Prop Xa
xow we n prove tht ny strting ddress nd register nk led to sfe in(nite exE eutionF ell tht proofs of existentillyEqunti(ed formuls re ll uilt with single onstrutor of the indutive type exF his mens tht we n use destruct to 4open up4 suh proofsF sn the proof elowD we wnt to perform this opening up on n pproprite use of the exec total lemmF his lemm9s onlusion egins with two existentil qunti(ersD so we wnt to tell destruct tht it should not stop t the (rst qunti(erF e omplish our gol y using n intro pattern with destructF gonsult the goq mnul for the detils of intro ptternsY the spei( pttern c c c tht we use here omplishes our gol of destruting oth qunti(ers t oneF
Theorem
cox Y
safe pc rsF
always safe
pc rsD
rs
@prog
pc AA
as c c cY
sf we print the proof term tht ws genertedD we n verify tht the proof is strutured s coxD with eh oEreursive ll properly gurdedF
always safeF
WI
5.4 Exercises
IF @A he(ne oEindutive type of in(nite trees rrying dt of (xed prmeter typeF ih node should ontin dt vlue nd two hild treesF @A he(ne funtion everywhere for uilding tree with the sme dt vlue t every nodeF @A he(ne funtion map for uilding n output tree out of two input trees y trversE ing them in prllel nd pplying twoErgument funtion to their orresponding dt vluesF @dA he(ne tree
falses
falseF
@eA he(ne tree true false where the root node hs vlue trueD its hildren hve vlue falseD ll nodes t the next hve the vlue trueD nd so onD lternting oolen vlues from level to levelF @fA rove tht true false is equl to the result of mpping the oolen 4or4 funtion orb over true false nd falsesF ou n mke orb ville with Require Import BoolFF ou my (nd the lemm orb false r from the sme module helpfulF our proof here should not e out the stndrd equlity aD ut rther out some new equlity reltion tht you de(neF
WP
WQ
Print predF pred a fun n X nat match n with |HH |S u u end X nat nat
e n use new ommndD
Extraction predF ExtractionD
(** val pred : nat -> nat **) let pred = function | O -> O | S u -> u
eturning H s the predeessor of H n ome ross s somewht of hkF sn some WR
situtionsD we might like to e sure tht we never try to tke the predeessor of HF e n enfore this y giving pred strongerD dependent typeF
Lemma QedF
zgtz
crushF
X HbH
FalseF
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 expnd the type of pred to inlude proof tht its rgument n is greter thn HF hen n is HD we use the proof to derive ontrditionD whih we n use to uild vlue of ny type vi vuous pttern mthF hen n is suessorD we hve no need for the proof nd just return the nswerF he proof rgument n e sid to hve dependent typeD euse its type depends on the value of the rgument nF yne spets in prtiulr of the de(nition of pred strong1 tht my e surprisingF e took dvntge of Definition9s syntti sugr for de(ning funtion rguments in the se of nD ut we ound the proofs lter with expliit fun expressionsF vet us see wht hppens if we write this funtion in the wy tht t (rst seems most nturlF
Definition pred strong1' @n X natA @pf X match n with | O match zgtz pf with end | S n' n' endF
Error X In environment
n
b HA X
nat Xa
nat
has
type 4n b H4 while
it is expected to have
type
he term zgtz pf fils to typeEhekF omehow the type heker hs filed to tke into ount informtion tht follows from whih match rnh tht term ppers inF he prolem is thtD y defultD match does not let us use suh implied informtionF o get re(ned typingD we must lwys rely on match nnottionsD either written expliitly or inferredF sn this seD we must use return nnottion to delre the reltionship etween the value of the match disriminee nd the type of the resultF here is no nnottion tht lets us delre reltionship etween the disriminee nd the type of vrile tht is lredy in sopeY heneD we dely the inding of pfD so tht we n use the return nnottion to express the needed reltionshipF e re luky tht goq9s heuristis infer the return luse @spei(llyD return n b H WS
natA for us in this seF sn generlD howeverD the inferene prolem is undeidleF he known
undeidle prolem of higher-order unication redues to the match type inferene prolemF yver timeD goq is enhned with more nd more heuristis to get round this prolemD ut there must lwys exist matches whose types goq nnot infer without nnottionsF vet us now tke look t the ygml ode goq genertes 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 hs disppered3 e get extly the ygml ode we would hve written mnullyF his is our (rst demonstrtion of the min tehnilly interesting feture of goq progrm extrtionX progrm omponents of type Prop re ersed systemtillyF e n reimplement our dependentlyEtyped pred sed on subset typesD de(ned in the stndrd lirry with the type fmily 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 gurryErowrd twin of exD exept tht sig is in TypeD while ex is in PropF ht mens tht sig vlues n survive extrtionD while ex proofs will lwys e ersedF he tul detils of extrtion of sigs re more sutleD s we will see shortlyF
e rewrite
pred strong1D
Locate
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
let pred_strong2 = function | O -> assert false (* absurd case *) | S n' -> n'
e rrive t the sme ygml ode s ws extrted from pred strong1D whih my seem surprising t (rstF he reson is tht vlue of sig is pir of two pieesD vlue nd proof out itF ixtrtion erses the proofD whih redues the onstrutor exist of sig to tking just single rgumentF en optimiztion elimintes uses of dttypes with single onstrutors tking single rgumentsD nd we rrive k where we strtedF e n ontinue on in the proess of re(ning pred9s typeF vet us hnge its result type to pture tht the output is relly the predeessor 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
S m}
Xa
he funtion proj1 sig extrts the se vlue from suset typeF fesides the use of tht funtionD the only other new thing is the use of the exist onstrutor to uild new sig vlueD nd the detils of how to do tht follow from the output of our erlier Print ommndF st lso turns out tht we need to inlude n expliit return luse hereD sine goq9s heuristis re not smrt enough to propgte the result type tht we wrote erlierF fy nowD the reder is proly redy to elieve tht the new pred strong leds to the sme ygml ode s we hve seen severl times so frD nd goq does not disppointF
Extraction pred strong3F
(** val pred_strong3 : nat -> nat **) let pred_strong3 = function | O -> assert false (* absurd case *) | S n' -> n'
e hve mnged to reh type tht isD in forml senseD the most expressive possile for predF eny other implementtion of the sme type must hve the sme inputEoutput ehviorF roweverD there is still room for improvement in mking this kind of ode esier to writeF rere is version tht tkes dvntge of ttiEsed theorem provingF e swith k to pssing seprte proof rgument insted of using suset type for the funtion9s inputD euse this leds to lener odeF
Definition pred strong4 @n X natA X refine @fun n match n with | O fun False rec
b H {m X
nat | n a S m }F
WU
exist
n'
e uild pred strong4 using ttiEsed provingD eginning with Definition ommnd tht ends in period efore de(nition is givenF uh ommnd enters the intertive proving modeD with the type given for the new identi(er s our proof golF e do most of the work with the refine ttiD to whih we pss prtil 4proof4 of the type we re trying to proveF here my e some piees left to (ll inD indited y undersoresF eny undersore tht goq nnot reonstrut with type inferene is dded s proof sugolF sn this seD we hve two sugolsX P
subgoals
False
subgoal P S n' a S
is X n'
e n see tht the (rst sugol omes from the seond undersore pssed to False recD nd the seond sugol omes from the seond undersore pssed to existF sn the (rst seD we see thtD though we ound the proof vrile with n undersoreD it is still ville in our proof ontextF st is hrd to refer to undersoreEnmed vriles in mnul proofsD ut utomtion mkes short work of themF foth sugols re esy to dishrge tht wyD so let us k up nd sk to prove ll sugols utomtillyF
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 insted of QedD so tht the de(nition we onstruted remins visileF his ontrsts to the se of ending proof with QedD where the detils of the proof re hidden fterwrdF vet us see wht our proof sript onstrutedF
pred strong4F
n0
S m }A
with
WV
fun
False
end
@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
S m}
AAAAA
natD n b H {m X nat | n a S
m}
e see the ode we enteredD with some proofs (lled inF he (rst proof oligtionD the seond rgument to False recD is (lled in with nstyElooking proof term tht we n e gld we did not enter y hndF he seond proof oligtion is simple re)exivity proofF e re lmost done with the idel implementtion of dependent predeessorF e n use goq9s syntx extension fility to rrive t ode with lmost no omplexity eyond rskell or wv progrm with omplete spei(tion in ommentF
AF AF
n
Definition pred strong5 @n X natA X refine @fun n match n with | O fun 3 | S n' fun n' endAY crushF DefinedF
b H {m X
nat | n a S m }F
yne other lterntive is worth demonstrtingF eent goq versions inlude fility lled Program tht stremlines this style of de(nitionF rere is omplete implementtion using ProgramF
crushF
pred strong6
@n X
natA @ X
b HA X {m X
nat | n a S m } Xa
rinting the resulting de(nition of pred strong6 yields term very similr to wht we uilt with refineF Program n sve time in writing progrms tht use suset typesF xonethelessD refine is often just s e'etiveD nd refine gives you more ontrol over the form the (nl term tkesD whih n e useful when you wnt to prove dditionl theorems out your de(nitionF Program will sometimes insert type sts tht n omplite theoremEprovingF WW
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 nottions to mke working with AF Notation 49es94 Xa @left AF Notation 49xo94 Xa @right Notation 49edue9 x4 Xa @if x then
sumbool
more onvenientF
Yes
else
No A
@at
level
SHAF
he Reduce nottion is notle euse it demonstrtes how if is overloded in goqF he if form tully works when the test expression hs ny twoEonstrutor indutive typeF woreoverD in the then nd else rnhesD the pproprite onstrutor rguments re oundF his is importnt when working with sumbool sD when we wnt to hve the proof stored in the test expression ville when proving the proof oligtions generted in the pproprite rnhF xow we n write eq nat decD whih ompres two nturl numersD returning either proof of their equlity or proof of their inequlityF
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 extrts to resonle ygml odeF
Extraction eq nat decF
m }F
(** 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
Definition DefinedF
eq nat dec'
decide equalityF
@n
natA X {n a m } C {n = m }F
gurious reders n verify tht the decide equality version extrts to the sme ygml ode s our more mnul version doesF ht ygml ode hd one undesirle propertyD whih is tht it uses Left nd Right onstrutors insted of the oolen vlues uilt into ygmlF e n (x thisD y using goq9s fility for mpping goq indutive types to ygml vrint typesF
Extract Extraction eq nat dec'F
Inductive
sumbool
(** 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 4smrt4 versions of the usul oolen opertors nd put them to good use in erti(ed progrmmingF por instneD here is sumbool version of oolen 4orF4
Notation 4x || y4 Xa @if
then
Yes
else Reduce y AF
vet us use it for uilding funtion tht deides list memershipF e need to ssume the existene of n equlity deision proedure for the type of list elementsF
x y
AD
{x a y } C {x = y }F
he (nl funtion is esy to write using the tehniques we hve developed so frF
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
A eq dec x x'
||
f x ls'
In dec
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')
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
P AAF
is trivil to writeF
n
Definition pred strong7 @n X natA X {{m | refine @fun n match n with | O cc | S n' n' endAY trivialF DefinedF
S m }}F
IHP
feuse we used maybeD one vlid implementtion of the type we gve pred strong7 would return cc in every seF e n strengthen the type to rule out suh vuous implementtionsD nd the type fmily sumor from the stndrd lirry provides the esiest strting pointF por type A nd proposition B D A C {B } desugrs to sumor A B D whose vlues re either vlues 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 nottions for esy use of the sumor onstrutorsF he seond nottion is speE ilized to sumor s whose A prmeters re instntited with regulr suset typesD sine this is how we will use sumor elowF AF Notation 4334 Xa @inright Notation 4 x 4 Xa @inleft x AF xow we re redy to give the (nl version of possilyEfiling predeessorF he sumor E sed type tht we use is mximlly expressiveY ny implementtion of the type hs the sme inputEoutput ehviorF
Definition pred strong8 @n X natA X {m X nat | refine @fun n match n with | O 33 | S n' n' endAY trivialF DefinedF
S m}
C {n a H}F
Notation 4x eI Y eP4 Xa @match e1 with | Unknown cc | Found x e2 endA @right associativityD at level THAF
he mening of x e1 Y e2 isX pirst run e1 F sf it fils to (nd n nswerD then nnoune filure for our derived omputtionD tooF sf e1 does (nd n nswerD pss tht nswer on to e2 to (nd the (nl resultF he vrile x n e onsidered ound in e2F IHQ
his nottion is very helpful for omposing rihlyEtyped proeduresF por instneD here is very simple implementtion of funtion to tke the predeessors of two nturls t oneF
Definition doublePred @n1 n2 X natA X {{p | refine @fun n1 n2 m1 pred strong7 n1 Y m2 pred strong7 n2 Y @m1D m2 AAY tautoF DefinedF
n1
@fst p A
n2
@snd p A}}F
e n uild sumor version of the 4ind4 nottion nd use it to write similrly strightforwrd version of this funtionF
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 AAY tautoF DefinedF
S
e2
@snd p A}
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 lnguge of types nd its typing rulesD in the style introdued in ghpter RF
TNat
TBoolF
e1 e2D
| |
HtBool HtAnd
st will e helpful to hve funtion for ompring two typesF e uild one using equalityF
Definition DefinedF
eq type dec
decide equalityF
t1 t2
enother nottion omplements the mondi nottion for maybe tht we de(ned erlierF ometimes we wnt to inlude 4ssertions4 in our proeduresF ht isD we wnt to run deision proedure nd fil if it filsY otherwiseD we wnt to ontinueD with the proof tht it produed mde ville to usF his in(x nottion ptures tht ideD for proedure tht returns n ritrry twoEonstrutor typeF
e2
else ccA
ith tht nottion de(nedD we n implement typeCheck funtionD whose ode is only more omplex thn wht we would write in wv euse it needs to inlude some extr type nnottionsF ivery e expression dds hasType proof oligtionD nd crush mkes short work of them when we dd hasType9s onstrutors 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 }}
e t }}F
Xa
IHS
t2
F e2 Y
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 typeEheker lso extrts to some resonle ygml 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 dpt this implementtion to use sumorD so tht we know our typeEheker only fils on illEtyped inputsF pirstD we de(ne n nlogue to the 4ssertion4 nottionF
Notation 4eI YYY eP4 Xa @if e1 then @right associativityD at level THAF
e2
else 33A
xextD we prove helpful lemmD whih sttes tht given expression n hve t most one typeF
Lemma
hasType e
t2D
hasType det
e t1D
t1 t2 crushF
hasType e
xow we n de(ne the typeEhekerF sts type expresses tht it only fils on untyple 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 oligtions with ontrditory ontextsF ine its sttement inludes Eound vriles tht do not pper in its onlusionD only eauto will pply this hintF
pinllyD the implementtion of nottions s neededF
typeCheck
refine @x F @e X expA X {t X type | hasType match e with | Nat TNat | Plus e1 e2 t1 F e1 Y
IHU
C { tD
hasType e t } Xa
t2
F e2 Y
crush' tt
hasTypeY eautoF
e ler FD the lol nme for the reursive funtionD to void strnge proofs tht refer to reursive lls tht we never mkeF he crush vrint crush' helps us y performing utomti inversion on instnes of the predites spei(ed in its seond rgumentF yne we throw in eauto to pply hasType det for usD we hve dishrged ll the sugolsF
DefinedF
he short implementtion here hides just how timeEsving utomtion isF ivery use of one of the nottions dds proof oligtionD giving us IP in totlF wost of these oligtions require multiple inversions nd either uses of hasType det or pplitions of hasType rulesF he results of simplifying lls to typeCheck' look deeptively similr to the results for typeCheckD ut now the types of the results provide more informtionF
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 nottions de(ned in this hpterD plus some extrsD re ville for import from the module MoreSpecif of the ook soureF IHV
IF rite funtion of type n m X natD {n m } C {n b m }F ht isD this funtion deides whether one nturl is less thn notherD nd its dependent type gurntees tht its results re urteF PF @A he(ne
var D
natF
@A he(ne n indutive type prop of propositionl logi formulsD onsisting of vriE lesD negtionD nd inry onjuntion nd disjuntionF @A he(ne funtion propDenote from vrile truth ssignments nd props to PropD sed on the usul menings of the onnetivesF epresent truth ssignments s funtions from var to boolF @dA he(ne funtion bool true dec tht heks whether oolen is trueD with mximlly expressive dependent typeF ht isD the funtion should hve type bD {b a true} C {b a true False}F @eA he(ne funtion decide tht determines whether prtiulr prop is true under prtiulr truth ssignmentF ht isD the funtion should hve type @truth X var boolA @p X propAD {propDenote truth p } C { propDenote truth p }F his funtion is proly esiest to write in the usul ttil styleD insted of progrmming with refineF bool true dec my ome in hndy s hintF @fA he(ne funtion negate tht returns simpli(ed version of the negtion of propF ht isD the funtion should hve type p X propD {p' X prop | truthD propDenote truth p propDenote truth p' }F o simplify vrileD just negte itF implify negtion y returning its rgumentF implify onjuntions nd disjuntions using he worgn9s lwsD negting the rguments reursively nd swithing the kind of onnetiveF decide my e useful in some of the proof oligtionsD even if you do not use it in the omputtionl prt of negate 9s de(nitionF vemms like decide llow us to ompenste for the lk of generl vw of the ixluded widdle in gsgF QF smplement the hvv stis(ility deision proedure for oolen formuls in onjunE tive norml formD with dependent type tht gurntees its orretnessF en exmple of resonle type for this funtion would e f X formulaD {truth X tvals | formulaTrue truth f } C { truthD formulaTrue truth f }F smplement t lest 4the si ktrking lgorithm4 s de(ned hereX
http://en.wikipedia.org/wiki/DPLL_algorithm
st might lso e instrutive to implement the unit propgtion nd pure literl elimiE ntion optimiztions desried there or some other optimiztions tht hve een used in modern e solversF
IHW
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 thtD within its setionD ilist is given type nat SetF reviouslyD every indutive type we hve seen hs either hd plin Set s its type or hs een predite with some type ending in PropF he full generlity of indutive de(nitions lets us integrte the expressivity IIH
of predites diretly into our norml progrmmingF he nat rgument to ilist tells us the length of the listF he types of ilist9s onstrutors tell us tht Nil list hs length O nd tht Cons list hs length one greter thn the length of its sulistF e my pply ilist to ny nturl numerD even nturl numers tht re only known t runtimeF st is this reking of the phase distinction tht hrterizes ilist s dependently typedF sn expositions of list typesD we usully see the length funtion de(ned (rstD ut here tht would not e very produtive funtion to odeF snstedD let us implement list ontenE 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
ilist @n1 C n2 A Xa
it is expected to have
type
sn goq9s ore lngugeD without expliit nnottionsD goq does not enrih our typing ssumptions in the rnhes of match expressionF st is ler tht the uni(tion vrile cIR should e resolved to H in this ontextD so tht we hve H C n2 reduing to n2D ut goq does not relize thtF e nnot (x the prolem using just the simple return luses we pplied in the lst hpterF e need to omine return luse with new kind of nnottionD n in luseF his is extly wht the inferene heuristis do in goq VFP nd lterF pei(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 dependeny of the match result type on the value of the disrimineeF ht in dds to our rsenl is wy of expressing dependeny on the type of the disrimineeF pei(llyD the n1 in the in luse ove is binding occurrence whose sope is the return luseF e my use in luses only to ind nmes for the rguments of n indutive type fmilyF ht isD eh in luse must e n indutive type fmily nme pplied to sequene of undersores nd vrile nmes of the proper lengthF he positions for parameters to the type fmily must ll e undersoresF rmeters re those rguments delred with setion vriles or with entries to the left of the (rst olon in n indutive de(nitionF hey nnot III
vry depending on whih onstrutor ws used to uild the disrimineeD so goq prohiits pointless mthes on themF st is those rguments de(ned in the type to the right of the olon tht we my nme with in lusesF yur app funtion ould e typed in soElled stratied type systemsD whih void true dependenyF e ould onsider the length indies to lists to live in seprteD ompileEtimeE only universe from the lists themselvesF yur next exmple would e hrder to implement in strti(ed systemF e write n injetion funtion from regulr lists to lengthEindexed listsF e strti(ed implementtion would need to duplite 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 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
ls A
Xa
Xa
@inject
ls A
a lsF
xow let us ttempt funtion tht is surprisingly triky to writeF sn wvD the list hed funtion rises n exeption when pssed n empty listF ith lengthEindexed listsD we n rule out suh invlid lls sttillyD 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
Xa
st is not ler wht to write for the Nil seD so we re stuk efore we even turn our funtion over to the type hekerF e ould try omitting the Nil seX
Xa
IIP
patternEmthingX
no clause found
for pattern
Nil
nlike in wvD we nnot use inexhustive pttern mthingD euse there is no onepE tion of Match exeption to e thrownF e might try using n in luse 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
Xa
in
sn this nd other sesD we feel like we wnt in luses with type fmily rguments tht re not vrilesF nfortuntelyD goq only supports vriles in those positionsF e ompletely generl mehnism ould only e supported with solution to the prolem of higherEorder uni(tionD whih is undeidleF here are useful heuristis for hndling nonE vrile indies whih re grdully mking their wy into goqD ut we will spend some time in this nd the next few hpters on e'etive pttern mthing on dependent types using only the primitive match nnottionsF yur (nlD working ttempt t hd uses n uxiliry funtion nd surprising return nnottionF
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
with
@ls X
ilist @S n AA X
Xa
hd' lsF
e nnotte our min match with type tht is itself matchF e write tht the funtion 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 feuse the index of ls is known to e nonzeroD the type heker redues the match in the type of hd' to AF
End
ilistF
n implement tagless interpreter tht oth removes this soure of runtime ine0eny nd gives us more on(dene tht our implementtion is orretF
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
| | | | | |
BConst And If
X bool exp Bool X exp Bool exp Bool exp Bool X tD exp Bool exp t exp t exp
t t1 t2 A
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
Pair
e hve stndrd lgeri dttype typeD de(ning type lnguge of nturlsD oolensD nd produt @pirA typesF hen we hve the indexed indutive type expD where the rgument to exp tells us the enoded type of n expressionF sn e'etD we re de(ning the typing rules for expressions simultneously with the syntxF e n give types nd expressions semntis in new styleD sed ritilly on the hne 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 ojet lnguge into 4ntive4 goq typesF st is deepE tively esy to implementF he only new thing we see is the 7type nnottionD whih tells goq to prse the match expression using the nottions ssoited with typesF ithout this nnottionD the would e interpreted s multiplition on nturlsD rther thn s the produt type onstrutorF type is one exmple of n identifer ound to notation scopeF e will del more expliitly with nottions nd nottion sopes in lter hptersF e n de(ne funtion expDenote tht 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
| | | |
Eq e1 e2 BConst b If
if
eq nat dec
@expDenote
e1 A
@expDenote
e2 A
then
true
else
false
And e1 e2
e'
b expDenote e1 88 expDenote e2 e1 e2 if expDenote e' then expDenote @expDenote e1D e' fst @expDenote e' A e' snd @expDenote e' A
e1 e2
expDenote e2 A
e1
else
expDenote e2
hespite the fny typeD the funtion de(nition is routineF sn ftD it is less omplited thn wht we would write in wv or rskell WVD sine we do not need to worry out pushing (nl vlues in nd out of n lgeri dttypeF he only unusul thing is the use of n expression of the form if E then true else false in the Eq seF ememer tht eq nat dec hs rih dependent typeD rther thn simple oolen typeF goq9s ntive if is overloded to work on test of ny twoEonstrutor typeD so we n use if to uild simple oolen from the sumbool tht eq nat dec returnsF e n implement our old fvoriteD onstnt folding funtionD nd prove it orretF st will e useful to write funtion pairOut tht heks if n exp of Prod type is pirD returning its two omponents if soF nsurprisinglyD (rst ttempt leds 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
Error X The reference t2 was not found
t2A
Xa
in the current environment e run gin into the prolem of not eing le to speify nonEvrile rguments in in lusesF he prolem would just e hopeless without use of n in luseD thoughD sine the result type of the match depends on n rgument to expF yur solution will e to use more generl typeD s we did for hdF pirstD we de(ne typeEvlued funtion to use in ssigning type to pairOutF Definition pairOutType @t X typeA Xa match t with | Prod t1 t2 option @exp t1 exp | unit endF
t2 A
hen pssed type tht is produtD pairOutType returns our (nl desired typeF yn ny other input typeD pairOutType returns unitD sine we do not re out extrting omponents of nonEpirsF xow we n write nother helper funtion to provide the defult ehvior of IIS
pairOutD
Definition pairOutDefault @t X typeA Xa match t return @pairOutType t A with | Prod None | tt endF
xow
pairOut
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 importnt sutlety in this de(nitionF goq llows us to use onvenient wvE style pttern mthing nottionD utD internlly nd in proofsD we see tht ptterns re expnded out ompletelyD mthing one level of indutive struture t timeF husD the defult se in the match ove expnds out to one se for eh onstrutor of exp esides is resolved di'erently in eh seF prom n PairD nd the undersore in pairOutDefault wv or rskell progrmmer9s perspetiveD wht we hve here is type inferene determining whih ode is run @returning either None or ttAD whih goes eyond wht is possile with type inferene guiding prmetri polymorphism in rindleyEwilner lngugesD ut is similr to wht goes on with rskell type lssesF ith pairOut villeD we n write cfold in strightforwrd wyF here re relly no surprises eyond tht goq veri(es tht this ode hs suh n expressive typeD given the smll nnottion urdenF sn some plesD we see tht goq9s match nnottion inferene is too smrt for its own goodD nd we hve to turn tht inferene 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
b2 A
| |
Pair Fst
e1 e2 e
Pair
@cfold
e1 A
@cfold
e2 A
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 orretness theorem for serious hurdleF
cfold
Xa cfold
@e X
@cfold
e1 A
expDenote
@cfold
e2 A
expDenote
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 nlysis on cfold e1 D nd we ttempt tht in the wy tht hs worked so frF
destruct @cfold
e1 AF
in
hypothesis e
goq gives us nother rypti error messgeF vike so mny othersD this one silly mens tht goq is not le to uild some proof out dependent typesF st is hrd to generte helpful nd spei( error messges for prolems like thisD sine tht would require some kind of understnding of the dependeny struture of piee of odeF e will enounter mny exmples of seEspei( triks for reovering from errors like this oneF por our urrent proofD we n use tti dep destruct de(ned in the ook Tactics moduleF qenerl elimintionGinversion of dependentlyEtyped hypotheses is undeidleD sine it must e implemented with match expressions tht hve the restrition on in luses tht we hve lredy disussedF dep destruct mkes est e'ort to hndle some ommon sesD relying upon the more primitive dependent destruction tti tht omes with goqF sn future hpterD we will lern out the expliit mnipultion of equlity proofs tht is ehind dep destruct 9s implementtion in vtD ut for nowD we tret it s useful lk oxF
dep destruct
@cfold
e1 AF
exp
his suessfully reks the sugol into S new sugolsD one for eh onstrutor of IIV
tht ould produe n exp NatF xote tht dep destruct is suessful in ruling out the other ses utomtillyD in e'et utomting some of the work tht we hve done mnully in implementing funtions like hd nd pairOutF his is the only new trik we need to lern to omplete the proofF e n k up nd give shortD utomted proofF he min inonveniene in the proof is tht we nnot write pttern tht mthes match without inluding se for every onstrutor of the indutive type we mth overF
RestartF
cfold
| | |
dep destruct
Eq If Fst
@cfold
EA
QedF
dep destruct
| None @cfold E A
else A a
destruct
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 vlue of type rbtree c d is redElk tree node whose root hs olor c nd tht hs lk depth dF he ltter property mens tht there re no more thn d lkEolored nodes on ny pth from the root to lefF et (rstD it n e unler tht this hoie of type indies trks ny useful propertyF o onvine ourselvesD we will prove tht every redElk tree is lnedF e will phrse our theorem in terms of depth lulting funtion tht ignores the extr informtion in the typesF st will e useful to prmeterize this funtion over omining opertionD so tht
IIW
we n reEuse the sme ode to lulte the minimum or mximum height mong ll pths from root to lefF
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 lnedEness deomposes nturlly into lower ound nd n upper oundF e prove the lower ound (rstF nsurprisinglyD tree9s lk depth provides suh ound on the minimum pth lengthF e use the rihlyEtyped proedure min dec to do se nlysis on whether min X Y equls 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 nlogous upperEound theorem sed on lk depthF nfortuntelyD symmetri proof sript does not su0e to estlish 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 sugols reminF 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
C IF
t1
IPH
e see tht IHt1 is almost the ft we needD ut it is not quite strong enoughF e will need to strengthen our indution hypothesis to get the proof to go throughF
AbortF sn prtiulrD we prove lemm tht provides stronger upper ound for trees with lk root nodesF e got stuk ove in se out red root nodeF ine red nodes hve only lk hildrenD our sr strengthening will enle 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 originl theorem follows esily from the lemmF e use the tti generalize pfD whihD when pf proves the proposition P D hnges the gol from Q to P Q F st is useful to do this euse it mkes the truth of P mnifest synttillyD so tht utomtion mhinery n rely on P D even if tht mhinery is not smrt enough to estlish 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 (nl lne theorem estlishes tht the minimum nd mximum pth lengths of ny tree re within ftor of two of eh 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 redy to implement n exmple opertion on our treesD insertionF snsertion n e thought of s reking the tree invrints lolly ut then relningF sn prtiulrD in intermedite sttes we (nd red nodes tht my hve red hildrenF he type rtree ptures the ide of suh nodeD ontinuing to trk lk 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 strting to de(ne insertD we de(ne predites pturing when dt vlue is in the set represented y norml or possilyEinvlid treeF Section presentF
IPI
Variable
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
rtree n A X Prop Xa
present a
a y b
present b
snsertion relies on two lning opertionsF st will e useful to give types to these opertions using reltive of the suset types from lst hpterF hile suset types let us pir vlue with proof out tht vlueD here we wnt to pir vlue with nother nonEproof dependentlyEtyped vlueF he sigT type (lls this roleF
Locate
4{ X 8 }4F @fun X
PA
sigT
Inductive
existT
ih lne funtion is used to onstrut new tree whose keys inlude the keys of two input treesD s well s new keyF yne of the two input trees my violte the redElk lterntion invrint @tht isD it hs n rtree typeAD while the other tree is known to e vlidF gruillyD the two input trees hve the sme lk depthF e lne opertion my return tree whose root is of either olorF husD we use sigT type to pkge the result tree with the olor of its rootF rere is the de(nition of the (rst lne opertionD whih pplies when the possilyEinvlid rtree elongs to the left of the vlid 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
a x b
fun
c d a
x bA
@BlackNode
c data d Ab}
endF
end
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 {`flkxode @RedNode a y b A data t b} end t1'
t2
e pply trik tht s ll the convoy patternF ell tht match nnottions only mke it possile to desrie dependene of match result type on the disrimineeF here is no utomti re(nement of the types of free vrilesF roweverD it is possile to e'et suh re(nement y (nding wy to enode free vrile type dependenies in the match result typeD so tht return luse n express the onnetionF sn prtiulrD 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 wnting to re(ne the type of one tree vrile t timeF e mth on one sutree of nodeD nd we wnt the type of the other sutree to e re(ned sed on wht we lernF e indite this with return luse strting like rbtree n FFFD where n is ound in n in ptternF uh match expression is pplied immeditely to the 4old version4 of the vrile to e re(nedD nd the type heker is hppyF efter writing this odeD even s do not understnd the preise detils of how lning worksF s onsulted ghris ykski9s pper 4edEflk rees in puntionl etting4 nd trnsried the ode to use dependent typesF vukilyD the detils re not so importnt hereY types lone will tell us tht insertion preserves lnedEnessD nd we will prove tht insertion produes trees ontining the right keysF rere is the symmetri funtion balance2D for ses where the possilyEinvlid tree ppers on the right rther thn 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
a t
{`flkxode
t data
@RedNode
a z b Ab}
xow we re lmost redy to get down to the usiness of writing n insert funtionF pirstD we enter setion tht delres vrile x D for the key we wnt to insertF
Definition insResult c n Xa match c with | Red rtree n | Black { c' X color 8 rbtree endF
c' n
ht isD inserting into tree with root olor c nd lk depth nD the vriety of tree we get out depends on cF sf we strted with red rootD then we get k possilyEinvlid tree of depth nF sf we strted with lk rootD we get k vlid tree of depth n with root node of n ritry olorF rere is the de(nition of insF eginD we do not wnt to dwell on the funtionl detilsF
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 trik is vrition of the onvoy ptternF sn eh of the lst two pttern IPR
mthesD we wnt to tke dvntge of the typing onnetion etween the trees a nd bF e might nively pply the onvoy pttern diretly on a in the (rst match nd on b in the seondF his stisi(es the type heker per seD ut it does not stisfy the termintion hekerF snside eh matchD we would e lling ins reursively on lollyEound vrileF he termintion heker is not smrt enough to tre the dt)ow into tht vrileD so the heker does not know tht this reursive rgument is smller thn the originl rgumentF e mke this ft lerer y pplying the onvoy pttern on the result of a recursive callD rther thn just on tht ll9s rgumentF pinllyD we re in the home streth of our e'ort to de(ne insertF e just need few more de(nitions of nonEreursive funtionsF pirstD we need to give the (nl hrteriztion of insert9s return typeF snserting into redErooted tree gives lkErooted tree where lk depth hs inresedD nd inserting into lkErooted tree gives tree where lk depth hs styed the sme nd where the root is n ritrry olorF
Definition insertResult c n Xa match c with | Red rbtree Black @S n A | Black { c' X color 8 rbtree endF Definition makeRbtree c n X match c with | Red fun r match r with a x | RedNode' end | Black fun r r endF
c' n
} into
insertResultsF
insResults
insResult c n
insertResult c n
Xa
BlackNode a x b
e modify goq9s defult hoie of impliit rguments for makeRbtreeD so tht we do not need to speify the c nd n rguments expliitly in lter llsF
Implicit Arguments
pinllyD we de(ne
makeRbtree c n F
insert
s simple omposition of
ins
nd Xa
makeRbtreeF
Definition
insert c n
makeRbtree
@ins t AF
@t X
rbtree c n A X
insertResult c n
es we noted erlierD the type of insert gurntees tht it outputs lned trees whose depths hve not inresed too muhF e lso wnt to know tht insert opertes orretly on trees interpreted s (nite setsD so we (nish this setion with proof of tht ftF
giving us the fts we wntedF e strt y proving the orretness of the lne opertionsF st is useful to de(ne ustom tti present balance tht enpsultes the resoning ommon to the two proofsF e use the keyword Ltac to ssign nme to proof sriptF his prtiulr sript just itertes etween crush nd identi(tion of tree tht is eing ptternEmthed on nd should e destrutedF
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 lne orretness theorems re simple (rstEorder logi equivlenesD where we use the funtion projT2 to projet the pylod of sigT vlueF
present z @projT2 @balance1 a y b AA rpresent z a z a y present z bF destruct a Y present balanceF QedF
Lemma
present balance1
@a X
Lemma
present balance2
@a X
o stte the theorem for insD it is useful to de(ne new typeElevel funtionD sine ins returns di'erent result types sed on the type indies pssed to itF ell tht x is the setion vrile stnding 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 sttement nd proof of the
ins
z t
oseF e proeed y indution on the struture of treeD followed y (nding se nlysis opportunities on expressions we see eing nlyzed in if or match expressionsF efter thtD we ptternEmth to (nd opportunities to use the theorems we proved out lningF piE nllyD we identify two vriles tht re sserted y some hypothesis to e equlD nd we use tht hypothesis to reple one vrile with the other everywhereF
Theorem
present insResult t
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
present ins
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
he hrd work is doneF he most redle wy to stte orretness of insert involves splitting the property into two olorEspei( theoremsF e write tti to enpsulte the IPU
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
@t X
rbtree Red n AD
z t AF
Theorem
present z
@z a
present
@t X
rbtree Black n AD
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
starF
xow we n mke our (rst ttempt t de(ning regexp type tht is indexed y predites on stringsF rere is resonleElooking de(nition tht is restrited to onstnt hrters nd ontentionF
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 Epropositionl inductive types must be
P2 AD
in Type
ht is lrge indutive typec sn goqD it is n indutive type tht hs onstrutor whih qunti(es over some type of type TypeF e hve not worked with Type very muh to this pointF ivery term of gsg hs typeD inluding Set nd PropD whih re ssigned type TypeF he type string Prop from the filed de(nition lso hs type TypeF st turns out tht llowing lrge indutive types in Set leds to ontrditions when omined with ertin kinds of lssil logi resoningF husD y defultD suh types re ruled outF here is simple (x for our regexp de(nitionD whih is to ple our new type in TypeF hile (xing the prolemD we lso expnd the list of onstrutors to over the remining regulr expression opertorsF
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
wny theorems out strings re useful for implementing erti(ed regexp mtherD nd few of them re in the Strings lirryF he ook soure inludes sttementsD proofsD nd hint ommnds for hndful of suh omittted theoremsF ine they re orthogonl to our use of dependent typesD we hide them in the rendered versions of this ookF e few uxiliry funtions help us in our (nl mther de(nitionF he funtion split will e used to implement the regexp ontention 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 hoie of two ritrry string predites nd funtions for deiding themF
IPW
Variable s X stringF yur omputtion will tke ple reltive to single (xed stringD so it is esiest to mke it VariableD rther thn n expliit rgument to our funtionsF
is the workhorse ehind splitF st serhes through the possile wys of splitting s into two pieesD heking the two predites ginst eh suh pirF split' progresses rightE toEleftD from splitting ll of s into the (rst piee to splitting ll of s into the seond pieeF st tkes n extr rgumentD nD whih spei(es how fr long we re in this serh proessF
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 c9 S cx generalize @eq nat dec @length S' A @S N AAY destruct I endY crushF DefinedF
here is one sutle point in the split' ode tht is worth mentioningF he min ody of the funtion is match on nF sn the se where n is known to e S n'D we write S n' in severl ples where we might e tempted to write nF roweverD without further work to rft proper match nnottionsD the typeEheker does not use the equlity etween n nd S n'F husD it is ommon to see ptterns repeted in match se odies in dependentlyEtyped goq odeF e n t lest use let expression to void opying the pttern more thn oneD repling the (rst se ody withX
S n'
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'
split itself is trivil to implement in terms of split'F e just sk split' to egin its serh with n a length s F Definition
split
X {
s1D
s2D s
s1
CC
s2
P1 s1
P2 s2 }
IQH
CC s2 P1 s1 P2 s2 }F refine @Reduce @split' @n Xa length s A AAY crush Y eautoF DefinedF End splitF
s1
C {
s1 s2D s
Implicit Arguments
split P1 P2 F
yne more helper funtion will ome in hndyX dec starD for implementing nother liner serh through wys of splitting stringD this time for implementing the uleene strF
P s }F
ome new lemms nd hints out the star type fmily re useful hereF e omit them hereY they re inluded in the ook soure t this pointF he funtion dec star implements single itertion of the strF ht isD it tries to (nd string pre(x mthing P D nd it lls prmeter funtion on the reminder of the stringF
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 instntite serh for more instnes of P in s F
P' dec
xow we ome to dec star itselfF st tkes s n input nturl l tht reords how muh of the string hs een serhed so frD s we did for split'F he return type expresses tht dec star is looking for n index into s tht splits s into nonempty pre(x nd su0xD suh tht the pre(x stis(es P nd the su0x stis(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
E @n C
S l' AA s A}
E @n C
S l' AA s A}
| |
O S
l'
P' dec
@n' Xa
S l' A
destruct @eq
nat dec X
@S
Y AAY crush
he work of dec star is nested inside nother liner serh y dec star'D whih provides the (nl funtionlity we needD ut for ritrry su0xes of s D rther thn just for s overllF
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
n' A
pinllyD we hve dec starF st hs strightforwrd implementtionF e introdue spurious mth on s so tht simpl will know to redue lls to dec starF he heuristi tht 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
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 mny of its elements stisfy prtiulr prediteF sn prtiulrD for n riE trry set A nd predite P over itX @A he(ne type plist X nat SetF ih plist n should e list of AsD where it is gurnteed tht t lest n distint elements stisfy P F here is wide ltitude in hoosing how to enode thisF ou should try to void using suset types or ny other mehnism sed on nnotting nonEdependent types with propositions fterEtheEftF @A he(ne version of list ontention tht works on plist sF he type of this new funtion should express s muh informtion s possile out the output plistF @A he(ne funtion
plistOut
for trnslting
plist s
to norml
@dA he(ne funtion plistIn for trnslting lists to plist sF he type of plistIn should mke it ler tht the est ound on P Emthing elements is hosenF ou my ssume tht you re given dependentlyEtyped funtion for deiding instnes of PF @eA rove thtD for ny list lsD plistOut @plistIn ls A a lsF his should e the only prt of the exerise where you use ttiEsed provingF @fA he(ne funtion grab X n @ls X plist @S nAAD sig P F ht isD when given plist gurnteed to ontin t lest one element stisfying P D grab produes suh IQQ
listsF
n elementF sig is the type fmily of sigm typesD nd sig P is extensionlly equivlent to {x X A | P x }D though the ltter form uses n etEexpnsion of P insted of P itself s the prediteF
IQR
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 hve erti(ed funtion for seleting n element of n ilist y positionF e ould do this using suset types nd expliit mnipultion of proofsD ut dependent types let us do it more diretlyF st is helpful to de(ne type fmily nD where n n is isomorphi to {m X nat | m ` n}F he type fmily nmes stnds for 4(niteF4
n essentilly mkes more rihlyEtyped opy of the nturl numersF ivery element
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
Xa
e pply the usul wisdom of delying rguments in Fixpoints so tht they my e inluded in return lusesF his still leves us with qundry in eh of the match sesF pirstD we need to (gure out how to tke dvntge of the ontrdition in the Nil seF ivery n hs type of the form S nD whih nnot unify with the O vlue tht we lern 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 |OA | 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 typeEheksD nd we see tht the prolem with the Cons se is tht the ptternEound vrile idx' does not hve n pprent type omptile with ls'F e need to use match nnottions to mke the reltionship expliitF nfortuntelyD the usul trik of postponing rgument inding will not help us hereF e need to mth on oth ls nd idx Y one or the other must e mthed (rstF o get round thisD we pply the onvoy pttern tht we met lst hpterF his pplition is little more lever thn those we sw eforeY we use the nturl numer predeessor funtion pred to express the reltionship IQT
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 |OA | 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 prolem left with this implementtionF hough we know tht the lol ls' in the Next se is equl to the originl ls'D the typeEheker is not stis(ed tht the reursive ll to get does not introdue nonEtermintionF e solve the prolem y onvoyE inding the prtil pplition of get to ls'D rther thn 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 |OA | 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 AF First n F
with
IQU
Check
X
Cons
H @Cons I @Cons P
NilAA
NilAAF
Cons
ilist nat Q
H @Cons I @Cons P
get
NilAAA FirstF
get
NilAAA
@Next
FirstAF
get
NilAAA
@Next @Next
FirstAAF
yur get funtion is lso quite esy to reson outF e show how with short exmple out n nlogue to the list map funtionF
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 esy to prove tht get 4distriutes over4 imap llsF he only triky it is rememE ering to use the dep destruct tti in ple of plin destruct when fed with 1ing tti error messgeF
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
done in vriety of wys in rskell using type lssesD nd we n do it muh more lenly nd diretly in goqF
nd n
AEindexed
type
BF
Inductive hlist X list A Type Xa | MNil X hlist nil | MCons X @x X AA @ls X list AAD B x hlist
ls
hlist @x XX ls AF
e n implement vrint of the lst setion9s get funtion for hlistsF o get the dependent typing to work outD we will need to index our element seletors y the types of dt tht they point toF
Variable
elm
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
feuse the element elm tht we re 4serhing for4 in list does not hnge ross the onstrutors of memberD we simplify our de(nitions y mking elm lol vrileF sn the de(nition of memberD we sy tht elm is found in ny list tht egins with elm D ndD if removing the (rst element of list leves elm presentD then elm is present in the originl listD tooF he form looks muh like predite for list memershipD ut we purposely de(ne member in Type so tht we my deompose its vlues to guide omputtionsF e n use member to dpt our de(nition of get to hlistsF he sme si match triks pplyF sn the MCons seD we form twoEelement onvoyD pssing oth the dt element x nd the reursor for the sulist mls' to the result of the inner matchF e did not need to do tht in get9s de(nition euse 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
End
endF
elm A
elm
fy putting the prmeters A nd B in TypeD we llow some very higherEorder usesF por instneD one use of hlist is for the simple heterogeneous lists tht we referred to erlierF
Definition Example
MCons
someTypes
nilF
someValues
S @MCons
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 Example
MCons somePairs MFirstAF
e n lso uild indexed lists of pirs in this wyF @ID PA @MCons @trueD X
de fruijn vrile representtionD whih we will disuss in more detil in lter hptersF riles re represented s member vluesY tht isD vrile is more or less onstrutive proof tht prtiulr 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 Const ts F
exp ts
ts
dom
@Arrow
dom ran AF
exp ts
ran
Implicit Arguments
Fixpoint typeDenote @t X typeA X Set Xa match t with | Unit unit | Arrow t1 t2 typeDenote t1 typeDenote endF
t2
xow it is strightforwrd to write n expression interpreterF he type of the funtionD expDenoteD tells us tht we trnslte expressions into funtions from properlyEtyped environE ments to (nl vluesF en environment for free vrile list ts is simply hlist typeDenote tsF ht isD for eh free vrileD the heterogeneous list tht is the environment must hve vlue of the vrile9s ssoited typeF e use hget to implement the Var seD nd we use MCons to extend the environment in the Abs seF
ts t A
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
vike for previous exmplesD our interpreter is esy to run with simplF
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
x
Unit
@Arrow
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
@Var
MFirstAAA MNilF
e re strting to develop the tools ehind dependent typing9s mzing dvntge over lterntive pprohes in severl importnt resF rereD we hve implemented omplete syntxD typing rulesD nd evlution semntis for simplyEtyped lmd lulus without even needing to de(ne syntti sustitution opertionF e did it ll without single line of proofD nd our implementtion is mnifestly exeutleF sn lter hpterD we will meet otherD more ommon pprohes to lnguge formliztionF uh pprohes often stte nd prove expliit theorems out type sfety of lngugesF sn the ove exmpleD we got type sfetyD termintionD nd other metEtheorems for freeD y redution to gsgD whih we know hs those propertiesF
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 sy tht list of length H hs no ontentsD nd list of length vlue nd list of length n'F
S n'
is pir of dt
Fixpoint n @n X natA X Set Xa match n with | O Empty set | S n' option @n n' A endF
IRP
e express tht there re no index vlues when n a OD y de(ning suh indies s type Empty setY nd we express thtD t n a S n'D there is hoie etween piking the (rst element of the list @represented s NoneA or hoosing lter element @represented y Some idxD where idx is n index into the list tilAF
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
Xa
yur new get implementtion needs only one dependent matchD nd its nnottion is inferred for usF yur hoies of dt struture implementtions led to just the right typing ehvior for this new de(nition to work outF
End
listF
reterogeneous lists re little trikier to de(ne with reursionD ut we then rep similr ene(ts in simpliity 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 dt elementsF
Variable
elm
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 hve no memersD nd memer types for nonempty lists re uilt y dding one new option to the type of memers of the list tilF hile for index we needed no new informtion ssoited with the option tht we ddD here we need to know tht the hed of the list equls the element we IRQ
re serhing forF e express tht with sum type whose left rnh is the pproprite equlity propositionF ine we de(ne fmember to live in TypeD we n insert Prop types s neededD euse Prop is sutype of TypeF e know ll of the triks needed to write (rst ttempt t get funtion 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 prolem reminsF he expression fst mls is not known to hve the proper typeF o demonstrte tht it doesD we need to use the proof ville 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 ptternEmthing on the equlity proof pfD we mke tht equlity known to the typeE hekerF ixtly why this works n e seen y studying the de(nition of equlityF
AA
Prop Xa
re equal
sn proposition x a yD we see tht x is prmeter nd y is regulr rgumentF he type of the onstrutor re equal shows tht y n only ever e instntited to x F husD within ptternEmth with re equalD ourrenes of y n e repled with ourrenes of x for typing purposesF
End
Implicit Arguments
IRR
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 hs nturl numer rgumentD whih gives the numer of hild trees in the seond rgumentD typed with ilistF e n de(ne two opertions on trees of nturlsX summing their elements nd inrementing their elementsF st is useful to de(ne generi fold funtion 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 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 tht
inc
t'
C nA
O ls
sumF
sum
@inc t A
sum tF
IRS
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
H @imap n0 A H i
n0 A
inc iA
e re left with single sugol whih does not seem provle diretlyF his is the sme prolem tht we met in ghpter Q with other nested indutive typesF
Check
tree indF
tree ind
@Node iAA
he utomtillyEgenerted indution priniple is too wekF por the Node seD it gives us no indutive hypothesisF e ould write our own indution prinipleD s we did in ghpter QD ut there is n esier wyD if we re willing to lter the de(nition of treeF
AbortF
Reset treeF
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
4tree4 in
he speilEse rule for nested dttypes only works with nested uses of other indutive typesD whih ould e repled with uses of new mutullyEindutive typesF e de(ned list reursivelyD so it my not e used for nested reursionF yur (nl solution uses yet nother of the indutive de(nition tehniques introdued in ghpter QD re)exive typesF snsted of merely using n to get elements out of ilistD we n dene ilist in terms of nF por the resons outlined oveD it turns out to e esier to work with n in ple of nF
e Node is indexed y nturl numer nD nd the node9s n hildren re represented s funtion from n n to treesD whih is isomorphi to the ilistEsed representtion tht we used oveF
End
treeF Node A n F
Implicit Arguments
e n rede(ne sum nd inc for our new tree typeF eginD it is useful to de(ne generi fold funtion (rstF his timeD it tkes in funtion whose rnge is some n typeD nd it folds nother funtion over the results of lling the (rst funtion t every possile n vlueF
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
rifoldr A B n F
idx
get
@Some
idx AAA
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 redy to prove the theorem where we got stuk eforeF e will not need to de(ne ny new indution prinipleD ut it will e helpful to prove some lemmsF
y2D
n n
natAD
IRU
plus
f2F
induction n Y QedF
crushF
sum tF
Theorem sum inc X tD sum @inc t A Hint Resolve sum inc'F induction t Y QedF
crushF
iven if goq would generte omplete indution priniples utomtilly for nested inE dutive de(nitions like the one we strted withD there would still e dvntges to using this style of re)exive enodingF e see one of those dvntges in the de(nition of incD where we did not need to use ny kind of uxiliry funtionF sn generlD re)exive enodings often dmit diret implementtions of opertions tht would require reursion if performed with more trditionl indutive dt struturesF
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
@n
@n
exp'
e Cond is prmeterized y nturl nD whih tells us how mny ses this onditionl hsF he test expressions re represented with funtion of type n n exp' BoolD nd the odies re represented with funtion of type n n exp' t D where t is the overll typeF he (nl exp' t rgument is the defult seF e strt implementing our interpreter with stndrd type denottion funtionF
| Bool endF
bool
o implement the expression interpreterD it is useful to hve the following funtion tht implements the funtionlity of Cond without involving ny syntxF
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 strightforwrd 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 cond
default A
exp'Denote exp'Denote
endF e will implement onstntEfolding funtion tht optimizes onditionlsD removing ses with knownEfalse tests nd ses tht ome fter knownEtrue testsF e funtion cfoldCond implements the hert of this logiF he onvoy pttern is used gin ner the end of the implementtionF Section cfoldCondF
IRW
Variable Variable
type'F default X exp' tF Fixpoint cfoldCond @n X natA X @n n exp' BoolA @n n exp' t A exp' t Xa
t
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'
fun
body
Cond
I @fun @fun
End
endF
end
end @bodies
NoneA
Implicit Arguments
vike for the interpretersD most of the tion ws in this helper funtionD nd is esy to writeF ISH
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
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 (nl orretness theoremD it is useful to know tht cfoldCond preserves expression meningsF his lemm formlizes tht propertyF he proof is stndrd mostlyE utomted oneD with the only wrinkle eing guided instnttion of the qunti(ers in the indution 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
QedF
ci with | NConst | Plus | Eq | BConst | Cond end dep destruct E | context if cf then else destruct endY crush AF
context match
st is lso useful to know tht the result of ll to cond is not hnged y sustituting new tests nd odies funtionsD so long s the new funtions hve the sme inputEoutput ehvior s the oldF st turns out thtD in goqD it is not possile to prove in generl tht funtions relted in this wy re equlF e tret this issue with our disussion of xioms in lter hpterF por nowD it su0es to prove tht the prtiulr funtion cond is extensional Y tht isD it is un'eted y sustitution of funtions with inputEoutput equivlentsF
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 (nl theorem is esy to proveF e dd our two lemms s hints nd perform stndrd utomtion with ptternEmthing of suterms to destrutF
Theorem
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
cfold correct
induction e Y crush Y repeat @match goal with | context cfold ci endY crush AF QedF
dep destruct
@cfold
EA
ISP
8.6 Exercises
ome of the type fmily de(nitions nd ssoited funtions from this hpter re duplited in the DepList module of the ook soureF ome of their nmes hve een hnged to e more sensile in generl ontextF IF he(ne tree nlogue of hlistF ht isD de(ne prmeterized type of inry trees with dt t their levesD nd de(ne type fmily htree indexed y treesF he struture of n htree mirrors its index treeD with the type of eh dt element @whih only our t levesA determined y pplying type funtion to the orresponding element of the index treeF he(ne type stnding for ll possile pths from the root of tree to leves nd use it to implement funtion tget for extrting n element of n htree y pthF he(ne funtion htmap2 for 4mpping over two trees in prllelF4 ht isD ISQ
htmap2
tkes in two htree s with the sme index treeD nd it forms new the sme index y pplying inry funtion pointwiseF
htree
with
epet this proess so tht you implement eh de(nition for eh of the three de(niE tion styles overed in this hpterX indutiveD reursiveD nd index funtionF PF rite dependentlyEtyped interpreter for simple progrmming lnguge with wvE style ptternEmthingD using one of the enodings of heterogeneous lists to represent the di'erent rnhes of case expressionF @here re other wys to represent the sme thingD ut the point of this exerise is to prtie using those heterogeneous list typesFA he ojet lnguge is de(ned informlly y this grmmrX
t p
e
e of
p eB |
stnds for vrileD nd b stnds for oolen onstntF he prodution for case expressions mens tht ptternEmth inludes zero or more pirs of ptterns nd expressionsD long with defult seF our interpreter should e implemented in the style demonstrted in this hpterF ht isD your de(nition of expressions should use dependent types nd de fruijn indies to omine syntx nd typing rulesD suh tht the type of n expression tells the types of vriles tht re in sopeF ou should implement simple reursive funtion trnslting types t to SetD nd your interpreter should produe vlues in the imge of this trnsltionF
x
ISR
Definition pred' @x X natA Xa match x with |OO | S n' let y Xa n' in y endF Theorem
reduce me
pred'
I a HF
gsg follows the trditions of lmd lulus in ssoiting redution rules with qreek lettersF goq n ertinly e sid to support the fmilir lph redution ruleD whih llows ISS
ptureEvoiding renming of ound vrilesD ut we never need to pply lph expliitlyD sine goq uses de fruijn representtion tht enodes terms nonillyF he delt rule is for unfolding glol de(nitionsF e n use it here to unfold the de(nition of pred'F e do this with the cbv ttiD whih tkes list of redution rules nd mkes s mny llEyEvlue redution steps s possileD using only those rulesF here is n nlogous tti lazy for llEyEneed redutionF
cbv deltaF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa @fun x X nat match x with |HH | S n' let y Xa n' in y endA I a H et this pointD we wnt to pply the fmous et redution of lmd lulusD to simplify the pplition of known funtion strtionF
cbv betaF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa match I with |HH | S n' let y Xa n' in y end a H xext on the list is the iot redutionD whih simpli(es single match term y determining whih pttern mthesF
cbv iotaF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa @fun n' X nat let y Xa n' in y A H a H xow we need nother et redutionF
cbv betaF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa @let y Xa H in y A a H he (nl redution rule is zetD whih reples let expression y its ody with the pproprite term susitutedF
cbv zetaF
IST
aaaaaaaaaaaaaaaaaaaaaaaaaaaa HaH
reflexivityF QedF
he stndrd eq reltion is ritilly dependent on the de(nitionl equlityF eq is often lled propositional equalityD euse it rei(es de(nitionl equlity s proposition tht my or my not holdF tndrd xiomtiztions of n equlity predite in (rstEorder logi de(ne equlity in terms of properties it hsD like re)exivityD symmetryD nd trnsitivityF sn ontrstD for eq in goqD those properties re impliit in the properties of the de(nitionl equlityD whih re uilt into gsg9s mettheory nd the implementtion of qllinF e ould dd new rules to the de(nitionl equlityD nd eq would keep its de(nition nd methods of useF his ll my mke it sound like the hoie of eq9s de(nition is unimportntF o the ontrryD in this hpterD we will see exmples where lternte de(nitions my simplify proofsF fefore tht pointD we will introdue e'etive proof methods for gols tht use proofs of the stndrd propositionl equlity 4s dtF4
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
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'
Implicit Arguments
e n de(ne
mapElike
funtion 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 indutive versions of the ilist de(nitionsD we proved lemm out the intertion of get nd imapF st ws strtegi hoie not to ttempt suh proof for the de(nitions tht we just gveD euse tht sets us on ollision ourse with the prolems tht re the sujet of this hpterF
Variable
elm
AF
fhlist B ls AD
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
rt of our single remining sugol isX
a0
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
end
a0
must e
re equalD
sine tht is the only onstrutor of eqF hereforeD oth the matches redue to the point where the onlusion follows y re)exivityF
destruct
a0F
his is one of goq9s stndrd error messges for informing us tht its heuristis for ttempting n instne of n undeidle prolem out dependent typing hve filedF e might try to nudge things in the right diretion y stting the lemm tht we elieve mkes the onlusion trivilF
assert @a0 a
The term
re equal
AF
has
sn retrospetD the prolem is not so hrd to seeF e)exivity proofs only show x a x for prtiulr vlues of x D wheres here we re thinking in terms of proof of a a elm D where the two sides of the equlity re not equl synttillyF husD the essentil lemm we need does not even typeEhek3 ss it time to throw in the towelc vukilyD the nswer is 4noF4 sn this hpterD we will see severl useful ptterns for proving oligtions like thisF por this prtiulr exmpleD the solution is surprisingly strightforwrdF destruct hs simpler siling case whih should ehve identilly for ny indutive type with one onstrutor of no rgumentsF
case
a0F
aaaaaaaaaaaaaaaaaaaaaaaaaaaa f a1 a f a1 st seems tht destruct ws trying to e too smrt for its own goodF
reflexivityF QedF
st will e helpful to exmine the proof terms generted y this sort of strtegyF e simpler exmple illustrtes wht is going onF
Lemma QedF
lemma1
simple
pf
with
re equal
endF
destruct pf is onvenient form for pplying caseF st runs intro to ring into sope ll qunti(ed vriles 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 wht we know out shorthnds for match nnottionsD we n write this proof in shorter form mnullyF
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 wht seems t (rst like
simpler
O
Lemma
lemma2
X @x X
pfF
AA
@pf X
a x AD
a match
with
re equal
endF
simple
destruct
AbortF
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 tht would simplify proofs of mny fts like
lemma2X
Lemma
lemma3
X @x X
pfF
AA
@pf X
a x AD
pf
re equal xF
simple
destruct
ITH
AbortF
his timeD even our mnul ttempt filsF
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
with
4x a x94
has
it is expected to have
type
he type error omes from our return nnottionF sn tht nnottionD the asEound vrile pf ' hs type x a x'D refering to the inEound vrile x'F o do dependent matchD we must hoose fresh nme for the seond rgument of eqF e re just s onstrined to use the 4rel4 vlue x for the (rst rgumentF husD within the return luseD the proof we re mthing on must equte two nonEmthing termsD whih mkes it impossile to equte tht proof with re)exivityF xonethelessD it turns out thtD with one thD we can prove this lemmF
a x AD
pf
re equal xF
X @U X TypeA @x X
UA
@p X
a x AD
re equal x
UIP re omes from the Eqdep module of the stndrd lirryF ho the goq uthors know of some lever trik for uilding suh proofs tht we hve not seen yetc sf they doD they did not use it for this proofF therD the proof is sed on n axiomF
Print fun
U
eq rect eqF
eq rect eq
Q pA
@h X
a p AD
sttes 4ft4 tht seems like ommon senseD one the nottion is deipheredF eq rect is the utomtillyEgenerted reursion priniple for eqF glling eq rect is nother wy of matching on n equlity proofF he proof we mth on is the rgument hD nd x is the ody of the matchF eq rect eq just sys tht matches on proofs of p a pD for ny pD re
eq rect eq
ITI
super)uous nd my e removedF erhps surprisinglyD we nnot prove eq rect eq from within goqF his proposition is introdued s n xiomY tht isD proposition sserted s true without proofF e nnot ssert just ny sttement without proofF edding False s n xiom would llow us to prove ny propositionD for instneD defeting the point of using proof ssistntF sn generlD we need to e sure tht we never ssert inconsistent sets of xiomsF e set of xioms is inonsistent if its onjuntion implies FalseF por the se of eq rect eq D onsisteny hs een veri(ed outside of goq vi 4informl4 mettheoryF his xiom is equivlent to nother tht is more ommonly known nd mentioned in type theory irlesF
Streicher KF UA
Streicher K
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
his is the unfortuntelyEnmed 4treiher9s xiom uD4 whih sys tht predite on properlyEtyped equlity proofs holds of ll suh proofs if it holds of re)exivityF
End
fhlist mapF
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
fhapp ls1 ls2 F fhapp
hls2 A
is ssoitiveF
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
4fhpp @lsIXalsI CC lsPA @lsPXalsQA @fhpp @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 sttement does not even typeEhekF e know tht the two fhlist types ppering in the error messge re lwys equlD y ssoitivity of norml list ppendD ut this ft is not pprent to the type hekerF his stems from the ft tht goq9s equlity is intensionalD in the sense tht type equlity theorems n never e pplied fter the ft to get term to typeEhekF snstedD we need to mke use of equlity expliitly in the theorem sttementF
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
he (rst remining sugol looks trivil 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
B ls3 AD
end
case
pfF
st seems we hve rehed nother se where it is unler how to use dependent match to implement se nlysis on our proofF he UIP re theorem n ome to our resue ginF
rewrite @UIP
re
pf
AF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa fhapp @ls1 XalsPA @ls2 XalsQA hls2 hls3 a fhapp @ls1 XalsPA @ls2 XalsQA hls2 hls3 ITQ
reflexivityF
yur seond sugol is trikierF
pf
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
ls3
end
rewrite @UIP
The term
re
pf
AF
4pf4
has
type 4 XX @lsI CC lsPA CC lsQ a XX lsI CC lsP CC lsQ4 type 4cSST a cSST4
e n only pply UIP re on proofs of equlity with synttilly equl operndsD whih is not the se of pf hereF e will need to mnipulte the form of this sugol to get us to point where we my use UIP reF e (rst step is otining proof suitle to use in pplying the indution hypothesisF snversion on the struture of pf is su0ient for thtF
injection
pf
pf
Y intro
pf 'F ls3
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 '
end
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 hve mde n importnt it of progressD s now only single ll to fhapp ppers in the onlusionF rying se nlysis on our proofs still will not workD ut there is move we n mke to enle itF xot only does just one ll to fhapp mtter to us nowD ut it lso does not matter what the result of the call isF sn other wordsD the sugol should remin true if we reple this fhapp ll with fresh vrileF he generalize tti helps us do extly thtF
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 onlusion hs gotten mrkedly simplerF st seems ounterintuitive tht we n hve n esier time of proving more generl theoremD ut tht is extly the se here nd for mny other proofs tht use dependent types hevilyF peking informllyD the reson why this kind of tivity helps is tht match nnottions only support vriles in ertin positionsF fy reduing more elements of gol to vrilesD uiltEin ttis n hve more suess uilding match terms under the hoodF sn this seD it is helpful to generlize 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 experiened dependent types hkerD the pperne of this gol term lls for elertionF he formul hs ritil property tht indites tht our prolems re overF o get our proofs into the right form to pply UIP reD we need to use ssoitivity of list ppend to rewrite their typesF e ould not do tht efore euse other prts of the gol require the proofs to retin their originl typesF sn prtiulrD the ll to fhapp tht we generlized must hve type @ls1 CC ls2 A CC ls3D for some vlues of the list vrilesF sf we rewrite the type of the proof used to typeEst this vlue to something like ls1 CC ls2 CC ls3 a ls1 CC ls2 CC ls3D then the lefthnd side of the equlity would no longer mth the type of the term we re trying to stF roweverD now tht we hve generlized over the fhapp llD the type of the term eing typeEst ppers expliitly in the gol nd may be rewritten as wellF sn prtiulrD the (nl msterstroke is rewriting everywhere in our gol using ssoitivity 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 tht we hve hieved the ruil propertyX the type of eh generlized equlity proof hs synttilly equl operndsF his mkes it esy to (nish the proof with UIP reF
re
pf0 AF
ITT
re
pf '0 AF
Implicit Arguments
AA
X TypeD
JMeq stnds for 4tohn wjor equlityD4 nme oined y gonor wfride s sort of pun out fritish politisF JMeq strts out looking lot like eqF he ruil di'erene is tht we my use JMeq on arguments of dierent typesF por instneD lemm tht we filed to estlish efore is trivil with JMeqF st mkes for prettier theorem sttements to de(ne some syntti shorthnd (rstF
Infix 4aa4 Xa JMeq @at
level
UHD
no associativity AF x
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
a xA X
pf
aa
re equal x
Xa
here is no quik wy to write suh proof y ttisD ut the underlying proof term tht we wnt is trivilF uppose tht we wnt to use UIP re' to estlish nother lemm of the kind of we hve run into severl times so frF
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 strightforwrdD ut there relly is no suh thing s free lunhF he use of rewrite is implemented in terms of n xiomX
Check
JMeq eq
F
y
JMeq eq
X @A X TypeA @x
AAD x
aa
ITU
st my e surprising tht we nnot prove tht heterogeneous equlity implies norml equlityF he di0ulties re the sme kind we hve seen so frD sed on limittions of match nnottionsF e n redo our fhapp ssoitivity proof sed round JMeqF
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
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 indutive hypothesis should e enough to mke the gol trivilF
rewrite
IHls1F
e see tht JMeq is not silver ulletF e n use it to simplify the sttements of equlity ftsD ut the goq typeEheker uses nonEtrivil heterogeneous equlity fts no more redily thn it uses stndrd equlity ftsF rereD the prolem is tht the form @e1 D e2 A is syntti sugr for n expliit pplition of onstrutor of n indutive typeF ht pplition mentions the type of eh tuple element expliitlyD nd our rewrite tries to hnge one of those elements without updting the orresponding type rgumentF e n get round this prolem y nother multiple use of generalizeF e wnt to ring into the gol the proper instne of the indutive hypothesisD nd we lso wnt to generlize the two relevnt uses of fhappF
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 xow we n rewrite with ppend ssoitivityD s eforeF
f0 A
rewrite
app assF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa f f0 X fhlist B @ls1 CC ls2 CC ls3 AD f aa f0 @a0D f A aa @a0D prom this pointD the gol is trivilF
f0 A
f f0 H Y
rewrite
HY
reflexivityF
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 diretion is perhps more interestingF essume tht we only hve the xiom of the Eqdep module villeF e n de(ne JMeq in wy tht stis(es the sme interfe s the omintion of the JMeq module9s indutive 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 sy thtD y de(nitionD x nd y re equl if nd only if there exists proof pf tht their types re equlD suh tht x equls the result of sting y with pfF his sttement n look strnge from the stndpoint of lssil mthD where we lmost never mention proofs expliitly with qunti(ers in formulsD ut it is perfetly legl goq odeF
ITW
e n esily prove theorem with the sme type s tht of the of JMeqF
JMeq re
onstrutor
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 nlogue to is in ppeling to UIP reF
JMeq eq
AAD
pf x
TA
return
with
TA
return
with
aaaaaaaaaaaaaaaaaaaaaaaaaaaa x a y
end
rewrite
x0
HF
re
x0 AY
reflexivityF
e see thtD in very forml senseD we re free to swith k nd forth etween the two styles of proofs out equlity proofsF yne style my e more onvenient thn the other for some proofsD ut we n lwys interovert etween our resultsF he style tht does not IUH
use heterogeneous equlity my e preferle in ses where mny results do not require the triks of this hpterD sine then the use of xioms is voided ltogether for the simple sesD nd wider udiene will e le to follow those 4simple4 proofsF yn the other hndD heterogeneous equlity often mkes for shorter nd more redle theorem sttementsF st is worth remrking tht it is possile to void xioms ltogether for equlities on types with deidle equlityF he Eqdep dec module of the stndrd lirry ontins prmetri proof of UIP re for suh sesF
Theorem
S eta
a @fun
AF
nfortuntelyD this theorem is not provle in gsg without dditionl xiomsF xone of the de(nitionl equlity rules fore funtion equlity to e extensionalF ht isD the ft tht two funtions return equl results on equl inputs does not imply tht the funtions re equlF e can ssert funtion extensionlity s n xiomF
Axiom ext eq X A @ xD f x a g x A f a gF
@f
B AD
his xiom hs een veri(ed mettheoretilly to e onsistent with gsg nd the two equlity xioms we onsidered previouslyF ith itD the proof of S eta is trivilF
S n AF
he sme xiom n help us prove equlity of typesD where we need to 4reson under qunti(ersF4
Theorem
forall eq
X @
a @
natD TrueAF
X
D ut we n use
change
to (x
@@
rewrite @ext
eq
@fun
match
TrueAAF
9.7 Exercises
IF smplement nd prove orret sustitution funtion for simplyEtyped lmd lulusF sn prtiulrX @A he(ne dttype typesF
@A he(ne type fmily exp X list type type Type of lmd expressionsD inluding oolen onstntsD vrilesD nd funtion pplition nd strtionF @A smplement de(nitionl interpreter for expsD y wy of reursive funtion over expressions nd sustitutions for free vrilesD like in the relted exmple from the lst hpterF @dA smplement funtion 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 indites tht its most reently ound free vrile hs type t'F he seond expression lso hs type t'D nd the jo of subst is to sustitute the seond expression for every ourrene of the 4(rst4 vrile of the (rst expressionF @eA rove tht subst preserves progrm meningsF ht 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 opertor for heterogeneous 4ons4 tht is de(ned in the ook9s DepList moduleF IUP
he mteril presented up to this point should e su0ient to enle good solution of this exeriseD with enough ingenuityF sf you get stukD it my e helpful to use the following strutureF xone of these elements need to pper in your solutionD ut we n t lest gurntee tht there is resonle solution sed on themF @A he DepList module will e usefulF ou n get the stndrd dependent list de(nitions thereD insted of opyingEndEpsting from the lst hpterF st is worth reding the soure for tht module overD sine it de(nes some new helpful funtions nd nottions tht we did not use lst hpterF @A he(ne reursive funtion liftVar X ts1 ts2 t t'D member t @ts1 CC ts2 A member t @ts1 CC t' XX ts2 AF his funtion should 4lift4 de fruijn vrile so tht its type refers to new vrile inserted somewhere in the index listF @A he(ne reursive funtion 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 whih performs similr lifting on n expF he onvoluted type is to get round restritions on match nnottionsF e dely 4relizing4 tht the (rst index of e is uilt with list ontention until fter dependent matchD nd the new expliit proof rgument must e used to st some terms tht ome up in the match odyF @dA he(ne funtion lift X ts t t'D exp ts t exp @t' XX ts A t D whih hndles simpler topElevel liftsF his should e n esy oneEliner sed on lift'F @eA he(ne reursive funtion 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 funtion is the workhorse ehind sustitution pplied to vrileF st returns inl to indite tht the vrile we pss to it is the vrile tht we re sustituting forD nd it returns inr to indite tht the vrile we re exmining is not the one we re sustituting forF sn the (rst seD we get proof tht the neessry typing reltionship holdsD ndD in the seond seD we get the originl vrile modi(ed to re)et the removl of the sustitutee from the typing ontextF @fA he(ne reursive funtion 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 sustitution in expressionsD employing the sme proofEpssing trik s for lift'F ou will proly wnt 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 orretness theorem for eh uxiliry funtionD leding up to the proof of subst orretnessF @iA ell of the resoning out equlity proofs in these theorems follows regulr ptternF sf you hve n equlity proof tht you wnt to reple with re equal somehowD run generalize on tht proof vrileF our gol is to get to the point where you n rewrite with the originl proof to hnge the type of the generlized versionF o void type errors @the infmous 4seondEorder uni(tion4 IUQ
filure messgesAD it will e helpful to run generalize on other piees of the proof ontext tht mention the equlity9s lefthnd sideF ou might lso wnt to use generalize dependentD whih generlizes not just one vrile ut lso ll vriles whose types depend on itF generalize dependent hs the sometimesE helpful property of removing from the ontext ll vriles tht it generlizesF yne you do mnge the mindEending trik of using the equlity proof to rewrite its own typeD you will e le to rewrite with UIP reF @jA e vrint of the ext eq xiom from the end of this hpter is ville in the ook module AxiomsD nd you will proly wnt to use it in the lift' nd subst' orretness proofsF @kA he change tti should ome in hndy in the proofs out lift nd substD where you wnt to introdue 4extrneous4 list ontentions with nil to mth the forms of erlier theoremsF @lA fe reful out destructing term 4too erlyF4 ou n use generalize on proof terms to ring into the proof ontext ny importnt propositions out the termF henD when you destruct the termD it is updted in the extr propositionsD tooF he case eq tti is nother lterntive to this pprohD sed on sving n equlity etween the originl term nd its new formF
IUR
Con
IUS
recursive
}F
nat
he ide is tht onstrutor represented s Con T n hs n rguments of the type tht we re de(ningF edditionllyD ll of the otherD nonEreursive rguments n e enoded in the type T F hen there re no nonEreursive rgumentsD T n e unitF hen there re two nonEreursive rgumentsD of types A nd B D T n e A B B F e n generlizer to ny numer of rguments vi tuplingF ith this de(nitionD it s esy to de(ne dttype representtion in terms of lists of onstrutorsF
Definition
datatype
Xa
list constructorF
rere re few exmple enodings for some ommon types from the goq stndrd lirryF hile our syntx type does not support type prmeters diretlyD we n implement them t the met levelD vi funtions from types to datatypesF
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
datatype
Xa
nilF
nilF
onstrutor with no rgumentsD so its one re)eted onstrutor indites no nonEreursive dt nd H reursive rgumentsF he representtion for bool just duplites this single rgumentless onstrutorF e get from bool to nat y hnging one of the onstrutors to indite I reursive rgumentF e get from nat to list y dding nonEreursive rgument of prmeter type AF es further exmpleD we n do the sme enoding for generi inry tree typeF
Empty set hs no onstrutorsD so its representtion is the empty listF unit hs one
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
ih dttype representtion stnds for fmily of indutive typesF por spei( rel dttype nd reputed representtion for itD it is useful to de(ne type of evidence tht the dttype is omptile with the enodingF
Section denoteF Variable T X TypeF his vrile stnds for the onrete dttype tht we re interested inF Definition
constructorDenote
@c X
constructorA Xa
IUT
ilist T @recursive c A TF e write tht onstrutor is represented s funtion returning T F uh funtion tkes two rgumentsD whih pk together the nonEreursive nd reursive rguments of the onstrutorF e represent tuple of ll reursive rguments using the lengthEindexed list type ilist tht we met in ghpter UF
nonrecursive c
Definition datatypeDenote Xa hlist constructorDenoteF pinllyD the evidene for type T is hetergeneous listD inluding onstrutor denottion for every onstrutor enoding in dttype enodingF ell thtD sine we re inside setion inding T s vrileD constructorDenote is utomtilly prmeterized y T F End
denoteF
ome exmple piees of evidene should help lrify the onventionF pirstD we de(ne some helpful nottionsD providing di'erent wys of writing onstrutor denottionsF here is relly just one nottionD ut we need severl versions of it to over di'erent hoies of whih vriles will e used in the ody of de(nitionF he egss ~> from the nottion will e rendered lter s F
4 4 4 4
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
Definition
xDenote
@T X TypeA @dt X
datatypeA
Xa
IUU
@R X TypeAD
datatypeDenote R dt
@T
R AF
he ide of reursion sheme is prmeterized y type nd reputed enoding of itF he priniple itself is polymorphi in type R D whih is the return type of the reursive funtion tht we men to writeF he next rgument is hetergeneous list of one se of the reursive funtion de(nition for eh dttype onstrutorF he datatypeDenote funtion turns out to hve just the right de(nition to express the type we needY set of funtion ses is just like n lternte set of onstrutors where we reple the originl type T with the funtion result type R F qiven suh re)eted de(nitionD xDenote invotion returns funtion from T to R D whih is just wht we wntedF e re redy to write some exmple funtions nowF st will e useful to use one new funtion from the DepList lirry inluded in the ook soureF
Check
hmakeF
hmake
hlist B
is kind of map lterntive tht goes from regulr list to n hlistF e n use it to de(ne generi size funtion whih ounts the numer of onstrutors used to uild vlue in dttypeF
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 prmeterized over reursion sheme fx F e instntite fx y pssing it the funtion result type nd set of funtion sesD where we uild the ltter with hmakeF he funtion rgument to hmake tkes three rgumentsX the representtion of onstrutorD its nonEreursive rgumentsD nd the results of reursive lls on ll of its reursive rgumentsF e only need the reursive ll results hereD so we ll them r nd ind the other two inputs with wildrdsF he tul se ody is simpleX we dd together the reursive ll results nd inrement the result y one @to ount for the urrent onstrutorAF his foldr funtion is n hlistEspei( version de(ned in the DepList moduleF st is instrutive to uild xDenote vlues for our exmple types nd see wht speilized size funtions 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 fniness of the generi size funtionD gsg9s stndrd omputtion rules su0e to normlize the generi funtion speiliztion to extly wht we would hve written mnullyF 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
egin normliztion gives us the nturl funtion de(nitionF e see this pttern repeted for our other exmple 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 funtion for natD it is useful to void full omputtionD so tht the reursive de(nition of ddition is not expnded inlineF e n omplish this with proper )gs for the cbv redution strtegyF
Eval
Eplus in
x F
@n X
CI
nat nat
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 Eplus 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
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 Eplus 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 dttype vluesD rendering them s humnE redle stringsF o do soD we will need it of metdt for eh onstrutorF pei(llyD we need the nme to print for the onstrutor nd the funtion to use to render its nonE reursive rgumentsF iverything else n e done generillyF
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 shorthnd for pplying the onstrutor PIF fy pplying it expliitly to n unknown pplition of the onstrutor ConD we help type inferene workF
AAF
es in erlier exmplesD we de(ne the type of metdt for dttype to e heterogeE neous list type olleting metdt for eh onstrutorF
Definition
print datatype
Xa
e will e doing some string mnipultion hereD so we import the nottions ssoited with stringsF
string scopeF
DepListF
xow it is esy to implement our generi printerD using nother funtion from IVH
Check
hmapF
hmap
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 estlish tht
print
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 4flse4 @fun 44A XXX HNilA bool xF a fun b X bool if b then 4true@A4 else 4flse@A4 X bool s Definition print nat Xa print @ 4y4 @fun 44A XXX 44 @fun 44A XXX HNilA nat xF Eval cbv beta iota delta Eappend in print natF a x F @n X natA X string Xa match n with | H7nt 4y4 CC 4@4 CC 44 CC 4A4 | S n' 44 CC 4@4 CC 44 CC 4D 4 CC end X nat string Eval simpl in a 4y@A4 X string
print nat
F n'
CC 4A4
HF
nat
IF
IVI
@pr X
stringA
match ls with | nil 4nil4 CC 4@4 CC 44 CC 4A4 | x XX ls' 4ons4 CC 4@4 CC pr x CC 4D 4 CC end X A X TypeD @A stringA list A string
Eappend in fun
A
F ls'
CC 4A4
Eval
print @ 4vef4 pr XXX 4xode4 @fun 44A XXX HNilA @dtree x AAF
@pr X
stringA
match t with | Leaf x 4vef4 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 hve developed enough mhinery tht it is old ht to de(ne generi funtion similr to the list map funtionF
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
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 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 | H7nt f H7nt | S n' f @S @F n' AA end X @nat natA nat nat
then
f true
else
f false
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 I7nt X nat Eval simpl in a Q7nt X nat Eval simpl in a S7nt
map nat S nat den nat xF
IF
map nat S
PF
IVQ
nat
T dtF
pirstD we hrterize when piee of evidene out dttype is eptleF he si ide is tht the type T should relly e n indutive type with the de(nition given y dd F emntillyD indutive types re hrterized y the ility to do indution on themF hereforeD we require tht the usul indution priniple is trueD with respet to the onstrutors given in the enoding dd F
@recursive c AAD
his de(nition n tke while to digestF he qunti(er over m X member c dt is onsidering eh onstrutor in turnY like in norml indution priniplesD eh onstrutor hs n ssoited proof seF he expression hget dd m then nmes the onstrutor we hve seletedF efter inding mD we quntify over ll possile rguments @enoded with x nd r A to the onstrutor tht m seletsF ithin eh spei( seD we quntify further over i X n @recursive c A to onsider ll of our indution hypothesesD one for eh reursive rgument of the urrent onstrutorF e hve ompleted hlf the urden of de(ning side onditionsF he other hlf omes in hrterizing when reursion sheme fx is vlidF he nturl ondition is tht fx ehves ppropritely when pplied to ny onstrutor pplitionF
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 onstrutors nd ll possile rguments to them y quntifying over mD x D nd rF he lefthnd side of the equlity tht follows shows ll to IVR
the reursive funtion on the spei( onstrutor pplition tht we seletedF he righthnd side shows n pplition of the funtion se ssoited with onstrutor mD pplied to the nonEreursive rguments nd to pproprite reursive lls on the reursive rgumentsF
End
okF
e re now redy to prove tht the size funtion we de(ned erlier lwys returns positive resultsF pirstD we estlish simple lemmF X n @ils X b HF induction ils Y crushF QedF
foldr plus foldr plus
Lemma
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
aaaaaaaaaaaaaaaaaaaaaaaaaaaa
fx
fx A
@hmake @fun @x X constructorA @ X nonrecursive x A @r X ilist nat @recursive x AA foldr plus I7nt r A
nat
dt A v
bH
yur gol is n inequlity over prtiulr ll to sizeD with its de(nition expndedF row n we proeed herec e nnot use induction diretlyD euse there is no wy for goq to know tht T is n indutive typeF snstedD we need to use the indution priniple enoded in our hypothesis dok of type datatypeDenoteOk dd F vet us try pplying it diretlyF
apply
dokF
4dttypehenoteyk dd4 with 4fx nt @hmke @fun @x X onstrutorA @ X nonreursive xA @r X ilist nt @reursive xAA foldr plus I7nt rA dtA v b H4F
wthing the type of dok with the type of our onlusion requires more thn simple (rstEorder uni(tionD so apply is not up to the hllengeF e n use the pattern tti to get our gol into form tht mkes it pprent extly wht the indution hypothesis isF
pattern vF
IVS
aaaaaaaaaaaaaaaaaaaaaaaaaaaa @fun t X T
fx
@hmake @fun @x X constructorA @ X nonrecursive x A @r X ilist nat @recursive x AA foldr plus I7nt r A
nat
dt A t
b HA
apply
H
dok Y crushF
XiX
fx
@hmake @fun @x X constructorA @ X nonrecursive x A @r X ilist nat @recursive x AA foldr plus I7nt r A @get r iA b H aaaaaaaaaaaaaaaaaaaaaaaaaaaa
hget
n @recursive c AD nat
dt A
@hmake @fun @x0 X constructorA @ X nonrecursive x0 A @r0 X ilist nat @recursive x0 AA foldr plus I7nt r0 A @imap @fx nat @hmake @fun @x0 X constructorA @ X nonrecursive x0 A @r0 X ilist nat @recursive x0 AA foldr plus I7nt r0 A dt AA r A b H
dt A m x
en indution hypothesis H is genertedD ut we turn out not to need it for this exmpleF e n simplify the gol using lirry theorem out the omposition of hget nd hmakeF
rewrite
hget hmakeF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa foldr plus I7nt @imap @fx nat @hmake @fun @x0 X constructorA @ X nonrecursive @r0 X ilist nat @recursive x0 AA foldr plus I7nt r0 A dt AA r A b H he lemm we proved erlier (nishes the proofF
x0 A
apply
foldr plusF
IVT
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 thtD in this exmpleD we only needed to use indution degenertely s se nlysisF e more involved theorem my only e proved using indution hypothesesF e will give its proof only in unutomted form nd leve e'etive utomtion s n exerise for the motivted rederF sn prtiulrD it ought to e the se tht generi map pplied to n identity funtion is itself n identity funtionF 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 lst theoremD fter dding nother useful lirry equlity s hintF Hint Rewrite hget hmap X cpdtF unfold map Y introsY pattern v Y apply dok Y crushF
H
XiX
fx T
n @recursive c AD
@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
@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 gol is n equlity whose two sides egin with the sme funtion ll nd initil rgumentsF e elieve tht the remining rguments re in ft equl s wellD nd the f equal tti pplies this resoning step for us formllyF
f equalF
IVU
aaaaaaaaaaaaaaaaaaaaaaaaaaaa
imap
@fx
@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 proeed y n inner indution on the heterogeneous list r of reursive ll resultsF e ould rrive t lener proof y reking this step out into n expliit lemmD ut here we will do the indution inline to sve speF
induction r Y
H
crushF
he se se is dishrged utomtillyD nd the indutive se looks like thisD where is the outer sr @for indution over T vluesA nd IHn is the inner sr @for indution over the reursive rgumentsAF
H
XiX
fx T
n @S nAD
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
ar aaaaaaaaaaaaaaaaaaaaaaaaaaaa
ICons
c x0 r A dd AA r
@fx
@imap @fx
@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
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 gol into two di'erent equlities over orresponding rgumentsF efter thtD the form of the (rst gol mthes our outer indution hypothesis HD when we give type inferene some help y speifying the right qunti(er instntitionF
f equalF apply @H
FirstAF
aaaaaaaaaaaaaaaaaaaaaaaaaaaa
imap
@fx
@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
IHrF
apply
i
IHr Y crushF
X n n aaaaaaaaaaaaaaaaaaaaaaaaaaaa
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 ginD speilized to di'erent IVW
n
vlueF
IWH
Check HF H X nat
st is nturl enough tht zero e onsidered s nturl numerF
Check natF
nat
X Set
prom set theory perspetiveD it is unsurprising to onsider the nturl numers s 4setF4
Check SetF
IWI
Set X Type
he type Set my e onsidered s the set of ll setsD onept tht set theory hndles in terms of classesF sn goqD this more generl notion is TypeF
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
yurrenes of Type re nnotted with some dditionl informtionD inside ommentsF hese nnottions hve to do with the seret ehind TypeX it relly stnds for n in(nite hierrhy 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 prdoxF es onvenieneD the universe hierrhy drives goq9s one vriety of sutypingF eny term whose type is Type t level i is utomtilly lso desried y Type t level j when j b iF sn the outputs of our (rst Check queryD we see tht the type level of Set9s type is @HACIF rere H stnds for the level of SetD nd we inrement it to rrive t the level tht classies SetF sn the seond query9s outputD we see tht the ourrene of Type tht we hek is ssigned fresh universe variable TopFQF he output type inrements TopFQ to move up level in the universe hierrhyF es we write ode tht uses de(nitions whose types mention universe vrilesD uni(tion my re(ne the vlues of those vrilesF vukilyD the user rrely hs to worry out the detilsF enother ruil onept 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 demonstrte the rule for determining whih universe type lives inF sn prtiulrD for type x X T1D T2D we tke the mximum of the universes of T1 nd T2F sn the (rst exmple queryD oth T1 @natA nd T2 @n T A re in SetD so the type is in SetD tooF sn the seond queryD T1 is SetD whih is t level @HACIY nd T2 is T D whih is t level HF husD the exists t the mximum of these two levelsF he third exmple illustrtes the sme outomeD where we reple Set with n ourrene of Type tht is ssigned universe vrile TopFWF his universe vrile ppers in the ples where H ppered in the previous queryF he ehindEtheEsenes mnipultion of universe vriles gives us preditivityF gonsider this simple de(nition of polymorphi identity funtionF
id
@T X SetA @x X
TA
Xa xF
SetF
@Type
Error AX should be coercible to
The
Ist
term has
4et4F
he prmeter T of id must e instntited with SetF nat is SetD ut Set is notF e n try (xing the prolem y generlizing our de(nition of idF
Reset idF
id
@T X TypeA @x X
TA
Xa xF
SetF
IWQ
id
Set X Type @B
TopFIU
BA
Type
Check
id idF
@cannot
enforce TopFIT
TopFITAF
his error messge reminds us tht the universe vrile for T still existsD even though it is usully hiddenF o pply id to itselfD tht vrile would need to e less thn itself in the type hierrhyF niverse inonsisteny error messges nnoune ses like this one where term ould only typeEhek y violting n implied onstrint over universe vrilesF uh errors demonstrte tht Type is predicativeD where this word hs gsg mening losely relted to its usul mthemtil meningF e preditive system enfores the onstrint thtD for ny ojet of qunti(ed typeD none of those qunti(ers my ever e instntited with the ojet itselfF smpreditivity is ssoited with populr prdoxes in set theoryD involving inonsistent onstrutions like 4the set of ll sets tht do not ontin themselvesF4 imilr prdoxes result from unontrolled impreditivity in goqF
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
in TypeF
his de(nition is large in the sense tht t lest one of its onstrutors tkes n rgument whose type hs type TypeF goq would e inonsistent if we llowed de(nitions like this one in their full generlityF snstedD we must hnge exp to live in TypeF e will go even further nd move exp9s index to Type s wellF
| | |
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 tht efore we hd to inlude n nnottion X Set for the vrile T in Const9s typeD ut we need no nnottion nowF hen the type of vrile is not knownD nd when tht vrile is used in ontext where only types re llowedD goq infers tht the vrile is of type TypeF ht is the right ehvior hereD ut it ws wrong for the Set version of expF yur new de(nition is eptedF e n uild some smple expressionsF
Check
X
Const
HF
Const
exp Pair
nat
@Const HA @Const
ttAF
Check
Pair
Check Eq @Const SetA @Const TypeAF Eq @Const SetA @Const Type @B TopFSW BA A X exp bool
e n hek mny expressionsD inluding fny expressions tht inlude typesF roweverD it is not hrd to hit typeEheking wllF
Check
Const
@Const
OAF
@cannot
enforce TopFRP
TopFRPAF
e re unle to instntite the prmeter T of Const with n exp typeF o see whyD it is helpful to print the nnotted version of exp9s indutive de(nitionF
exp
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
X Type @B
e see tht the index type of exp hs een ssigned to universe level TopFVF sn dditionD eh of the four ourrenes of Type in the types of the onstrutors gets its own universe vrileF ih of these vriles ppers expliitly in the type of expF sn prtiulrD ny IWS
type exp T lives t universe level found y inrementing y one the mximum of the four rgument vrilesF e onsequene of this is tht exp must live t higher universe level thn ny type whih my e pssed to one of its onstrutorsF his onsequene led to the universe inonsistenyF trngelyD the universe vrile TopFV only ppers in one pleF ss there no restrition imposed on whih types re vlid rguments to expc sn ftD there is restritionD ut it only ppers in glol set of universe onstrints tht re mintined 4o' to the sideD4 not ppering expliitly in typesF e n print the urrent dtseF
Print UniversesF TopFIW ` TopFW TopFIS ` TopFW TopFIR ` TopFW TopFII ` TopFW
Coq.Init.DatatypesFQV Coq.Init.DatatypesFQU
Print Universes outputs mny more onstrintsD ut we hve olleted only those tht mention Top vrilesF e see one onstrint for eh universe vrile ssoited with onstrutor rgument from exp9s de(nitionF TopFIW is the type rgument to EqF he onstrint for TopFIW e'etively sys tht TopFIW must e less thn TopFVD the universe of exp9s indiesY n intermedite vrile TopFW ppers s n rtift of the wy the onstrint ws genertedF he next onstrintD for TopFISD is more omplitedF his is the universe of the seond rgument to the Pair onstrutorF xot only must TopFIS e less thn TopFVD ut it lso omes out tht TopFV must e less thn Coq.Init.DatatypesFQVF ht is this new universe vrilec st is from the de(nition of the prod indutive fmilyD to whih types of the form A B B re desugredF 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 tht the onstrint is enforing tht indies to exp must not live in higher universe level thn B Eindies to prodF he next onstrint ove estlishes symmetri ondition for AF hus it is pprent tht goq mintins tortuous set of universe vrile inequlities ehind the senesF st my look like some funtions re polymorphi in the universe levels of their rgumentsD ut wht is relly hppening is impertive updting of system of onstrintsD suh tht ll uses of funtion re onsistent with glol set of universe levelsF hen the onstrint system my not e evolved soundlyD we get universe inonsisteny errorF omething interesting is reveled in the nnotted de(nition of IWT
prodF
e type
prod A
lives t universe tht is the mximum of the universes of A nd B F prom our erlier experimentsD we might expet tht prod 9s universe would in ft need to e one higher thn the mximumF he ritil di'erene is thtD in the de(nition of prodD A nd B re de(ned s parameters Y tht isD they pper nmed to the left of the min olonD rther thn ppering @possily unnmedA to the rightF rmeters re not s )exile s norml indutive type rgumentsF he rnge types of ll of the onstrutors of prmeterized type must shre the sme prmetersF xonethelessD when it is possile to de(ne polymorphi type in this wyD we gin the ility to use the new type fmily in more wysD without triggering universe inonsisteniesF por instneD nested pirs of types re perfetly leglF
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
prod
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 prmeters ring us is the ility to void quntifying over types in the types of onstrutorsF uh qunti(tion indues lessEthn onstrintsD while prmeters only introdue lessEthnEorEequlEto onstrintsF goq inludes one more @potentilly onfusingA feture relted to prmetersF hile qllin does not support rel universe polymorphismD there is onveniene fility tht mimis universe polymorphism in some sesF e n illustrte wht this mens with simple exmpleF
foo nat
X Set
foo True
IWU
X Prop he si pttern here is tht goq is willing to utomtilly uild 4opiedEndEpsted4 version of n indutive de(nitionD where some ourrenes of Type hve een repled y Set or PropF sn eh ontextD the typeEheker tries to (nd the vlid replements tht re lowest in the type hierrhyF eutomti loning of de(nitions n e muh more onvenient thn mnul loningF e hve lredy tken dvntge of the ft tht we my reEuse the sme fmilies of tuple nd list types to form vlues in Set nd TypeF smittion polymorphism n e onfusing in some ontextsF por instneD it is wht is responsile for this weird ehviorF
Bar
barF
bar
X Prop
he type tht goq omes up with my e used in stritly more ontexts thn the type one might hve expetedF
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 nturl to wnt funtion to extrt the (rst omponents of dt strutures like theseF hoing so is esy enough for sigF
@P X
PropA @x X
sig P A X A Xa
IWV
| exist endF
e run into troule with version tht hs een hnged to work with
exF
PropA @x X
ex P A X A Xa
return type
has sort
in
sort
Type
Prop
sn forml goq prlneD 4elimintion4 mens 4ptternEmthingF4 he typing rules of qllin forid us from ptternEmthing on disriminee whose type elongs to PropD whenE ever the result type of the match hs type esides PropF his is sort of 4informtion )ow4 poliyD where the type system ensures tht the detils of proofs n never hve ny e'et on prts of development tht re not lso mrked s proofsF his restrition mthes informl prtieF e think of progrms nd proofs s lerly seprtedD ndD outside of onstrutive logiD the ide of omputing with proofs is illEformedF he distintion lso hs prtil importne in goqD where it 'ets the ehvior of extrE tionF ell tht extrtion is goq9s fility for trnslting goq developments into progrms in generlEpurpose progrmming lnguges like ygmlF ixtrtion erases proofs nd leves progrms inttF e simple exmple with sig nd ex demonstrtes the distintionF
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
Extraction sym sigF
H a n A Xa
ex
@x X
| ex endF
intro n pf
ex intro
@sym
eq pf
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
T2 A
HF PHH
ConstP
expP nat
@ConstP HA @ConstP
ttA ttAF
Check
PairP
PairP
Check
EqP
expP bool
Check
ConstP
@ConstP
OAF
ConstP
sn this seD our vitory is relly shllow oneF es we hve mrked expP s fmily of proofsD we nnot deonstrut our expressions in the usul progrmmti wysD whih mkes them lmost useless for the usul purposesF smpreditive qunti(tion is muh more useful in de(ning indutive fmilies tht we relly think of s judgmentsF por instneD this ode de(nes notion of equlity tht is stritly stronger thn the se equlity 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 Check @Base @Base IAAF Base @Base IA X eqPlus @Base IA @Base IA
Base n A
11.3 Axioms
hile the spei( logi qllin is hrdoded into goq9s implementtionD it is possile to dd ertin logil rules in ontrolled wyF sn other wordsD goq my e used to reson out mny di'erent re(nements of qllin where stritly more theorems re provleF e hieve this y sserting axioms without proofF PHI
e will motivte the ide y touring through some stndrd xiomsD s enumerted in goq9s online peF s will dd dditionl ommentry s ppropriteF
Classical PropD
Axiom classic X P X PropD P PF en Axiom my e delred with ny typeD in ny of the universesF here is synonym Parameter for AxiomD nd tht synonym is often lerer for ssertions not of type PropF por instneD we n ssert the existene of ojets with ertin propertiesF Parameter n X natF Axiom positive X n b HF Reset nF his kind of 4xiomti presenttion4 of theory is very ommon outside of higherEorder logiF roweverD in goqD it is lmost lwys preferle to stik to de(ning your ojetsD funtionsD nd predites vi indutive de(nitions nd funtionl progrmmingF sn generlD there is signi(nt urden ssoited with ny use of xiomsF st is esy to ssert set of xioms tht together is inconsistentF ht isD set of xioms my imply FalseD whih llows ny theorem to provedD whih defets the purpose of proof ssistntF por exmpleD we ould ssert the following xiomD whih is onsistent y itself ut inonsistent when omined 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 sujet of the lw of the exluded middle itselfD this xiom is usully quite hrmE lessD nd mny prtil goq developments ssume itF st hs een proved mettheoretilly to e onsistent with gsgF rereD 4proved mettheoretilly4 mens tht someone proved on pper tht exluded middle holds in model of gsg in set theoryF ell of the other xioms tht we will survey in this setion hold in the sme modelD so they re ll onsistent togetherF
PHP
ell tht goq implements constructive logi y defultD where exluded middle is not provleF roofs in onstrutive logi n e thought of s progrmsF e qunti(er denotes dependent funtion typeD nd disjuntion denotes vrint typeF sn suh settingD exluded middle ould e interpreted s deision proedure for ritrry propositionsD whih omputility theory tells us nnot existF husD onstrutive logi with exluded middle n no longer e ssoited with our usul notion of progrmmingF qiven ll thisD why is it ll right to ssert exluded middle s n xiomc he intuitive justi(tion is tht the elimintion restrition for Prop prevents us from treting proofs s progrmsF en exluded middle xiom tht qunti(ed over Set insted of Prop would e prolemtiF sf development used tht xiomD we would not e le to extrt the ode to ygml @soundlyA without implementing genuine universl deision proedureF sn ontrstD vlues whose types elong to Prop re lwys ersed y extrtionD so we sidestep the xiom9s lgorithmi onsequenesF feuse the proper use of xioms is so preriousD there re helpful ommnds for deterE mining whih xioms theorem relies onF
X PropD
PF
Closed under
Theorem tautoF
Error X
t2
X PropD
PF
tauto
PY
failedF P AY
destruct @classic
tautoF
Assumptions t2F
AxiomsX
classic
X PropD
P is
st is possile to void this dependene in some spei( sesD where exluded middle provleD for deidle fmilies 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
m AY
intuitionF
eq n
a mF m AY tautoF
n
PHQ
Closed under
winstrem mthemtil prtie ssumes exluded middleD so it n e useful to hve it ville in goq developmentsD though it is lso nie to know tht theorem is proved in simpler forml system thn lssil logiF here is similr story for proof irrelevanceD whih simpli(es proof issues tht would not even rise in minstrem mthF
Require Import ProofIrrelevanceF Print proof irrelevanceF BBB proof irrelevance X @P X PropA @p1
p2
P AD p1
p2
his xiom sserts tht ny two proofs of the sme proposition re equlF sf we repled p1 a p2 y p1 p2D then the sttement would e provleF roweverD equlity is stronger notion thn logil equivleneF ell this exmple funtion from ghpter 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 wnt to prove tht di'erent proofs of from our rihlyEtyped predeessor funtionF
n
irrel
@pf1
pf2
b HAD
he proof sript is simpleD ut it involved peeking into the de(nition of pred strong1F por more omplited funtion de(nitionsD it n e onsiderly more work to prove tht they do not disriminte on detils of proof rgumentsF his n seem like shmeD sine the Prop elimintion restrition mkes it impossile to write ny funtion tht does othE erwiseF nfortuntelyD this ft is only true mettheoretillyD unless we ssert n xiom like proof irrelevance F ith tht 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
sn the hpter on equlityD we lredy disussed some xioms tht re relted to proof irrelevneF sn prtiulrD goq9s stndrd lirry inludes this xiomX
TypeA @x X
Q pA
@h X
a p AD
his xiom sys tht it is permissile to simplify pttern mthes over proofs of equlities e a eF he xiom is logilly equivlent to some simpler orollriesF
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 orollries re speil ses of proof irrelevneF sn developments tht only need proof irrelevne for equlityD there is no need to ssert full irrelevneF enother fet of proof irrelevne is thtD like exluded middleD it is often provle for spei( propositionsF por instneD UIP is provle whenever the type A hs deidle equlity opertionF he module Eqdep dec of the stndrd lirry ontins proofF e similr phenomenon pplies to other notle sesD inluding lessEthn proofsF husD it is often possile to use proof irrelevne without sserting xiomsF
here re two more si xioms tht re often ssumedD to void omplitions tht 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 sys tht two funtions re equl if they mp equl inputs to equl outputsF uh fts re not provle in generl in gsgD ut it is onsistent to ssume tht they reF e simple orollry shows tht the sme property pplies to preditesF sn some sesD one might prefer to ssert this orollry s the xiomD to restrit the onsequenes to proofs PHS
nd not progrmsF
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
AD B x AD
AAD
Closed under
his funtion trnsforms deidle predite P into funtion tht produes n elE ement stisfying P from proof tht suh n element existsF he funtions f nd g D in onjuntion with n ssoited injetivity propertyD re used to express the ide tht the set A is ountleF nder these onditionsD simple rute fore lgorithm gets the jo doneX we just enumerte ll elements of AD stopping when we (nd one stisfying P F he existene proofD spei(ed in terms of unique existene 3D gurntees termintionF he de(nition of this opertor in goq uses some interesting tehniquesD s seen in the implementtion of the ConstructiveEpsilon moduleF gountle hoie is provle in set theory without ppeling to the generl xiom of hoieF o support the more generl priniple in goqD we must lso dd n xiomF rere is funtionl version of the xiom of unique hoieF
X @A X TypeA @B X A TypeA @R X @ x X AD 3 y X B x D R x y A
AD B x
PropAD
PHT
AD B x D
AD R x
@f x A
his xiom lets us onvert reltionl spei(tion R into funtion implementing tht spei(tionF e need only prove tht R is truly funtionF en lternteD stronger formultion pplies to ses where R mps eh input to one or more outputsF e lso simplify the sttement of the theorem y onsidering only nonEdependent funtion typesF
ClassicalChoiceF
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 priniple is proved s theoremD sed on the unique hoie xiom nd n dditionl xiom of reltionl hoie from the RelationalChoice moduleF sn set theoryD the xiom of hoie is fundmentl philosophil ommitment one mkes out the universe of setsF sn goqD the hoie xioms sy something wekerF por instneD onsider the simple resttement of the choice xiom where we reple existentil qunti(E tion y its gurryErowrd nlogueD suset 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
AD
{y X
R x y }A
i the gurryErowrd orrespondeneD this 4xiom4 n e tken to hve the sme mening s the originlF st is implemented trivilly s trnsformtion not muh deeper thn unurryingF husD we see tht the utility of the xioms tht we mentioned erlier omes in their usge to uild progrms from proofsF xorml set theory hs no expliit proofsD so the mening of the usul xiom of hoie is sutlely di'erentF sn qllinD the xioms implement ontrolled relxtion of the restritions on informtion )ow from proofs to progrmsF roweverD when we omine n xiom of hoie with the lw of the exluded middleD the ide of 4hoie4 eomes more interestingF ixluded middle gives us highly nonE omputtionl wy of onstruting proofsD ut it does not hnge the omputtionl nture of progrmsF husD the xiom of hoie is still giving us wy of trnslting etween two di'erent sorts of 4progrmsD4 ut the input progrms @whih re proofsA my e written in rih lnguge tht goes eyond norml omputilityF his truly is more thn repkging funtion with di'erent typeF he goq tools support ommndEline )g -impredicative-setD whih modi(es qllin in more fundmentl wy y mking Set impreditiveF e term like T X SetD T hs type SetD nd indutive de(nitions in Set my hve onstrutors tht quntify over rguments of ny typesF o mintin onsistenyD n elimintion restrition must e imposedD similrly to the restrition for PropF he restrition only pplies to lrge indutive typesD where some PHU
onstrutor qunti(es over type of type TypeF sn suh sesD vlue in this indutive type my only e ptternEmthed over to yield result type whose type is Set or PropF his ontrsts with PropD where the restrition pplies even to nonElrge indutive typesD nd where the result type my only hve type PropF sn old versions of goqD Set ws impreditive y defultF vter versions mke Set preditive to void inonsisteny with some lssil xiomsF sn prtiulrD one should wth out when using impreditive Set with xioms of hoieF sn omintion with exluded middle or predite extensionlityD this n led to inonsistenyF smpreditive Set n e useful for modeling inherently impreditive mthemtil oneptsD ut lmost ll goq developments get y (ne without itF
Definition cast @x y X SetA @pf X match pf with | re equal v endF Eval compute in @cast @re
a IQ X nat
equal
a y A @v X
xA
Xa
cast
n proeed smoothlyF
@nat
cast
Theorem QedF
change
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
t3 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 gomputtion gets stuk in ptternEmth on the proof t3F he struture of t3 is not knownD so the mth nnot proeedF st turns out more si prolem leds to this PHV
prtiulr situtionF e ended the proof of t3 with QedD so the de(nition of t3 is not ville to omputtionF ht is esily (xedF
Reset t3F
Theorem
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
t3
change
t3
@fun
FirstAA
IPF
match match
functional extensionality
FFFF e elide most of the detilsF e very unwieldy tree of nested mthes on equlity proofs ppersF his time evlution relly is stuk on use of n xiomF sf we re reful in using ttis to prove n equlityD 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
PIH
PII
Theorem autoF
bool neq
true
falseF
crush would hve dishrged this golD ut the defult hint dtse for auto ontins no hint tht ppliesF
AbortF
st is hrd to ome up with boolEspei( hint tht is not just resttement of the theorem we men to proveF vukilyD simpler form su0esF
true
falseF
= D try pplying yur hint sysX 4whenever the onlusion mthes the pttern congruenceF4 he I is ost for this ruleF huring proof serhD whenever multiple rules pplyD rules re tried in inresing ost orderD so it pys to ssign high osts to reltively expensive Extern hintsF Extern hints my e implemented with the full vt lngugeF his exmple shows se where hint uses matchF
both
X xD
P x
Q xF
forall and
X zD
P zF
crush mkes no progress eyond wht intros would hve omplishedF auto will not pply the hypothesis both to prove the golD euse the onlusion of both does not unify with the onlusion of the golF roweverD we n teh auto to hndle this kind of golF
apply @proj1 @H
X AA
e see tht n Extern pttern my ind uni(tion vriles tht we use in the ssoited ttiF proj1 is funtion from the stndrd lirry for extrting proof of R from proof of R S F
End
forall andF
efter our suess on this exmpleD we might get more mitious nd seek to generlize the hint to ll possile predites P F
apply @proj1 @H
X AA
goq9s auto hint dtses work s tles mpping head symbols to lists of ttis to tryF feuse of thisD the onstnt hed of n Extern pttern must e determinle sttillyF sn our (rst Extern hintD the hed symol ws notD sine x = y desugrs to not @eq x y AY ndD in the seond exmpleD the hed symol ws P F his restrition on Extern hints is the min limittion of the auto mehnismD preventing us from using it for generl ontext simpli(tions tht re not keyed o' of the form of the onlusionF his is perhps just s wellD sine we n often ode more e0ient ttis with speilized vt progrmsD nd we will see how in lter setions of the hpterF e hve used Hint Rewrite in mny exmples so frF crush uses these hints y lling autorewriteF yur rewrite hints hve tken the form Hint Rewrite lemma X cpdtD dding them to the cpdt rewrite dtseF his is euseD in ontrst to autoD autorewrite hs no defult dtseF husD we set the onvention tht crush uses the cpdt dtseF his exmple shows diret use of autorewriteF
Section
autorewriteF
PIQ
A f
X SetF X A
f f
AF f
Hypothesis
X xD X
@f
xA
f xF
Rewrite f f
my dbF f xF db Y
reflexivityF
here re few wys in whih autorewrite n led to troule when insu0ient re is tken in hoosing hintsF pirstD the set of hints my de(ne nonterminting rewrite systemD in whih se invotions to autorewrite my not terminteF eondD we my dd hints tht 4led autorewrite down the wrong pthF4 por instneX
g xF
AbortF
yur new hint ws used to rewrite the gol into form where the old hint ould no longer e ppliedF his 4nonEmonotoniity4 of rewrite hints ontrsts with the sitution for autoD where new hints my slow down proof serh ut n never 4rek4 old proofsF
Reset garden pathF
works with qunti(ed equlities tht inlude dditionl premisesD ut we must e reful to void similr inorret 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
f x
g xF
PIR
is X is X is X
AbortF
he inpproprite rule (red the sme three times s eforeD even though we know we will not e le to prove the premisesF
Reset garden pathF
yur (nlD suessfulD ttempt uses n extr rgument to Hint tti to pply to generted premisesF
Rewrite
tht spei(es
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
dbF
f g
g xF reflexivityF
st n lso e useful to use the autorewrite with hypothesesD s well s in the onlusionF
db
x AAA db
@f
yA
in Y assumptionF
yne ommon use for match ttis is identi(tion of sujets for se nlysisD s we see in this tti de(nitionF
Ltac nd if Xa match goal with | if c then else destruct X endF he tti heks if the onlusion is n ifD destructing the test expression if soF gertin lsses of theorem re trivil to prove utomtilly with suh ttiF 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 tht we use here is lled tacticalD or tti omintorF he ehvior of repeat t is to loop through running t D running t on ll generted sugolsD running t on their generted sugolsD nd so onF hen t fils t ny point in this serh treeD tht prtiulr sugol is left to e hndled y lter ttisF husD it is importnt never to use repeat with tti tht lwys sueedsF enother very useful vt uilding lok is context patternsF Ltac nd if inside Xa match goal with | context if c then else destruct X endF he ehvior of this tti is to (nd ny suterm of the onlusion tht is n if nd then destruct the test expressionF his version susumes 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 gols tht nd if does not simplify su0ientlyF
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
wny deision proedures n e oded in vt vi 4repeat match loopsF4 por instneD we n implement suset of the funtionlity of tautoF
True constructor
constructor intro
X X X
False
H H H
endF
ine match ptterns n shre uni(tion vriles etween hypothesis nd onlusion ptternsD it is esy to (gure out when the onlusion mthes hypothesisF he exact tti solves gol ompletely when given proof term of the proper typeF st is lso trivil to implement the 4introdution rules4 for few of the onnetivesF smplementing elimintion rules is only little more workD sine we must give nme for hypothesis to destructF he lst rule implements modus ponensF he most interesting prt is the use of the vtElevel let with fresh expressionF fresh tkes in nme se nd returns fresh hypothesis vrile sed on tht nmeF e use the new nme vrile H s the nme we ssign to the result of modus ponensF he use of generalize hnges our onlusion to e n implition from Q F e ler the originl hypothesis nd move Q into the ontext with nme HF
my tautoF
X @P
FalseA @P Q A True QF
y lering every implition tht we useF sf we wnt to implement similrlyEomplete proedure for qunti(er instntitionD we need wy to ensure tht prtiulr proposition is not lredy inluded mong our hypothesesF o do tht e'etivelyD we (rst need to lern it more out the semntis of matchF st is tempting to ssume tht match works like it does in wvF sn ftD there re few ritil di'erenes in its ehviorF yne is tht we my inlude ritrry expressions in ptternsD insted of eing restrited to vriles nd onstrutorsF enother is tht the sme vrile my pper multiple timesD induing n impliit equlity onstrintF here is relted pir of two other di'erenes tht re muh more importnt thn the othersF match hs backtracking semantics for failureF sn wvD pttern mthing works y (nding the (rst pttern to mth nd then exeuting its odyF sf the ody rises n exeptionD then the overll mth rises the sme exeptionF sn goqD filures in se odies insted trigger ontinued serh through the list of sesF por instneD this @unneessrily veroseA proof sript worksX
Theorem m1 X TrueF match goal with intro | | True constructor endF QedF
he (rst se mthes trivillyD ut its ody tti filsD sine the onlusion does not egin with qunti(er or implitionF sn similr wv mthD tht would men tht the whole ptternEmth filsF sn goqD we ktrk nd try the next ptternD whih lso mthesF sts ody tti sueedsD so the overll tti sueeds s wellF he exmple shows how filure n move to di'erent pttern within matchF pilure n lso trigger n ttempt to (nd a dierent way of matching a single patternF gonsider nother exmpleX
QF
goq prints 4H1 4F fy pplying idtac with n rgumentD onvenient deugging tool for 4leking informtion out of matchesD4 we see tht this match (rst tries inding H to H1 D whih nnot e used to prove Q F xonethelessD the following vrition on the tti sueeds t proving the golX
he tti (rst uni(es H with H1 D s eforeD ut exact H fils in tht seD so the tti engine serhes for more possile vlues of HF iventullyD it rrives t the orret vlueD so PIV
tht exact
xow we re equipped to implement tti for heking tht proposition is not mong our hypothesesX
Ltac notHyp P Xa match goal with | X P fail I | match P with | cI cP rst | idtac end endF
notHyp P1
notHyp P2
| fail P
e use the equlity heking tht is uilt into ptternEmthing to see if there is hypothesis tht mthes the proposition extlyF sf soD we use the fail ttiF ithout rgumentsD fail signls norml tti filureD s you might expetF hen fail is pssed n rgument nD n is used to ount outwrds through the enlosing ses of ktrking serhF sn this seD fail I sys 4fil not just in this ptternEmthing rnhD ut for the whole matchF4 he seond se will never e tried when the fail I is rehedF his seond seD used when P mthes no hypothesisD heks if P is onjuntionF yther simpli(tions my hve split onjuntions into their omponent formulsD so we need to hek tht t lest one of those omponents is lso not representedF o hieve thisD we pply the rst ttilD whih tkes list of ttis nd ontinues down the list until one of them does not filF he fail P t the end sys to fail oth the rst nd the match wrpped round itF he ody of the cI cP se gurntees thtD if it is rehedD we either sueed ompletely or fil ompletelyF husD if we reh the wildrd seD P is not onjuntionF e use idtacD tti tht would e silly to pply on its ownD sine its e'et is to sueed t doing nothingF xonethelessD idtac is useful pleholder for ses like wht we see hereF ith the nonEpresene hek implementedD it is esy to uild tti tht tkes s input proof term nd dds its onlusion s new hypothesisD only if tht onlusion is not lredy presentD filing otherwiseF
pf
Y introF
e see the useful type of opertor of vtF his opertor ould not e implemented in qllinD ut it is esy to support in vtF e end up with t ound to the type of pfF e hek tht t is not lredy presentF sf soD we use generalizeGintro omo to dd new hypothesis proved y pfF ith these ttis de(nedD we n write tti completer for dding to the ontext ll onsequenes of set of simple (rstEorder formulsF
Ltac
completer
Xa PIW
repeat match goal with constructor | |H X destruct H | H X c cD H' X c generalize @H H' AY clear H Y intro | xD intro
|
H
endF
extend
X xD c x D @H X H' A
H'
X c c
e use the sme kind of onjuntion nd implition hndling s previouslyF xote thtD sine is the speil nonEdependent se of D the fourth rule hndles intro for implitionsD tooF sn the (fth ruleD when we (nd ft H with premise mthing one of our hypothesesD we dd the pproprite instntition of H 9s onlusionD if we hve not lredy dded itF e n hek tht completer is working properlyX
PropF
Q x S xF
H1 H2
X xD X xD
P x
P x R x
R xF
X xD completerF
A
S xF
x H
X Q x H3 X R x H4 X S x aaaaaaaaaaaaaaaaaaaaaaaaaaaa
H0 S x
P x
HY
intro
X c c
endF
he only di'erene is in the modus ponens ruleD where we hve repled n unused uni(tion vrile c with wildrdF vet us try our exmple gin with this versionX
PropF
Q x S xF
H1 H2
X xD X xD
P x
P x R x
R xF
X xD
S xF
completer'F
Theorem
t1'
natD x a xF
for match
goal
AbortF
he prolem is tht uni(tion vriles my not ontin lollyEound vrilesF sn this seD c would need to e ound to x a x D whih ontins the lol qunti(ed vrile x F fy using wildrd in the erlier versionD we voided this restritionF PPI
he goq VFP relese inludes speil pttern form for uni(tion vrile with n expliit set of free vrilesF ht uni(tion vrile is then ound to funtion from the free vriles to the 4rel4 vlueF sn goq VFI nd erlierD there is no suh workroundF xo mtter whih version you useD it is importnt to e wre of this restritionF es we hve lluded toD the restrition is the ulprit ehind the in(niteElooping ehvior of completer'F e unintentionlly mth qunti(ed fts with the modus ponens ruleD irumE venting the 4lredy present4 hek nd leding to di'erent ehviorF
ls' A
in
et this pointD we hopefully rememer tht pttern vrile nmes must e pre(xed y question mrks in vtF
ls' A
in
he prolem is tht vt trets the expression S @length ls' A s n invotion of tti S with rgument length ls'F e need to use speil nnottion to 4espe into4 the qllin prsing nonterminlF
constr X@
@length
ls' AA
his de(nition is eptedF st n e little wkwrd to test vt de(nitions like thisF rere is one methodF
nilA
in
False
e use the pose ttiD whih extends the proof ontext with new vrile tht is set equl to prtiulr termF e ould lso hve used idtac n in ple of pose nD whih would hve printed the result without hnging the ontextF n only hs the length lultion unrolled one stepF ht hs hppened here is thtD y esping into the constr nonterminlD we referred to the length funtion of qllinD rther thn the length vt funtion tht we re de(ningF
AbortF
Reset lengthF
he thing to rememer is tht qllin terms uilt y ttis must e ound expliitly vi let or similr tehniqueD rther thn inserting vt lls diretly in other qllin termsF
Ltac length ls Xa match ls with | nil O | XX cls9 let ls Xa length constr X@ ls A endF
ls'
in
nilA
in
n Xa Q X nat aaaaaaaaaaaaaaaaaaaaaaaaaaaa
False
AbortF
e n lso use nonymous funtion expressions nd lol funtion de(nitions in vtD s this exmple of stndrd list map funtion 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 funtions n hve no impliit rgumentsF st my seem surprising tht we need to pss T D the rried type of the output listD expliitlyF e nnot just use type of f D euse f is n vt termD not qllin termD nd vt progrms re dynmilly typedF f ould use very syntti methods to deide to return di'erently typed terms for di'erent inputsF e lso ould not reple constr X@dnil T A with constr XnilD euse we hve no stronglyEtyped ontext to use to infer the prmeter to nilF vukilyD we do hve su0ient ontext within constr X@x9 XX ls AF ometimes we need to employ the opposite diretion of 4nonterminl espeD4 when we wnt to pss omplited tti expression s n rgument to nother ttiD s we might wnt to do in invoking mapF
ltac X@fun x
constr X@xD x AA
@I XX P XX Q XX
nilA
in
False
AbortF
Ltac
inster n
Xa PPR
X c
generalize @H
x AY inster n'
inster egins y pplying propositionl simpli(tionF xextD it heks if ny hin length reminsF sf soD it tries ll possile wys of instntiting qunti(ed hypotheses with properlyE typed lol vrilesF st is ritil to relize thtD if the reursive ll inster n' filsD then the match goal just seeks out nother wy of unifying its pttern ginst proof stteF husD this smll mount of ode provides n elegnt demonstrtion of how ktrking match enles exhustive serhF e n verify the e0y of inster with two short exmplesF he uiltEin firstorder tti @with no extr rgumentsA is le to prove the (rst ut not the seondF
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 QedF
inster H1
x yD P
@g
x yA
@f
Q
x AF
test inster
PF
H3 H4
x yD P
@g
x yA
@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 X
x yD x
u v AF
test inster2
P x
QF
@f
yA
@f
x AF
insterF
he style employed in the de(nition of inster n seem very ounterintuitive to funtionl progrmmersF sullyD funtionl progrms umulte stte hnges in expliit rguments to reursive funtionsF sn vtD the stte of the urrent sugol is lwys impliitF xonetheE lessD in ontrst to generl impertive progrmmingD it is esy to undo ny hnges to this stteD nd indeed suh 4undoing4 hppens utomtilly t filures within matchesF sn this wyD vt progrmming is similr to progrmming in rskell with stteful filure mond tht supports omposition opertor long the lines of the rst ttilF puntionl progrmming purists my ret indignntly to the suggestion of progrmming this wyF xonethelessD s with other kinds of 4mondi progrmmingD4 mny prolems re muh simpler to solve with vt thn they would e with expliitD pure proof mnipultion in wv or rskellF o demonstrteD we will write si simpli(tion proedure for logil PPS
implitionsF his proedure is inspired y one for seprtion logiD where onjunts in formuls re thought of s 4resouresD4 suh tht we lose no ompleteness y 4rossing out4 equl onE junts on the two sides of n implitionF his proess is omplited y the ft thtD for resons of modulrityD our formuls n hve ritrry nested tree struture @rnhing t onjuntionsA nd my inlude existentil qunti(ersF st is helpful for the mthing proess to 4go under4 qunti(ers nd in ft deide how to instntite existentil qunti(ers in the onlusionF o distinguish the implitions tht our tti hndles from the implitions tht will show up s 4pluming4 in vrious lemmsD we de(ne wrpper de(nitionD nottionD nd ttiF
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 lemms out imp will e useful in the tti tht 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 rfting our matcher tti will e uxiliry support for serhing through formul treesF he search prem tti implements running its tti rgument tac on every suformul of n imp premiseF es it trverses treeD search prem pplies some of the ove lemms to rewrite the gol to ring di'erent suformuls to the hed of the golF ht isD for every suformul P of the implition premiseD we wnt P to 4hve turnD4 where the premise is rerrnged into the form P Q for some Q F he tti tac should expet to see gol in this form nd fous its ttention on the (rst onjunt of the premiseF
end in match goal with | c !b search P | c !b apply comm premY search P | !b progress @tac || @apply and True endF
|| @apply and True premY tac A || match P with | cI cP @apply assoc prem1Y search P1 A || @apply assoc prem2Y search P2 A
premY tac AA
o understnd how search prem worksD we turn (rst to the (nl matchF sf the premise egins with onjuntionD we ll the search proedure on eh of the onjuntsD or only the (rst onjuntD if tht lredy yields se where tac does not filF search P expets nd mintins the invrint tht the premise is of the form P Q for some Q F e pss P expliitly s kind of deresing indution mesureD to void looping forever when tac PPU
lwys filsF he seond match se lls ommuttivity lemm to relize this invrintD efore pssing ontrol to searchF he (nl match se tries pplying tac diretly nd thenD if tht filsD hnges the form of the gol y dding n extrneous True onjunt nd lls tac ginF search itself tries the sme triks s in the lst se of the (nl matchF edditionllyD if neither worksD it heks if P is onjuntionF sf soD it lls itself reursively on eh onjuntD (rst pplying ssoitivity lemms to mintin the golEform invrintF e will lso wnt dul funtion search concD whih does tree serh through n imp onlusionF
end in match goal with !b c search P | !b c apply comm concY search P | | !b progress @tac || @apply and True endF
|| @apply and True concY tac A || match P with | cI cP @apply assoc conc1Y search P1 A || @apply assoc conc2Y search P2 A
concY tac AA
xow we n prove numer of lemms tht re suitle for pplition y our serh ttisF e lemm tht is ment to hndle premise should hve the form P Q !b R for some interesting P D nd lemm tht is ment to hndle onlusion should hve the form P !b Q R for some interesting Q F
Theorem QedF
impF
False P !b QF
False prem
P QD
X PropD
Theorem ex prem X @T X TypeA @P X @ xD P x Q !b R A @ex P Q !b R AF impF QedF Theorem ex conc X @T X TypeA @P X @Q !b P x R A @Q !b ex P R AF impF QedF
PropA @Q
X PropAD
PropA @Q
X PropA xD
e will lso wnt 4se se4 lemm for (nishing proofs where neltion hs removed every onstituent of the onlusionF
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 tti sueeds t proving simple exmpleF
QF
sn the generted proofD we (nd tre of the workings of the serh ttisF
t2F Q
prem2
@False
prem
@P Xa
QA
@P
Q AAAA
PPW
P Q
X PropD
@P
FalseA P !b P Q
e n lso see tht matcher is wellEsuited for ses where some humn intervention is needed fter the utomtion (nishesF
AbortF
matcher even sueeds t guessing qunti(er instntitionsF st is the uni(tion tht ours in uses of the Match lemm tht does the rel work hereF
Theorem QedF
t4
matcherF
X @P X
nat PropA QD @ xD P
QA
!b
@ xD
P x AF
@ex
nat P
QA
@Match @P XaA @and True conc @ex conc @fun x0 X nat P x0 A x @Match @P Xa x A @imp True @P XarueAAAAAAAA X @P X nat PropA @Q X PropAD @ x X natD P x Q A !b Q @ x X natD P x A
PQH
por exmpleD we n write tti tht instntites the qunti(ers of universllyE qunti(ed hypothesisF he tti should not need to know wht the pproprite instnE tintitions reY rtherD we wnt these hoies (lled with pleholdersF e hope thtD when we pply the speilized hypothesis lterD syntti uni(tion will determine onrete vluesF fefore we re redy to write ttiD we n try out its ingredients one t timeF
Theorem t5 X @ introsF
natD S x b x A P b IF
o instntite
evar
@y X
natAF
he proof ontext is extended with new vrile yD whih hs een ssigned to e equl to fresh uni(tion vrile cPUWF e wnt to instntite H with cPUWF o get hold of the new uni(tion vrileD rther thn just its lis yD we perform trivil llEyEvlue redution in the expression yF sn prtiulrD we only request the use of one redution ruleD deltaD whih dels with de(nition unfoldingF e pss )g further stipulting tht only the de(nition of y e unfoldedF his is simple trik for getting t the vlue of synonym vrileF
yur instntition ws suessfulF e n (nish y using the re(ned formul to reple the originlF
clear
H
HY
intro
HF
PbI e n (nish the proof y using apply9s uni(tion to (gure out the proper vlue of cPVIF @he originl uni(tion vrile ws repled y notherD s often hppens in the internls of the vrious ttis9 implementtionsFA
apply QedF
HF
xow we n write tti tht enpsultes the pttern we just employedD instntiting ll qunti(ers of prtiulr hypothesisF
Ltac insterU H Xa repeat match type of H with | x X cD 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 Theorem t5' X @ x X natD S x b x A P b IF intro H Y insterU H Y apply HF QedF
HY
intro
his prtiulr exmple is somewht sillyD sine apply y itself would hve solved the gol originllyF eprte forwrd resoning is more useful on hypotheses tht end in existentil qunti(tionsF fefore we go through n exmpleD it is useful to de(ne vrint of insterU tht does not ler the se hypothesis we pss to itF
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
P v1 u1 H1 H2
X vD uD P X v1 u1 v2 @g
u1 u2 AF
v uF u2D
P v2 u2 P
@f
v1 v2 A
Theorem t6 X introsF
v1 v2D
u1D
u2D P
@f
v1 v2 A
@g
u1 u2 AF
PQP
xeither eauto nor firstorder is lever enough to prove this golF e n help out y doing some of the work with qunti(ers ourselvesF
do P
insterKeep H1F H1 F
yur proof stte is extended with two generi instnes of 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 golD so we eliminte the two new existentil qunti(ersF repeat match goal with | H X ex destruct endF eautoF QedF End t6F
yur insterU tti does not fre so well with qunti(ed hypotheses tht lso ontin implitionsF e n see the prolem in slight modi(tion of the lst exmpleF e introdue new unry predite Q nd use it to stte n dditionl requirement of our hypothesis H1 F
H
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
P v1 u1 H1 H2
X vD Q v uD X v1 u1 v2 u2D @g
u1 u2 AF
P v uF
P v2 u2 P
@f
v1 v2 A
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 sript does not hit ny errors until the very endD when n error messge like this one is displyedF PQQ
Ia cRQVR X A X Type B X Type Q X A Prop P X A B Prop f X A A A g X 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
u1 u2 A
here is nother similr line out di'erent existentil vrileF rereD 4existentil vrile4 mens wht we hve lso lled 4uni(tion vrileF4 sn the ourse of the proofD some uni(tion vrile cRQVR ws introdued ut never uni(edF ni(tion vriles re just devie to struture proof serhY the lnguge of qllin proof terms does not inlude themF husD we nnot produe proof term without instntiting the vrileF he error messge shows tht cRQVR is ment to e proof of Q v2 in prtiulr proof stteD whose vriles nd hypotheses re displyedF st turns out tht cRQVR ws reted y insterUD s the vlue of proof to pss to H1 F ell thtD in qllinD implition is just degenerte se of qunti(tionD so the insterU ode to mth ginst lso mthed the implitionF ine ny proof of Q v2 is s good s ny other in this ontextD there ws never ny opportunity to use uni(tion to determine extly whih proof is ppropriteF e expet similr prolems with ny implitions in rguments to insterUF
e n rede(ne insterU to tret implitions di'erentlyF sn prtiulrD we ptternEmth on the type of the type T in x X cD FFFF sf T hs type PropD then x 9s instntition should e thought of s proofF husD insted of piking new uni(tion vrile for itD we insted pply userEsupplied tti tacF st is importnt tht we end this speil Prop se with || fail ID so thtD if tac fils to prove T D we ort the instntitionD rther thn ontinuing on to the defult qunti(er hndlingF
with
PQR
| x X cD 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
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
P v1 u1 H1 H2
X vD Q v uD X v1 u1 v2 u2D @g
u1 u2 AF
P v uF
P v2 u2 P
@f
v1 v2 A
Theorem
t6
v1 v2D Q v1
Q v2
u1D
u2D P
@f
v1 v2 A
@g
u1 u2 AF
e n prove the gol y lling insterKeep with tti tht tries to (nd nd pply Q hypothesis over vrile out whih we do not yet know ny P ftsF e need to egin this tti ode with idtac Y to get round strnge limittion in goq9s proof engineD where (rstElss tti rgument my not egin with matchF
introsY do P
match
fail I
PQS
repeat match goal with destruct | H X ex endY eautoF QedF End t7F
st is often useful to instntite existentil vriles expliitlyF e uiltEin tti provides one wy 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 existentil vrile ppering in the urrent golD with the lst existentil ppering ssigned numer ID the seond lst ssigned numer PD nd so onF he nmed existentil is repled everywhere y the term to the right of the XaF he instantiate tti n e onvenient for explortory provingD ut it leds to very rittle proof sripts tht re unlikely to dpt to hnging theorem sttementsF st is often more helpful to hve tti tht n e used to ssign vlue to term tht is known to e n existentilF fy employing roundout implementtion tehniqueD we n uild tti tht generlizes this funtionlityF sn prtiulrD our tti equate will ssert tht two terms re equlF sf one of the terms hppens to e n existentilD then it will e repled everywhere with the other termF
fils if it is not possile to prove x a y y reflexivityF e perform the proof only for its uni(tion side e'etsD lering the ft x a y fterwrdF ith equateD we n uild less rittle version of the prior exmpleF X p X nat natD fst p a QF econstructor Y match goal with | fst cx a Q equate endY reflexivityF QedF
Theorem
t9
@QD PA
PQT
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
SS
FFFnd so onF his proedure lwys works @t lest on mhines with in(nite resouresAD ut it hs serious drwkD whih we see when we print the proof it genertes tht PST PQU
is evenF he (nl proof term hs length liner in the input vlueF his seems like shmeD sine we ould write trivil nd trustworthy progrm to verify evenness of onstntsF he proof heker ould simply ll our progrm where neededF st is lso unfortunte not to hve stti typing gurntees tht our tti lwys ehves ppropritelyF yther invotions of similr ttis might fil with dynmi type errorsD nd we would not know out the ugs ehind these errors until we hppened to ttempt to prove omplex enough golsF he tehniques of proof y re)etion ddress oth omplintsF e will e le to write proofs like this with onstnt size overhed eyond the size of the inputD nd we will do it with veri(ed deision proedures written in qllinF por this exmpleD we egin y using type from the MoreSpecif module @inluded in the ook soureA to write erti(ed evenness hekerF
Proved
P |
Uncertain
X P
partial P F
PF
e ring into sope some nottions for the partial typeF hese overlp with some of the nottions we hve seen previously for spei(tion typesD so they were pled in seprte sope tht needs seprte 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 ptternEmthing to write funtion tht performs surprising fetF hen given partial P D this funtion partialOut returns proof of P if the partial vlue ontins proofD nd it returns @uselessA proof of True otherwiseF prom the stndpoint of wv nd rskell progrmmingD it seems impossile to write suh typeD ut it is trivil with return nnottionF
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
st my seem strnge to de(ne funtion like thisF roweverD it turns out to e very useful in writing re)etive verison of our erlier prove even ttiX
Ltac prove even reective Xa match goal with | isEven cx exact @partialOut @check endF
even N AA
e identify whih nturl numer we re onsideringD nd we 4prove4 its evenness y pulling the proof out of the pproprite check even llF
Theorem QedF
even 256'
isEven PSTF
Print
X
even 256'
isEven PST
partialOut
@check
even
PSTA
e n see onstnt wrpper round the ojet of the proofF por ny even numerD this form of proof will su0eF ht hppens if we try the tti with n odd numerc
Theorem
even 255
isEven PSSF
for match
goal
hnkfullyD the tti filsF o see more preisely wht goes wrongD we n run mnully the ody of the matchF
even
PSSAAF
Error X The term 4prtilyut @hek even PSSA4 has 4mth hek even PSS with | es isiven PSS | xo rue end4 while it is expected to have type 4isiven PSS4
type
es usulD the typeEheker performs no redutions to simplify error messgesF sf we redued the (rst term ourselvesD we would see tht check even PSS redues to NoD so tht the (rst term is equivlent to TrueD whih ertinly does not unify with isEven PSSF
AbortF
PQW
galore
X @True
true galoreF
and ind
True True @fun X True or introl @True @True TrueAA IA H X True True True True @True TrueA
X
es we might expetD the proof tht tauto uilds ontins expliit pplitions of nturl dedution rulesF por lrge formulsD this n dd liner mount of proof size overhedD eyond the size of the inputF o write re)etive proedure for this lss of golsD we will need to get into the tul 4re)etion4 prt of 4proof y re)etionF4 st is impossile to seEnlyze Prop in ny wy in qllinF e must reect Prop into some type tht we can nlyzeF his indutive type is good ndidteX
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 reursive funtion to 4unre)et4 this syntx 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 esy to prove tht every formul in the rnge of
tautDenote
is trueF
tautDenote tF
o use tautTrue to prove prtiulr formulsD we need to implement the syntx re)etion proessF e reursive vt funtion does the joF PRH
Ltac tautReect P Xa match P with | True TautTrue | cI cP let t1 Xa tautReect P1 in let t2 Xa tautReect P2 in constr X@utend t1 t2 A | cI cP let t1 Xa tautReect P1 in let t2 Xa tautReect P2 in constr X@utyr t1 t2 A | cI cP let t1 Xa tautReect P1 in let t2 Xa tautReect P2 in constr X@utsmp t1 t2 A endF
ith tautReect villeD it is esy to (nish our re)etive ttiF e look t the gol formulD re)et itD nd pply tautTrue to the re)eted formulF
Ltac obvious Xa match goal with | c let t Xa tautReect P in exact @tautTrue t A endF
e n verify tht obvious solves our originl exmpleD with proof term tht does not mention detils of the proofF
Theorem QedF
true galore'
X @True
a
TautTrueAAAA
@TautImp @TautAnd TautTrue TautTrueA @TautOr TautTrue @TautAnd TautTrue @TautImp TautTrue X True True True True @True TrueA
st is worth onsidering how the re)etive tti improves on pureEvt implementtionF he formul re)etion proess is just s dEho s eforeD so we gin little thereF sn generlD proofs will e more omplited thn formul trnsltionD nd the 4generi proof rule4 tht we pply here is on muh etter forml footing thn reursive vt funtionF he dependent type of the proof gurntees tht it 4works4 on ny input formulF his is ll in PRI
Section monoidF Variable A X SetF Variable e X AF Variable f X A Infix 4C4 Xa fF Hypothesis Hypothesis Hypothesis
assoc
AF
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
C @b C c AF
e dd vriles nd hypotheses hrterizing n ritrry instne of the lgeri struture of monoidsF e hve n ssoitive inry opertor nd n identity element for itF st is esy to de(ne n expression tree type for monoid expressionsF e Var onstrutor is 4thEll4 se for suexpressions tht we nnot modelF hese suexpressions ould e tul qllin vrilesD or they ould just use funtions tht our tti is unle to understndF
Inductive mexp X Set Xa | Ident X mexp | Var X A mexp | Op X mexp mexp mexpF
xextD we write n 4unEre)et4 funtionF
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 normlize expressions y )ttening them into listsD vi ssoitivityD so it is helpful to hve denottion funtion for lists of monoid vluesF
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 funtion itself is esy 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
me2
denote
funtionsF
Lemma
@ml1 CC
ml2 AF
Theorem atten correct X meD mdenote Hint Resolve atten correct'F induction QedF
me Y crushF
me
mldenote
@atten
me AF
xow it is esy to prove theorem tht will e the min tool ehind our simpli(tion ttiF
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
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 (nl monoid tti works on gols tht equte two monoid termsF e re)et eh nd hnge the gol to refer to the re)eted versionsD (nishing o' y pplying monoid reect nd simplifying uses of mldenoteF
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
c dD a
C @b C c A C dF
re)exivityF
hs nonilized oth sides of the equlityD suh tht we n (nish the proof y
reflexivityF QedF
st is interesting to look t the form of the proofF
monoid reect
@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
he proof term ontins only resttements of the equlity opernds in re)eted formD followed y use of re)exivity on the shred nonil formF
End
monoidF
ixtensions of this si pproh re used in the implementtions of the ring nd ttis tht ome pkged with goqF
eld
trnslting the formul into vlue like Imp @Var P A @Var P AD euse qllin funtion hs no wy of ompring the two P s for equlityF o rrive t nie implementtion stisfying these riteriD we introdue the quote tti nd its ssoited lirryF
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 lirry nd represents ountle vrile typeF he rest of formula9s de(nition should e old ht y nowF he quote tti will implement injetion from Prop into formula for usD ut it is not quite s smrt s we might likeF sn prtiulrD it interprets implitions inorretlyD so we will need to delre wrpper de(nition for implitionD s we did in the lst hpterF 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 denottion funtionF 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 fmily implements mps from index vluesF sn this seD we de(ne n ssignment s mp from vriles to PropsF formulaDenote works with n ssignmentD nd we use the varmap nd funtion to onsult the ssignment in the Atomic seF he (rst rgument to varmap nd is defult vlueD in se the vrile 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 shorthnd for prtiulr vrile eing trueD nd now we re redy to de(ne some helpful funtions sed on the ListSet module of the stndrd lirryD whih @unsurprisinglyA presents view of lists s setsF
PRS
ListSetF
index eq
decide equalityF
x y
indexD {x a y } C {x = y }F
Definition
add
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 wht it mens for ll memers of n index set to represent true propositionsD nd we prove some lemms out this notionF
Fixpoint allTrue @s X match s with | nil True | v XX s' holds endF Theorem
allTrue add allTrue s
set
indexA X Prop Xa
allTrue s'
v sD
holds v allTrue @add s v AF induction s Y crush Y match goal with | context if ci then endY crushF QedF
else destruct
Theorem
allTrue In
v sD
allTrue s
v atomicsF
Hint Resolve
partial scopeF
xow we n write funtion forward whih implements deonstrution of hypothesesF st hs dependent typeD in the style of ghpter TD gurnteeing orretnessF he rguments PRT
to forward re gol formul f D set known of tomi formuls tht we my ssume re trueD hypothesis formul hypD nd suess ontinution cont tht we ll when we hve 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 funtion implements nlysis of the (nl golF st lls implitionsF
forward
to hndle
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 Definition my tauto @f X formulaA X formulaDenote introY refine @Reduce @backward nil f AAY crushF DefinedF End my tautoF
F known' f2 A
e simple wrpper round backward gives us the usul type of prtil deision proedureF
atomics f
yur (nl tti implementtion is now firly strightforwrdF pirstD we intro ll quntiE PRU
(ers tht do not ind PropsF hen we ll the quote ttiD whih implements the re)etion for usF pinllyD we re le to onstrut n ext proof vi partialOut nd the my tauto qllin funtionF
Ltac my tauto Xa repeat match goal with | x X cD match type of P with | Prop fail I | intro end endY quote formulaDenote Y match goal with | formulaDenote cm cf exact @partialOut @my endF
e few exmples demonstrte how the tti worksF
tauto m f
AA
Theorem QedF
mt1
my tautoF
TrueF
tauto
@Empty
vm
PropA
TruthA
e see
my tauto
Theorem QedF
mt2
my tautoF
x y
natD x a y !b x a yF
@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
gruillyD oth instnes of x a y re represented with the sme indexD End idxF he vlue of this index only needs to pper one in the varmapD whose form revels tht varmaps re represented s inry treesD where index vlues denote pths from tree roots to levesF PRV
S yA
@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 gol ontined three distint tomi formulsD nd we see tht threeEelement varmap is genertedF st n e interesting to oserve di'erenes etween the level of repetition in proof terms generted y my tauto nd tauto for espeilly trivil theoremsF
Theorem QedF
mt4
my tautoF
@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
True True True True True True False TrueA @H1 X True True True True True FalseA TrueA @H3 X True True True True FalseA TrueA @H5 X True True True FalseA TrueA @H7 X True True FalseA TrueA @H9 X True FalseA ind @fun @ X TrueA @H11 X FalseA False
ind
and ind
@fun @ X
and ind
@fun @ X
and ind
@fun @ X
and ind
@fun @ X
and ind and
@fun @ X
H9 A H7 A H5 A H3 A H1 A H
False H11 A
13.5 Exercises
IF smplement re)etive proedure for normlizing systems of liner equtions over rE tionl numersF sn prtiulrD the tti should identify ll hypotheses tht re liner equtions over rtionls where the eqution righthnd sides re onstntsF st should normlize eh hypothesis to hve lefthnd side tht is sum of produts of onstnts nd vrilesD with no vrile ppering multiple timesF henD your tti should dd together ll of these equtions to form single new equtionD possily lering the origE inl equtionsF ome oe0ients my nel in the dditionD reduing the numer of vriles tht pperF o work with rtionl numersD import module QArith nd use Local Open Scope Q scopeF ell of the usul rithmeti opertor nottions will then work with rtionlsD nd there re shorthnds for onstnts H nd IF yther rtionls must e written s num 5 den for numertor num nd denomintor denF se the in(x opertor aa in ple of aD to del with di'erent wys of expressing the sme numer s frtionF por instneD theorem nd proof like this one should work with your ttiX
hroughoutD the ring tti will e helpful for proving mny simple fts out rtioE nlsD nd ttis like rewrite re orretly overloded to work with rtionl equlity aaF @A he(ne n indutive type exp of expressions over rtionls @whih inhit the goq type Q AF snlude vriles @represented s nturl numersAD onstntsD dditionD sutrtionD nd multiplitionF @A he(ne funtion lookup for reding n element out of list of rtionlsD y its position in the listF @A he(ne funtion expDenote tht trnsltes representing vrile vluesD to Q F @dA he(ne reursive funtion of the equtions re trueF
eqsDenote
expsD
over
@eA pix representtion lhs of )ttened expressionsF here len is the numer of vrilesD represent )ttened eqution s ilist Q lenF ih position of the list gives the oe0ient of the orresponding vrileF @fA rite reursive funtion linearize tht tkes onstnt k nd n expression e nd optionlly returns n lhs equivlent to k B eF his funtion returns None when it disovers tht the input expression is not linerF he prmeter len of lhs should e prmeter of linearizeD tooF he funtions singletonD everywhereD nd map2 from DepList will proly e helpfulF st is lso helpful to know tht Qplus is the identi(er for rtionl dditionF @gA rite reursive funtion linearizeEqs X list @exp B Q A option @lhs B Q AF his funtion linerizes ll of the equtions in the list in turnD uilding up the sum of the equtionsF st returns None if the lineriztion of ny onstituent eqution filsF @hA he(ne denottion funtion for
lhsF k
@iA rove thtD when exp lineriztion sueeds on onstnt linerized version hs the sme mening s k B eF
nd expression eD the
@jA rove thtD when linearizeEqs sueeds on n eqution list eqsD then the (nl summedEup eqution is true whenever the originl eqution list is trueF @kA rite tti ndVarsHyps to serh through ll equlities on rtionls in the ontextD reursing through dditionD sutrtionD nd multiplition to (nd the list of expressions tht should e treted s vrilesF his list should e suitle s n rgument to expDenote nd eqsDenoteD ssoiting Q vlue to eh nturl numer tht stnds for vrileF @lA rite tti reect to re)et list of vrile vluesF
Q
expression into
expD
@mA rite tti reectEqs to re)et formul tht egins with sequene of impliE tions from liner equlities whose lefthnd sides re expressed with expDenoteF PSI
his tti should uild list @exp B Q A representing the equtionsF ememer to give n expliit type nnottion when returning nil listD s in constr X@dnil @exp B Q AAF @nA xow this (nl tti should do the joX
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
nat exp Plus X exp exp expF Fixpoint eval @e X expA X nat Xa
| |
Const
eval e1
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 mnul proof tht
e2 A
double
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 spes to seprte the two indutive sesF he seond se mentions utomtillyE generted hypothesis nmes expliitlyF es resultD innouous hnges to the theorem stteE ment n invlidte 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
in
IHx1
nd
IHx2
nowD not
IHe1
nd
IHe2F
AbortF
PSR
e might deide to use more expliit invotion of induction to give expliit inders for ll of the nmes tht we will referene lter 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 trivialF simplF rewrite IHe1F rewrite IHe2F rewrite mult plus trivialF QedF
IHe2
distr lF
e pss induction n intro patternD using | hrter to seprte out instrutions for the di'erent indutive sesF ithin seD we write c to sk goq to generte nme utomtillyD nd we write n expliit nme to ssign tht nme to the orresponding new vrileF st is pprent thtD to use intro ptterns to void proof rittlenessD one needs to keep trk of the seemingly unimportnt fts of the orders in whih vriles re introduedF husD the sript keeps working if we reple e y x D ut it hs eome more lutteredF ergulyD neither proof is prtiulrly esy to followF ht tegory of omplint hs to do with understnding proofs s stti rtiftsF es with progrmming in generlD with serious projetsD it tends to e muh more importnt to e le to support evolution of proofs s spei(tions hngeF nstrutured proofs like the ove exmples n e very hrd to updte in onert with theorem sttementsF por instneD onsider how the lst proof sript plys out when we modify times to introdue 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 trivialF simplF rewrite
IHe1F
e2 A
IHe2
in
PSS
AbortF gn you spot wht went wrongD without stepping through the sript stepEyEstepc he prolem is tht trivial never filsF yriginllyD trivial hd een sueeding in proving n equlity tht follows y re)exivityF yur hnge to times leds to se where tht equlity is no longer trueF trivial hppily leves the flse equlity in pleD nd we ontinue on to the spn of ttis intended for the seond indutive seF nfortuntelyD those ttis end up eing pplied to the rst se instedF he prolem with trivial ould e 4solved4 y writing solve trivial instedD so tht n error is signled erly on if something unexpeted hppensF roweverD the root prolem is tht the syntx of tti invotion does not imply how mny sugols it produesF wuh more onfusing instnes of this prolem re possileF por exmpleD if lemm L is modi(ed to tke n extr hypothesisD then uses of apply L will generl more sugols thn eforeF yld unstrutured proof sripts will eome hopelessly jumledD with ttis pplied to inpproprite sugolsF feuse of the lk of strutureD there is usully reltively little to e glened from knowledge of the preise point in proof sript where n error is risedF 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 wny rel developments try to mke essentilly unstrutured proofs look strutured y pplying reful indenttion onventionsD idempotent seEmrker ttis inluded soley to serve s doumenttionD nd so onF ell of these strtegies su'er from the sme kind of filure of strtion tht ws just demonstrtedF s like to sy tht if you (nd yourself ring out indenttion in proof sriptD it is sign tht the sript is strutured poorlyF e n rewrite the urrent proof with single ttiF 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 roustness of the sriptF e no longer need to worry out ttis from one se eing pplied to di'erent seF tillD the proof sript is not espeilly redleF roly most reders would not (nd it helpful in explining why the theorem is trueF he sitution gets worse in onsidering extensions to the theorem we wnt to proveF vet us dd multiplition nodes to our exp type nd see how the proof fresF 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
trivial F
pattern with Q
branchesF
AbortF nsurprisinglyD the old proof filsD euse it expliitly sys tht there re two indutive sesF o updte the sriptD we mustD t minimumD rememer the order in whih the indutive ses re genertedD so tht we n insert the new se in the pproprite pleF iven thenD it will e pinful to dd the seD euse we nnot wlk through proof steps intertively when they our inside n expliit 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 muh nier is the style of proof tht we hve followed in most of this ookF Reset eval timesF
PSU
Hint
cpdtF
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 sugol reminsX IHe2 X eval e3 B eval e4 a
Mult
end
eval e2
PSV
does not know how to (nish this golF e ould (nish the proof mnullyF
IHe2 Y crushF
rewrite
roweverD the proof would e esier to understnd nd mintin if we seprted this insight into seprte lemmF
crushF
a b c dD b
B dF
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 omplited indutive proof might rely on one hint for eh indutive seF he lemm for eh hint ould restte the ssoited seF gompred to mnul proof sriptsD we rrive t more redle resultsF ripts no longer need to depend on the order in whih ses re genertedF he lemms re esier to digest seprtely thn re frgments of tti odeD sine lemm sttements inlude omplete proof ontextsF uh ontexts n only e extrted from monolithi mnul proofs y stepping through sripts intertivelyF he more ommon sitution is tht lrge indution hs severl esy ses tht uE tomtion mkes short work ofF sn the remining sesD utomtion performs some stndrd simpli(tionF emong these sesD some my require quite involved proofsY suh se my deserve hint lemm of its ownD where the lemm sttement my opy the simpli(ed version of the seF elterntivelyD the proof sript for the min theorem my e extended with some utomtion ode trgeted t the spei( seF iven suh trgeted sripting is more desirle thn mnul provingD euse it my e red nd understood without knowledge of proof9s hierrhil strutureD se orderingD or nme inding strutureF
ing with higherEorder logiD most theorems fll within no ovious deidle theoriesF st is inevitle tht most longElived utomted proofs will need updtingF fefore we re redy to updte our proofsD we need to write them in the (rst pleF hile fullyEutomted sripts re most roust to hnges of spei(tionD it is hrd to write every new proof diretly in tht formF snstedD it is useful to egin theorem with explortory proving nd then grdully re(ne it into suitle utomted formF gonsider this theorem from ghpter UD whih we egin y proving in mostly mnul wyD invoking crush fter eh steop to dishrge ny lowEhnging fruitF yur mnul e'ort involves hoosing whih expressions to seEnlyze onF
@e X
QedF
dep destruct
sn this omplete proofD it is hrd to void notiing ptternF e rework the proofD strting over the ptterns we (ndF
Reset cfold correctF
@e X
he expression we wnt to destrut here turns out to e the disriminee of matchD nd we n esily enough write tti tht destruts ll suh expressionsF
goal
with | Plus context match ci with NConst | Eq | BConst | And | If | Pair | Fst | Snd end
endY
tF
PTH
his tti invotion dishrges the whole seF st does the sme on the next two sesD ut it gets stuk on the fourth seF
tF tF tF
he sugol9s onlusion 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 expnd our
t
e3 AA
goal
context match
with
dep destruct E
else A a
destruct
t'
e (nl revision of
goal
with | Plus context match ci with NConst | Eq | BConst | And | If | Pair | Fst | Snd end
@if ci then else A a destruct context match pairOut ci with Some | None end
E
dep destruct E
| |
endY
t F t F
QedF
PTI
e n tke the (nl tti nd move it into the initil prt of the proof sriptD rriving t nielyEutomted 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
QedF
endY
iven fter we put together nie utomted proofsD we must del with spei(tion hnges tht n invlidte themF st is not generlly possile to step through singleEtti proofs intertivelyF here is ommnd Debug On tht lets us step through points in tti exeutionD ut the deugger tends to mke ounterintuitive hoies of whih points we would like to stop tD nd perEpoint output is quite veroseD so most goq users do not (nd this deugging mode very helpfulF row re we to understnd wht hs roken in sript tht used to workc en exmple helps demonstrte useful pprohF gonsider wht would hve hppened in our proof of reassoc correct if we hd (rst dded n unfortunte rewriting hintF
Reset reassoc correctF
Theorem
eval e1
confounder
QedF
crushF
eval e2
e1
B @eval
e2
C I E IA B
eval e3F
Hint
Rewrite confounder
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 sugol reminsX
Mult
end
PTP
eval e2
he poorlyEhosen rewrite rule (redD hnging the gol to form where nother hint no longer ppliesF smgine tht we re in the middle of lrge development with mny hintsF row would we dignose the prolemc pirstD we might not e sure whih se of the indutive proof hs gone wrongF st is useful to seprte out our utomtion proedure nd pply it mnullyF
RestartF
Ltac
Xa
crush Y
match goal with | context match ci with Const | Plus | Mult end destruct E Y crush endF
induction eF
ine we see the sugols efore ny simpli(tion oursD it is ler tht this is the se for onstntsF t mkes short work of itF
tF
he (nl sugol is for multiplitionD nd it is here tht we get stuk in the proof stte summrized oveF
tF
info
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 detiled tre of t 9s exeution ppersF ine we re using the very generl crush ttiD mny of these steps hve no e'et nd only our s instnes of more generl strtegyF e n opyEndEpste the detils to see where things go wrongF
UndoF
e ritrrily split the sript into hunksF he (rst few seem not to do ny hrmF
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
autorewrite
he next step is reveled s the ulpritD ringing us to the (nl unproved sugolF
with
cpdt
in BF
with
cpdt
in BF
st ws the (nl of these four ttis tht mde the rewriteF e n (nd out extly wht hppenedF he info ommnd presents hierrhil views of proof stepsD nd we n zoom down to lower level of detil y pplying info to one of the steps tht ppered in the originl treF
UndoF
info autorewrite
with
cpdt
in BF
eval e2 A
he wy rewrite is displyed is somewht roqueD ut we n see tht theorem confounder is the (nl ulpritF et this pointD we ould remove tht hintD prove n lternte version of the key lemm rewrD or ome up with some other remedyF pixing this kind of prolem tends to e reltively esy one the prolem is reveledF
AbortF
ometimes hnge to development hs undesirle performne onsequenesD even if PTR
it does not prevent ny old proof sripts from ompletingF sf the performne onsequenes re severe enoughD the proof sripts n e onsidered roken for prtil purposesF rere is one exmple of performne surpriseF
trans eqF
he entrl element of the prolem is the ddition of trnsitivity s hintF ith trnE sitivity villeD it is esy for proof serh to wind up exploring exponentil serh spesF e lso dd few other ritrry vriles nd hypothesesD designed to led to troule lterF
PropF Q x y R x yF
R x y
X X
x yD P x y x yD S x y
f x
f yF
e prove simple lemm very quiklyD using the Time ommnd to mesure extly how quiklyF
Lemma
slow
Time
eauto TF
x yD P x y
Q x y
S x y
f x
f yF
Finished transaction
in HF
secs
@HFHTVHHRuDHFs A
QedF
xow we dd di'erent hypothesisD whih is innoent enoughY in ftD it is even provle s theoremF
Hypothesis Lemma
slow'
H3
x yD x P x y
f x
f yF
Time
X x yD eauto TF
Q x y
S x y
f x
f yF
Finished transaction
in PF
secs
@IFPTRHUWuDHFs A
hy hs the serh time gone up so muhc he info ommnd is not muh helpD sine it only shows the result of serhD not ll of the pths tht turned out to e worthlessF
RestartF info
HY
intro
H0 Y
intro
H4 Y
trans eqF
PTS
apply
re equalF
eexact HF
apply
H2 Y eexact H4 F
his output does not tell us why proof serh tkes so longD ut it does provide lue tht would e useful if we hd forgotten tht we dded trnsitivity s hintF he eauto tti is pplying depthE(rst serhD nd the proof sript where the rel tion is ends up uried inside hin of pointless invotions of trnsitivityD where eh invotion uses re)exivity to dishrge one sugolF ih inrement to the depth rgument to eauto dds nother silly use of trnsitivityF his wsted proof e'ort only dds liner time overhedD s long s proof serh never mkes flse stepsF xo flse steps were mde efore we dded the new hypothesisD ut somehow the ddition mde possile new fulty pthF o understnd whih pths we enledD we n use the debug ommndF
RestartF debug
eauto TF
he output is lrge proof treeF he eginning of the tree is enough to revel wht is hppeningX 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 hoie eauto mkes is to pply H3 D sine H3 hs the fewest hypotheses of ll of the hypotheses nd hints tht mthF roweverD it turns out tht the single hypothE esis generted is unprovleF ht does not stop eauto from trying to prove it with n exponentillyEsized tree of pplitions of trnsitivityD re)exivityD nd symmetry of equlityF st is the hildren of the initil apply H3 tht ount for ll of the notiele time in proof exeutionF sn more relisti developmentD we might use this output of info to relize tht dding trnsitivity s hint ws d ideF
14.3 Modules
vst hpter9s exmples of proof y re)etion demonstrte opportunities for implementing strt proof strtegies with stronger forml gurntees thn n e hd with vt sriptE ingF goq9s module system provides nother tool for more rigorous development of generi theoremsF his feture is inspired y the module systems found in tndrd wv nd yE jetive gmlD nd the disussion tht follows ssumes fmilirity with the sis of one of PTU
those systemsF wv modules filitte the grouping of strt types with opertions over those typesF woreoverD there is support for functorsD whih re funtions from modules to modulesF e nonil exmple of funtor is one tht uilds dt struture implementtion from module tht desries domin of keys nd its ssoited omprison opertionsF hen we dd modules to se lnguge with dependent typesD it eomes possile to use modules nd funtors to formlize kinds of resoning tht re ommon in lgerF por instneD this module signture ptures the essene of the lgeri struture known s groupF e group onsists of rrier set GD n ssoitive inry opertion f D left identity element e for f D nd n opertion i tht is left inverse for f 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 Module Type GROUP THEOREMSF Declare Module M X GROUPF Axiom Axiom
ident'
@f
b c AF
wny useful theorems hold of ritrry groupsF e pture some suh theorem stteE ments in nother module signtureF
X aD
M.f
M.e
a aF
aA
M.f
inverse'
X aD
M.f
@M.i
M.e
F
e'
e' a
a aA
M.e
e implement generi proofs of these theorems with funtorD whose input is n ritrry group MF he proofs re ompletely mnulD sine it would tke some e'ort to uild suitle generi utomtionY rtherD these theorems n serve s sis for n utomted proedure for simplifying group expressionsD long the lines of the proedure for monoids from the lst hpterF e tke the proofs from the ikipedi pge on elementry group theoryF
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 tht 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 produe integerEspei( versions of the generi group theoremsF Module IntTheorems Xa Group@IntAF
PTW
Check
IntTheorems.unique ident
F a aA
e' e'
IntTheorems.unique ident
e'
Int.GD
Int.e
a aA
a HF
es in wvD the module system provides n e'etive wy to struture lrge developmentsF nlike in wvD goq modules dd no expressivenessY we n implement ny module s n inhitnt of dependent reord typeF st is the seondElss nture of modules tht mkes them esier to use thn dependent reords in mny seF feuse modules my only e used in quite restrited wysD it is esier to support onvenient module oding through speil ommnds nd editing modesD s the ove exmple demonstrtesF en isomorphi implementtion with reords would hve su'ered from lk of suh onvenienes s module sutyping nd importtion of the (elds of moduleF
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 wke(le egins y de(ning vrile VS holding the list of (lenmes to e inluded in the projetF he primry trget is coqD whih depends on the onstrution of n uxilE iry wke(le lled Makefile.coqF enother rule explins how to uild tht (leF e ll PUH
coq makefileD using the -R )g to speify tht (les in the urrent diretory should e onE sidered to elong to the lirry LibF his wke(le will uild ompiled version of eh moduleD suh tht X.v is ompiled into X.voF xow ode in B.v my refer to de(nitions in A.v fter running Require Import
Lib.AF
virry Lib is presented s moduleD ontining sumodule AD whih ontins the de(nitions from A.vF hese re genuine modules in the sense of goq9s module systemD nd they my e pssed to funtors nd so onF Require Import is onvenient omintion of two more primitive ommndsF Require (nds the .vo (le ontining the nmed moduleD ensuring tht the module is loded into memE oryF Import lods ll topElevel de(nitions of the nmed module into the urrent nmespeD nd it my e used with lol modules tht do not hve orresponding .vo (lesF enother ommndD LoadD is for inserting the ontents of nmed (le vertimF st is generlly etE ter to use the moduleEsed ommndsD sine they void rerunning proof sriptsD nd they filitte reorgniztion of diretory struture without the need to hnge odeF xow we would like to use our lirry from di'erent developmentD lled Client nd found in diretory CLIENTD whih hs its own wke(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 hnge the coq makefile ll to indite where the lirry nd E.v n refer to de(nitions from Lib module A fter running
Lib
Require Import
Lib.AF
Require Import
Client.DF
PUI
st n e useful to split lirry into severl (lesD ut it is lso inonvenient for lient ode to import lirry modules individullyF e n get the est of oth worlds yD for exmpleD dding n extr soure (le Lib.v to Lib 9s diretory nd wke(leF
Require Export
Require Import
LibF
he two wke(les ove shre lot of odeD soD in prtieD it is useful to de(ne ommon wke(le tht is inluded y multiple lirryEspei( wke(lesF he remining ingredient is the proper wy of editing lirry ode (les in roof qenerlF ell this snippet of .emacs ode from ghpter PD whih tells roof qenerl where to (nd the lirry ssoited with this ookF
(custom-set-variables ... ; '(coq-prog-args '("-I" "/path/to/cpdt/src")) '(coq-prog-args '("-R" "LIB" "Lib" "-R" "CLIENT" "Client")) ... )
hen working on multiple projetsD it is useful to leve multiple versions of this setting in your .emacs (leD ommenting out ll ut one of them t ny moment in timeF o swith etween projetsD hnge the ommenting struture nd restrt imsF
PUP
PUQ
Module
ConcreteF
var
Definition Definition
Xa
stringF
Xa
var eq
string decF
e will formlize si simplyEtyped lmd lulusF he syntx of expressions nd types follows wht we would write in ontextEfree grmmrF
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
st is useful to de(ne syntx extension tht lets us write funtion types in more stndrd nottionF
Infix 4!b4 Xa
Arrow
@right
associativityD
at
level
THAF
xow we turn to typing judgmentF e will need to de(ne it in terms of typing ontextsD whih we represent s lists of pirs of vriles nd typesF
Definition
ctx
Xa
he de(nitions of our judgments will e prettier if we write them using mix(x syntxF o de(ne judgment for looking up the type of vrile in ontextD we (rst reserve nottion for the judgmentF eserved nottions enle mutullyEreursive de(nition of judgment nd its nottionY in this senseD the reservtion is like forwrd delrtion in gF
associativityD
at
level
WHD
at
next level AF
xow we de(ne the judgment itselfD for vrile typingD using where luse to ssoite nottion 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
type Prop Xa
G x t AF
he sme tehnique pplies to de(ning the min typing judgmentF e use n at next level luse to use the rgument e of the nottion to e prsed t low enough preedene 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
level
WHD
at
next level AF
PUS
|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
ran G e t AF
st is useful to know tht vrile lookup results re unhnged y dding extr indings to the end of ontextF
Lemma
G1
weaken lookup
|Ev
X t CC G' |Ev
x
x t G' G1D
H Y crush
Hint Resolve
weaken lookupF
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
wuh of the inonveniene of (rstEorder enodings omes from the need to tret ptureE voiding sustitution expliitlyF e must strt y de(ning sustitution funtionF
e re sustituting expression e1 for every free ourrene of x F xote tht this de(nition is speilized to the se where e1 is losedY sustitution is sustntilly more omplited otherwiseD potentilly involving expliit lphEvritionF vukilyD our exmple of type sfety for llEyEvlue semntis only requires this restrited vriety of sustitutionF
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 sustitution in wellEtyped termsD where we ssume tht e1 is losed nd hs type xt F
e1
xtF
associativityD
at level WHAF
o prove type preservtionD we will need lemms proving onsequenes of vrile 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
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
QedF
H Y crush Y
eauto
Implicit Arguments
enother set of lemms llows us to remove provly unused vriles from the ends of typing ontextsF |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 lookup
v t t' G1D
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
CC @xD xt A XX nil G1 |Ev x X t G1 |Ee e X tF introsY eapply shadow QedF
G1
Lemma
shadow hasType
X G1 e |Ee e X t
t t D
hasType'Y
eautoF
Hint Resolve
shadow hasTypeF
hisjointness fts my e extended to lrger ontexts when the pproprite oligtions re metF PUV
Lemma disjoint cons X x x' t @G X ctxAD x 5 G 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
disjoint consF
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 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 wrp the lst theorem into n esierEtoEpply form speilized to losed expressionsF
e nottion for sustitution will mke the opertionl semntis esier to redF
x e1 e2 A
@no
associativityD
at
level
VHAF
o de(ne llEyEvlue smllEstep semntisD we rely on stndrd judgment hrE terizing whih expressions re vluesF
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
associativityD
at
level
WHAF
val e2
App
e2 e1
Cong1
val e1
e2
aab
e2'
App e1 e2
aab
App e1 e2'
e1 e2 AF
he progress theorem sys tht ny wellEtyped expression n tke stepF o del with limittions of the induction ttiD we put most of the proof in lemm whose sttement uses the usul trik of introduing extr equlity 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 similr pttern works for the preservtion theoremD whih sys tht ny step of exeuE tion preserves n expression9s typeF
G e tD G
|Ee
PVH
nil |Ee e' X tF induction IY inversion PY match goal with X | H X |Ee Abs endY eautoF QedF
crush Y
eautoY
H
inversion
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 ws reltively simple exmpleD giving only tste of the proof urden ssoited with onrete syntxF e were helped y the ft thtD with llEyEvlue semntisD we only need to reson out sustitution in losed expressionsF here ws lso no need to lphEvry n expressionF
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 proeeds muh the sme s in the lst setionF ine vriles re numersD ontexts n e simple lists of typesF his mkes it possile to write the lookup judgment without mentioning inequlity of vrilesF
PVI
Definition
ctx
Xa
list typeF
associativityD
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
at
level
WHD
at
next level AF
type Prop Xa
G x t AF
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
at
level
WHD
at
next level AF
type Prop Xa
G e t AF
sn the hasType se for funtion strtionD there is no need to hoose vrile nmeF e simply push the funtion domin type onto the ontext GF
Hint
Constructors hasTypeF
Lemma weaken lookup X G |Ev v X t G CC G' |Ev v X tF induction IY crushF QedF Hint Resolve Theorem weaken G |Ee e X t
G' v t GD
G' G e tD
PVP
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 ustitution is esier to de(ne thn with onrete syntxF hile our old de(nition needed to use two omprisons for equlity of vrilesD the de fruijn sustitution only needs one omprisonF 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 similr theorems out inversion of vrile 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
G1
subst neq
inversion IY
X tF
crushF
Hint Resolve
subst neqF
Ht'
nil
|Ee
e1
xtF
he next lemm is inluded solely to guide eautoD whih will not pply omputtionl equivlenes utomtillyF
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
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
subst hasType closedF
subst hasTypeY
eautoF
e1 x e2 A
@no
associativityD
at
level
VHAF
PVR
Inductive val X exp Prop Xa | VConst X bD val @Const b A | VAbs X eD val @Abs e AF Hint
Constructors valF associativityD
at
level
WHAF
val e2
App
e2 e1
val e1
e2
aab
e2'
App e1 e2
aab
App e1 e2'
e1 e2 AF
ine we hve dded the right hintsD the progress nd preservtion theorem sttements nd proofs re extly the sme s in the onrete enoding exmpleF
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
PVS
induction IY inversion PY match goal with | H X |Ee Abs X endY eautoF QedF
crush Y
eautoY
H
inversion
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
Module
LocallyNamelessF
free var bound var
Definition Definition
Xa stringF Xa natF
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 onstrutors for free vsF ound vrilesD nd note tht the lk of vrile nnottion 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
associativityD
@right
at
level
THAF
es typing only depends on types of free vrilesD our ontexts orrow their form from the onrete inding exmpleF
Definition
ctx
Xa
list @free
var
typeAF
associativityD
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
at
level
WHD
at
next level AF
type Prop Xa
G x t AF
he (rst unusul opertion we need is openingD where we reple prtiulr ound vrile with prtiulr free vrileF henever we 4go under inderD4 in the typing judgment or elsewhereD we hoose new free vrile to reple the old ound vrile of the inderF ypening implements the replement of one y the otherF st is like speilized version of the sustitution funtion we used for pure de fruijn termsF
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 reson out n expression9s set of free vrilesF o keep things simpleD we represent sets s lists tht my ontin duplitesF xote how muh esier this opertion is to implement thn over pure de fruijn termsD sine we do not need to mintin seprte numeri rgument tht keeps trk of how deeply we hve desended 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 hve wellEformedness judgment for our termsF his notion is lled en expression my e delred to e losedD up to prtiulr mximum 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
Constructors lclosedF
@App
e1 e2 A
associativityD
at
level
WHD
at
next level AF
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
G e t AF
gompred to the previous versionsD only the TAbs rule is surprisingF he rule uses conite quantiifcationF ht isD the premise of the rule qunti(es over ll x vlues tht re not memers of (nite set LF e proof my hoose ny vlue of L when pplying TAbsF en lternteD more intuitive version of the rule would (x L to e freeVars e'F st turns out tht the greter )exiility of the rule ove simpli(es mny proofs signi(ntlyF his typing judgment my e proved equivlent to the more intuitive versionD though we will not rry out the proof hereF pei(llyD wht our version of TAbs sys is thtD to prove tht Abs e' hs funtion typeD we must prove tht ny opening of e' with vrile not in L hs the proper typeF por eh x hoieD we extend the ontext G in the usul wyF
Hint
Constructors hasTypeF
e prove stndrd wekening theorem for typingD dopting more generl form thn in the previous setionsF
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
weaken hasTypeF
X tA
crush
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 lol losure will e useful lterF
Lemma
lclosed S
x e nD
induction e Y inversion IY
lnF
PVW
lclosed n
n eD
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
freshOk
for freshF
LD String.length x
sumLengths L
String.length s1
String.length s2F
Hint
cpdtF
String.length
Lemma
X nD
@primes n A a PWH
S nF
crushF
cpdtF crushF
Theorem freshOk X LD In @fresh LA LF introsY apply freshOk'Y unfold freshY QedF Hint Resolve
freshOkF
xow we n prove tht wellEtypedness implies lol losureF fresh will e used for us utomtilly y eauto in the Abs seD driven y the presene of freshOk s hintF
G e tD
Lemma lclosed open X n eD lclosed xD open x n e a eF induction IY lnF QedF Hint Resolve Open Scope
list scopeF
n e
e re now lmost redy to get down to the detils of sustitutionF pirstD we prove six lemms relted to treting lists s setsF
In cons2
x'
T A lsD
X
ls AF
@x
x'
T A lsD
In x ls In x
QedF
crushF
@x' XX
Lemma
In app1
@x X
T A ls2 ls1D
In x ls1
Lemma
In app2
@x X
T A ls2 ls1D
PWI
In x ls2
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 sustitution funtion yetD thnks to the ft tht we only susitute for free vrilesD whih re distinguished synttilly from ound vrilesF 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 hndy to de(ne disjointness of vrile nd ontext di'erently thn in previous exmplesF e use the stndrd list funtion mapD s well s the funtion fst for projeting the (rst element of pirF e write dfst rther thn just fst to sk tht fst9s impliit rguments e instntited with inferred vluesF 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 vrile lookup will e needed on the rod to our usul theorem onneting sustitution nd typingF
PWP
Lemma
lookup disj'
t G1D
Lemma lookup disj X t GD x 5 G 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 tht sustitution nd opening ommute under pproprite irumE stnesF Lemma open subst X x0 e' nD
lclosed n
e1
e' A
subst
@open
x0 n e' AF
e stte orollry of the lst result whih 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 estlishes the vlidity of wekening vrile lookup judgments with fresh vrilesF
Lemma disj push X x0 @t X typeA x 5 G x = x0 x 5 @x0D t A XX GF unfold disj Y crushF QedF Hint Resolve
disj pushF
GD
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
consF
pinllyD it is useful to stte version of the is useful in our min sustitution proofF
TAbs
tht
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
|Ee
open x O e'
ran A
xow we n prove the min indutive lemm in mnner similr to wht worked for onrete indingF
Lemma
G1
hasType subst'
|Ee e X t GD G1 a
G1 e tD xt A
CC @xD
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
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
hasType substF
e tD
subst'Y
eautoF
Notation 4 x b eI eP4 Xa @subst Inductive val X exp Prop Xa | VConst X bD val @Const b A | VAbs X eD val @Abs e AF Hint
Constructors valF
x e1 e2 A
@no
associativityD
at
level
THAF
associativityD
at
level
WHAF
val e2
e2
@open
x O e1 A
e2
val e1
e2
aab
e2'
App e1 e2
aab
App e1 e2'
e1 e2 AF
PWS
he only interesting hnge is tht the Beta rule requires identifying fresh vrile x to use in opening the strtion odyF e ould hve voided this y implementing more generl open tht llows sustituting expressions for vrilesD not just vriles for vrilesD ut it simpli(es the proofs to hve just one generl sustitution funtionF xow we re redy to prove progress nd preservtionF he sme proof sript from the lst exmples su0es to prove progressD though signi(ntly di'erent lemms 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 estlish preservtionD it is useful to formlize priniple of sound lphEvritionF sn prtiulrD when we open n expression with prtiulr vrile nd then immeditely sustitute for the sme vrileD we n reple tht vrile with ny other tht 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 egin it is useful to stte diret orollry whih is esier to pply in proof serhF 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 setions9 preservtion proof sripts (nish the joF
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
x1 = x2 [e1 /x1 ][e2 /x2 ]e = [e2 /x2 ][[e2 /x2 ]e1 /x1 ]e
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
he lssi implementtion of sustitution in de fruijn terms requires n uxiliry operE tionD liftingD whih inrements the indies of ll free vriles in n expressionF e need to lift whenever we go under inderF st is useful to write n uxiliry funtion liftVar tht lifts vrileY tht isD liftVar x y will return y C I if y x D nd it will return y otherwiseF his simple desription uses numers rther thn our dependent n fmilyD so the tul spei(tion is more involvedF PWV
gomining numer of dependent types triksD we wind up with this onrete relizE 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
xow it is esy to implement the min lifting opertionF
n' A
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 sustitution itselfD we will need to pply some expliit type stsD sed on equlities etween typesF e single equlity will su0e for ll of our stsF sts sttement is somewht strngeX it qunti(es over vrile f of type n nD ut then never mentions f F therD quntifying over f is useful euse n is dependent type tht is inhited 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 ontrdition when n a HD euse we hve round vlue f of the uninhited type n HF
@pred n A a nF
xow we de(ne nottion to stremline our st expressionsF he ode f return nD r for e denotes st of expression e whose type n e otined y sustituting some numer n1 for n in rF f should e proof tht n1 a n2D for ny n2F sn tht seD the type of the st expression is r with n2 sustituted for nF
typesD this would e simple de(nitionF ith dependenyD it is resonly intriteD nd our min tsk in utomting proofs out it will e hiding tht intriyF
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 esy to de(ne our (nl sustitution funtionF he strtion se involves two stsD where one uses the sym eq funtion 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 (nl ommuttivity theorem is out substD ut our proofs will rely on few more uxiliry de(nitionsF pirstD we will wnt n opertion more tht inrements the index of n while preserving its interprettion s numerF
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
eondD we will wnt 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
Ltac
simp
repeat match
goal
with
yur (rst two hints (nd ples where equlity proofs re ptternEmthed onF he (rst hint mthes ptternEmthes in the onlusionD while the seond hint mthes ptternE mthes in hypothesesF sn eh seD we pply the lirry theorem UIP reD whih sys tht ny proof of ft like e a e is itself equl to re equalF ewriting with this ft enles redution of the ptternEmth tht 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
n equlity hypothesisF
HY
X Next
a Next
injection
clear
sf we hve two equlity hypotheses tht shre lefthnd sideD we n use one to rewrite the otherD ringing the hypotheses9 righthnd sides together in single equtionF QHI
X ci a D
H'
X ci a
rewrite
in
H'
pinllyD we would like utomti use of qunti(ed equlity hypotheses to perform rewritE ingF e ptternEmth hypothesis H sserting proposition P F e try to use H to perform rewriting everywhere in our golF he rewrite sueeds if it genertes no dditionl hypotheE sesD ndD to prevent in(nite loops in proof serhD we ler H if it egins with universl qunti(tionF
X c
rewrite
in BY match
endAF
sn implementing nother level of utomtionD it will e useful to mrk whih free vriE les we generted with ttisD s opposed to whih were present in the originl theorem sttementF e use dummy mrker predite Generated to reord tht informtionF e tti not generated fils if nd only if its rgument is generted vrileD nd tti generate reords tht its rgument is genertedF
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 tti destructG performs se nlysis on n vluesF he uiltEin se nlysis ttis re not smrt enough to hndle ll situtionsD nd we lso wnt to mrk new vriles s genertedD to void in(nite loops of se nlysisF yur destructG tti will only proeed if its rgument is not genertedF 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 tti will e desterD whih inorportes ll of simp 9s simE pli(tions nd dds heuristis for utomti se nlysis nd utomti qunti(er instnE titionF QHP
IH Y
rewrite
in
IH
his si ide su0es for ll of our expliit qunti(er instntitionF e dd one more vrint tht hndles ses where n opportunity for rewriting is only exposed if two di'erent qunti(ers re instntited t oneF
generalize @IH
IH
n D y X n D H X a D X @f X n A @g X n AD
x y AY
clear
IH Y
intro
IH Y
rewrite
in
IH
| | |
ci with
| Next | Next
end end
context match
ci with
ci
destructG E
ell tht simp will simplify equlity proof terms of fts 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 equtions do not hve synttilly equl sidesF e n get to the point where they do hve equl sides y performing se nlysis on nF henever we do soD the n a H se will e ontrditoryD llowing us to dishrge it y (nding free vrile of type n H nd performing inversion on itF sn the n a S n' seD the sides of these equlities will simplify to equl vluesD s neededF he next two hints identify n vlues tht re good ndidtes for suh se nlysisF
QHQ
end | x X n @pred cnAD y X n cn match goal with | context nzf x destruct nY inversion end
pinllyD we (nd match disriminees of option typeD enforing tht we do not destrut ny disriminees tht re themselves match expressionsF gruillyD we do these se nlyses with case eq insted of destructF he former dds equlity hypotheses to reord the reltionships etween old vriles nd their new dedued formsF hese equlities will e used y our qunti(er instntition heuristiF
context match
ci with
None
Some
end
end fail I
ih itertion of the loop ends y lling simp ginD ndD fter no more progress n e mdeD we (nish y lling eautoF
endY
simp AY
eautoF
16.3 Theorems
e re now redy to prove our min theoremD y wy of progression of lemmsF he (rst pir of lemms hrterizes the intertion of sustitution nd lifting t the vrile 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
@f0 X
n n A fD
QHR
Some fF
xextD we de(ne notion of greterEthnEorEequl for theorem for itD nd dd tht 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
Prop Xa
n ge f1 f2 n ge @Next f1 A @Next f2 AF
Constructors n geF
n ge inv'
Hint
Lemma
match f1D f2 with | Next f1'D Next | D True endF destruct IY desterF QedF
n ge f1
n1 n2
@f1 X
n n1 A @f2 X n n2 AD n ge f1'
f2'
f2
f2'
Lemma
n ge inv
n1 n2
@f1 X
n n1 A @f2 X n n2 AD
@f1 Xa Next
f1 A
ge inv'
@f2 Xa Next
f2 AAY desterF
Lemma Next cong X n @f1 f1 a f2 Next f1 a Next f2F desterF QedF Hint Resolve Lemma
Next congF
f2
liftVar
in terms of
n geF
match liftVar f0 f in n n' return n n' @n @pred n' A | First n0 fun First
n ge g
liftVar more
@f X
f0
| 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 prtiulr wy of hnging the form of golD so tht other hints re le to mthF
Hint Extern I @ a lift @Next @more cfAAA change @Next @more f AA with @more @Next f AAF
e suggest pplying the f equal tti to simplify equlities over expressionsF por instneD this would redue gol App f1 x1 a App f2 x2 to two gols f1 a f2 nd x1 a x2F
A f equalF
yur onsidertion of lifting in isoltion (nishes with nother hint lemmF he uxiliry lemm with strengthened indution hypothesis is where we put n ge to useD nd we do not need to mention tht predite gin ftewrdF
Lemma
n ge g
double lift'
@e X
exp n A f gD
lift
@lift
e gA
@more f AF
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
double liftF
FirstF
xow we hrterize the intertion of sustitution nd lifting on vrilesF e strt with more generl form substVar lift' of the (nl lemm substVar liftD with the ltter proved s diret orollry of the formerF
Lemma
@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
substVar lift'
f
QHT
Lemma
substVar lift
substVar
a match substVar f0 f with | Some f Some @liftVar | None None endF introsY generalize @substVar QedF
@liftVar
f0 A g A f
lift' f0 f g AY desterF
e follow similr deomposition for the expressionElevel theorem out sustitution 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
@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
e1
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 subst
Lemma
lift subst
n g
@e2 X
exp @S n AA e3D
e2 g e3 A FirstF
Hint Resolve
lift substF
yur lst uxiliry lemm hrterizes sitution where sustitution n undo the e'ets 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 Lemma
undo liftF
@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 (nl theorem is speilized to the se of sustituting in n expression with extly two free vrilesD whih yields sttement tht is redle enoughD s sttements out de fruijn indies goF his proof sript is resilient to spei(tion hngesF st is esy to dd new onstrutors to the lnguge eing tretedF he proofs dpt utomtilly to the ddition of ny onE strutor whose suterms eh involve zero or one new ound vrilesF ht isD to dd suh onstrutorD we only need to dd it to the de(nition of exp nd dd @quite oviousA ses for it in the de(nitions of lift nd substF
QHV
Inductive uexp X Set Xa | UVar X string uexp | UApp X uexp uexp uexp | UAbs X string uexp uexpF
he expliit presene of vrile nmes fores us to think out issues of freshness nd vrile ptureF he rye lterntive would look like thisF
Reset uexpF
| |
UApp UAbs
e hve voided ny mention of vrilesF snstedD we enode the inding done y strtion using the inding filities ssoited with qllin funtionsF por instneD we might represent the term x. x x s UAbs @fun x UApp x x AF goq hs uiltEin support for mthing inders in nonymous fun expressions to their usesD so we void needing to implement our own inderEmthing logiF his de(nition is not quite ryeD euse of the rod vriety of funtions tht goq would llow us to pss s rguments to UAbsF e n thus onstrut mny uexps tht do not orrespond to norml lmd termsF hese devints re lled exotic termsF sn vpD funtions my only e written in very restritive omputtionl lngugeD lkingD mong other thingsD pttern mthing nd reursive funtion de(nitionsF husD thnks to reful lning t of design deisionsD exoti terms re not possile with usul rye enodings in vpF yur de(nition of uexp hs more fundmentl prolemX it is invlid in qllinF
Error X Non strictly
positive
occurrence of
4uexp4 in
e hve violted rule tht we onsidered eforeX n indutive type my not e de(ned in terms of funtions over itselfF y k in ghpter QD we onsidered this exmple nd the resons why we should e gld tht goq rejets itF husD we will need to use more leverness to rep similr ene(tsF he root prolem is tht our expressions ontin vriles representing expressions of the sme kindF wny useful kinds of syntx involve no suh ylesF por instneD it is esy to use rye to enode stndrd (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
nfortuntelyD there re other reursive funtions tht we might like to write ut nnotF yne simple exmple is funtion to ount the numer of onstrutors used to uild propF o look inside Forall or ExistsD we need to look inside the qunti(er9s odyD whih is represented s funtionF sn qllinD s in most sttillyEtyped funtionl lngugesD the only wy to intert with funtion is to ll itF e hve no hope of doing tht hereY the domin of the funtion in question hs n ritry type T D so T my even e uninhitedF sf we hd universl wy of onstruting vlues to look inside funtionsD we would hve unovered onsisteny ug in goq3 e re still su'ering from the possiility of writing exoti termsD suh s this exmpleX
true prop
prop
else
false propAF
husD the ide of uniform wy of looking inside inder to (nd nother wellEde(ned prop is hopelessly doomedF e lever rye vrint lled weak HOAS mnges to rule out exoti terms in goqF rere is wek rye version of untyped lmd 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 postulte the existene of some set var of vrilesD nd vrile nodes pper exE pliitly in our syntxF e inder is represented s funtion over variablesD rther thn s funtion over expressionsF his reks the yle tht led goq to rejet the literl rye de(nitionF st is esy to enode our previous exmpleD x. x xX
Example
self app
Xa
UAbs
@fun
UApp
ht out exoti termsc he prolems they used erlier me from the ft tht qllin is expressive enough to llow us to perform se nlysis on the types we used s the domins of inder funtionsF ith wek ryeD we use n strt type var s the dominF ine we ssume the existene of no funtions for deonstruting var sD goq9s type soundness enfores tht no qllin term of type uexp n tke di'erent vlues depending on the vlue of var ville in the typing ontextD except y inorporting those vriles into uexp vlue in legl wyF ek rye retins the other disdvntge of our previous exmpleX it is hrd to write reursive funtions tht deonstrut termsF es with the previous exmpleD some funtions are implementleF por instneD we n write funtion to reverse the funtion nd rgument positions of every UApp nodeF
| 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 impossile to write funtion to ompute the size of n expressionF e would still need to mnufture vlue of type var to peer under inderD nd tht is impossileD euse var is n strt typeF
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 enpsulte hoies of
var
Definition
Uexp
Xa
varD
uexp varF
his type Uexp is our (nlD exotiEtermEfree representtion of lmd termsF snside the ody of Uexp funtionD var vlues my not e deonstruted illeglyD for muh the sme reson s with wek ryeF e simply trde n strt type for prmetri polymorphismF yur running exmple x. x x is esily 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
snluding ll mentions of var expliitly helps lrify wht is hppening hereD ut it is onvenient to let goq9s lol type inferene (ll in these ourrenes for usF
Example
self app'
Uexp
Xa fun
UAbs
@fun QIP
UApp
e n go further nd pply the rye tehnique to dependentlyEtyped esD where qllin typing gurntees tht only wellEtyped terms n e representedF por the rest of this hpterD we onsider the exmple of simplyEtyped lmd lulus with nturl numers nd dditionF e strt with onventionl de(nition of the type lngugeF
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 lmd lulusD with one importnt hngeF xow our setion vrile var is not just typeF therD it is function returning typesF he ide is tht vrile of ojet lnguge type t is represented y var t F xote how this enles us to void indexing the exp type with representtion 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
s eforeF
Exps
exp var tF
without using
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
Exp ran
Xa
e se for funtion strtion is not s nturlD ut we n implement one ndidte in terms of type fmily Exp1D suh tht Exp1 free result represents n expression of type result with one free vrile 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
xow it is esy to enode numer of exmple progrmsF
ran A
Xa
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 syntxEdeonstruting funtionsD suh s CountVarsD whih ounts how mny nodes pper in n ExpF pirstD we write version countVars for expsF he min trik is to speilize countVars to work over expressions where var is instntited s fun unitF ht isD every vrile is just vlue of type unitD suh tht vriles rry no informtionF he importnt thing is tht we hve vlue tt of type unit villeD to use in desending 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
EF
e turn countVars into CountVars with expliit instntition of polymorphi Exp vlue e n write n undersore for the prmter to ED euse lol type inferene is le to infer the proper vlueF
Definition
CountVars t
@E X
Exp t A
nat Xa countVars @E AF
ehves plusilyF
CountVars
CountVars zeroF
CountVars oneF
QIR
aH X nat
Eval compute in aI X nat Eval compute in aI X nat Eval compute in aP X nat Eval compute in aQ X nat
CountVars identF
CountVars appF
e might wnt to go further nd ount ourrenes of single distinguished free vrile in n expressionF sn this seD it is useful to instntite var s fun boolF e will represent the distinguished vrile with true nd ll other vriles 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 wrp countOne into CountOneD whih we type using the Exp1 de(nition from eforeF CountOne opertes on n expression E with single free vrileF e pply n instntited E to true to mrk this vrile s the one countOne should look forF countOne itself is reful to instntite ll other vriles with falseF
Definition
countOne
CountOne t1 t2
@E
trueAF
@E X
Exp1 t1 t2 A
nat Xa
CountOne
on few exmplesF
XA
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
App'
Eval compute in aI X nat Eval compute in aP X nat Eval compute in aI X nat Eval compute in aI X nat
CountOne ident1F
he rye enoding turns out to e just s generl s the (rstEorder enodings we sw previouslyF o provide tste of tht generlityD we implement trnsltion into onrete syntxD rendered in humnEredle stringsF his is s esy s representing vriles s stringsF
scopeF
Fixpoint natToString @n X natA X string Xa match n with | O 4y4 | S n' 4@4 CC natToString n' CC 4A4 endF
puntion toString tkes n extr rgument curD whih holds the lst vrile nme sE signed to inderF e uild new vrile nmes y extending cur with primesF he funtion returns pir of the next ville vrile nme nd of the tul 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
ToString t
@E X
Exp t A
Eval compute in ToString a 4y47string X string Eval compute in ToString a 4@yA47string X string
zeroF
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 (nl exmple is ruil to using rye to enode stndrd opertionl semntisF e de(ne ptureEvoiding sustitutionD in terms of funtion atten whih tkes in n expression tht represents vriles s expressionsF atten reples 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
e'
Abs'
@fun
atten
plttening turns out to implement the hert of sustitutionF e pply E2D whih hs one free vrileD to E1D repling the ourrenes of the free vrile y opies of E1F atten tkes re of removing the extr Var pplitions round these opiesF
Exp t1 A
@E2 X
Exp1 t1 t2 A
Exp t2
Xa fun
Eval compute in Subst one ident1F a fun var X type Type X Exp Nat
Const'
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
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
Constructors ValF
B AF
ine this lnguge is more omplited thn the one we onsidered in the hpter on (rstEorder enodingsD we will use expliit evlution ontexts to de(ne the semntisF e vlue of type Ctx t u is ontext tht yields n expression of type u when (lled y n expression of type t F e hve one ontext for eh position of the App nd Plus onstrutorsF
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 hrterizes when ontexts re vlidD enforing the stndrd llEyEvlue restrition tht ertin positions must hold vluesF
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 spei( 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 pinllyD we hve the step reltion itselfD whih omines our ingredients in the stndrd wyF sn the ongruene ruleD we introdue the extr vrile E1 nd its ssoited equlity to mke the rule esier 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
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
@Abs
BA X
aab
Subst X B
Sum
n2 A
isCtx C
E1
E' E1 E2 AF
o prove type soundness for this semntisD we need to overome one ruil ostleF QIW
tndrd proofs use indution on the struture of typing derivtionsF yur enoding mixes typing derivtions with expression syntxD so we wnt to indut over expression strutureF yur expressions re represented s funtionsD whih do notD in generlD dmit indution in goqF roweverD euse of our use of prmetri polymorphismD we know tht our expressions doD in ftD hve indutive strutureF sn prtiulrD every losed vlue of Exp type must elong to the following reltionF
Exp t
Prop Xa
Closed E1 Closed E2 Closed @Plus E1 Closed E1 Closed E2 Closed @App E1 Closed @Abs E1 AF
X
dom ran
CApp
dom ran
ran AA E2D
CAbs
@E1 X
E2 A
row n we prove suh ftc st proly nnot e estlished in goq without xiomsF therD one would hve to estlish it mettheoretillyD resoning informlly outside of goqF por nowD we ssert the ft s n xiomF he lter hpter on intensionl trnsformtions shows one pproh to removing the need for n xiomF
Axiom closed X t @E X Exp t AD Closed EF he usul progress nd preservtion theorems re now very esy to proveF sn ftD preservtion is impliit in our dependentlyEtyped de(nition of StepF his is huge winD euse we void ompletely the theorem out sustitution nd typing tht mde up the ulk of eh proof in the hpter on (rstEorder enodingsF he progress theorem yields to few lines of utomtionF e de(ne slight vrint of crush whih lso looks for hnes to use the theorem inj pair2 on hypothesesF his theorem dels with n rtift of the wy tht 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 indution over funtionsD in the form of expressions EF he judgment Closed provides the perfet frmeworkY we indut over Closed derivtionsF Lemma progress' X t @E X Exp t AD
QPH
induction IY crush Y repeat match goal with | H X Val endY eauto TF QedF
Y clear
H Y my crush'
yur (nl proof of progress mkes one topElevel use of the xiom oveF X t @E X Exp t AD Val E E'D E aab E'F introsY apply progress'Y apply closed F QedF
progress
closed
tht we sserted
Theorem
associativityD
at
level
WHAF
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
E2 B V2 VD
E1 E2 AF
QPI
Hint
Constructors BigStepF
o prove ruil intermedite lemmD we will wnt to nme the trnsitiveEre)exive losure of the smllEstep reltionF
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
associativityD
at
level
WHAF
Exp t
Prop Xa
E1 E2 AF
Theorem MultiStep trans X E1 aabB E2 E2 aabB E3 E1 aabB E3F induction IY eautoF QedF Theorem Big Val X t @E E aaab V Val VF induction IY crushF QedF Theorem
V
@E1
E2 E3
Exp t AD
Exp t AD
Val V
Val Big
@V X
Exp t AD
enother useful property dels with pushing multiEstep evlution inside of ontextsF
isCtx C
Multi Cong
t t'
@C X
Ctx t t' AD
Lemma
Multi Cong'
t t'
@C X
Ctx t t' A E1
E2 E E'D
QPP
isCtx C
E1
CongY
autoF
Hint Resolve
Multi Cong'F
nrestrited use of trnsitivity of aabB n led to very lrge eauto serh spesD whih hs very inonvenient e0ieny onsequenesF snstedD we de(ne speil tti mtrans tht tries pplying trnsitivity with prtiulr intermedite 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 resonly short proof of one diretion of the equivlene etween igEstep nd smllEstep semntisF e inlude proof ses spei( to rules of the igEstep semntisD sine leving the detils to eauto would led to very slow proof sriptF he use of solve in mtrans 9s de(nition keeps us from going down unfruitful pthsF
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 redy to prove the other diretion of the equivleneF pirstD we wrp n erlier lemm in form tht will work etter with eautoF
Lemma
Val V2
V1 V1
Big Val'
@V1
V2
Exp t AD
QedF
crushF
a V2 aaab
V2F
Hint Resolve
Big Val'F
xow we uild some quite involved tti support for resoning out equlities over QPQ
rye termsF pirstD we will ll equate conj F G to determine the onsequenes of n equlity 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 onjuntion e 1 a e' 1 FFF e n a e' nF e hrdode pttern for eh vlue 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
z2 A
he min tti is my crushD whih generlizes our erlier my crush' y performing inE version on hypotheses tht equte rye termsF goq9s uiltEin inversion is only designed to e useful on equlities over indutive typesF rye terms re funtionsD so inversion is not very helpful on themF o perform the equivlent of discriminateD we instntite the terms with var s fun unit nd then ppel to norml discriminateF his elimintes some ontrditory sesF o perform the equivlent of injectionD we must onsider ll possile var instntitionsF ome firly intrite logi strings together these elementsF he detils re not worth disussingD sine our onlusion will e tht one should void deling with proofs of fts like this oneF
Ltac
my crush
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 4vr4 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
Xa
QPR
my crush'F
endY
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 tht omplited tti villeD the proof of the min lemm is strightforwrdF
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
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 tht working diretly with rye terms n esily led to extremely intrite proofsF st is usully etter ide to stik to indutive proofs out instantiated rye termsY in the se of this exmpleD tht mens proofs out exp insted of ExpF uh results n usully e wrpped into results out Exp without further indutionF hi'erent theorems demnd di'erent vrints of this underlying dvieD nd we will onsider severl of them in the hpters to omeF
QPS
Module STLCF Inductive type X Type Xa | Nat X type | Arrow X type type typeF Infix 4!b4 Xa
Arrow
@right
associativityD
at
level
THAF
| |
exp t
X X
Const Plus
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
Exp t
Xa
varD
exp var tF
Abs var t1 t2 F
he de(nitions tht follow will e esier to red if we de(ne some prsing nottions for the onstrutorsF
level
UHAF
Notation 4BA n4 Xa @Const n A @at level UHAF Infix 4C4 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 exmples will e useful for testing the funtions we will writeF
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 ojet lnguge types s met lnguge typesF
Fixpoint typeDenote @t X typeA X Set Xa match t with | Nat nat | t1 !b t2 typeDenote t1 typeDenote endF
t2
he ruil trik of the expression interpreter is to represent vriles using the typeDenote funtionF hue to limittions in goq9s syntx extension systemD we nnot tke dvntge QPU
of some of our nottions when they pper in ptternsD soD to e onsistentD in ptterns we void nottions ltogetherF
@e X
exp typeDenote t A X
typeDenote t
Xa
Plus e1 e2
expDenote e1
expDenote e2
e1 e2 e'
e2 A
Definition ExpDenote t @e X Exp t A Xa expDenote @e AF ome tests estlish tht ExpDenote produes qllin terms like we might write mnuE 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 updte to the higherEorder se our ommon exmple of onstnt folding funtionF he workhorse funtion cfold is prmeterized to pply to n exp tht uses ny QPV
var
typeF en output of cfold uses the sme var type s the inputF es in the de(nition of expDenoteD we nnot use most of our nottions in ptternsD ut we use them freely to mke the odies of match ses esier to redF
Section cfoldF Variable var X type TypeF Fixpoint cfold t @e X exp match e with | Var v 5v
| |
Const n
var t A
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
e1 e2 e'
n2 A
e2
Definition
Cfold t
@E X
Exp t A
Exp t
Xa fun
cfold
@E AF
xow we would like to prove the orretness of CfoldD whih follows from simple indutive 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
destruct
@cfold
EA
X t @E X Exp t AD ExpDenote @Cfold E A a ExpDenote EF unfold ExpDenoteD Cfold Y introsY apply QedF End STLCF
Cfold correct
Theorem
cfold correctF
QPW
Module
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
PSLCF
| | |
exp t
X
nat exp Nat Plus X exp Nat exp Nat exp Nat
Const App
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
Pair
t1 t2D
QQH
Inl
t1 t2D
Inr
SumCase
End
varsF
t1 t2 tD
Xa
varD
exp var tF
Var var t F
Const var F
level
UHAF
Notation 4BA n4 Xa @Const n A @at level UHAF Infix 4C4 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 49se9 e 9of9 x eI | y eP4 Xa @SumCase @at level UWAF Example Example Example
swap
@fun
e1 A
@fun
e2 AA
e few exmples n e de(ned esilyD using the nottions oveF @Nat BB Nat !b Nat BB NatA Xa fun pD 5P 5pD 5I 5pF zo X Exp @Nat BB NatA Xa fun BAHD BAIF swap zo X Exp @Nat BB NatA Xa fun swap d zo F 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
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
@e X
exp typeDenote t A X
typeDenote t
Xa
expDenote e1
expDenote e2
e1 e2 e'
e2 A
e'
expDenote e2 A
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
e'
Definition
ExpDenote t
@e X
Exp t A
Xa
expDenote
@e AF
x
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
in
x0 A
QQP
Eval cbv beta iota delta Eplus 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 dpt the cfold funtion using the sme si dependentEtypes trik tht we pplied in n erlier hpter to very similr funtion for lnguge without vrilesF 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
n2 A
| | | |
e1 e2 e'
e2
e1 e2 e'
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
| | |
Inl Inr
e' e'
SumCase
End
cfoldF Cfold t
endF
Definition
@E X
Exp t A
Exp t
Xa fun
cfold
@E AF
he proofs re lmost s strightforwrd s eforeF e (rst estlish two simple theorems out pirs nd their projetionsF
X TypeF QQR
v1 v2 v
X X
AF BF
BF v2 A
Theorem pair eta1 X @v1D destruct v Y crushF QedF Theorem pair eta2 X @v1D destruct v Y crushF QedF End pairsF Hint Resolve
v1
fst vF
v2 A
v2
snd vF
o the proof sript for the min lemmD we dd just one more match seD deteting when se nlysis is pproprite on disriminees of mthes over sum typesF
Lemma
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
cfold correct
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
Theorem
cfold correctF
QQS
associativityD
source scopeF
at
level
THA X
source scopeF
Open Scope source scopeF Bind Scope source scope with typeF Delimit Scope source scope with sourceF
e expliitly ple our nottions inside sope nmed source scopeD nd we ssoite delimiting key source with source scopeF ithout further ommndsD our nottions would only e used in expressions like @FFFA7soureF e lso open our sope lolly within this QQT
moduleD so tht we void repeting 7soure in mny plesF purtherD we bind our sope to typeF sn some irumstnes where goq is le to infer tht some suexpression hs type typeD tht suexpression will utomtilly e prsed in source scopeF he other ritil new ingredient is generliztion of the Closed reltion from two hpters goF he new reltion exp equiv hrters when two expressions my e onE sidered synttilly equlF e need to e le to hndle ses where eh expression uses di'erent var typeF sntuitivelyD we will wnt to ompre expressions tht use their vriE les to store soureElevel nd trgetElevel vluesF e express pirs of equivlent vriles using list prmeter to the reltionY vrile expressions will e onsidered equivlent if nd only if their vriles elong to this listF he rule for funtion strtion extends the list in higherEorder wyF he remining rules just implement the ovious ongruene 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
var2 t
}7type
G nD
G x1 y1 x2 y2D
End
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
EqApp exp equivF
st turns out thtD for ny prmetri expression ED ny two instntitions of E with prtiulr var types must e equivlentD with respet to n empty vrile listF he prE metriity of qllin gurntees thisD in muh the sme wy tht it gurnteed the truth of the xiom out ClosedF husD we ssert n nlogous xiom hereF
Axiom
Exp equiv
var2D
QQU
End
SourceF
xow we need to de(ne the g lngugeD where inry funtion types re repled with unry ontinution typesD nd we dd produt types euse they will e useful in our trnsltionF
Module CPSF Inductive type X Type Xa | TNat X type | Cont X type type | Prod X type type typeF
Notation 49xt94 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 Bind Scope cps scope with typeF Delimit Scope cps scope with cpsF Section varsF Variable var X type TypeF
scopeF
e g progrm is series of indings of primitive opertions @primopsAD followed y either hlt with (nl progrm result or y ll to ontinutionF he rguments to these progrmEending opertions re enfored to e vrilesF o use the vlues of ompound expressions instedD those expressions must e deomposed into indings of primopsF he primop lnguge itself similrly fores vriles for ll rguments esides odies of funtion strtionsF
|
App
prog
@var t prog
primop t
progA
with primop X type Type Xa | Const X nat primop Nat | Plus X var Nat var Nat primop
|
Abs
Nat
X tD @var t
progA
QQV
|
Pair
primop @t "bA
X
t1 t2D
var t1
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
|
Fst
var t2
t2 A
Implicit Arguments Implicit Arguments Implicit Implicit Implicit Implicit Implicit Implicit Arguments Arguments Arguments Arguments Arguments Arguments
App var t F
Notation 49rlt9 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 4C4 Xa Plus @left associativityD at level UWA X cps
scopeF
cps 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 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 Open Scope
cps scope cps scopeF
scopeF
scopeF
with
prog primopF
sn interpreting typesD we tret ontinutions s funtions with odomin nat s our ritrry progrm result typeF
natD hoosing
| Nat nat | t' "b typeDenote t' nat | t1 BB t2 @typeDenote t1 B typeDenote endF
t2 A7type
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 typeDenote t A
typeDenote t
Xa
fun
v1 v2
progDenote
@e x A
v2 A
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 trnsltion itself egins with typeElevel ompiltion funtionF e hnge every funtion into ontinution whose rgument is pirD onsisting of the trnsltion of the originl rgument nd of n expliit return pointerF Fixpoint cpsType @t X Source.typeA X CPS.type Xa match t with | Nat Nat 7ps | t1 !b t2 @cpsType t1 BB @cpsType t2 "bA "bA7ps end7soureF xow we n de(ne the expression trnsltionF he nottion x e1 Y e2 stnds for trnslting soureElevel expression e1 D inding x to the gElevel result of running the trnslted progrmD nd then evluting gElevel expression e2 in tht 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 vriety of higherEorderD oneEpss g trnsltionF he trnsltion cpsExp is prmeterized not only y the expression e to trnslteD ut lso y metElevel ontinutionF he ide is tht cpsExp evlutes the trnsltion of e nd lls the ontinution on the resultF ith this onventionD cpsExp itself is nturl mth for the nottion 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
|
Const n
fun nY
k x
Plus e1 e2
fun x1 e1 Y x2 e2 Y x x1 C x2 Y
k x
App
e1 e2
fun
end
k f
e1
@fun
e2 AAF
ine nottions do not survive the losing of setionsD we rede(ne the nottion ssoited QRI
with
cpsExpF
e1
@fun
e2 AA
cps scopeF
e wrp cpsExp into the prmetri version CpsExpD pssing n lwysEhlt ontinution t the root of the reursionF
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 Eval compute in CpsExp oneF a fun var X type Type X Prog Eval compute in CpsExp zpoF a fun var X type Type X Prog
x
BAHY
Halt x
BAIY
Halt x
BAHY
x0
BAIY
x1
@x C
x0 AY Halt x1
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
x1D
kf
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
f0D
kf
dd
Prog ProgDenote
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
@CpsExp
zeroAF
ProgDenote
@CpsExp
oneAF
ProgDenote
@CpsExp
zpoAF
ProgDenote
@CpsExp
app identAF
ProgDenote
@CpsExp
app ident'AF
yur min indutive lemm out cpsExp needs notion of omptiility etween soureE level nd gElevel vluesF e express omptiility with logical relation Y tht isD we de(ne inry reltion y reursion on type strutureD nd the funtion se of the reltion onsiders funtions relted if they mp relted rguments to relted resultsF sn detilD the funtion se is slightly more omplitedD sine it must del with our ontinutionEsed 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 end7soureF
he min lemm is now esily stted nd provedF he most surprising spet of the sttement is the presene of two versions of the expression to e ompiledF he (rstD e1 D uses var hoie tht mkes it suitle rgument to expDenoteF he seond expressionD e2D uses var hoie tht mkes its ompiltionD cpsExp e2 kD suitle rgument to progDenoteF e use exp equiv to ssert tht e1 nd e2 hve the sme underlying strutureD up to vrile orrespondene list GF e hypothesis out G ensures tht ll of its pirs of vriles QRQ
elong to the logil reltion lrF e lso use lrD in onert with some qunti(tion over ontinutions nd progrm resultsD in the onlusion of the lemmF he lemm9s proof should e unsurprising y nowF st uses our stndrd g of vt triks to help out with qunti(er instntitionY crush nd eauto n hndle the restF
Lemma
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 @ cA a progDenote @ r A R | t1 X Source.type match goal with | Hlr X lr t1 cI cPD 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
@ t v1 v2D kD rD
exp equiv G
cpsExp correct In
G t t
@e1 X @v1D
exp
v2 AA G
tA
@e2 X
exp
t AD
e1 e2
@existT
lr t v1 v2 A
cpsExp correct9s
hypothesis out GF
Lemma vars easy X t v1 v2D In @existT @fun t0 @Source.typeDenote @v1D v2 AA nil lr t v1 v2F crushF QedF
e mnul pplition of where we use the xiom Exp
equiv
t0
typeDenote
@cpsType
t0 AA7typeA t
cpsExp correct
CpsExpF
his is
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
Theorem
QRR
19.2 Exercises
IF hen in the lst hpter we implemented onstnt folding for simplyEtyped lmd lulusD it my hve seemed nturl to try pplying et redutionsF his would hve een lot more troule thn is pprent t (rstD euse we would hve needed to onvine goq tht our normlizing funtion lwys termintedF st might lso seem tht et redution is lost use euse we hve no e'etive wy of sustituting in the exp typeY we only mnged to write sustitution funtion for the prmetri Exp typeF his is not s ig of prolem s it seemsF por instneD for the lnguge we uilt y extending simplyEtyped lmd lulus with produts nd sumsD it lso ppers tht we need sustitution for simplifying case expressions whose disriminees re known to e inl or inrD ut the funtion is still implementleF por this exeriseD extend the produts nd sums onstnt folder from the lst hpter so tht it simpli(es case expressions s wellD y heking if the disriminee is known inl or known inrF elso extend the orretness theorem to pply to your new de(nitionF ou will proly wnt to ssert n xiom relting to n expression equivlene reltion like the one de(ned in this hpterF eny suh xiom should only mention syntxY it should not mention ny ompiltion or denottion funtionsF pollowing the formt of the xiom from the lst hpter is the sfest et to void proving worthless theoremF
QRS
member t G exp G t
| | |
Nat
exp G
Nat
Abs
Implicit Arguments
QRT
typeDenote G
typeDenote t
Xa
n e1
fun n e2 fun s
e1 e2 e'
expDenote e1 s
expDenote e2 s
e2 s A
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
G tA
hlist var
Phoas.exp var t Xa
n e1
e1 s
phoasify 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 trivil to estlish the trnsltion9s 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 tht ny output of Phoasify is wellEformedD in sense strong enough to let us void sserting lst hpter9s xiomF Print WfF
QRU
e2 s
a fun @t X typeA @E X Exp t A var1 var2 X type TypeD exp X t X typeD Exp t Prop
Wf
equiv nil @E
var1 A
@E
var2 A
var2
type TypeF
sn the ourse of proving wellEformednessD we will need to trnslte k nd forth etween the de fruijn nd rye representtions of free vrile informtionF he funtion zip omines two de fruijn sustitutions 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 lemms out
zip
var2 t }7type
Xa XX @htl
s2 A
@v1D
hhd s2 A
zip s1'
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 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 Lemma
In zip unsimpl zipF
m Y crushF
phoasify wf
s2 A
Constructors
crushF
phoasify wf
QRV
QedF
apply @phoasify
wf e
@HNil @B Xa
var1 AA
@HNil @B Xa
var2 AAAF
xowD if we ompose Phoasify with ny trnsltion over rye termsD we n verify the omposed trnsltion without relying on xiomsF he onlusion of Phoasify wf is roustly useful in verifying wide vriety of trnsltions tht use wide vriety of var instntitionsF
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
lookup ts' n
@left
associativityD
at
level
IAF
ith lookupD we n de(ne notion of wellEformedness for rye expressions tht we re treting 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
level ontextsD the set of rye ontexts tht will our in the proofD where we will e induting over n exp equiv derivtionF
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 onnetion etween lookup nd makeGD y wy of lemm out lookupF
Opaque eq nat decF
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
ts A
makeG
@ XX AA reflexivityF
exp equiv G
tsD G
Wf wf '
G t e1
@e2 X
e1 e2
makeG ts
QSH
Lemma
Wf wf
@E X
Exp t AD
Wf E
@x X
T AD
x congruenceF QedF
e n use these theorems to implement makeVarD whih trnsltes proof out into de fruijn index vrile with losely relted typeF
lookup
a a yF
@x
T AD
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
xow dbify is strightforwrd to de(neF e use the funtions proj1 nd proj2 to deompose proofs of onjuntionsF
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
ts t
Xa
fun
DeBruijn.Const n
QSI
Phoas.Plus e1 e2 DeBruijn.Plus
e2
@proj2 wfAA
Phoas.App DeBruijn.App
| Phoas.Abs endF
fun wf @dbify e1 @proj1 wfAA @dbify e2 @proj2 wfAA e1 fun wf DeBruijn.Abs @dbify @e1 @length
ts AA
wfA
e de(ne the prmetri trnsltion Dbify y ppeling to the wellEformedness trnslE tion theorem Wf wf tht we proved erlierF
wf W AF
@E X
Phoas.Exp t A
@W X
Wf E A
DeBruijn.exp nil t Xa
o prove soundnessD it is helpful to lssify set of ontexts whih depends on de fruijn index sustitutionF
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 nlogous lemm to the one we proved onneting timeD we onnet makeG' nd hgetF
makeG
nd
lookupF
his
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
In makeG' contraF
ts A nD
ts AD
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
QedF
repeat match goal with | context match cpf with re equal rewrite @UIP re pf A endY crush Y elimtype FalseY eautoF
In makeG'F
end
exp equiv G
G ts
dbify sound
G t
@e1 X
Phoas.exp
tA
@e2 X
Phoas.exp
t AD
@w X wf
e1 e2 ts e1 A sD s
makeG' s
Phoas.expDenote e2F
sn the usul wyD we wrp dbify sound into the (nl soundness theoremD formlly estE lishing the expressive equivlene 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
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
occurrence of
4vl4 in
e would like to represent vlues @whih re ll funtion strtionsA s funtions from vriles to expressionsD where we represent vriles s the sme vlue type tht we re de(ningF ht wyD vlue n e sustituted in funtion ody simply y pplying the QSR
ody to the vlueF nfortuntelyD the positivity restrition rejets this de(nitionD for muh the sme reson tht we ould not use the lssil rye enodingF e n try n lternte pproh sed on de(ning val like usul lss of syntxF
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 vriles re represented s vluesF e would like to e le to write reursive de(nition like this oneX
Fixpoint
expV
Xa
exp
@val
expV AF
yf ourseD this kind of de(nition is not struturlly reursiveD so goq will not llow itF qetting 4sustitution for free4 seems to require some similr kind of selfErefereneF sn this hpterD we will onsider n lternte tke on the prolemF e dd level of indiE retionD introduing more expliit syntx to rek the yle in type de(nitionsF pei(llyD we represent funtion vlues s numers tht index into closure heap tht our opertionl semntis mintins longside the expression eing evlutedF
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
else
lookup ls' n
@left
associativityD
at
level
IAF
he seond of our two de(nitions expresses when one list extends notherF e will write ls2 to indite tht ls1 ould evolve into ls2 Y tht 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
ls1F
lookup
nd
extendsF
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 lsF
else destruct
ls2
l1 AY crushF
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 ls2
lookup contraF extends lookup
else
destruct
ls1 ls2 n vD
ls1 55 n a Some v ls2 55 n a Some vF intros c c c c l cY crush Y induction l Y crush Y match goal with | context if ci then else destruct endY crush Y elimtype FalseY eautoF QedF
QST
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 deling expliitly with the nittyEgritty of losure hepsF hy is this etter thn deling with the nittyEgritty of vrilesc he inonveniene of modeling lmd lulusE style inders omes from the presene of nested sopesF rogrm evlution will only involve one global losure hepF elsoD the short development tht we just (nished n e reused for mny di'erent ojet lngugesF xone of these de(nitions or theorems needs to e redone to hndle spei( ojet lnguge feturesF fy dding the theorems s hintsD no perEojetE lnguge e'ort is required to pply the ritil fts s neededF
Module SourceF e de(ne the syntx of soure expressions in our usul wyF 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 Definition
Exp Bool var F
Xa
varD
exp varF
e will implement igEstep opertionl semntisD where expressions re mpped to vluesF e vlue is either funtion or oolenF e represent funtion s numer tht will e interpreted s n index into the glol losure hepF
Definition
closure
Xa
Definition
closures
Xa
list closureF
yur evlution reltion hs four plesF e mp n initil losure hep nd n expression into (nl losure hep nd vlueF he interesting ses re for AbsD where we push the ody onto the losure hepY nd for AppD where we perform lookup in losure hepD to (nd the proper funtion ody to exeute nextF
closures
cs v
@VFun
v1 A
e2 cs3 v2
55
Some c
v3
EvAbs
eval
@VFun @length
cs AA
EvBool
eval
X cs bD cs @Bool b A
cs
@VBool b AF
e simple wrpper produes n evlution reltion suitle for use on the min expression type ExpF
closuresA
@E X
ExpA
@cs2 X
closuresA
@v X
valA Xa
o prove our trnsltion9s orretnessD we will need the usul notions of expression equivE lene 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
var1
G f1 x1 f2 x2D
EqAbs
X G f1 f2D @ v1 v2D exp equiv @@v1D v2 A XX G A @f1 exp equiv G @Abs f1 A @Abs f2 A
x1 A
@App
f2 x2 A v1 A
@f2
v2 AA
QSV
EqBool
End
exp equivF
G bD
@E X
ExpA
Xa
var1 var2D
var1 A
@E
var2 AF
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
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
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
cs n v2 c v3D
QSW
cs
55
eval eval
v2 A v3
EvBind
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
| | |
EvPair EvFst
evalP cs @Pair v1
X X
cs v1 v2D
cs v1 v2D
v2 A cs
@VPair
v1 v2 A
v2 AA cs v1 v2 AA cs v2
EvSnd
EvBool
@P X
ProgA
@v X
valA Xa eval cs @P A vF
pinllyD we de(ne g trnsltion in the sme wy s in our previous exmple for simplyEtyped lmd lulusF
Reserved Notation 4x eI Y eP4 @right Section cpsExpF Variable var X TypeF Import
SourceF
associativityD
at
level
UTD
e1
at
next level AF
Fixpoint cpsExp @e X exp var A X @var prog var A prog var Xa match e with | Var v fun k k v
|
App e1 e2
QTH
CPS.App f p
Abs e'
fun
var A
@fun
k f
Bool b
fun
CPS.Bool
bY
end
k x
e1
@fun @fun
e2 AAF
e1
e2 AAF
@E X
ExpA
Prog
Xa fun
cpsExp
var
@e' X
var
Source.exp var A Xa
xow we n de(ne our orretness reltion crD whih is prmeterized y soureElevel nd gElevel losure hepsF
s1 s2
X X
Source.closuresF CPS.closuresF
SourceF
ynly equl oolens re reltedF por two funtion ddresses l1 nd l2 to e reltedD they must point to vlid funtions in their respetive losure hepsF he ddress l1 must point QTI
to funtion f1D nd l2 must point to the result of ompiling funtion f2F purtherD f1 nd f2 must e equivlent synttilly in some vrile environment GD nd every vrile pir in G must itself elong to the reltion we re de(ningF
CrFun
x1 A
@f2
x2 AA
s1 s2 v1 v2 A
@no
associativityD
at
level
UHAF
o prove our min lemmD it will e useful to know tht soureElevel evlution never removes old losures from losure hepF
Lemma
Source.eval cs1
eval monotone
cs1 e cs2 vD
e cs2 v
Lemma
cs1
cr monotone
cs1' v2
cs2 cs2' v1 v2D cs1 8 cs2 |! v1 cs1' 8 cs2' |! v1 v2F induction QY crush Y eautoF QedF
Hint Resolve
e stte trivil ft out the vlidity of vrile environmentsD so tht we my dd this ft s hint tht 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
s2
|!
v1
v2 AF
Hint Resolve
pushF
yur (nl preprtion for the min lemm involves dding e'etive hints out the g lnguge9s opertionl semntisF he following tti performs one step of evlutionF st uses the vt ode eval hnf in e to ompute the head normal form of eD where the hed norml form of n expression in n indutive type is n pplition of one of tht indutive type9s onstrutorsF he (nl line elow uses solve to ensure tht we only tke Bind step if full evlution derivtion for the ssoited primop my e found efore proeedingF
Ltac evalOne Xa match goal with | CPS.eval cs 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 usul pprohF por gols tht evlute progrmsD we insted sk to tret one or more pplitions of evalOne s single stepD whih helps us void pssing eauto n exessively lrge ound on proof tree depthF
evalOne Y
repeat
evalOneF
he (nl lemm proeeds y indution on n evlution derivtion for n expression e1 tht is equivlent to some e2 in some environment GF en initil losure hep for eh lnguge is qunti(ed overD suh tht ll vrile pirs in G re omptileF he lemm9s onlusion pplies to n ritrry ontinution kD sserting tht (nl gElevel losure hep s2 nd gElevel progrm result vlue r2 existF hree onditions estlish tht s2 nd r2 re hosen properlyX ivlution of e2 9s omE piltion with ontinution k must e equivlent to evlution of k r2F he originl progrm result r1 must e omptile with r2 in the (nl losure hepsF pinllyD s2' must e proper evolution of the originl gElevel hep s2 F
Lemma
cpsExp correct
s1 e1 s1' r1D
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 sript follows our stndrd pprohF sts min loop pplies three hintsF pirstD we perform inversion on ny derivtion of equivlene etween soureElevel funtion vlue QTQ
nd some other vlueF eondD we eliminte redundnt equlity hypothesesF pinllyD we look for opportunities to instntite indutive hypothesesF e identify n sr y its syntti formD noting the expression E tht it pplies toF st is importnt to instntite sres in the right orderD sine existentillyEqunti(ed vriles in the onlusion of one sr my need to e used in instntiting the universl qunti(ers of di'erent srF husD we perform quik hek to fail I if the sr we found pplies to n expression tht ws evluted fter nother expression E' whose sr we did not yet instntiteF he )ow of losure heps through soureElevel evlution is used to implement the hekF sf the hypothesis H is indeed the right sr to hndle nextD we use the guess tti to guess vlues for its universl qunti(ers nd prove its hypotheses with eautoF his tti is very similr to inster from ghpter IPF st tkes two rgumentsX the (rst is vlue to use for ny properlyEtyped universl qunti(erD nd the seond is the hypothesis to instntiteF he (nl inner match dedues if we re t the point of exeuting the ody of lled funtionF sf soD we help guess y sying tht the initil losure hep will e the urrent losure hep cs extended with the urrent ontinution kF sn ll other sesD guess is smrt enough to operte 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 cs |! D X context VFun guess @k XX cs A H | guess tt H end end endY crush AY eauto IQF QedF
he (nl theorem follows esily from this lemmF
Theorem
CpsExp correct
Source.Eval nil E cs
@Source.VBool b A
E cs bD
unfold
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
crush Y
QTS