In type theory, an intersection type can be allocated to values that can be assigned both the type and the type . This value can be given the intersection type in an intersection type system.[1]
Generally, if the ranges of values of two types overlap, then a value belonging to the intersection of the two ranges can be assigned the intersection type of these two types. Such a value can be safely passed as argument to functions expecting either of the two types.
For example, in Java the class Boolean implements both the Serializable and the Comparable interfaces. Therefore, an object of type Boolean can be safely passed to functions expecting an argument of type Serializable and to functions expecting an argument of type Comparable.
Intersection types are composite data types. Similar to product types, they are used to assign several types to an object.
However, product types are assigned to tuples, so that each tuple element is assigned a particular product type component.
In comparison, underlying objects of intersection types are not necessarily composite. A restricted form of intersection types are refinement types.
Intersection types are useful for describing overloaded functions.[2] For example, if number=>number is the type of function taking a number as an argument and returning a number, and string=>string is the type of function taking a string as an argument and returning a string, then the intersection of these two types can be used to describe (overloaded) functions that do one or the other, based on what type of input they are given.
The type theoretic study of intersection types is referred to as the intersection type discipline.[3]
Remarkably, program termination can be precisely characterized using intersection types.[4]
TypeScript example
TypeScript supports intersection types,[5] improving expressiveness of the type system and reducing potential class hierarchy size, demonstrated as follows.
The following program code defines the classes Chicken, Cow, and RandomNumberGenerator that each have a method produce returning an object of either type Egg, Milk, or number.
Additionally, the functions eatEgg and drinkMilk require arguments of type Egg and Milk, respectively.
classEgg{privatekind:"Egg"}classMilk{privatekind:"Milk"}// produces eggsclassChicken{produce(){returnnewEgg();}}// produces milkclassCow{produce(){returnnewMilk();}}// produces a random numberclassRandomNumberGenerator{produce(){returnMath.random();}}// requires an eggfunctioneatEgg(egg:Egg){return"I ate an egg.";}// requires milkfunctiondrinkMilk(milk:Milk){return"I drank some milk.";}
The following program code defines the ad hoc polymorphic function animalToFood that invokes the member function produce of the given object animal.
The function animalToFood has two type annotations, namely ((_:Chicken)=>Egg) and ((_:Cow)=>Milk), connected via the intersection type constructor &.
Specifically, animalToFood when applied to an argument of type Chicken returns an object of type Egg, and when applied to an argument of type Cow returns an object of type Milk.
Ideally, animalToFood should not be applicable to any object having (possibly by chance) a produce method.
// given a chicken, produces an egg; given a cow, produces milkletanimalToFood:((_:Chicken)=>Egg)&((_:Cow)=>Milk)=function(animal:any){returnanimal.produce();};
Finally, the following program code demonstrates type safe use of the above definitions.
varchicken=newChicken();varcow=newCow();varrandomNumberGenerator=newRandomNumberGenerator();console.log(chicken.produce());// Egg { }console.log(cow.produce());// Milk { }console.log(randomNumberGenerator.produce());//0.2626353555444987console.log(animalToFood(chicken));// Egg { }console.log(animalToFood(cow));// Milk { }//console.log(animalToFood(randomNumberGenerator)); // ERROR: Argument of type 'RandomNumberGenerator' is not assignable to parameter of type 'Cow'console.log(eatEgg(animalToFood(chicken)));// I ate an egg.//console.log(eatEgg(animalToFood(cow))); // ERROR: Argument of type 'Milk' is not assignable to parameter of type 'Egg'console.log(drinkMilk(animalToFood(cow)));// I drank some milk.//console.log(drinkMilk(animalToFood(chicken))); // ERROR: Argument of type 'Egg' is not assignable to parameter of type 'Milk'
The above program code has the following properties:
Lines 1–3 create objects chicken, cow, and randomNumberGenerator of their respective type.
Lines 5–7 print for the previously created objects the respective results (provided as comments) when invoking produce.
Line 9 (resp. 10) demonstrates type safe use of the method animalToFood applied to chicken (resp. cow).
Line 11, if uncommented, would result in a type error at compile time. Although the implementation of animalToFood could invoke the produce method of randomNumberGenerator, the type annotation of animalToFood disallows it. This is in accordance with the intended meaning of animalToFood.
Line 13 (resp. 15) demonstrates that applying animalToFood to chicken (resp. cow) results in an object of type Egg (resp. Milk).
Line 14 (resp. 16) demonstrates that applying animalToFood to cow (resp. chicken) does not result in an object of type Egg (resp. Milk). Therefore, if uncommented, line 14 (resp. 16) would result in a type error at compile time.
Comparison to inheritance
The above minimalist example can be realized using inheritance, for instance by deriving the classes Chicken and Cow from a base class Animal.
However, in a larger setting, this could be disadvantageous.
Introducing new classes into a class hierarchy is not necessarily justified for cross-cutting concerns, or maybe outright impossible, for example when using an external library.
Imaginably, the above example could be extended with the following classes:
a class Horse that does not have a produce method;
a class Sheep that has a produce method returning Wool;
a class Pig that has a produce method, which can be used only once, returning Meat.
This may require additional classes (or interfaces) specifying whether a produce method is available, whether the produce method returns food, and whether the produce method can be used repeatedly.
Overall, this may pollute the class hierarchy.
Comparison to duck typing
The above minimalist example already shows that duck typing is less suited to realize the given scenario.
While the class RandomNumberGenerator contains a produce method, the object randomNumberGenerator should not be a valid argument for animalToFood.
The above example can be realized using duck typing, for instance by introducing a new field argumentForAnimalToFood to the classes Chicken and Cow signifying that objects of corresponding type are valid arguments for animalToFood.
However, this would not only increase the size of the respective classes (especially with the introduction of more methods similar to animalToFood), but is also a non-local approach with respect to animalToFood.
Comparison to function overloading
The above example can be realized using function overloading, for instance by implementing two methods animalToFood(animal:Chicken):Egg and animalToFood(animal:Cow):Milk.
In TypeScript, such a solution is almost identical to the provided example.
Other programming languages, such as Java, require distinct implementations of the overloaded method.
This may lead to either code duplication or boilerplate code.
Comparison to the visitor pattern
The above example can be realized using the visitor pattern.
It would require each animal class to implement an accept method accepting an object implementing the interface AnimalVisitor (adding non-local boilerplate code).
The function animalToFood would be realized as the visit method of an implementation of AnimalVisitor.
Unfortunately, the connection between the input type (Chicken or Cow) and the result type (Egg or Milk) would be difficult to represent.
Limitations
On the one hand, intersection types can be used to locally annotate different types to a function without introducing new classes (or interfaces) to the class hierarchy.
On the other hand, this approach requires all possible argument types and result types to be specified explicitly.
If the behavior of a function can be specified precisely by either a unified interface, parametric polymorphism, or duck typing, then the verbose nature of intersection types is unfavorable.
Therefore, intersection types should be considered complementary to existing specification methods.
Dependent intersection type
A dependent intersection type, denoted , is a dependent type in which the type may depend on the term variable .[6]
In particular, if a term has the dependent intersection type , then the term has both the type and the type , where is the type which results from replacing all occurrences of the term variable in by the term .
Scala example
Scala supports type declarations [7] as object members. This allows a type of an object member to depend on the value of another member, which is called a path-dependent type.[8]
For example, the following program text defines a Scala trait Witness, which can be used to implement the singleton pattern.[9]
traitWitness{typeTvalvalue:T{}}
The above trait Witness declares the member T, which can be assigned a type as its value, and the member value, which can be assigned a value of type T.
The following program text defines an object booleanWitness as instance of the above trait Witness.
The object booleanWitness defines the type T as Boolean and the value value as true.
For example, executing System.out.println(booleanWitness.value) prints true on the console.
Let be the type (specifically, a record type) of objects having the member of type .
In the above example, the object booleanWitness can be assigned the dependent intersection type .
The reasoning is as follows. The object booleanWitness has the member T that is assigned the type Boolean as its value.
Since Boolean is a type, the object booleanWitness has the type .
Additionally, the object booleanWitness has the member value that is assigned the value true of type Boolean.
Since the value of booleanWitness.T is Boolean, the object booleanWitness has the type .
Overall, the object booleanWitness has the intersection type .
Therefore, presenting self-reference as dependency, the object booleanWitness has the dependent intersection type .
Alternatively, the above minimalistic example can be described using dependent record types.[10]
In comparison to dependent intersection types, dependent record types constitute a strictly more specialized type theoretic concept.[6]
Intersection of a type family
An intersection of a type family, denoted , is a dependent type in which the type may depend on the term variable . In particular, if a term has the type , then for each term of type , the term has the type . This notion is also called implicit Pi type,[11] observing that the argument is not kept at term level.
Additionally, generic type parameters can have constraints that require their (monomorphized) type-arguments to implement multiple interfaces, whereupon the runtime type represented by the generic type parameter becomes an intersection-type of all listed interfaces.
^ abKopylov, Alexei (2003). "Dependent intersection: A new way of defining records in type theory". 18th IEEE Symposium on Logic in Computer Science. LICS 2003. IEEE Computer Society. pp. 86–95. CiteSeerX10.1.1.89.4223. doi:10.1109/LICS.2003.1210048.
^Pollack, Robert (2000). "Dependently typed records for representing mathematical structure". Theorem Proving in Higher Order Logics, 13th International Conference. TPHOLs 2000. Springer. pp. 462–479. doi:10.1007/3-540-44659-1_29.
Mariko ShinodaInformasi latar belakangNama lainMariko-sama (麻里子様code: ja is deprecated )Maririn (まりりんcode: ja is deprecated )Lahir11 Maret 1986 (umur 38)AsalMaebaru, Fukuoka, JepangGenreJ-popPekerjaanPenyanyi, pemeran, tarento, peragawati, seiyuTahun aktif2006 - sekarangArtis terkaitAKB48 Mariko Shinoda (篠田 麻里子code: ja is deprecated , Shinoda Mariko, lahir 11 Maret 1986) atau yang akrab dipanggil Mariko-sama atau Maririn, adalah peragawati, pemeran, seiyū dan t...
Penjumlahan beralih ke halaman ini. Untuk kegunaan lain, lihat Penjumlahan (disambiguasi). Operasi aritmetikalbs Penambahan (+) suku + suku yang ditambah + penambah tinambah + penambah } = {\displaystyle \scriptstyle \left.{\begin{matrix}\scriptstyle {\text{suku}}\,+\,{\text{suku}}\\\scriptstyle {\text{yang ditambah}}\,+\,{\text{penambah}}\\\scriptstyle {\text{tinambah}}\,+\,{\text{penambah}}\end{matrix}}\right\}\,=\,} jumlah {\displaystyle \scriptstyle {\text{jumlah}}} Pengurangan (−) suku...
العلاقات البحرينية الموزمبيقية البحرين موزمبيق البحرين موزمبيق تعديل مصدري - تعديل العلاقات البحرينية الموزمبيقية هي العلاقات الثنائية التي تجمع بين البحرين وموزمبيق.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: و�...
Bridge in New Hampshire and Norwich, VermontLedyard BridgeCoordinates43°42′13″N 72°17′59″W / 43.70361°N 72.29972°W / 43.70361; -72.29972CarriesVermont Route 10A,New Hampshire Route 10A,Appalachian TrailCrossesConnecticut RiverLocaleHanover, New Hampshire and Norwich, VermontMaintained byNew Hampshire Department of TransportationCharacteristicsDesignBeam bridge, originally a covered bridgeHistoryConstruction start1998Opened1859, 2000Closed1935[1]Loca...
Untuk penggunaan emotikon di Wikipedia, lihat Templat:Emosikon. Artikel ini sudah memiliki daftar referensi, bacaan terkait, atau pranala luar, tetapi sumbernya belum jelas karena belum menyertakan kutipan pada kalimat. Mohon tingkatkan kualitas artikel ini dengan memasukkan rujukan yang lebih mendetail bila perlu. (Pelajari cara dan kapan saatnya untuk menghapus pesan templat ini) artikel ini perlu dirapikan agar memenuhi standar Wikipedia. Tidak ada alasan yang diberikan. Silakan kembangkan...
This template was considered for deletion on 2006 May 20. The result of the discussion was keep. Anti-war Template‑classThis template is within the scope of WikiProject Anti-war, a collaborative effort to improve the coverage of the anti-war movement on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.Anti-warWikipedia:WikiProject Anti-warTemplate:WikiProject Anti-warAnti-war articlesTemplateThis templ...
Eastern Catholic Church Slovak Greek Catholic ChurchCathedral of St. John the Baptist in PrešovClassificationEastern CatholicOrientationEastern ChristianityTheologyCatholic theologyPolityEpiscopalGovernanceMetropolitanatePopeFrancisPrimateJonáš MaximAssociationsCongregation for the Oriental ChurchesRegionSlovakiaLiturgyByzantine RiteHeadquartersPrešov, SlovakiaMembers207,320[1]Other name(s)Slovak Byzantine Catholic Church Part of a series onParticular churches sui iurisof the Cath...
Koleksi Reinhart yang dihimpun oleh Oskar Reinhart sekarang disimpan di sebuah museum di rumah lamanya, Am Römerholz di Winterthur, Kanton Zurich, Swiss, serta Museum Oskar Reinhart di pusat Winterthur. Museum tersebut masuk dalam Konfederasi Swiss, Kantor Budaya Federal (Bundesamt für Kultur, Bern). Koleksi tersebut terdiri dari lukisan-lukisan karya para seniman yang meliputi Pierre-Auguste Renoir, Eduard Manet, Paul Cézanne, Eugène Delacroix, Théodore Géricault, Camille Corot, Honor...
Structure of the French Resistance This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Departmental Committee of Liberation – news · newspapers · books · scholar...
University University of Helmstedt in the 17th century The Juleum in Helmstedt, historical great auditorium of the University, built in 1592 in Weser renaissance architecture The University of Helmstedt (German: Universität Helmstedt; official Latin name: Academia Julia, Julius University) was a university in Helmstedt in the Duchy of Brunswick-Wolfenbüttel that existed from 1576 until 1810. History Founded by and named after Duke Julius of Brunswick-Wolfenbüttel on 15 October 1576, the fi...
Shipping route around the Cape of Good Hope This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Cape Route – news · newspapers · books · scholar · JSTOR (March 2021) (Learn how and when to remove this message) Ptolemy's world map implied that Africa was part of an outer landmass, separating the Atlantic from the...
A major contributor to this article appears to have a close connection with its subject. It may require cleanup to comply with Wikipedia's content policies, particularly neutral point of view. Please discuss further on the talk page. (December 2016) (Learn how and when to remove this message) Exterior view of the church The Church of the Apostles is an American evangelical church located in the Buckhead neighborhood of Atlanta, Georgia. The church was founded in 1987 by Michael Youssef, who ...
Intravenous medication used in anesthesia Not to be confused with Propanol. PropofolClinical dataTrade namesDiprivan, others[1]AHFS/Drugs.comMonographLicense data US DailyMed: Propofol Pregnancycategory AU: C DependenceliabilityPhysical: Very High Psychological: no dataAddictionliabilityModerate[2]Routes ofadministrationIntravenousDrug classGABA receptor agonist;sedative;hypnoticATC codeN01AX10 (WHO) Legal statusLegal status AU: S4 (Prescription o...
Historical bronze statue in Rome Location of the Colossus (in red near the center) in a map of Rome The Colossus of Nero (Colossus Neronis) was a 30-metre (98 ft) bronze statue that the Emperor Nero (37–68 AD) created in the vestibule of his Domus Aurea, the imperial villa complex which spanned a large area from the north side of the Palatine Hill, across the Velian ridge to the Esquiline Hill in Rome. It was modified by Nero's successors into a statue of the sun god Sol. The statue wa...
1962 studio album by Dean MartinFrench StyleStudio album by Dean MartinReleased1962RecordedFebruary 1962GenreTraditional pop, lounge music[1]Length35:36LabelRepriseDean Martin chronology Dino: Italian Love Songs(1962) French Style(1962) Cha Cha de Amor(1962) French Style is Dean Martin's first LP for Reprise Records. Recorded during February 1962, it features French-themed popular songs and chansons arranged by Neal Hefti. Among them C'est si bon, which frequently appears on D...
Questa voce sull'argomento ciclisti spagnoli è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Eukene LarrarteNazionalità Spagna Ciclismo SpecialitàPista, strada Squadra Bizkaia-Durango CarrieraSquadre di club 2020Eneicat-RBH Global2021Laboral Kutxa-Fundación Euskadi2022- Bizkaia-Durango Nazionale 2018- Spagna(pista)2021- Spagna(strada) Palmarès Europei su pista ArgentoGrenchen 2023Scratch Statistiche aggiornate all'8 febbraio 2...
Не следует путать с Парламентской ассамблеей Совета Европы — организации 46 государств Европы. Европейский парламент на официальных языках: Английский: European Parliament Болгарский: Европейски парламент Венгерский: Európai Parlament Греческий: Ευρωπαϊκό Κοινοβούλιο Датский: Europa-Par...
Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Certaines informations figurant dans cet article ou cette section devraient être mieux reliées aux sources mentionnées dans les sections « Bibliographie », « Sources » ou « Liens externes » (septembre 2013). Vous pouvez améliorer la vérifiabilité en associant ces informations à des références à l'aide d'appels de notes. Statue représentant le monstre du Loch Ness dan...