Table Of ContentSound and Complete Bidirectional Typechecking for Higher-
Rank Polymorphism with Existentials and Indexed Types
JoshuaDunfield NeelakantanR.Krishnaswami
UniversityofBritishColumbia UniversityofBirmingham
Vancouver,Canada Birmingham,England
6
1
0
2 Abstract Since we relied on equality information to omit the nil case,
n Bidirectionaltypechecking,inwhichtermseithersynthesizeatype it seems reasonable to look to logical accounts of equality. In
a or are checked against a known type, has become popular for its proof theory, it is possible to formulate equality in (at least) two
J differentways.Thebetter-knownistheidentitytypeofMartin-Löf,
scalability,itserrorreporting,anditseaseofimplementation.Fol-
butGADTsactuallycorrespondbesttotheequalityofSchroeder-
9 lowingprinciplesfromprooftheory,bidirectionaltypingcanbeap-
Heister (1994) and Girard (1992). The Girard–Schroeder-Heister
1 pliedtomanytypeconstructs.Theprinciplesunderlyingabidirec-
(GSH)approachintroducesequalityviathereflexivityprinciple:
tionalapproachtoindexedtypes(generalizedalgebraicdatatypes)
] are less clear. Building on proof-theoretic treatments of equality,
L Γ ⊢ t=t
we give a declarative specification of typing based on focaliza-
P tion. Thisapproach permitsdeclarative rulesfor coverage of pat- TheGSHeliminationrulewasoriginallyformulatedinasequent
. tern matching, as well as support for first-class existential types calculusstyle,asfollows:
s
c usingafocalizedsubtypingjudgment.Weuserefinementtypesto forallθ.ifθ∈csu(s,t)thenθ(Γ)⊢ θ(C)
[ avoidexplicitlypassingequalityproofsinourtermsyntax,making
our calculus close to languages such as Haskell and OCaml. An Γ,(s=t)⊢ C
1 explicit rule deduces when atype isprincipal, leading toreliable Here,wewritecsu(s,t)foracompletesetofunifiersofsandt.So
v substitutionprinciplesforarichtypesystemwithsignificanttype therulesaysthatwecaneliminateanequalitys = tif,forevery
6 inference.Wealsogiveasetofalgorithmictypingrules,andprove substitution θ that makes the terms s and t equal, we can give a
0 thatitissoundandcompletewithrespecttothedeclarativesystem. proofofthegoalC.
1 The proof requires a number of technical innovations, including Thisrulehasthreeimportant features, twogood andone bad.
5 provingsoundnessandcompletenessinamutually-recursivefash- First,theruleisan invertibleleft rule(the conclusion of therule
0 ion. implies the premise, and it decomposes the assumptions to the
.
1 left of the turnstile), which is known to correspond to a pattern
0 matching rule (Krishnaswami 2009). This aligns with the use of
1. Introduction
6 GADTsinprogramminglanguageslikeHaskellandOCaml,which
1 Consider a list type Vec with a numeric index representing its indeedusepatternmatchingtopropagateequalityinformation.
: length,writteninHaskell-likenotationasfollows: Second,whentherearenounifiers,therearenopremises:ifwe
v
assumeaninconsistentequation,wecanimmediatelyconcludethe
Xi data Vec : Nat -> * -> * where goal.Specializingtheruleabovetotheequality0=1,weget:
[] : A -> Vec 0 A
r (::) : A -> Vec n A -> Vec (succ n) A Γ,(0=1)⊢ C
a
Wecanusethisdefinitiontowriteaheadfunctionthatalwaysgives Together, these two features line up nicely with our definition of
usanelementoftypeAwhenthelengthisatleastone: head,wheretheimpossibilityofthecasefor[]wasindicatedby
theabsenceofapatternclause.SotheuseofequalityinGADTs
head:∀n,A.(Vecsucc(n)A)→A correspondsperfectlywiththeGirard–Schroeder-Heisterequality.
head(x::xs)=x Alas,wecannotsimplygiveaprooftermassignmentforfirst-
order logic and call it a day. The third important feature of the
Thisclausaldefinitionomitstheclausefor[],whichhasanindex
GSHequalityruleisitsuseofunification:itworksbytreatingthe
of0.Thetypeannotationtellsusthathead’sargumenthasanindex
free variables of the two terms as unification variables. But type
ofsucc(n)forsomen.Sincethereisnonaturalnumber nsuch
inference algorithms also use unification, introducing unification
that0=succ(n),thenilcasecannotoccurandcanbeomitted.
variables to stand for unknown types. So we need to understand
Thisisanentirelyreasonableexplanationforprogrammers,but
how to integrate these two uses of unification, or at least how to
language designers and implementors will have more questions.
keepthemdecentlyapart,inordertotakethislogicalspecification
First, how can we implement such a type system? Clearly we
andimplementtypeinferenceforit.
neededsomeequalityreasoningtojustifyleavingoffthenilcase,
This problem—formulating indexed types in a logical style,
which is not trivial in general. Second, designers of functional
while retaining the ability to do type inference for them—is the
languages are accustomed to the benefits of the Curry–Howard
subjectofthispaper.
correspondence, and expect a logical reading of type systems to
accompanytheoperationalreading.Sowhatisthelogicalreading Contributions. The equivalence of GADTs to the combination
ofGADTs? ofexistential typesandequalityconstraintshaslongbeen known
1 2016/1/21
(Xietal.2003).OurfundamentalcontributionistoreduceGADTs return type constraints. These two features lead to all the key
tostandardlogicalingredients,whileretainingtheimplementability difficultiesintypecheckingforGADTs.
of the type system. We accomplish this by formulating a system
ofindexedtypesinabidirectionalstyle(combiningtypesynthesis Universal,existentials,andtypeinference. Practicaltypedfunc-
with checking against a known type), which combines practical tionallanguagesmustsupportsomedegreeoftypeinference,most
implementabilitywiththeoreticaltidiness. critically the inference of type arguments. That is, if we have a
function fof type ∀a.a→a, and wewant toapply itto thear-
• Our language supports implicithigher-rankpolymorphism (in gument 3, then we want to write f 3, and not f [Nat] 3 (as we
whichquantifiers canbenested under arrows) including exis- would in pure System F). Even with a single type argument, the
tentialtypes.Whilealgorithmsforhigher-rankuniversalpoly- latterstyleisnoisy,andprogramsusingevenmoderateamountsof
morphismarewell-known(PeytonJonesetal.2007;Dunfield polymorphismrapidlybecomeunreadable.
andKrishnaswami2013), ourapproach tosupportingexisten- However,omittingtypeargumentshassignificantmetatheoret-
tialtypesisnovel. ical implications. In particular, it forces us to include subtyping
in our typing rules, so that (for instance) the polymorphic type
Our system goes beyond the standard practice of tying exis-
∀a.a→aisasubtypeofitsinstantiations(likeNat→Nat).
tentials to datatype declarations (Läufer and Odersky 1994),
Forthesubtyperelationinducedbypolymorphism,subtypeen-
infavourofafirst-classtreatmentofimplicitexistentialtypes.
tailmentisdecidable(undermodestrestrictions).Mattersgetmore
This approach has historically been thought difficult, because
complicatedwhenexistentialtypesareadded.Existentialsarenec-
theunrestrictedcombinationofuniversalandexistentialquan-
essarytoencodeequalityconstraintsinGADTs,butthenaivecom-
tificationseems to require mixed-prefix unification (i.e.,solv-
binationofexistentialanduniversaltypesrequiresunificationun-
ingequationsunderalternatingquantifiers).Weusetheproof-
der a mixed prefix of alternating quantifiers (Miller 1992), which
theoretictechniqueoffocusingtogiveanovelpolarizedsubtyp-
is undecidable. Thus, programming languages traditionally have
ingjudgment,whichletsustreatalternatingquantifiersinaway
stringentlyrestrictedtheuseofexistentialtypes.Theytieexisten-
thatretainsdecidabilitywhilemaintainingessential subtyping
tial introduction and elimination to datatype declarations, so that
properties,suchasstabilityundersubstitutionandtransitivity.
thereisalwaysasyntacticmarkerforwhentointroduceorelimi-
• OurlanguageincludesequalitytypesinthestyleofGirardand nateexistentialtypes.Thispermitsleavingexistentialsoutofsub-
Schroeder-Heister, but without an explicit introduction form. typingaltogether,atthepriceofnolongerpermittingimplicitsub-
for equality. Instead, we treat equalities as property types, in typing(suchasusingλx.x+1attype∃a.a→a).
the style of intersection or refinement types: we do not write While thisis apractical solution, it increases thedistance be-
explicit equality proofs in our syntax, permitting us to more tweensurfacelanguagesandtheirtype-theoreticcores.Ourgoalis
closelymodelhowequalitiesareusedinOCamlandHaskell. togiveadirecttype-theoreticaccountofthefeaturesofoursurface
• Ourcalculusincludesnestedpatternmatching,whichfitsneatly languages,avoidingcomplexelaborationpasses.Thekeyproblem
inthebidirectional framework, andallowsaformalspecifica- inmixed-prefixunificationisthattheorderinwhichtoinstantiate
tionofcoveragecheckingwithGADTs. quantifiersisunclear.WhendecidingΓ ⊢ ∀a.A(a) ≤ ∃b.B(b),
we have the choice to choose an instantiation for a or for b, so
• Ourdeclarativesystemtrackswhetherornotaderivationhasa
that we prove the subtype entailment Γ ⊢ A(t) ≤ ∃b.B(b) or
principal type. The system includes an unusual “higher-order
thesubtypeentailmentΓ ⊢ ∀a.A(a) ≤ B(t).Analgorithmwill
principality” rule, which says that if only a single type can
introduceaunificationvariablefor aandthenforb,or theother
be synthesized for a term, then that type is principal. While
wayaround—andthischoicematters!Withthefirstorder,bmay
this style of hypothetical reasoning is natural to explain to
dependona,butnotviceversa;withthesecondorder,theallowed
programmers,itisalsoextremelynon-algorithmic.
dependenciesarereversed.Accuratedependencytrackingamounts
• We formulate an algorithmic type system (Section 5) for our toSkolemization,whichmeanswehavea“reduction”totheunde-
declarativecalculus,andprovethattypecheckingisdecidable, cidableproblemofhigher-orderunification.
deterministic(5.3),andsoundandcomplete(Sections6–7)with We adopt an idea from polarized type theory. In the language
respecttothedeclarativesystem. ofpolarization,universalsareanegativetype,andexistentialsare
a positive type. So we introduce two mutually-recursive subtype
Ouralgorithmicsystem(and,toalesserextent,ourdeclarative relations: Γ ⊢ A ≤+ B for positive types and Γ ⊢ A ≤− B
system) uses some techniques developed by Dunfield and Krish- fornegativetypes.Thepositivesubtyperelationonlydeconstructs
naswami(2013),butweextendthesetoafarrichertypelanguage existentials, and the negative subtype relation only deconstructs
(existentials, indexed types, sums, products, equations over type universals.Thisfixestheorderinwhichquantifiersareinstantiated,
variables),andwedifferbysupportingpatternmatching,polarized makingtheproblemdecidable(infact,ratherstraightforward).
subtyping,andprincipalitytracking. The price we pay is that fewer subtype entailments are deriv-
able. Fortunately, all such entailments can be recovered by η-
Appendixandproofs. Theappendixhasfiguresdefiningallthe
expansions.Moreover,thelostsubtypeentailmentsseemtoallrely
judgments, including some omitted here for space reasons. Full
on“clever” quantifier reversals(which arerareinprogramming).
proofsareavailablefrom:
Sowekeepfundamentalexpressivity,yetgaindecidability.
github.com/joshuadunfield/lics39/raw/master/lics39_proofs.pdf
Equality as a property. The usual convention in Haskell and
OCamlistomakeequalityproofsinGADTdefinitionsimplicit.We
wouldliketomodelthisfeaturedirectly,sothatourcalculusstays
2. Overview
closetosurfacelanguages, withoutsacrificingthelogicalreading
To orient the reader, we give an overview and rationale of the ofthesystem.Inthiscase,theappropriatelogicalconceptscome
novelties in our type system, before getting into the details of fromthe theory of intersection types. A typing judgment such as
the typing rules and algorithm. As is well-known (Cheney and e:A×Bcanbeviewedasgivinginstructionsonhowtoconstruct
Hinze 2003; Xi et al. 2003), GADTs can be desugared into type a value (pair an A with a B). But types can also be viewed as
expressions that use equality and existential types to express the properties, where e : X is read “e has property X”. To model
2 2016/1/21
GADTsaccurately,wetreatequationst=t′usingapropertytype Expressions e ::= x|()|λx.e|es+ |recx.v|(e:A)
constructor A ∧ P, read “A with P”, to model elements of type |he1,e2i|inj1e|inj2e|case(e,Π)
Asatisfyingtheproperty(equation)P.WealsointroduceP ⊃ A, |[]|e1 ::e2
read “P implies A”, for its adjoint dual. Then, standard rules for Values v ::= x|()|λx.e|recx.v|(v:A)
property types, whichomit explicit proof terms,can explainwhy |hv ,v i|inj v|inj v|[]|v ::v
1 2 1 2 1 2
OCamlandHaskelldonotrequireexplicitequalityproofs. Spines s ::= ·|es
Handling equality constraints through intersection types also Nonemptyspines s+ ::= es
meansthatcertainrestrictionsontypingthatareusefulfordecid-
Patterns ρ ::= x|hρ ,ρ i|inj ρ|inj ρ|[]|ρ ::ρ
ability,suchasrestrictingpropertyintroductiontovalues,arisenat- 1 2 1 2 1 2
Branches π ::= ~ρ⇒e
urally from the semantic point of view—via the value restriction
neededforsoundlymodelingintersectionanduniontypes(Davies Branchlists Π ::= ·| π||Π
andPfenning2000;DunfieldandPfenning2003).
Figu(cid:0)re1. (cid:1)Sourcesyntax
Bidirectionality,patternmatching,andprincipality. Something
thatisnot,byitself,novelinourapproachisourdecisiontoformu-
Mappingoverlists. First,webeginwiththetraditionalmapfunc-
lateboththedeclarativeandalgorithmicsystemsinabidirectional
tion,whichtakesafunctionandappliesittoeveryelementofalist.
style.Bidirectionalchecking(PierceandTurner2000)isapopular
implementationchoiceforsystemsrangingfromdependent types recmap.λf.λxs.case xs, []⇒[]
(Coquand 1996; Abel et al. 2008) and contextual types (Pientka ||y::ys⇒(fy)::mapfys
2008)toobject-orientedlanguages(Oderskyetal.2001),butalso :∀n:N.∀α:⋆.∀β:⋆(cid:0).(α→β)→Vecnα→Vecnβ
has good proof-theoretic foundations (Watkinset al. 2004), mak- (cid:1)
This code is simply a recursive function that case-analyzes its
ing it useful both for specifying and implementing type systems.
Bidirectionalapproachesmakeitcleartoprogrammerswherean- secondargumentxs.Givenanemptyxs,itreturnstheemptylist;
notationsareneeded(whichisgoodforspecification),andcanalso givenaconscelly :: ys,itappliestheargumentfunctionftothe
removeunneedednondeterminismfromtyping(whichisgoodfor headyandmakingarecursivecallonthetailys.
Inaddition,weannotatethedefinitionwithatype.Wehavetwo
bothimplementationandprovingitscorrectness).
However,itisworthhighlightingthatbecausebothbidirection- type parameters α and β for the input and output element types.
Since we are working with length-indexed lists, we also have a
alityand pattern matching arise fromfocalization, these twofea-
turesfittogetherextremelywell.Infact,byfollowingtheblueprint length index parameter n, which lets us show by typing that the
inputandoutputtomaphavethesamelength.
of focalization-based pattern matching, we can give a coverage-
Inoursystem,thistypeannotationismandatory.Fulltypeinfer-
checking algorithm that explains when it is permissible to omit
encefordefinitionsusingGADTsrequirespolymorphicrecursion,
clausesinGADTpatternmatching.
whichisundecidable.Asaresult,thisexamplealsorequiresanno-
Inthepropositionalcase,thetypesynthesisjudgmentofabidi-
tationinOCamlandGHCHaskell.However,HaskellandOCaml
rectional type system generates principal types: if a type can be
inferpolymorphictypeswhennopolymorphicrecursionisneeded.
inferredforaterm,thattypeisunique.Thispropertyislostonce
Weadoptthesimplerrulethatallpolymorphicdefinitionsarean-
quantifiers are introduced into the system, which is why it is not
notated.ThischoiceismotivatedbyVytiniotisetal.(2010), who
much remarked upon. However, prior work on GADTs, starting
analyzedalargecorpusofHaskell codeandshowedthatimplicit
withSimonetandPottier(2007),hasemphasizedtheimportanceof
let-generalization was rarely used: programmers tend to annotate
thefactthathandlingequalityconstraintsismucheasierwhenthe
polymorphicdefinitionsfordocumentationpurposes.
typeofascrutineeisprincipal.Essentially,thisensuresthatnoex-
istentialvariablescanappearinequations,whichpreventsequation NestedpatternsandGADTs. Now,weconsiderthezipfunction,
solvingfrominterferingwithunification-basedtypeinference.The whichconvertsapairoflistsintoalistofpairs.InordinaryMLor
OutsideInalgorithmtakesthisconsequenceasadefinition,permit- Haskell,wemustconsiderwhattodowhenthetwolistsarenotthe
tingnon-principaltypesjustsolongastheydonotchangetheval- samelength.However,withlength-indexedlists,wecanstatically
uesofequations.However,Vytiniotisetal.(2011)notethatwhile rejectpassingtwolistsofdifferinglength:
theirsystemissound,theynolongerhaveacompletenessresultfor
theirtypesystem. reczip.λp.case p, ([],[])⇒[]
Weusethisinsighttoextendourbidirectionaltypecheckingal- ||(x::xs,y::ys)⇒(x,y)::zip(xs,ys)
gorithmtotrackprincipality:Thejudgmentswegivetrackwhether :∀n:N.∀α:⋆.(cid:0)∀β:⋆.(Vecnα×Vecnβ)→Vecn(α×β)
typesareprincipal,andweusethistogivearelativelysimplespeci- (cid:1)
ficationforwhetherornottypeannotationsareneeded.Weareable In this case expression, we give only two patterns, one for when
togiveaverynaturalspectoprogrammers—casesonGADTsmust bothlistsareemptyandoneforwhenbothlistshaveelements,with
scrutinizetermswithprincipaltypes,andaninferredtypeisprinci- thetypeannotationindicatingthatbothlistsmustbeoflengthn.
paljustwhenitistheonlytypethatcanbeinferredforthatterm— Typingshowsthatthecaseswhereonelistisemptyandtheother
whichsoundlyandcompletelycorrespondstotheimplementation- non-empty areimpossible, soour coverage checking rulesaccept
sideconstraints:atypeisprincipalwhenitcontainsnoexistential thisasacompletesetofpatterns.Thisexamplealsoillustratesthat
unificationvariables. wesupportnestedpatternmatching.
4. DeclarativeTyping
3. Examples
Expressions. Expressions (Figure 1) are variables x; the unit
Inthissection,wegivesomeexamplesoftermsfromourlanguage, value();functionsλx.e;applicationstoaspinees+;fixedpoints
whichillustratethekeyfeaturesofoursystemandgiveasenseof rec x.v; annotations (e : A); pairs he ,e i; injections into a
1 2
how many typeannotations areneeded inpractice. Tohelpmake sum type inj e; case expressions case(e,Π) where Π is a list of
k
thispointclearly,alloftheexampleswhichfollowareunsugared: branchesπ,whichcaneliminatepairsandinjections(seebelow);
theyaretheactualtermsfromourcorecalculus. theemptyvector[];andconsingaheade toatailvectore .
1 2
3 2016/1/21
Universalvariables α,β,γ favourofthespine,soe e e isparsedastheapplicationofe to
1 2 3 1
Sorts κ ::= ⋆|N thespinee2e3,whichistechnicallye2 (e3 ·).Patternsρ consist
Types A,B,C::= 1|A→B|A+B|A×B ofpatternvariables,pairs,andinjections.Abranchπisasequence
|α|∀α:κ.A|∃α:κ.A of patterns~ρ with a branch body e. We represent patterns as se-
|P⊃A|A∧P|VectA quences,whichenablesustodeconstructtuplepatterns.
Terms/monotypes t,τ,σ ::= zero|succ(t)|1|α Types. WewritetypesasA,B andC. Wehavetheunit type1,
|τ→σ|τ+σ|τ×σ functions A → B, sums A+B, and products A×B. We have
Propositions P,Q ::= t=t′ universalandexistentialtypes∀α : κ.Aand∃α:κ.A;theseare
Contexts Ψ ::= ·|Ψ,α:κ |Ψ,x:Ap predicative quantifiers over monotypes (see below). We write α,
Polarities ± ::= +|− β,etc.fortypevariables; theseareuniversal,except whenbound
Binaryconnectives ⊕ ::= →|+|× withinanexistentialtype.WealsohaveaguardedtypeP⊃A,read
Principalities p,q ::= !| 66! “PimpliesA”.ThisimplicationcorrespondstotypeA,providedP
|{z} holds.ItsdualistheassertingtypeA∧P,read“AwithP”,which
sometimesomitted witnessesthepropositionP.Inboth,Phasnoruntimecontent.
Figure2. Syntaxofdeclarativetypesandcontexts Sorts, terms, monotypes, and propositions. Terms and mono-
typest,τ,σshareagrammarbutaredistinguishedbytheirsortsκ.
Naturalnumberszeroandsucc(t)aretermsandhavesortN.Unit
checking,eq.elim. subtyping coverage 1hasthesort⋆ofmonotypes.Avariableαstandsforatermora
Ψ/P⊢e Cp Ψ⊢A≤±B Ψ⊢ΠcoversA~ monotype,dependingonthesortκannotatingitsbinder.Functions,
sums,andproductsofmonotypesaremonotypesandhavesort⋆.
⇐ Wetendtoprefertfortermsandσ,τformonotypes.
spinetyping typechecking match,eq.elim. ApropositionP orQissimplyanequationt = t′.Notethat
Ψ⊢s:Ap≫Bq Ψ⊢e Ap Ψ/P⊢Π::A~ Cp terms,whichrepresentruntime-irrelevantinformation,aredistinct
fromexpressions;however,anexpressionmayincludetypeanno-
⇐ ⇐ tationsoftheformP⊃AandA∧P,wherePcontainsterms.
principality-recovering patternmatching
Contexts. AdeclarativecontextΨisanorderedsequenceofuni-
spinetyping Ψ⊢Π::A~ Cp versalvariabledeclarationsα : κandexpressionvariabletypings
Ψ⊢s:Ap≫B⌈q⌉
x : Ap,wherepdenoteswhetherthetypeAisprincipal(Section
⇐
typesynthesis 4.2).AvariableαcanbefreeinatypeAonlyifαwasdeclaredto
Ψ⊢e Bp theleft:α:⋆, x:αpiswell-formed,butx:αp, α:⋆isnot.
Figure3. Dependencys⇒tructureofthedeclarativejudgments 4.1 Subtyping
We give our two subtyping relations in Figure 4. We treat the
universal quantifier as a negative type (since it is a function in
Ψ⊢ A≤± B UndercontextΨ,typeAisasubtypeofB, System F), and the existential as a positive type (since it is a
decomposingheadconnectivesofpolarity± pair in System F). We have two typing rules for each of these
connectives,correspondingtotheleftandrightrulesforuniversals
Ψ⊢ Atype nonpos(A) nonneg(A)
≤Refl± andexistentialsinthesequentcalculus.Wetreatallothertypesas
±
Ψ⊢ A≤ A havingnopolarity.Thepositiveandnegativesubtypejudgmentsare
Ψ⊢ A≤− B nonpos(A) nonpos(B) mutuallyrecursive,andthe≤−+rulepermitsswitchingthepolarity
≤− ofsubtypingfrompositivetonegativewhenbothofthetypesare
Ψ⊢ A≤+ B + non-positive,andconverselyfor≤+.Whenbothtypesareneither
−
Ψ⊢ A≤+ B nonneg(A) nonneg(B) positivenornegative,werequirethemtobeequal(≤Refl).
≤+ In logical terms, functions and guarded types are negative;
Ψ⊢ A≤− B − sums, products and assertion types are positive. Wecould poten-
tiallyoperate on these types in the negative and positive subtype
Ψ⊢ τ:κ Ψ⊢ [τ/α]A≤− B Ψ,β:κ⊢ A≤− B
≤∀L ≤∀R relations,respectively.Leavingout(forexample)functionsubtyp-
Ψ⊢ ∀α:κ.A≤− B Ψ⊢ A≤− ∀β:κ.B ingmeans thatwewillhavetodosomeη-expansions toget pro-
gramstotypecheck;weomittheserulestokeeptheimplementation
Ψ,α:κ⊢ A≤+ B Ψ⊢ τ:κ Ψ⊢ A≤+ [τ/β]B
complexitylow.Thisalsoillustratesanicefeatureofbidirectional
≤∃L ≤∃R
Ψ⊢ ∃α:κ.A≤+ B Ψ⊢ A≤+ ∃β:κ.B typing:wearerelativelyfreetoadjustthesubtyperelationtotaste.
Figure4. Subtypinginthedeclarativesystem 4.2 Typingjudgments
Principality. Ourtypingjudgmentscarryprincipalities:A!means
thatAisprincipal,andA66! meansAisnotprincipal.Notethata
Values v are standard for a call-by-value semantics; the vari- principalityispartofajudgment,notpartofatype.Inthechecking
ablesintroducedbyfixedpointsareconsideredvalues,becausewe judgmentΨ ⊢ e ⇐ A pthetypeAisinput;ifp = !,weknow
onlyallowfixedpointsofvalues.Aspinesisalistofexpressions— thateisnottheresultofguessing.Forexample,theein(e:A)is
argumentstoafunction.Allowingemptyspines(written·)iscon- checkedagainstA!.InthesynthesisjudgmentΨ⊢ e⇒Ap,the
venientinthetypingrules,butwouldbestrangeinthesourcesyn- typeA isoutput, and p = ! means itisimpossibletosynthesize
tax,so(inthegrammar of expressions e)werequireanonempty anyothertype,asinΨ⊢ (e:A)⇒A!.
spines+.Weusuallyomittheemptyspine·,writinge e instead Wesometimesomitaprincipalitywhenitis66!(“notprincipal”).
1 2
ofe e ·.Sinceweusejuxtapositionforbothapplicationes+and Wewritep⊑q,read“patleastasprincipalasq”,forthereflexive
1 2
spines, somestringsareambiguous; weresolvethisambiguityin closureof!⊑66!.
4 2016/1/21
echk-I Expressioneisacheckedintroductionform λx.echk-I ()chk-I he1,e2ichk-I injkechk-I []chk-I e1 ::e2chk-I
Figure5. “Checkingintroform”
Ψ⊢ e⇐Ap UndercontextΨ,expressionechecksagainstinputtypeA Ψ⊢ Ptrue UndercontextΨ,checkP
Ψ⊢ e⇒Ap UndercontextΨ,expressionesynthesizesoutputtypeA
DeclCheckpropEq
Ψ⊢ s:Ap≫Cq UndercontextΨ, Ψ⊢ (t=t)true
passingspinestoafunctionoftypeAsynthesizestypeC;
Ψ⊢ s:Ap≫C⌈q⌉
inthe⌈q⌉form,recoverprincipalityinqifpossible
x:Ap∈Ψ Ψ⊢ e⇒Aq Ψ⊢ A≤pol(B)B Ψ⊢ Atype Ψ⊢ e⇐A!
DeclVar DeclSub DeclAnno
Ψ⊢ x⇒Ap Ψ⊢ e⇐Bp Ψ⊢ (e:A)⇒A!
vchk-I Ψ,α:κ⊢ v⇐Ap Ψ⊢ τ:κ Ψ⊢ es:[τ/α]A66! ≫Cq
Decl1I Decl∀I Decl∀Spine
Ψ⊢ ()⇐1p Ψ⊢ v⇐(∀α:κ.A)p Ψ⊢ es:(∀α:κ.A)p≫Cq
Ψ⊢ Ptrue Ψ⊢ e⇐Ap vchk-I Ψ/P⊢ v⇐A! Ψ⊢ Ptrue Ψ⊢ es:Ap≫Cq
Decl∧I Decl⊃I Decl⊃Spine
Ψ⊢ e⇐(A∧P)p Ψ⊢ v⇐(P⊃A)! Ψ⊢ es:(P⊃A)p≫Cq
Ψ,x:Ap⊢ v⇐Ap Ψ,x:Ap⊢ e⇐Bp Ψ⊢ e⇒Ap Ψ⊢ s:Ap≫C⌈q⌉
DeclRec Decl I Decl E
Ψ⊢ recx.v⇐Ap Ψ⊢ λx.e⇐A→Bp Ψ⊢ es⇒Cq
′ → →
forallC .
Ψ⊢ s:A!≫C66! if Ψ⊢ s:A!≫C′66! thenC′ =C Ψ⊢ s:Ap≫Cq
DeclSpineRecover DeclSpinePass
Ψ⊢ s:A!≫C⌈!⌉ Ψ⊢ s:Ap≫C⌈q⌉
Ψ⊢ e⇐Ap Ψ⊢ e⇒A!
Ψ⊢ s:Bp≫Cq Ψ⊢ Π::A⇐Cp
DeclEmptySpine Decl Spine
Ψ⊢ ·:Ap≫Ap Ψ⊢ es:A→Bp≫Cq Ψ⊢ ΠcoversA
DeclCase
→ Ψ⊢ case(e,Π)⇐Cp
UndercontextΨ,incorporatepropositionP
Ψ/P ⊢ e⇐Cp mgu(σ,τ)=θ
andcheckeagainstC
mgu(σ,τ)=⊥ θ(Ψ)⊢ θ(e)⇐θ(C)p
DeclCheck⊥ DeclCheckUnify
Ψ/(σ=τ)⊢ e⇐Cp Ψ/(σ=τ)⊢ e⇐Cp
Figure6. Declarativetyping,omittingrulesfor×,+,andVec
Spine judgments. The ordinary form of spine judgment, Ψ ⊢ IfsomeC′ 6=C,thenCiscertainlynotprincipal,andwemust
s : A p ≫ C q, says that if arguments s are passed to a applyDeclSpinePass,whichsimplytransitionsfromtheordinary
function of type A, the function returns type C. For a function judgmenttotherecoveryjudgment.
e applied to one argument e , we write e e as syntactic sugar Figure3showsthedependenciesbetweenthedeclarativejudg-
1 1
for e (e ·). Supposing e synthesizes A → A , we apply ments.Giventhecyclecontainingthespinetypingjudgments,we
1 1 2
Decl→Spine,checkinge againstA andusingDeclEmptySpine needtostopandask:IsDeclSpineRecoverwell-founded?Forwell-
1 1
toderiveΨ⊢ ·:A p≫A p. foundedness of type systems, we can often make a straightfor-
2 2
RuleDecl∀Spinedoesnotdecomposee sbutinstantiatesa∀. wardargument that,aswemovefromtheconclusion of aruleto
Note that, even if the given type ∀α : κ.A isprincipal (p = !), itspremises, either the expression gets smaller, or the expression
thetype[τ/α]Ainthepremiseisnotprincipal—wecouldchoosea staysthesamebutthetypegetssmaller.InDeclSpineRecover,nei-
differentτ.Infact,theqinDecl∀Spineisalsoalways66!,becauseno ther the expression nor the type get smaller. Fortunately, the rule
rulederivingtheordinaryspinejudgmentcanrecoverprincipality. that gives rise to the arrow from “spine typing” to “type check-
The recovery spine judgment Ψ ⊢ s : A p ≫ C ⌈q⌉, ing”inFigure3—Decl→Spine—doesdecomposeitssubject,and
however,canrestoreprincipalityinsituationswherethechoiceof anyderivations ofarecoveryjudgment lurkingwithinthesecond
τinDecl∀Spinecannot affecttheresulttypeC. IfAisprincipal premiseofDeclSpineRecover mustbeforasmallerspine.Inthe
(p = !)buttheordinaryspinejudgmentproducesanon-principal appendix(Lemma??,p.??),weprovethattherecoveryjudgment,
C, wecan tryto recover principalitywithDeclSpineRecover. Its andalltheotherdeclarativejudgments,arewell-founded.
firstpremiseisΨ⊢ s:A! ≫C66!;itssecondpremise(really,an
infinitesetofpremises)quantifiesoverallderivationsofΨ ⊢ s : Example. Appendix A has an example showing how the spine
A ! ≫ C′66!.IfC′ = Cinallsuchderivations,thentheordinary typingrulesworktorecoverprincipality.
spineruleserredonthesideofcaution:Cisactuallyprincipal,so
wecansetq=!intheconclusionofDeclSpineRecover. Subtyping. RuleDeclSubinvokesthesubtypingjudgment,atthe
polarityofB,thetypebeingcheckedagainst.ThisallowsDeclSub
to play the role of an existential introduction rule, by applying
subtypingrule≤∃RwhenBisanexistentialtype.
5 2016/1/21
Patternmatching. RuleDeclCasechecks that thescrutinee has checkequation instantiation
a principal type, and then invokes the two main judgments for Γ ⊢t1⊜t2:κ⊣∆ Γ ⊢α^:=t:κ⊣∆
~
pattern matching. The Ψ ⊢ Π :: A ⇐ C p judgment checks
that each branch in the list of branches Π is well-typed, and the
~ equiv.props. equiv.types
Ψ ⊢ ΠcoversAjudgmentdoescoveragecheckingforthelistof
~ Γ ⊢P≡Q⊣∆ Γ ⊢A≡B⊣∆
branches.BothofthesejudgmentstakeavectorAofpatterntypes
tosimplifythespecificationofcoveragechecking.
TheΨ⊢ Π::A~ ⇐Cpjudgment(rulesintheappendix’sFig- checkprop. subtyping coverage
ure15)systematicallychecksthecoverageofeachbranchinΠ:rule Γ ⊢Ptrue⊣∆ Γ ⊢A<:±B⊣∆ Γ ⊢ΠcoversA~
DeclMatchEmptysucceedsontheemptylist,andDeclMatchSeq
checks one branch and recurs on the remaining branches. Rules
spinetyping typechecking equalityelim.
forsums,units,andproductsbreakdownpatternslefttoright,one
Γ ⊢s:Ap≫Bq⊣∆ Γ ⊢e Ap⊣∆ Γ/s⊜t:κ⊣∆⊥
constructor at a time. Products also extend the sequences of pat-
ternsandtypes,withDeclMatch×breakingdownapatternvector ⇐
headedbyapairpatternhp,p′i,~pintop,p′,~p,andbreakingdown
~ ~ principality-recovering patternmatching
thetypesequence (A×B),CintoA,B,C.Once allthepatterns spinetyping ~
areeliminated,theDeclMatchBaserulesaysthatifthebodytype- Γ ⊢s:Ap≫B⌈q⌉⊣∆ Γ ⊢Π::A Cp⊣∆
checks,thenthebranchtypechecks.Forcompleteness,thevariable
⇐
and wildcardrules arerestrictedso that any top-level existentials typesynthesis
andequationsareeliminatedbeforediscardingthetype. Γ ⊢e Bp⊣∆
TheexistentialeliminationruleDeclMatch∃unpacksanexis-
Figure7. Dependencystructu⇒reofthealgorithmicjudgments
tentialtype,andDeclMatch∧breaksapartaconjunctionbyelim-
inatingtheequalityusingunification.TheDeclMatch⊥rulesays
that if the equation is false then the branch always succeeds, be-
nately,itwouldbestraightforwardtoaddsuchrules,followingthe
causethiscaseisimpossible.TheDeclMatchUnifyruleunifiesthe
styleofDunfieldandKrishnaswami(2013).
twotermsofanequationandappliesthesubstitutionbeforecon-
tinuing to check typing. Together, these two rules implement the
5. AlgorithmicTyping
Schroeder-Heisterequalityeliminationrule.Becauseourlanguage
of terms has only simple first-order terms, either unification will Our algorithmic rulesclosely mimicour declarative rules, except
fail,orthereisamostgeneralunifier. thatwheneveradeclarativerulewouldmakeaguess,thealgorith-
~
TheΨ ⊢ ΠcoversA judgment (intheappendix’s Figure16) micruleaddstothecontextanexistentialvariable(writtenwitha
checkswhetherasetofpatternscoversallpossiblecases.Aswith hatα^).Astypecheckingproceeds,weaddsolutionstotheexisten-
matchtyping,wesystematicallydeconstructthesequenceoftypes tialvariables,reflectingincreasingknowledge.Hence,eachdeclar-
in the branch, but we also need auxiliary operations to expand ative typing judgment has a corresponding algorithmic judgment
the patterns. For example, the Π ❀× Π′ operation takes every withanoutputcontextaswellasaninputcontext.Thealgorithmic
branch hp,p′i,~ρ ⇒ e and expands it to p,p′,~ρ ⇒ e. To keep typecheckingjudgmentΓ ⊢ e⇐Ap ⊣∆takesaninputcontext
the sequence of patterns aligned with the sequence of types, we Γandyieldsanoutputcontext∆thatincludesincreasedknowledge
also expand variables and wildcard patterns into two wildcards: aboutwhatthetypeshavetobe.Thenotionofincreasingknowl-
x,~ρ ⇒ ebecomes_,_,~ρ ⇒ e.Afterexpandingoutallthepairs, edgeisformalizedbyajudgmentΓ −→∆(Section5.2).
DeclCovers×checkscoveragebybreakingdownthepairtype. Figure 7 shows a dependency graph of the algorithmic judg-
For sum types, we expand a list of branches into two lists, ments.Eachdeclarativejudgmenthasacorrespondingalgorithmic
onefor eachinjection.SoΠ ❀+ Π kΠ willsendallbranches judgment,butthealgorithmicsystemaddsjudgmentssuchastype
L R equivalencecheckingΓ ⊢ A ≡ B ⊣ ∆andvariableinstantiation
headed by inj p into Π and all branches headed by inj p into
1 L 2 Γ ⊢ α^ := t : κ ⊣ ∆. Declaratively, thesejudgmentscorrespond
Π , with variables and wildcards being sent to both sides. Then
R to uses of reflexivity axioms; algorithmically, they correspond to
DeclCovers+checkstheleftandrightbranchesindependently.
solvingexistentialvariablestoequateterms.
Aswithtyping,DeclCovers∃justunpackstheexistentialtype.
We give the algorithmic typing rules in Figure 11; rules for
Likewise, DeclCoversEqBot and DeclCoversEq handle the two
mostother judgments areintheappendix. Our styleof specifica-
cases arising from equations. If an equation isunsatisfiable, cov-
tionbroadlyfollowsDunfieldandKrishnaswami(2013):weadapt
erage succeeds since there are no possible values of that type. If
theirmechanisms ofvariableinstantiation,context extension,and
it is satisfiable, we apply the substitution and continue coverage
contextapplication(tobothtypesandothercontexts).Ourversions
checking.
ofthesemechanisms,however,supportindices,equationsoveruni-
These rules do not check for redundancy: DeclCoversEmpty
versalvariables,andthe∃/⊃/∧connectives.Wealsodifferinour
appliesevenwhenbranchesareleftover.WhenDeclCoversEmpty
formulationofspinetyping,andbybeingabletotrackwhichtypes
isapplied,wecouldmarkthe· ⇒ e branch,andissueawarning
1 areprincipal.TheexampleinAppendixAshowshowthealgorith-
forunmarkedbranches.Thisseemsbetterasawarningthananer-
micspinetypingrulesworktorecoverprincipality.
ror,sinceredundancyisnotstableundersubstitution.Forexample,
acaseover(Vec n A)with[]and::branchesisnotredundant— Syntax. Expressionsarethesameasinthedeclarativesystem.
butifwesubstitute0forn,the::branchbecomesredundant.
Existential variables. The algorithmic system adds existential
variablesα^,β^,γ^totypesandterms/monotypes(Figure8).Weuse
Synthesis. Bidirectionaltypingisaformofpartialtypeinference,
thesamemeta-variablesA,... foralgorithmictypes.Wewriteu
whichPierceandTurner(2000) saidshould“eliminateespecially
foreitherauniversalvariableαoranexistentialvariableα^.
those type annotations that are both common and silly”. But our
rulesareratherparsimoniousinwhattheysynthesize;forinstance, Contexts. An algorithmic context Γ is a sequence that, like a
()doesnotsynthesize1,andsomightneedanannotation.Fortu- declarative context, may contain universal variable declarations
6 2016/1/21
Universalvariables α,β,γ [·]· = ·
Existentialvariables α^,β^,γ^ [Ω,x:Ap](Γ,x:AΓp) = [Ω]Γ, x:[Ω]Ap if[Ω]A=[Ω]AΓ
Variables u ::= α|α^ [Ω,α:κ](Γ,α:κ) = [Ω]Γ, α:κ
Types A,B,C::= 1|A→B|A+B|A×B [Ω,◮u](Γ,◮u) = [Ω]Γ
|α| α^ |∀α:κ.A|∃α:κ.A [Ω,α=t](Γ,α=t′) = (cid:2)[Ω]t/α(cid:3)[Ω]Γ if[Ω]t=[Ω]t′
|P⊃A|A∧P|VectA [Ω]Γ′whenΓ =(Γ′,α^:κ=t′)
Propositions P,Q ::= t=t′ [Ω,α^ :κ=t]Γ = [Ω]Γ′whenΓ =(Γ′,α^:κ)
Binaryconnectives ⊕ ::= →|+|× [Ω]Γ otherwise
Terms/monotypes t,τ,σ ::= zero|succ(t)|1|α|α^
Figure10. ApplyingacompletecontextΩtoacontext
|τ→σ|τ+σ|τ×σ
Contexts Γ,∆,Θ ::= ·|Γ,u:κ |Γ,x:Ap
|Γ,α^ :κ=τ |Γ,α=t |Γ,◮u for contexts with a hole is useful: Γ = Γ0[Θ] means Γ has the
form(Γ ,Θ,Γ ).Forexample,ifΓ = Γ [β^] = (α^,β^,x : β^),then
Completecontexts Ω ::= ·|Ω,α:κ|Ω,x:Ap L R 0
|Ω,α^ :κ=τ|Ω,α=t|Ω,◮u Γ0[β^ =α^]=(α^,β^ =α^,x:β^).
Possibly-inconsistentcontexts ∆⊥ ::= ∆|⊥ 5.2 ThecontextextensionrelationΓ −→∆
Figure 8. Syntax of types, contexts, and other objects in the A context Γ is extended by a context ∆, written Γ −→ ∆, if ∆
algorithmicsystem has at least as much information as Γ, while conforming to the
samedeclarativecontext—thatis,[Ω]Γ = [Ω]∆forsomeΩ.Ina
sense,Γ −→∆saysthatΓ isentailedby∆:allpositiveinformation
[Γ]τ when(α=τ)∈Γ (cid:2)Γ[α^ :κ=τ](cid:3)α^ = [Γ]τ
[Γ]α = derivablefromΓcanalsobederivedfrom∆(whichmayhavemore
(cid:12)α otherwise (cid:2)Γ[α^ :κ](cid:3)α^ = α^ information,say,thatα^ isequaltoaparticulartype).Wegivethe
[Γ](P⊃A) = ([Γ]P)⊃([Γ]A) [Γ](∀α:κ.A) = ∀α:κ.[Γ]A rulesforextensioninFigure14intheappendix.
[Γ](A∧P) = ([Γ]A)∧([Γ]P) [Γ](∃α:κ.A) = ∃α:κ.[Γ]A Extension allows solutions to change, if information is pre-
[[ΓΓ]]((VAe⊕ctBA)) == V([Γec]A()[Γ⊕]t)([(Γ[Γ]B]A)) [Γ](t1=t2) = ([Γ]t1)=([Γ]t2) servedorincreased:(α^ :⋆,β^ :⋆=α^)−→(α^ :⋆=1,β^ :⋆=α^)
directlyincreasesinformationaboutα^,andindirectlyincreasesin-
Figure9. Applyingacontext,asasubstitution,toatype formationaboutβ^.Moreinterestingly,if∆=(α^:⋆=1,β^:⋆=α^)
andΩ = (α^:⋆ = 1,β^:⋆ = 1),then∆ −→ Ω:whilethesolution
ofβ^inΩisdifferent,inthesensethatΩcontainsβ^ :⋆=1while
α:κandexpressionvariabletypingsx:Ap.However,itmayalso ∆containsβ^ :⋆ = α^,applyingΩtothesolutionsgivesthesame
have(1)unsolvedexistentialvariabledeclarationsα^ : κ(included
result:[Ω]α^ =[Ω]1=1,whichisthesameas[Ω]1=1.
intheΓ,u : κproduction);(2)solved existentialvariabledeclara-
Extension is quite rigid, however, in two senses. First, if a
tionsα^ :κ=τ;(3)equationsoveruniversalvariablesα=τ;and
declarationappearsinΓ,itappearsinallextensionsofΓ.Second,
(4)markers◮u. extension preserves order. For example, if β^ is declared after α^
An equation α = τ must appear to the right of the universal
in Γ, then β^ will also be declared after α^ in every extension of
variable’sdeclarationα : κ.Weusemarkersasdelimiterswithin
Γ.Thisholdsforeveryvarietyofdeclaration,includingequations
ocofnittsexlatss.tFporermexisaem’spoleu,tpruutleco⊃nIteaxdtd(s∆◮,◮P,Pw,∆hi′c)hshteolulslditbehodwromppuecdh. socfoupninivgerasnadlvdaerpiaebnldeesn.cTiheiss,rwighiidcihtyaariedsnoinnterinvfioarlciinngatyspetetivnagriwabitlhe
(Weabusenotationbywriting◮Pratherthanclutteringthecontext higher-rankpolymorphism.
withadummyαandwriting◮α.)
Acompletealgorithmiccontext,denotedbyΩ,isanalgorith-
5.3 Determinacy
miccontextwithnounsolvedexistentialvariabledeclarations.
Assuming an equality can yield inconsistency: for example, Givenappropriateinputs(Γ,e,A,p)tothealgorithmicjudgments,
zero = succ(zero). We write ∆⊥ for either a valid algorithmic onlyonesetofoutputs(C,q,∆)isderivable(Theorem5(Determi-
context∆orinconsistency⊥. nacyofTyping)intheappendix,p.21).Weusethisproperty(for
spinejudgments)intheproofofsoundness.
5.1 Contextsubstitution[Γ]AandholenotationΓ[Θ]
6. Soundness
An algorithmic context can be viewed as a substitution for its
solved existential variables. Forexample, α^ = 1,β^ = α^→1can We show that the algorithmic system is sound with respect to
be applied as if it were the substitution 1/α^,(α^→1)/β^ (applied thedeclarativesystem.Soundnessforthemutually-recursivejudg-
righttoleft),orthesimultaneoussubstitution1/α^,(1→1)/β^.We ments depends on lemmas for the auxiliary judgments (instanti-
write[Γ]AforΓ appliedasasubstitution(Figure9). ation,equality elimination,checkprop, algorithmicsubtyping and
Applying acompletecontext toatypeA (provided itiswell- matchcoverage),whichareinAppendixE.2forspacereasons.
formed: Ω ⊢ A type) yields a type [Ω]A with no existentials. Themainsoundnessresulthassixmutually-recursiveparts,one
Suchatypeiswell-formedunderthedeclarativecontextobtained foreachofthechecking,synthesis,spine,andmatchjudgments—
by dropping all the existential declarations and applying Ω to includingtheprincipality-recoveringspinejudgment.Weomitthe
declarationsx:A(toyieldx:[Ω]A).Wecanthinkofthiscontext partsforthematchjudgments;seetheappendix,p.22.
astheresultofapplyingΩtoitself:[Ω]Ω.Moregenerally,wecan Theorem8(SoundnessofAlgorithmicTyping).Given∆−→Ω:
applyΩtoanycontextΓ thatitextends:contextapplication[Ω]Γ
isgiveninFigure10.Theapplication[Ω]Γ isdefinedifandonlyif (i)IfΓ ⊢ e⇐Ap ⊣∆andΓ ⊢ Aptype
Γ −→ Ω(contextextension; seeSection5.2),andapplyingΩto then[Ω]∆⊢ [Ω]e⇐[Ω]Ap.
anysuchΓ yieldsthesamedeclarativecontext[Ω]Ω. (ii)IfΓ ⊢ e⇒Ap ⊣∆then[Ω]∆⊢ [Ω]e⇒[Ω]Ap.
Inadditiontoappendingdeclarations(asinthedeclarativesys- (iii)IfΓ ⊢ s:Ap≫Bq ⊣∆andΓ ⊢ Aptype
tem),wesometimesinsert andreplacedeclarations, soanotation then[Ω]∆⊢ [Ω]s:[Ω]Ap≫[Ω]Bq.
7 2016/1/21
Γ ⊢ e⇐Ap ⊣∆ UnderinputcontextΓ,expressionechecksagainstinputtypeA,withoutputcontext∆
Γ ⊢ e⇒Ap ⊣∆ UnderinputcontextΓ,expressionesynthesizesoutputtypeA,withoutputcontext∆
UnderinputcontextΓ,
Γ ⊢ s:Ap≫Cq ⊣∆
passingspinestoafunctionoftypeAsynthesizestypeC;
Γ ⊢ s:Ap≫C⌈q⌉ ⊣∆
inthe⌈q⌉form,recoverprincipalityinqifpossible
(x:Ap)∈Γ Γ ⊢ e⇒Aq ⊣Θ Θ⊢ A<:pol(B)B ⊣∆ Γ ⊢ A!type Γ ⊢ e⇐[Γ]A! ⊣∆
Var Sub Anno
Γ ⊢ x⇒[Γ]Ap ⊣Γ Γ ⊢ e⇐Bp ⊣∆ Γ ⊢ (e:A)⇒[∆]A! ⊣∆
1I 1Iα^
Γ ⊢ ()⇐1p ⊣Γ Γ[α^ :⋆]⊢ ()⇐α^ ⊣Γ[α^ :⋆=1]
vchk-I Γ,α:κ⊢ v⇐Ap ⊣∆,α:κ,Θ Γ,α^ :κ⊢ es:[α^/α]A ≫Cq ⊣∆
∀I ∀Spine
Γ ⊢ v⇐∀α:κ.Ap ⊣∆ Γ ⊢ es:∀α:κ.Ap≫Cq ⊣∆
enotacase Γ ⊢ Ptrue ⊣Θ Θ⊢ e⇐[Θ]Ap ⊣∆ vchk-I Γ,◮P /P ⊣Θ Θ⊢ v⇐[Θ]A! ⊣∆,◮P,∆′
∧I ⊃I
Γ ⊢ e⇐A∧Pp ⊣∆ Γ ⊢ v⇐P⊃A! ⊣∆
vchk-I Γ,◮P /P ⊣⊥ Γ ⊢ Ptrue ⊣Θ Θ⊢ es:[Θ]Ap≫Cq ⊣∆ Γ,x:Ap⊢ v⇐Ap ⊣∆,x:Ap,Θ
⊃I⊥ ⊃Spine Rec
Γ ⊢ v⇐P⊃A! ⊣Γ Γ ⊢ es:P⊃Ap≫Cq ⊣∆ Γ ⊢ recx.v⇐Ap ⊣∆
Γ,x:Ap⊢ e⇐Bp ⊣∆,x:Ap,Θ Γ[α^ :⋆,α^ :⋆,α^:⋆=α^ →α^ ],x:α^ ⊢ e⇐α^ ⊣∆,x:α^ ,∆′
1 2 1 2 1 2 1
I Iα^
Γ ⊢ λx.e⇐A→Bp ⊣∆ Γ[α^ :⋆]⊢ λx.e⇐α^ ⊣∆
→ →
Γ ⊢ e⇒Ap ⊣Θ Γ ⊢ s:A!≫C66! ⊣∆ Γ ⊢ s:Ap≫Cq ⊣∆
Θ⊢ s:Ap≫C⌈q⌉ ⊣∆ FEV(C)=∅ (p=66!) or (q=!) or (FEV(C)6=∅)
E SpineRecover SpinePass
Γ ⊢ es⇒Cq ⊣∆ Γ ⊢ s:A!≫C⌈!⌉ ⊣∆ Γ ⊢ s:Ap≫C⌈q⌉ ⊣∆
(cid:0) (cid:1)
→
Γ ⊢ e⇐Ap ⊣Θ
Θ⊢ s:[Θ]Bp≫Cq ⊣∆
Γ ⊢ ·:Ap≫Ap ⊣Γ EmptySpine Γ ⊢ es:A→Bp≫Cq ⊣∆ Spine Γ ⊢ e⇒A! ⊣Θ
Θ⊢ Π::[Θ]A⇐[Θ]Cp ⊣∆
→
Γ[α^ :⋆,α^ :⋆,α^ :⋆=α^ →α^ ]⊢ es:(α^ →α^ ) ≫C ⊣∆ ∆⊢ Πcovers[∆]A
2 1 1 2 1 2
α^Spine Case
Γ[α^ :⋆]⊢ es:α^ ≫C ⊣∆ Γ ⊢ case(e,Π)⇐Cp ⊣∆
Figure11. Algorithmictyping,omittingrulesfor×,+,andVec
(iv)IfΓ ⊢ s : A p ≫ B ⌈q⌉ ⊣ ∆ andΓ ⊢ Ap type then Proof sketch—SpineRecover case. By i.h., [Ω]Γ ⊢ [Ω]s :
[Ω]∆⊢ [Ω]s:[Ω]Ap≫[Ω]B⌈q⌉. [Ω]A ! ≫ [Ω]C q. Our goal is to apply DeclSpineRecover,
which requires that we show that for all C′ such that [Ω]Θ ⊢
Much of this proof is simply “turning the crank”: applying s:[Ω]A!≫C′66!,wehaveC′ =[Ω]C.Supposewehavesucha
the induction hypothesis to each premise, yielding derivations of C′.Bycompleteness(Theorem11),Γ ⊢ s:[Γ]A!≫C′′ q ⊣∆′′
corresponding declarative judgments (with Ω applied to every- where∆′′ −→ Ω′′.Wealreadyhave(asasubderivation)Γ ⊢ s :
thing in sight), and applying the corresponding declarative rule; A ! ≫ C66! ⊣ ∆, so by determinacy, C′′ = C and q =66! and
for example, in the Sub case we finish the proof by applying ∆′′ = ∆.Withthehelpoflemmasabout contextapplication, we
DeclSub.TheSpineRecovercaseisinteresting:wedofinishbyap- canshowC′ = [Ω′′]C′′ = [Ω′′]C=[Ω]C.(Usingcompleteness
plyingDeclSpineRecover,butsinceDeclSpineRecovercontainsa is permitted since our measure says a non-principality-restoring
premisethatquantifiesoveralldeclarativederivationsofacertain judgmentissmaller.)
form, we must appeal to completeness! Consequently, soundness
andcompletenessarereallytwopartsofonetheorem.
These parts are mutually recursive—later, we’ll see that the 7. Completeness
DeclSpineRecovercaseofcompletenessmustappealtosoundness
We show that the algorithmic system is complete with respect
(toshowthatthealgorithmictypehasnofreeexistentialvariables).
to the declarative system. As with soundness, we need to show
Wecannotinductonthegivenderivationalone,becausethederiva-
completenessoftheauxiliaryalgorithmicjudgments.Weomitthe
tionsinthe“forall”partofDeclSpineRecoverarenotsubderiva-
full statements of these lemmas; as an example, if [Ω]α^ = [Ω]τ
tions.Soweneedamoreinvolvedinductionmeasurethatcanmake
andα^ ∈/ FV(τ)thenΓ ⊢ α^ :=τ:κ ⊣∆.
theleapsbetweensoundness andcompleteness: lexicographic or-
der with (1) the size of the subject term, (2) the judgment form,
withordinaryspinejudgmentsconsideredsmallerthanrecovering 7.1 Separation
spinejudgments,and(3)theheightofthederivation: To show completeness, we will need to show that wherever the
declarativeruleDeclSpineRecoverisapplied,wecanapplytheal-
ordinaryspinejudgment gorithmicruleSpineRecover.Thus,weneedtoshowthatsemantic
e/s/Π, < , height(D) principality—that noother typecan begiven—entails that atype
* recoveringspinejudgment + hasnofreeexistentialvariables.
8 2016/1/21
The principality-recovering rules are potentially applicable ∆ −→ Ω′ anddom(∆) = dom(Ω′) andΩ −→ Ω′ and
when we start with a principal type A ! but produce C66!, with Γ ⊢ s : [Γ]A p′ ≫ B′ q′ ⊣ ∆ andB′ = [∆]B′ and
Decl∀Spinechanging!to66!.Completeness(Thm.11)willusethe B=[Ω′]B′.
“forall”partofDeclSpineRecover,whichquantifiesoveralltypes (iv)Aspart(iii),butwith≫B⌈q⌉··· and≫B′⌈q′⌉···.
producedbythespinerulesunderagivendeclarativecontext[Ω]Γ.
By i.h. we get an algorithmic spine judgment Γ ⊢ s : A′ ! ≫ Proofsketch—DeclSpineRecovercase. Byi.h.,Γ ⊢ s:[Γ]A!≫
C′66! ⊣ ∆.SinceA′isprincipal,unsolvedexistentialsinC′must C′ 66! ⊣ ∆ where ∆ −→ Ω′ and Ω −→ Ω′ and dom(∆) =
havebeenintroducedwithinthisderivation—theycan’tbeinΓ al- dom(Ω′)andC=[Ω′]C′.
ready.Thus,wemighthaveα^ :⋆⊢ s:A′ !≫β^66! ⊣α^ :⋆,β^ :⋆ To apply SpineRecover, we need to show FEV([∆]C′) = ∅.
whereaDecl∀Spinesubderivationintroducedβ^,butα^can’tappear Suppose, for a contradiction, that FEV([∆]C′) 6= ∅. Construct
inC′.Wealsocan’tequateα^ andβ^ in∆,whichwouldbetanta- a variant of Ω′ called Ω2 that has a different solution for some
mount to C′ = α^. Knowing that unsolved existentials in C′ are α^ ∈ FEV([∆]C′). By soundness (Thm. 11), [Ω2]Γ ⊢ [Ω2]s :
[Ω ]A ! ≫ [Ω ]C′66!.Usingaseparationlemmawiththetrivial
“new”andindependent fromthoseinΓ meanswecanarguethat, 2 2
iftherewereanunsolvedexistentialinC′,itwouldcorrespondto separationΓ = (Γ ∗ ·)weget∆ = (∆L ∗ ∆R)and(Γ ∗ ·) −∗→
(∆ ∗ ∆ ) and FEV(C′) ⊆ dom(∆ ). That is, all existentials
anunforcedchoiceinaDecl∀Spinesubderivation,invalidatingthe L R R
in C′ were introduced within the derivation of the (algorithmic)
“forall”partofDeclSpineRecover.Formalizingclaimslike“must
spinejudgment.Thus,applyingΩ tothingsgivesthesameresult
havebeenintroduced”requiresseveraldefinitions. 2
asΩ,exceptforC′,giving[Ω]Γ ⊢ [Ω]s : [Ω]A ! ≫ [Ω ]C′66!.
2
Definition1(Separation). Nowinstantiatethe“forallC ”premisewithC =[Ω ]C′,giving
2 2 2
AnalgorithmiccontextΓ is separable into ΓL ∗ ΓR if(1)Γ = C = [Ω2]C′. But we chose Ω2 to have a different solution for
(ΓL,ΓR) and(2)forall(α^ :κ = τ) ∈ ΓR itisthecasethat α^ ∈FEV(C′),sowehaveC6=[Ω2]C′:Contradiction.Therefore
FEV(τ)⊆dom(ΓR). FEV([∆]C′)=∅,sowecanapplySpineRecover.
IfΓ isseparableintoΓ ∗ Γ ,thenΓ isself-contained inthe
L R R
sense that all existential variables declared in ΓR have solutions 8. DiscussionandRelatedWork
whose existential variables are themselves declared in Γ . Every
R
contextΓ isseparableinto·∗Γ andintoΓ ∗·. A staggering amount of work has been done on GADTs and in-
dexedtypes,andforspacereasonswecannot offeracomprehen-
Definition2(Separation-PreservingExtension).
sivesurveyoftheliterature.Sowecomparemoredeeplytofewer
TheseparatedcontextΓ ∗Γ extendsto∆ ∗Γ ,written
L R L R papers,tocommunicateourunderstandingofthedesignspace.
(ΓL∗ΓR)−∗→(∆L∗∆R),if(ΓL,ΓR)−→(∆L,∆R)
anddom(ΓL)⊆dom(∆L)anddom(ΓR)⊆dom(∆R). Proof theory and type theory. As described in Section 1, there
Separation-preserving extension says that variables from one aretwologicalaccountsofequality—theidentitytypeofMartin-
side of∗ haven’t “jumped” to the other side. Thus, ∆ may add LöfandtheequalitytypeofSchroeder-Heister(1994)andGirard
L
existentialvariablestoΓ ,and∆ mayaddexistentialvariablesto (1992). The Girard/Schroeder-Heister equality has a more direct
L R
Γ ,butnovariablefromΓ endsupin∆ andnovariablefromΓ connection topatternmatching, whichiswhywemake useof it.
R L R R
endsupin∆L.Itisnecessarytowrite(ΓL ∗ ΓR) −∗→ (∆L ∗ ∆R) Coquand (1996) pioneered the study of pattern matching in de-
ratherthan(ΓL∗ΓR) −→ (∆L∗∆R),becauseonly−∗→ includes pendenttypetheory.OneperhapssurprisingfeatureofCoquand’s
thedomainconditions.Forexample,(α^∗β^) −→ (α^,β^ =α^)∗·, pattern-matching syntax isthat itisstrictlystronger than Martin-
butβ^hasjumpedtotheleftof∗inthecontext(α^,β^ =α^)∗·. Löf’seliminators. Hisrules canderive the uniqueness of identity
proofsaswellasthedisjointnessofconstructors.Constructordis-
Weprovemanylemmasabout separation, butuseonlyoneof
jointnessisalsoderivablefromtheGirard/Schroeder-Heisterequal-
them in the subsequent development (in the DeclSpineRecover
ity,becausethereisnounifierfortwodistinctconstructors.
caseoftypingcompleteness),andthenonlythepartforspines.It
Infuturework,wehopetostudytherelationbetweenthesetwo
saysthatifwehaveaspinewhosetypeAmentionsonlyvariables
notionsofequalityinmoredepth;richerequationaltheories(such
inΓ ,thentheoutputcontext∆extendsΓ andpreservesseparation,
R
asthetheoryofcommutativeringsortheβη-theoryofthelambda
andtheoutputtypeCmentionsonlyvariablesin∆ :
R
calculus)donothavedecidableunification,butitseemsplausible
Lemma(Separation—Main). that there are hybrid approaches which might let us retain some
If ΓL∗ΓR ⊢s:Ap≫Cq⊣∆orΓL∗ΓR ⊢s:Ap≫C⌈q⌉ ⊣∆ of the convenience of the G/SH equality rule while retaining the
andΓL∗ΓR ⊢ AptypeandFEV(A)⊆dom(ΓR)then∆=(∆L∗ decidabilityofMartin-Löf’sJeliminator.
∆R)and(ΓL∗ΓR)−∗→(∆L∗∆R)andFEV(C)⊆dom(∆R).
Indexedandrefinementtypes. DependentML(XiandPfenning
7.2 Completenessoftyping 1999)indexedprogramswithpropositionalconstraints,extending
theMLtypedisciplinetomaintainadditionalinvariantstrackedby
Like soundness, completeness has six mutually-recursive parts.
theconstraints. DML collected constraints from theprogram and
Again,thematchjudgmentsareintheappendix,p.22.
passedthemtoaconstraintsolver,atechniqueusedbysystemslike
Theorem11(CompletenessofAlgorithmicTyping). Stardust(Dunfield2007)andliquidtypes(Rondonetal.2008).
GivenΓ −→Ωsuchthatdom(Γ)=dom(Ω):
From phantom types to GADTs. Leijen and Meijer (1999) in-
(i)IfΓ ⊢ Aptypeand[Ω]Γ ⊢ [Ω]e⇐[Ω]Apandp′ ⊑p troduced the term phantom type to describe a technique for pro-
thenthereexist∆andΩ′suchthat∆−→Ω′anddom(∆)= gramming in ML/Haskell where additional type parameters are
dom(Ω′)andΩ−→Ω′andΓ ⊢ e⇐[Γ]Ap′ ⊣∆. usedtoconstrainwhenvaluesarewell-typed.Thisideaprovedto
(ii)IfΓ ⊢ Ap type and[Ω]Γ ⊢ [Ω]e ⇒ A p thenthere have many applications, ranging from foreign function interfaces
exist∆,Ω′,A′,andp′ ⊑ p suchthat∆ −→ Ω′ and (Blume2001)toencodingJava-stylesubtyping(FluetandPucella
dom(∆)=dom(Ω′)andΩ−→Ω′ 2006). Phantom typesallow constructing valueswithconstrained
andΓ ⊢ e⇒A′p′ ⊣∆andA′=[∆]A′andA=[Ω′]A′. types, but do not easily permit learning about type equalities by
(iii)IfΓ ⊢ Ap typeand[Ω]Γ ⊢ [Ω]s : [Ω]A p ≫ B qand analyzingthem,puttingapplicationssuchasintensionaltypeanal-
p′ ⊑ pthenthereexist∆,Ω′,B′,andq′ ⊑ qsuchthat ysis (Harper and Morrisett 1995) out of reach. Both Cheney and
9 2016/1/21
Hinze (2003) and Xi et al. (2003) proposed treating equalities as Matthias Blume. No-longer-foreign: Teaching an ML compiler to speak C
afirst-classconcept, givingexplicitly-typed calculiforequalities, “natively”.ElectronicNotesinTheoreticalComputerScience,59(1),2001.
butwithoutstudyingalgorithmsfortypeinference. JamesCheneyandRalfHinze. First-classphantomtypes. TechnicalReport
Simonet and Pottier (2007) gave a constraint-based algorithm CUCISTR2003-1901,CornellUniversity,2003.
for type inference for GADTs. It is this work which first identi- ThierryCoquand. Analgorithmfortype-checkingdependenttypes. Scienceof
fied the potential intractibility of type inference arising from the ComputerProgramming,26(1–3):167–177,1996.
interactionofhypotheticalconstraintsandunificationvariables.To RowanDaviesandFrankPfenning.Intersectiontypesandcomputationaleffects.
InICFP,pages198–208,2000.
resolvethisissuetheyintroducethenotionoftractableconstraints
JoshuaDunfield. RefinedtypecheckingwithStardust. InProgrammingLan-
(i.e.,constraintswherehypothetical equationsnever containexis-
guagesmeetsProgrammingVerification(PLPV’07),2007.
tentials),andrequireplacingenoughannotationsthatallconstraints
JoshuaDunfieldandNeelakantanR.Krishnaswami. Completeandeasybidi-
aretractable.Ingeneral,thiscouldrequireannotationsoncaseex-
rectional typechecking for higher-rank polymorphism. In ICFP, 2013.
pressions, so subsequent work focused on relaxing this require- arXiv:1306.6032 [cs.PL].
ment. Though quite different in technical detail, stratified infer- Joshua DunfieldandFrankPfenning. Type assignment forintersectionsand
ence (Pottier and Régis-Gianas 2006) and wobbly types (Peyton unionsincall-by-valuelanguages.InFoSSaCS,pages250–266,2003.
Jonesetal.2006)bothworkbypushingtypeinformationfroman- Matthew Fluet and Riccardo Pucella. Phantom types and subtyping.
notationstocaseexpressions,withstratifiedtypeinferenceliterally arXiv:cs/0403034 [cs.PL],2006.
movingannotationsaround,andwobblytypestrackingwhichparts JacquesGarrigueandDidierRémy. Ambivalenttypesforprincipaltypeinfer-
ofatypehavenounificationvariables.ModernGHCusestheOut- encewithGADTs.InAPLAS,2013.
sideInalgorithm(Vytiniotisetal.2011),whichfurtherrelaxesthe Jean-YvesGirard.Afixpointtheoreminlinearlogic.PosttoLinearLogicmail-
constraint:aslongascaseanalysiscannot modifywhatisknown inglist,http://www.seas.upenn.edu/~sweirich/types/archive/1992/
msg00030.html,1992.
aboutanequation,thecaseanalysisispermitted.
RobertHarperandGregMorrisett. Compilingpolymorphismusingintensional
Inourtypesystem,thecheckingjudgmentofthebidirectional
typeanalysis.InPOPL,pages130–141.ACMPress,1995.
algorithm serves to propagate annotations, and our requirement
GeorgiosKarachalias,TomSchrijvers,DimitriosVytiniotis,andSimonPeyton
that the scrutinee of a case expression be principal ensures that
Jones.GADTsmeettheirmatch:pattern-matchingwarningsthataccountfor
no equations contain unification variables. This is close in effect GADTs,guards,andlaziness.InICFP,pages424–436,2015.
to stratified types, and is less expressive than OutsideIn. This is NeelakantanR.Krishnaswami. Focusingonpatternmatching. InPOPL,pages
a deliberate design choice to keep the declarative specification 366–378.ACMPress,2009.
simple,ratherthananinherentlimitofourapproach.Tospecifythe KonstantinLäuferandMartinOdersky.Polymorphictypeinferenceandabstract
OutsideInapproach,thecaseruleinourdeclarativesystemshould datatypes.ACMTrans.Prog.Lang.Sys.,16(5):1411–1430,1994.
permitscrutinizinganexpressionifalltypesthatcanbesynthesized DaanLeijenandErikMeijer.Domainspecificembeddedcompilers.InUSENIX
forithaveexactlythesameequations, eveniftheydifferintheir Conf.Domain-SpecificLanguages(DSL’99),pages109–122,1999.
monotypeparts.Wethoughtsuchaspecisharderforprogrammers DaleMiller.Unificationunderamixedprefix.J.SymbolicComputation,14(4):
todevelopanintuitionforthansimplysayingthatascrutineemust 321–358,1992.
synthesizeauniquetype.However,thetechniqueweuse—higher- MartinOdersky,MatthiasZenger,andChristophZenger. Coloredlocaltype
inference.InPOPL,pages41–53,2001.
orderruleswithimplicationalpremiseslikeDeclSpineRecover—
Simon Peyton Jones, Dimitrios Vytiniotis, Stephanie Weirich, and Geoffrey
shouldworkforthiscase.
Washburn. Simpleunification-basedtypeinferenceforGADTs. InICFP,
Morerecently,GarrigueandRémy(2013)proposedambivalent
pages50–61,2006.
types, which are a way of deciding when it is safe to generalize
SimonPeytonJones,DimitriosVytiniotis,StephanieWeirich,andMarkShields.
the type of a function using GADTs. This idea is orthogonal to Practicaltypeinferenceforarbitrary-ranktypes.J.FunctionalProgramming,
our calculus, simply because we do no generalization at all: ev- 17(1):1–82,2007.
erypolymorphicfunctiontakesanannotation.However,Garrigue BrigittePientka.Atype-theoreticfoundationforprogrammingwithhigher-order
andRémy(2013)alsoemphasizetheimportanceofmonotonicity, abstractsyntaxandfirst-classsubstitutions. InPOPL,pages371–382,2008.
whichsaysthatsubstitutionshouldbestableundersubtyping,that BenjaminC.Pierce.TypesandProgrammingLanguages.MITPress,2002.
is,givingamoregeneral typeshould not causesubtyping tofail. BenjaminC.PierceandDavidN.Turner. Localtypeinference. ACMTrans.
Thisconditionissatisfiedbyourbidirectionalsystem. Prog.Lang.Sys.,22:1–44,2000.
Karachalias et al. (2015) developed a coverage algorithm for FrançoisPottierandYannRégis-Gianas.Stratifiedtypeinferenceforgeneralized
GADTs that depends on external constraint solving; we offer a algebraicdatatypes.InPOPL,pages232–244,2006.
moreself-containedbutstilllogically-motivatedapproach. PatrickRondon,MingKawaguchi,andRanjitJhala. Liquidtypes. InPLDI,
pages159–169,2008.
Extensions. To keep our formalization manageable, we left out PeterSchroeder-Heister. Definitionalreflectionandthecompletion. InExten-
sionsofLogicProgramming,LNCS,pages333–347.Springer,1994.
some features that would be desirable in practice. In particular,
VincentSimonetandFrançoisPottier. Aconstraint-basedapproachtoguarded
weneed(1)typeconstructorswhichtakeargumentsand(2)recur-
algebraicdatatypes. ACMTransactionsonProgrammingLanguagesand
sivetypes(Pierce2002,chapter 20).Theprimaryissuewithboth
Systems(TOPLAS),29(1):1,2007.
ofthesefeaturesisthattheyneedtopermitusingexistentialsand
DimitriosVytiniotis,SimonPeytonJones,andTomSchrijvers. Letshouldnot
other“large”typeconnectives,andoursystemseeminglyrelieson begeneralised. InWorkshoponTypesinLanguageDesignandImpl.(TLDI
monotypes (which cannot contain such connectives). Thislimita- ’10),pages39–50,2010.
tionshouldcreatenodifficultiesintypicalpractice,ifwetreatuser- Dimitrios Vytiniotis, Simon Peyton Jones, Tom Schrijvers,and Martin Sulz-
definedtypeconstructors,suchasList,asmonotypesandexpand mann. OutsideIn(X):Modular type inferencewith localassumptions. J.
thedefinitiononlyasneeded:whencheckinganexpressionagainst FunctionalProgramming,21(4–5):333–412,2011.
ausertypeconstructor,andwhendemandedbypatternmatching. KevinWatkins,IlianoCervesato,FrankPfenning,andDavidWalker.Aconcur-
rentlogicalframework:Thepropositionalfragment.InTypesforProofsand
Programs,pages355–377.SpringerLNCS3085,2004.
References HongweiXiandFrankPfenning.Dependenttypesinpracticalprogramming.In
POPL,pages214–227,1999.
AndreasAbel,ThierryCoquand,andPeterDybjer. Verifyingasemanticβη-
HongweiXi,ChiyanChen,andGangChen. Guardedrecursivedatatypecon-
conversion test for Martin-Löf type theory. In Mathematics of Program
structors.InPOPL,pages224–235,2003.
Construction(MPC’08),volume5133ofLNCS,pages29–56,2008.
10 2016/1/21