HAL Id: hal-02548305
https://hal.archives-ouvertes.fr/hal-02548305
Submitted on 20 Apr 2020
HAL is a multi-disciplinary open access archive for the deposit and dissemination of sci- entific research documents, whether they are pub- lished or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
Specifying in Coq inheritance used in Computer Algebra Libraries
Sylvain Boulmé
To cite this version:
Sylvain Boulmé. Specifying in Coq inheritance used in Computer Algebra Libraries. [Research Report]
lip6.2000.013, LIP6. 2000. �hal-02548305�
inheritane used in Computer Algebra Libraries
SylvainBoulme
Laboratoired'InformatiquedeParis 6(LIP6),
UniversitePierreetMarieCurie(Paris6),
8,rueduCapitaineSott,75015Paris,Frane.
Sylvain.Boulmelip6.fr
Abstrat. ThispaperispartofFOC[3℄aprojetfordevelopingComputerAlgebralibraries,ertied
in Coq [2℄. FOC has developed a methodology for programming Computer Algebra libraries, using
modules and objets inOaml. In order to speify modularity features usedby FOCin Oaml, we
areodinginCoqatheoryforextensiblereordswithdependentelds.Thistheoryintendstoexpress
espeiallythekindofinheritanewithmethodredenitionandlatebinding,thatFOCusesinitsOaml
programs.
TheunitofFOCareodedasreords.Aswewanttoenodesemantiinformationonunits,theelds
ofourreordsmaybeproofs.Thus,oureldsmaydependoneahothers.WealledthemDreords.
Then,weintrodueanewdatatype,alledmixDre,torepresent FOClasses.Atually,mixDresare
useful for desribing a hierarhy of Dreords in a inremental way. InmixDres, elds anbe only
delaredortheyanberedened.MixDresanbeextendedbyinheritane.
1 Introdution
This work lies within thesopeof FOC,aprojetfordevelopingalibrary forComputer Algebra, written
in Oaml and ertied in Coq. Units of suh a libraryare aimed to oer dierent views of mathematial
algebrai strutures, from the purely abstrat one, verylose to mathematis to some fully implemented
ones,wherethearrierandtheodefortheoperatorsareompletelyxed.Forexample,thereexistsaunit
U
1
desribing the(abstrat) notion of ring, a seond oneU
2
for the integraldomains and athird oneU
3
givingthe implementation of Z=2Zonthe booleans. So aunit providesdelarations of identiers,possibly
some ode for ertain identiers, and, as this library is to be ertied, someassertions on identiers and
ode.A unit is rarelybuilt independently of the othersand there are usually several kindsof dependene
betweenunits.For example,theunit ofintegraldomains U
2
isbuiltupon U
1 and U
3
givesaninstantiation
oftheabstrat representationofthearrierofU
2
.Therefore,ourlibraryis ahierarhy|oragraph|of
units.
Wefaeup thequestion:how toproeed to theertiation ofthis library,in orderto ensurethat the
assertionsputintheunitsareorret?AsaunitU isbuiltuponsomeotherunitsU
i
,theassertions(sotheir
proofs)ofU maydependofsomeassertionsoftheU
i
.Thesedependeniesmaybehandledasebyase,by
amethod just driven bythe assertionsin U. Evidently, this is notagood solutionassomesharingof the
treatmentofdependeniesanbedone.Theonstrutionofthelibrarymustbeabletobedoneinaninre-
mentalway.Inpartiular,onemustbeabletobuildtheunitstheonesfromtheothers,byexpressingonlythe
dierenesbetweenthem.WeproposeinthispaperadesriptioninCoqofsuhalibraryonstrutionsystem.
Howtorepresentaunit?Aunitintroduesaertainnumberoffuntions,whihouldbealledbyother
units ofthelibrary.Thus, onemustprovideanon-ambiguousnameforthefuntion ofagivenlibrary.But
at the sametime, it is onvenient that twofuntions \having the same meaning" in dierentunits share
thesame name. Wehooseto represent theunits of our libraryviareords (withthe \." notation)whih
oerat thesametimeanon-ambiguouswaytoindiate afuntion ofalibrary(itisnotforexamplebythe
ase,in approaheswith overloading),andat thesametimethepossibilityof sharingeld namesbetween
reords:andthus toindiatebyasamenameofthedierentfuntions.
Thus, roughlyspeaking, a unit will be oded as areord. As ourunits will ontainstypes, programs,
lasses in objet-oriented language,mixDres are generatorsof Dreords. In mixDres, elds an be only
delared or they an be redened. MixDres an be extended by inheritane. Thus, mixDres desribe a
familyofDreords.
Ourrequirementsonreordsarethefollowing:asamenameouldbesharedbetweenanyreordstypes;
elds may depends onother elds;wewantanotionofsubtyping betweenreordstype,with itsassoiate
oerion.Wewantdenesoperationonreords(oerions,inheritane,...).
2 Reords with dependent elds in Coq
In this setion, wepresentquikly the reords of theurrentversionof Coq, explaining why they donot
meet theserequirements.Then,weintrodueourproperdenitionofreords,alled Dreords.
2.1 Reords in Coq V6.3.1
InCoqV6.3.1,reordsareodedviaindutivedenitions.AtypereordSissimplyanindutivetypewith
oneonstrutor, alledBuild S by default.Field aessis oded asprojetionsassoiatedto thisindutive
type. For instane the followingdenition of the type reordpair introduesthe name pair and the two
labelsfstandsnd.TheonstrutorBuildpairisassoiatedtothistypeandthelabelsareusedtoreate
theaessfuntionsto theelds ofthereord:
Struture pair[A,B:Set℄: Set := f fst: A; snd: B g.
isatuallyamarofor:
Indutive pair[A,B:Set℄:Set :=
Build_pair: A->B->(pair A B).
Definition fst := [A,B:Set; x:(pair A B)℄
Cases x of (Build_pair fst _) => fst end.
Definition snd := [A,B:Set; x:(pair A B)℄
Cases x of (Build_pair _ snd) => snd end.
There isan important restritionon labels, whih must notbeshared by dierentreord types.With
themehanismofoerion,thisrestritionanbepartially raised.Moreover,enodingreordsviaamaro
mehanism and oerions operate at the level of reord types. So this implementation does not meetour
requirementsonreords,andwehavetointrodueourownnotion.Wedothatstepbystep,rstintroduing
somenotationsandtheoding ofeldaess.
2.2 A rst sightof Dreords
Roughly speaking, aDreord an be seen asa funtion from a given nite set of labels to a set of elds.
Applyingthisfuntiontoagivenlabelperformseldaess.Asthetypesoftheseeldsmaydier,anotion
ofDreordsignatureassoiatingitstypetoeaheldisthereforeneeded.
Notations A is a type parameter (of sort Set) of the theory, whih denotes the type of the labels. The
equalityofAisassumedtobedeidable.
LetLandL
1
belistsoflabelsandaagivenlabel.Wesupposegiventhefollowingdenitions:
2:(a 2 L)istrueifabelongstoL.
:(L L
1
)istrueifLontainsL
1 .
6\:(L 6\L
1
)istrueifLandL
1
havenoommonlabels
b:: b
L istrueifLdoesnotontaintwoourrenesofthesamelabel.
n:(LnL
1
)isafuntionwhihreturnsthelistoflabelsin Lwhih donotbelong toL
1 .
TheodeCoqgivenhereisin \impliitargumentsmode":someargumentsoffuntionsareleftimpliit
afuntion Dreordoftypesign!Type.Theywillbedenedfurther.
A Dreordis,by denition,aterm oftype(Dreord s),where s isatermof typesign.The funtion
signlreturnsthelist oflabelsof aDreord andwill alsobedened further.In thefollowing,expressions
(signl s)aredenoted byjsj.
Fieldaess is dened bytwofuntions, fieldand fieldT,whih takes aDreord D and alabel a as
arguments.(field D a)istheeldassoiatedwith ain DandfieldTreturnsthetypeof(field D a).
fieldT: (s:sign) (Dreord s)->A->Type
field:(s:sign ; i:(Dreord S) ; a:A ; H:(a2js j))(fieldT i a)
Notethat theexpression (fieldT D a) makes sense onlyif thelabela guresin D. So, fieldTisnot
supposedto beuseddiretly.
Weturn nowto theoding ofsignandDreord.ThediÆultyisto expressthedependeniesbetween
theelds.So,wemakeanintermediarystepbyintroduingtelesopes.
2.3 Telesopes
In[8℄,theoneptoftelesope isusedtoexpressdependeniesbetweenelds ofreord-likestrutures.This
notionwasrstintroduedby[6℄to expressdependeniesbetweenontexts.
We introdue here telesopes with labels whih implementation departs from those of [8℄ but we still
namethisnewversiontelesopes.
Pair with dependentelds ApairwithdependenteldsisaCartesian-produt-liketype.Asusual,itis
odedbyadependentsumupontwoanonialinjetions:
Struture dpair[T2:Type; T1:T2->Type℄ : Type:= fx2: T2; x1: (T1 x2)g.
Letusremarkthat thedierentourrenesofTypeinthisdenition denotedierentTypen wherenisan
impliitlevelofuniverse.Thepreedentdenitionisatually:
Struture dpair[T2:Typei; T1:T2->Typej℄: Typek:=fx2: T2; x1: (T1 x1)g.
where i<kand j<k.This mehanism(invisiblefor theuser)preventstheonstrutionof paradoxes(f.
[9℄and[4℄).
In this denotation
2
represents a onstrutor of binary existential type, and ;
T
is a type with one
element:;,alledhereemptytelesope.
Telesopesaredened byaniterationof thistypedpaironitself (seebelow).Moreover,eaheld will
belabelled.Theselabelsmaybeusedforexampletodenenotionsofeldaess,subsignature,...Theyare
rmlyattahedtotheeldsandmaybeonsideredasapartofthedenition ofthetelesope:forexample,
theyarenotsubmittedto-onversion.Now,theontentofaeldmaydependonthepreedingonesinthe
struture.Asonsideredin [7℄and[5℄,inahighorderontext,dependeniesannotbeexpressedbylabels,
beauseofvariableaptures.Dependenieshavetobeexpressedbybound variables.
Thus,informally,alabelledtelesopeanbedenotedasatermoftype
n [x
n :T
a
n
n
; ::: ; x
1 :(T
a1
1 x
n :::x
2 )℄;
T
where
n
denotesadependentsumtypebuilduponnanonialinjetions;whereT
i
arefuntionswithvalues
intypes,labelledbya
i
,themselvesindependentofx
i
variables;and,;
T
isatypewithasingleelement:the
emptytelesope.
Formally, telesopes are dened through two types: sigtel, the type of \telesope signatures", and
impltelthetypeof\telesopeimplementations".ThesortofsigtelandimpltelidType,aseldsmaylie
inSetorProporevenin Type.But,beauseofuniverseonstraints,eldsofatelesopeleaveinauniverse
twobase types:EsigTthe typehavingonlyoneelementwhihrepresentsthetypeoftheemptysignature,
and(FunIn a T)thetype,labelledbya,offuntionswithvaluesinT.
Indutive EsigT: Type := Esig_: EsigT.
Struture FunIn[a:A; T:Type℄: Type:=
fdom: Type; fun:> (dom->T)g.
Fixpoint sigtel[l:(list A)℄:Type :=
Cases l of
nil => EsigT
| (ons a m) => (FunIn a (sigtel m))
end.
The \>" on fun in FunIn delares the funprojetion asa Coq oerion. Without it, if s a term of type
(FunIn a T)andxatermoftype(dom s),theterm(s x)doesnottypehek,beause(FunIn a T)isnot
afuntion type.Withthis oerion,thistermtypeheks,andmean((fun s) x)(seebelowinimpltel).
Telesope implementations Telesopeimplementations aredened in thesameway,byaniterationon
dependentpairs:
Indutive EimplT: Type := Eimpl_: EimplT.
Struture dpairT[T:Type,f:T->Type; a:A℄: Type:=
fdprojT1: T; dprojT2: (f dprojT1) g.
Fixpoint impltel[l:(list A)℄:(sigtel l)->Type:=
<[l:(list A)℄(sigtel l)->Type>Cases l of
nil => [_℄EimplT
| (ons a m) =>
[s℄(dpairT [x:(dom s)℄(impltel (s x)) a)
end.
Thesetworeursivetypessigtelandimpltel ouldalternativelybedened by usingindutivetypes
ofCoq.Forinstane,sigtelouldbewriteas:
Indutive sigtel: (list A)->Type :=
Esig: (sigtel (nil A))
| Csig: (a:A; l:(list A); dom:Type)(dom->(sigtel l))->(sigtel (ons a l)).
But,ifreursivetypes(denedbyxpoint)arelessgeneralthanindutiveones,theyaremoreonvenient
tohandleinsomesituation.Inversionlemmasonindutivetypesarenotwellautomatiallygeneratedwhen
usingdependenttypes,whereastheysimplyorrespondtoredutiononreursivetypes.
Also,dening impltelbyanindutivetyperequires totypeitin ahigheruniversethansigtel,whih
isagainstintuition.With thereursivedenition,imptelliesinaloweruniversethansigtel.Thus, inall
thisimplementation,weuseonly\not-reursive"indutivetypes(exeptfordeningontOandsubsig,see
below).Forthat,wepass thereursivealls asan argument of theindutive type(likein ontinuations):
forexample,FunInorrespondsto theCsigonstrutor,withTasparameter,to apturethereursiveall.
Thenweuseaxpoint,toexpressthereursivealls.Theounterpartofthismethodisthatsuhreursive
denitionsoftypeareharderto establishandto understand.
Field aess Field aess is done by two funtions, fieldsig whih returns the type of the eld, and
fiedimplwhihreturnsthiseld.Thesetwofuntionsarenottotallydened.ThetypeDummywithasingle
onstrutorfooisusedtoexpressthispartiality.
Indutive Dummy: Type := foo: Dummy.
Hypothesis eqA_de:(x, y:A)fx=yg+f~x=yg.
Fixpoint fieldsig[a:A; l:(list A)℄:(s:(sigtel l))(impltel s)->Type :=
<[l:(list A)℄(s:(sigtel l))(impltel s)->Type>Cases l of
nil => [_;_℄Dummy
| (ons b m) => [s;i℄
if (eqA_de a b) then
[_℄(dom s)
else
[_℄(fieldsig a (dprojT2 i))
end.
Fixpoint fieldimpl[a:A; l:(list A)℄:(s:(sigtel l); i:(impltel s))(fieldsig a i):=
<[l:(list A)℄(s:(sigtel l); i:(impltel s))(fieldsig a i)>Cases l of
[s;i℄<[H:a=b+~a=b℄if H then [_℄(dom s) else [_℄(fieldsig a (dprojT2 i))>
if (eqA_de a b) then
[_℄(dprojT1 i)
else
[_℄(fieldimpl a (dprojT2 i))
end.
From telesopes to Dreords ADreord is atelesope whih labels (a
i
in the informaldenition) are
pairwiseddistint.Thisisonlya\semanti"property:theaesstoaeldhastobenonambiguous.Allthe
operationsonDreordsmaybebuiltindependentlyofthisondition:theyarerstlydenedontelesopes.
Inarstattempt,weodedDreordsbyonsideringatthesametimeoperationalandsemantiaspets.It
beamequiklyunmanageablebeausesemantionsiderationspolutted theode.
Thissemantipropertyisenodedbyputtingguardsinordertorestrittheuseofthetelesopes.These
guards are the prediate denoted by 2, , 6\ andb. They are deidable (under the assumption of the
deidabilityof labelsequality),andtheyanbedishargedbytheCoqtypeheker.
Coding the guards on the lists Toexpress the fat that guardsexpress only that the \Dreord semanti"
is fullled,they are put into Prop.As they aredeidable, their valuesmaybe:the typeTrue orthetype
False.TheyareimplementedasinstantiationsofthetwoprediatesAllDandExDbelow.
Variable P:A->(list A)->Prop.
Hypothesis P_de: (x:A; l:(list A))f(P x l)g+f~(P x l)g.
Fixpoint AllD[l:(list A)℄: Prop :=
Cases l of
nil => True
| (ons a m) => if (P_de a m) then [_℄(AllD m) else [_℄False end.
Fixpoint ExD[l:(list A)℄: Prop :=
Cases l of
nil => False
| (ons a m) => if (P_de a m) then [_℄True else [_℄(ExD m) end.
Denition1. SignaturesofDreordareatriple:alistsignl,aproofsignldfthatthislistisdouble-free
(guardinstantiating AllDabove),anda sigtelsignpbuilt onsignl.
Struture sign: Type := f
sign_l: (list A);
sign_l_df:
\
signl;
sign_p:> (sigtel sign_l) g.
Letusremarkhere,thatsignpisaCoqoerion, fromsignto sigtel.
Denition2. Dreordsaresimply telesopes, built uponaDreordsignature:
Definition Dreord[s:sign℄:=(impltel s).
Thetransformationoftelesopeinto aDreordisthusonlyatypeoerion.
Denition3. Funtionsfor aessingeldsare:
Definition fieldT:(s:sign)(Dreord s)->A->Type
:=[s;i;a℄(fieldsig eqA_de a i).
Definition field:(s:sign; i:(Dreord s); a:A; H:(a2jsj))(fieldT i a)
:=[s;i;a;H℄(fieldimpl eqA_de a i).
3 Operations and relations between Dreord signatures
This setionpresentsoperators and properties of Dreords. Theyare rstinformally introdued, then the
Properties Between Dreord signatures, there is a natural relation, subsign, of subsignature: s
1 is a
subsignature of s
2
(we will informally write s
1 :> s
2 ), if s
1
an be transformed into s
2
by forgetting or
permutingsomeelds. Internally,thisoneptof subsignatureisimplementedasanindutivetypesubsig
ontelesopesignatures,whihallowtoreasonbyindution on\proofs"ofsubsignatures(f.below).
Theorem1. The relation subsign of typesign->sign->Typeis a preorder, whose assoiated relation of
equivalene anbeeasily dened:itorrespondstosubsignonsignaturesofequallength.
Proof ThishasbeenprovedinCoq:
(* Preorder properties*)
Lemma subsign_refl:(s:sign)(subsi gn s s).
Lemma subsign_trans:(s1,s2,s3:sig n)(su bsig n s1 s2)->(subsign s2 s3)->(subsign s1 s3).
(* Properties of the assoiated equivalene *)
Lemma subsign_antisym:(s1,s2:sign )(sub sign s1 s2)->(subsign s2 s1)
->(length js1j)=(length js2 j).
Lemma subsign_sym:(s1,s2:sign)(su bsign s1 s2)
->(length js1j)=(length js2 j)->(subsign s2 s1).
Assoiatedwith thisoneptofsubsignature,there isafuntion oereforonvertingDreords,whih
preservesthe extensionalbehaviorof Dreords (equalityof the elds aessed viathe samelabels). These
oerionswill orrespondtooerionsonobjetsin theFOCprojet.
Theorem2. Let s1ands2twosignatures suhthats1:>s2.Then the funtion oereof type
(Dreord s1)->(Dreord s2)has the following property (alledsubsign ext):
Let ibea(Dreord s1), thenforany labela injs2j,
the aess toa via field on iis equal tothe one on
(oere i).
S1 subsign S2 coerce
i
field field
Proof LetusassumethedenitionofeqTdep 1
,thedependentequalityovertypes.Thetheoremsubsignext
hasbeenprovedinCoq:
Lemma subsign_ont:(s1,s2:sign)(s ubsig n s1 s2)->js1jjs2 j.
Lemma subsign_ext_T: (s1,s2:sign; H:(subsign s1 s2); i:(Dreord s1); a:A)(a2jsj)
->(fieldT i a)==(fieldT (oere H i) a).
Theorem subsign_ext: (s1,s2:sign; H1:(subsign s1 s2); i:(Dreord s1); a:A; H2:(a2js2j))
(eqT_dep 2![T:Type℄T (field i (ont_inl (subsign_ont H1) H2) 2
)
(field (oere H1 i) H2)).
This last property (shown in Coq) guarantees the orretion of the implementation of subsignature
with respet toits semantis.Inpartiular, forevery\proof"ofsubsignaturebetweentwosignatures,the
assoiatedoerionsatDreordslevelareequivalent(withrespettoeld aess).
1
Withthefollowingdenitionwithimpliitargumentson:
Indutive eqTdep[U:Type; P:U->Type; p:U; x:(P p)℄: (q:U)(P q)->Prop:=
eqTdepintro: (eqTdep x x).
2
tionsonsignatures (forgettingelds, permutingelds, ...). Moreformally,it is dividedin twoparts.First,
subsignontOgivestheskeletontheseelementarytransformationstopassfromjs1jtojs2j.Andthenthese
suessionoftransformationsisexpressedatthelevelofsigtelsbysubsign p:
Struture subsign[s1,s2:sign℄: Type :=
f subsign_ontO: (ontO js1 j js2 j);
subsign_p:> (subsig subsign_ontO s1 s2)g.
ontOisdened by:
Indutive ontO:(list A)->(list A)->Set :=
ontO_nil: (l:(list A))(ontO l (nil A))
| ontO_ons: (a1,a2:A)(l1,l2:(list A))a1=a2->(ontO l1 l2)->
(ontO (ons a1 l1) (ons a2 l2))
| ontO_lift:(a:A; l,m:(list A))(ontO l m)->(ontO (ons a l) m)
| ontO_swap:(a1,a2:A; l1,l2:(list A))
(ontO l1 l2)->(ontO (ons a1 (ons a2 l1)) (ons a2 (ons a1 l2)))
| ontO_trans: (l1,l2,l3:(list A))(ontO l1 l2)->(ontO l2 l3)->(ontO l1 l3).
Thensubsigisdenedasfollows:
Indutive subsig: (l1, l2:(list A))(ontO l1 l2)->(sigtel l1)->(sigtel l2)->Type :=
subsig_E: (l:(list A); s:(sigtel l))(subsig (ontO_nil l) s Esig)
| subsig_C: (a:A; l1, l2:(list A); T:Type; f:T ->(sigtel l1); g:T ->(sigtel l2);
H:(ontO l1 l2))
((x:T)(subsig H (f x) (g x)))->(subsig (ontO_ons (refl_equal A a) H)
(Csig a f) (Csig a g))
| subsig_lift: (a:A; l1, l2:(list A); T:Type; f:T ->(sigtel l1); s:(sigtel l2);
H:(ontO l1 l2))
((x:T)(subsig H (f x) s))->(subsig (ontO_lift a H) (Csig a f) s)
| subsig_swap:
(a1, a2:A; l1, l2:(list A); T1, T2:Type;
f:T1 -> T2 ->(sigtel l1); g:T2 -> T1 ->(sigtel l2))
(H:(ontO l1 l2))
((x:T1; y:T2)(subsig H (f x y) (g y x))) ->
(subsig (ontO_swap a1 a2 H)
(Csig a1 [x:T1℄(Csig a2 [y:T2℄(f x y)))
(Csig a2 [y:T2℄(Csig a1 [x:T1℄(g y x))))
| subsig_trans:
(l1, l2, l3:(list A); s1:(sigtel l1); s2:(sigtel l2); s3:(sigtel l3);
H1:(ontO l1 l2); H2:(ontO l2 l3))
(subsig H1 s1 s2) -> (subsig H2 s2 s3) -> (subsig (ontO_trans H1 H2) s1 s3).
where
Definition Esig: (sigtel (nil A)) := Esig_.
Definition Csig: (a:A; l:(list A); T:Type)(T->(sigtel l))->(sigtel (ons a l))
:=[a,l,T,f℄(Build_FunIn a f).
IfwewouldhavenotdenedontO,butdiretlysubsig,itwouldnotbepossibletohavearightnotionof
\suessionoftransformations".Thisnotionishoweverneessarytodenethemergeofsignature(f.3.3),
beausetheuseofpermutationrulewillhaveaninueneontheorderofthelabellistintheresultsignature.
The funtion of oerions between impltels, oereimpltel,is then a trivial indution of aproof of
subsig.Hereis itstype:
Definition oere_impltel: (l1, l2:(list A); s1:(sigtel l1); s2:(sigtel l2);
H:(ontO (eq A) l1 l2))(subsig H s1 s2) -> (impltel s1) -> (impltel s2).
Thus,
Definition oere: (s1,s2:(sign))(subsign s1 s2)->(Dreord s1)->(Dreord s2)