1. 變型(variance)
很多編程語言支持子類型(subtyping)慧脱。
例如殖氏,如果Cat
是Animal
的子類型附井,
那么Cat
類型的表達式译秦,就可以被用于任何Animial
類型表達式可以出現(xiàn)的地方。
變型(variance)指的是劣纲,復雜類型之間的子類型關(guān)系逢捺,是否會保持其元素類型之間的子類型關(guān)系。
Within the type system of a programming language, a typing rule or a type constructor is:
(1) covariant, if it preserves the ordering of types (≤), which orders types from more specific to more generic;
(2) contravariant, if it reverses this ordering;
(3) bivariant, if both of these apply (i.e., both I<A> ≤ I<B> and I<B> ≤ I<A> at the same time);
(4) invariant or nonvariant, if neither of these applies.
2. 協(xié)變類型構(gòu)造器(covariant type constructor)
協(xié)變類型構(gòu)造器癞季,保持了參數(shù)類型之間的子類型關(guān)系劫瞳,
例如,[Cat]
是[Animal]
的子類型绷柒,其中Cat
是Animal
的子類型志于,
因此,類型構(gòu)造器[]
是協(xié)變的废睦。
3. 逆變類型構(gòu)造器(contravariant type constructor)
一般而言伺绽,函數(shù)f :: S1 → S2
可以安全替換函數(shù)g :: T1 → T2
,
如果與函數(shù)g
相比嗜湃,函數(shù)f
接受更一般的參數(shù)類型奈应,返回更特化的結(jié)果類型。
函數(shù)之間的子類型關(guān)系由下式確定购披,
S1 → S2 ≦ T1 → T2杖挣,如果T1 ≦ S1且S2 ≦ T2
逆變類型構(gòu)造器,倒轉(zhuǎn)了參數(shù)類型之間的子類型關(guān)系刚陡,
例如惩妇,Cat
是Animal
的子類型,但是Animal -> String
是Cat -> String
的子類型橘荠,
因此屿附,類型構(gòu)造器(-> String)
是逆變的。
參考
Haxe Manual: Type System - Variance
Wikipedia: Covariance and contravariance
Microsoft Docs: Covariance and Contravariance in Generics