Unit type

In the area of mathematical logic and computer science known as type theory, a unit type is a type that allows only one value (and thus can hold no information). The carrier (underlying set) associated with a unit type can be any singleton set. There is an isomorphism between any two such sets, so it is customary to talk about the unit type and ignore the details of its value. One may also regard the unit type as the type of 0-tuples, i.e. the product of no types.

The unit type is the terminal object in the category of types and typed functions. It should not be confused with the zero or empty type, which allows no values and is the initial object in this category. Similarly, the Boolean is the type with two values.

The unit type is implemented in most functional programming languages. The void type that is used in some imperative programming languages serves some of its functions, but because its carrier set is empty, it has some limitations (as detailed below).

In programming languages

Several computer programming languages provide a unit type to specify the result type of a function with the sole purpose of causing a side effect, and the argument type of a function that does not require arguments.

  • In Haskell, Rust, and Elm, the unit type is called () and its only value is also (), reflecting the 0-tuple interpretation.
  • In ML descendants (including OCaml, Standard ML, and F#), the type is called unit but the value is written as ().
  • In Scala, the unit type is called Unit and its only value is written as ().
  • In Common Lisp the type named NULL is a unit type which has one value, namely the symbol NIL. This should not be confused with the NIL type, which is the bottom type.
  • In Python, there is a type called NoneType which allows the single value of None. In Python's optional static type annotations, this type is represented as None.[1]
  • In Swift, the unit type is called Void or () and its only value is also (), reflecting the 0-tuple interpretation.
  • In Java, the unit type is called Void and its only value is null.
  • In Go, the unit type is written struct{} and its value is struct{}{}.
  • In PHP, the unit type is called null, which only value is NULL itself.
  • In JavaScript, both Null (its only value is null) and Undefined (its only value is undefined) are built-in unit types.
  • in Kotlin, Unit is a singleton with only one value: the Unit object.
  • In Ruby, nil is the only instance of the NilClass class.
  • In C++, the std::monostate unit type was added in C++17. Before that, it is possible to define a custom unit type using an empty struct such as struct empty{}.

Void type as unit type

In C, C++, C#, D, and PHP, void is used to designate a function that does not return anything useful, or a function that accepts no arguments. The unit type in C is conceptually similar to an empty struct, but a struct without members is not allowed in the C language specification (this is allowed in C++). Instead, 'void' is used in a manner that simulates some, but not all, of the properties of the unit type, as detailed below. Like most imperative languages, C allows functions that do not return a value; these are specified as having the void return type. Such functions are called procedures in other imperative languages like Pascal, where a syntactic distinction, instead of type-system distinction, is made between functions and procedures.

Difference in calling convention

The first notable difference between a true unit type and the void type is that the unit type may always be the type of the argument to a function, but the void type cannot be the type of an argument in C, despite the fact that it may appear as the sole argument in the list. This problem is best illustrated by the following program, which is a compile-time error in C:

void f(void) {}
void g(void) {}

int main(void)
{
  f(g()); // compile-time error here
  return 0;
}

This issue does not arise in most programming practice in C, because since the void type carries no information, it is useless to pass it anyway; but it may arise in generic programming, such as C++ templates, where void must be treated differently from other types. In C++ however, empty classes are allowed, so it is possible to implement a real unit type; the above example becomes compilable as:

class unit_type {};
const unit_type the_unit;

unit_type f(unit_type) { return the_unit; }
unit_type g(unit_type) { return the_unit; }

int main()
{
  f(g(the_unit));
  return 0;
}

(For brevity, we're not worried in the above example whether the_unit is really a singleton; see singleton pattern for details on that issue.)

Difference in storage

The second notable difference is that the void type is special and can never be stored in a record type, i.e. in a struct or a class in C/C++. In contrast, the unit type can be stored in records in functional programming languages, i.e. it can appear as the type of a field; the above implementation of the unit type in C++ can also be stored. While this may seem a useless feature, it does allow one for instance to elegantly implement a set as a map to the unit type; in the absence of a unit type, one can still implement a set this way by storing some dummy value of another type for each key.

In Generics

In Java Generics, type parameters must be reference types. The wrapper type Void is often used when a unit type parameter is needed. Although the Void type can never have any instances, it does have one value, null (like all other reference types), so it acts as a unit type. In practice, any other non-instantiable type, e.g. Math, can also be used for this purpose, since they also have exactly one value, null.

public static Void f(Void x) { return null; }
public static Void g(Void x) { return null; }

public static void main(String[] args)
{
    f(g(null));
}

Null type

Statically typed languages give a type to every possible expression. They need to associate a type to the null expression. A type will be defined for null and it will only have this value.

For example in D, it's possible to declare functions that may only return null:

typeof(null) returnThatSpecialThing(){
    return null;
}

null is the only value that typeof(null), a unit type, can have.

See also

  • Singleton pattern (where a particular class has only one instance, but narrowly-typed non-nullable references to it are usually not held by other classes)

Notes

  1. ^ van Rossum, Guido; Levkivskyi, Ivan. "PEP 483 - Using None". Python Enhancement Proposals. Python Software Foundation. Retrieved 2 March 2024.

References

Read other articles:

Bosanska banovinaБосанска бановинаBanat di Kerajaan Hungaria1154–1377 Coat of arms Perbahan wilayah BosniaSejarahSejarah • Didirikan 1154• Tvrtko I dimahkotai sebagai Raja Bosnia 1377 Didahului oleh Digantikan oleh Kadipaten Bosnia krjKerajaan Bosnia Sekarang bagian dari Bosnia dan Herzegovina Kroasia Montenegro Serbia Banat Bosnia (bahasa Bosnia: Bosanska banovina, banovina Bosna/Босанска бановина, бановина ...

 

 

Angkatan Udara dan Pertahanan Udara SerbiaРатно ваздухопловство и противваздухопловна одбрана Војске СрбијеRatno vazduhoplovstvo i protivvazduhoplovna odbrana Vojske SrbijeLambang Angkatan Udara SerbiaDibentuk19122006 (Formasi Terkini)Negara SerbiaTipe unitAngkatan udaraJumlah personel3.000 personel (estimasi 2021)Bagian dari Angkatan Bersenjata SerbiaMarkasZemun, BeogradMotoЗа слободу и част Отаџбине (Za sl...

 

 

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Januari 2023. Acestrorhynchus isalineae Status konservasiRisiko rendahIUCN134656931 TaksonomiKerajaanAnimaliaFilumChordataKelasActinopteriOrdoCharaciformesFamiliAcestrorhynchidaeGenusAcestrorhynchusSpesiesAcestrorhynchus isalineae Naércio Aquino de Menezes dan Jacq...

Ini adalah nama Batak Toba, marganya adalah Panjaitan. Nurmala Kartini SjahrirDr. Nurmala Kartini Sjahrir (nama lahir: Kartini boru Panjaitan; lahir 1 Februari 1950), adalah seorang doktor di bidang antropologi, ketua Asosiasi Antropologi Indonesia, mantan ketua umum Partai Perjuangan Indonesia Baru, dan istri (alm) Dr. Sjahrir, ibu Pandu Patria Sjahrir serta adik dari Luhut Binsar Panjaitan.[1] Kehidupan pribadi Anak dari pasangan (alm) Bonar Pandjaitan (Osi Paulina) dan (alm) Siti F...

 

 

German Catholic prelate (1472–1537) This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (April 2014) (Learn how and when to remove this template message) His EminenceNikolaus von SchönbergArchbishop of CapuaArchdioceseCapuaAppointed12 September 1520Term ended28 April 1536PredecessorIppolito d'EsteSuccessorTommaso CaraccioloOther post(s)Cardinal-Priest of San Si...

 

 

4e cérémonie des Saturn Awards Saturn Awards Organisée par Academy of Science Fiction, Fantasy and Horror Films Détails Date 15 janvier 1977 Lieu États-Unis Site web http://www.saturnawards.org/ Résumé Meilleur film de science-fiction L'Âge de cristal Meilleur film fantastique Les Gaspards Meilleur film d'horreur Trauma Chronologie 3e cérémonie des Saturn Awards 5e cérémonie des Saturn Awards modifier  La 4e cérémonie des Saturn Awards, récompensant le...

American college basketball rivalry Illinois–Iowa men's basketball rivalry Illinois Fighting Illini Iowa Hawkeyes SportCollege basketballFirst meetingFebruary 14, 1908Iowa 46 – Illinois 36Latest meetingMarch 10, 2024Illinois 73 – Iowa 61StadiumsState Farm Center, Carver–Hawkeye ArenaStatisticsMeetings total169All-time seriesIllinois leads, 92–77Largest victoryIllinois, 118–85 (1990)Longest win streakIllinois, 7 (2008–2012)Current win streakIllinois, 2 (2024–present) 100km62mil...

 

 

Sporting event delegationVietnam at theParalympicsIPC codeVIENPCVietnam Paralympic AssociationOfficials5Medals Gold 1 Silver 2 Bronze 2 Total 5 Summer appearances2000200420082012201620202024 Vietnam made its Paralympic Games debut at the 2000 Summer Paralympics in Sydney, with just two competitors: Nguyen Thi Xuan Anh in the women's 800m sprint (T54 category) in athletics, and Truong Cong Hung in the men's up to 52 kg category in powerlifting. The country's delegation in 2004 was slightl...

 

 

Voce principale: Molfetta Sportiva. Molfetta SportivaStagione 1993-1994Sport calcio Squadra Molfetta Allenatore Giuseppe Raffaele Presidente Raffaele Belgiovine Serie C210º posto nel girone C. Maggiori presenzeCampionato: Colonna, Roca (32) Miglior marcatoreCampionato: Micciola (10) 1992-1993 1994-1995 Si invita a seguire il modello di voce Questa voce raccoglie le informazioni riguardanti la Molfetta Sportiva nelle competizioni ufficiali della stagione 1993-1994. Rosa N. Ruolo Calciat...

2018 American superhero drama television series Black LightningGenre Action Crime drama Science fiction Superhero Based onBlack Lightningby Tony IsabellaTrevor Von EedenDeveloped bySalim AkilStarring Cress Williams China Anne McClain Nafessa Williams Christine Adams Marvin Krondon Jones III Damon Gupton James Remar Jordan Calloway Chantal Thuy Opening themeBlack Lightning by GodhollyComposerKurt FarquharCountry of originUnited StatesOriginal languageEnglishNo. of seasons4No. of episodes58 (li...

 

 

17th-century French dramatist (1639–1699) For other people named Jean Racine, see Jean Racine (disambiguation). Racine redirects here. For other uses, see Racine (disambiguation). This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (April 2016) (Learn how and when to remove this message) Jean RacinePortrait of RacineBornJean-Baptiste Racine(1639-12-21)21 Decembe...

 

 

Music genre For the hip hop subgenre, see Nerdcore. NintendocoreOther namesNintendo rock[1][2]nerdcore[3][4][5][6]video game rock[7]video game metal[8]8-bit metalcore[9]Stylistic originsChiptunehardcore punkvideo game musicheavy metalpost-hardcoremetalcoreextreme metalCultural originsEarly 2000s, United StatesTypical instrumentsElectronicelectric guitarsynthesizerpersonal computerdrumsOther topicsBandsnerdcorecrunkcoredig...

此条目序言章节没有充分总结全文内容要点。 (2019年3月21日)请考虑扩充序言,清晰概述条目所有重點。请在条目的讨论页讨论此问题。 哈萨克斯坦總統哈薩克總統旗現任Қасым-Жомарт Кемелұлы Тоқаев卡瑟姆若马尔特·托卡耶夫自2019年3月20日在任任期7年首任努尔苏丹·纳扎尔巴耶夫设立1990年4月24日(哈薩克蘇維埃社會主義共和國總統) 哈萨克斯坦 哈萨克斯坦政府...

 

 

Canton of the Federation of Bosnia and Herzegovina Canton in Federation of Bosnia and Herzegovina, Bosnia and HerzegovinaZenica-Doboj Canton Zeničko-dobojski kanton[1]Zeničko-dobojski kanton / Зеничко-добојски кантон (Bosnian)Zeničko-dobojska županija (Croatian)Зеничко-добојски кантон / Zeničko-dobojski kanton (Serbian)Canton FlagCoat of armsLocation of the Zenica-Doboj CantonCoordinates: 44°14′N 18°12′E / 44.233°N ...

 

 

2016 single by Keith UrbanBlue Ain't Your ColorSingle by Keith Urbanfrom the album Ripcord Released8 August 2016 (2016-08-08)Recorded2016GenreCountry bluescountry popLength3:50LabelHit RedCapitol NashvilleSongwriter(s)Steven Lee OlsenHillary LindseyClint LagerbergProducer(s)Dann HuffKeith UrbanKeith Urban singles chronology Wasted Time (2016) Blue Ain't Your Color (2016) The Fighter (2017) Blue Ain't Your Color is a song recorded by New Zealand-born Australian country music sin...

2016 studio album by Theatres des VampiresCandylandStudio album by Theatres des VampiresReleased14 October 2016GenreGothic metalLength39:58LabelScarlet RecordsProducerChristian IceTheatres des Vampires chronology Moonlight Waltz Tour 2011(2012) Candyland(2016) Professional ratingsReview scoresSourceRatingNew Noise Magazine linkEternal Terror4/6 link Candyland is the tenth studio album by Italian gothic metal band Theatres des Vampires, released through Scarlet Records on 14 October 20...

 

 

Noisy-le-SecNegaraPrancisArondisemenBobignyAntarkomunebelum ada pada 2005 Noisy-le-Sec merupakan sebuah komune di pinggiran timur Paris, di Seine-Saint-Denis dikenal sebagai le neuf trois (sembilan tiga), dari nomor administratif resmi departemen, 93. Terletak 8.6 km (5.3 mil) dari pusat kota Paris. Angkutan Noisy-le-Sec dilayani oleh stasiun Noisy-le-Sec pada RER jalur E Paris. Pranala luar Official website Diarsipkan 2008-07-05 di Wayback Machine. (in French) lbsKomune di aire urbaine ...

 

 

Music genre Dancehall popStylistic originsDancehalldance-popR&Breggaeroots reggaerapreggaetonCultural originsEarly 2000s, JamaicaUnited StatesCanadaUnited Kingdom Dancehall pop is a sub-genre of the Jamaican genre dancehall that originated in the early 2000s.[1] Developing from the sounds of reggae, dancehall pop is characteristically different in its fusion with western pop music and digital music production.[2] Dancehall pop is also different from dancehall in that most ...

Member of the EU Commission European Commissionerfor CompetitionFlag of the EUIncumbentMargrethe Vestagersince 1 November 2014Member ofthe European CommissionReports toPresident of the European CommissionTerm length5 yearsFormation7 January 1958; 66 years ago (1958-01-07)First holderHans von der Groeben This article is part of a series onPolitics of the European Union Member states (27) Austria Belgium Bulgaria Croatia Cyprus Czech Republic...

 

 

Dewan Perwakilan Rakyat Kabupaten Nagan RayaDewan Perwakilan Rakyat Kabupaten Nagan Raya 2019-2024JenisJenisUnikameral Jangka waktu5 tahunSejarahSesi baru dimulai2 September 2019PimpinanKetuaJonniadi, S.E. (Demokrat) sejak 25 Oktober 2019 Wakil Ketua IDedy Irmayanda, S.P., M.M. (Golkar) sejak 25 Oktober 2019 Wakil Ketua IIPuji Hartini, S.T., M.M. (Partai SIRA) sejak 25 Oktober 2019 KomposisiAnggota25Partai & kursi   NasDem (2)   PKB (1)   Demokrat...