Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Unit type

From Wikipedia, the free encyclopedia
Type that allows only one value
This article is about the notion used incomputer programming andtype theory. For types of measurement units, seeUnits of measurement. For other uses, seeUnit (disambiguation).

In the area ofmathematical logic andcomputer science known astype theory, aunit type is atype that allows only one value (and thus can hold no information). The carrier (underlying set) associated with a unit type can be anysingleton set. There is anisomorphism between any two such sets, so it is customary to talk aboutthe unit type and ignore the details of its value. One may also regard the unit type as the type of 0-tuples, i.e. theproduct of no types.

The unit type is theterminal object in thecategory of types and typed functions. It should not be confused with thezero orempty type, which allowsno values and is theinitial object in this category. Similarly, theBoolean is the type withtwo values.

The unit type is implemented in mostfunctional programming languages. Thevoid 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

[edit]

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

  • InHaskell,Rust, andElm, the unit type is called() and its only value is also(), reflecting the 0-tuple interpretation.
  • InML descendants (includingOCaml,Standard ML, andF#), the type is calledunit but the value is written as().
  • InScala, the unit type is calledUnit and its only value is written as().
  • InCommon Lisp the type namedNULL is a unit type which has one value, namely the symbolNIL. This should not be confused with theNILtype, which is thebottom type.
  • InPython, there is a type calledNoneType which allows the single value ofNone. In Python's optional static type annotations, this type is represented asNone.[1]
  • InSwift, the unit type is calledVoid or() and its only value is also(), reflecting the 0-tuple interpretation.
  • InJava, the unit type is calledVoid and its only value isnull. It cannot be instantiated. It is used ingenerics for denoting return types ofvoid.
  • InGo, the unit type is writtenstruct{} and its value isstruct{}{}.
  • InPHP, the unit type is called null, which only value is NULL itself.
  • InJavaScript, bothNull (its only value isnull) andUndefined (its only value isundefined) are built-in unit types.
  • inKotlin,Unit is a singleton with only one value: theUnit object.
  • InRuby,nil is the only instance of theNilClass class.
  • InC++, thestd::monostate unit type was added inC++17. Before that, it is possible to define a custom unit type using an empty struct such asstruct Empty {}.
  • InDart, bothNull and the empty record ((), since Dart 3) have a single possible value, respectively,null and().

Void type as unit type

[edit]

InC,C++,C#,D, andPHP,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 emptystruct, 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 likePascal, where a syntactic distinction, instead of type-system distinction, is made between functions and procedures.

Difference in calling convention

[edit]

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:

voidf(void){}voidg(void){}intmain(void){f(g());// compile-time error herereturn0;}

This issue does not arise in most programming practice in C, because since thevoid type carries no information, it is useless to pass it anyway; but it may arise ingeneric programming, such as C++templates, wherevoid 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:

classUnitType{};constexprUnitTypeUNIT;UnitTypef(UnitType)noexcept{returnUNIT;}UnitTypeg(UnitType)noexcept{returnUNIT;}intmain(){f(g(UNIT));return0;}

For brevity,UNIT is not implemented as asingleton; seesingleton pattern for further explanation on singleton units.

Difference in storage

[edit]

The second notable difference is that the void type is special and can never be stored in arecord 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 aset as amap 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

[edit]

In Java Generics, type parameters must be reference types. The wrapper typeVoid is often used when a unit type parameter is needed.

importjava.util.concurrent.*;ExecutorServiceexecutorService=Executors.newFixedThreadPool(2);CompletableFuture<Void>future=CompletableFuture.runAsync(()->{try{// Simulate some workSystem.out.println("Task started.");Thread.sleep(2000);// Simulate a 2-second taskSystem.out.println("Task completed.");}catch(InterruptedExceptione){System.err.println("Task was interrupted.");}},executorService);

Although theVoid 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.

publicstaticVoidf(Voidx){returnnull;}publicstaticVoidg(Voidx){returnnull;}publicstaticvoidmain(String[]args){f(g(null));}

Null type

[edit]

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

For example in D, it is possible to declare functions that may only returnnull (in fact,typeof(null) isvoid):

typeof(null)returnThatSpecialThing(){returnnull;}voidwriteTypeOfNull(){writeln(typeof(null));// prints: void}

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

See also

[edit]
  • Any type
  • 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

[edit]
  1. ^van Rossum, Guido; Levkivskyi, Ivan."PEP 483 - Using None".Python Enhancement Proposals. Python Software Foundation. Retrieved2 March 2024.

References

[edit]
Uninterpreted
Numeric
Pointer
Text
Composite
Other
Related
topics
Retrieved from "https://en.wikipedia.org/w/index.php?title=Unit_type&oldid=1314366104"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp