| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/Type_variable |
In type theory and programming languages, a type variable is a mathematical variable ranging over types. Even in programming languages that allow mutable variables, a type variable remains an abstraction, in the sense that it does not correspond to some memory locations.
Programming languages that support parametric polymorphism make use of universally quantified type variables. Languages that support existential types make use of existentially quantified type variables. For example, the following OCaml code defines a polymorphic identity function that has a universally quantified type, which is printed by the interpreter on the second line:
In mathematical notation, the type of the function id is interface List<E>{ voidadd(Ex); Iterator<E>iterator(); } interface Map<K,V>{ Vput(Kkey,Vvalue); Vget(Objectkey); }
In C++, template parameters must be declared with the template<typenameT=int> classBox{ private: Tvalue; public: explicitBox(Tvalue): value{value}{} // ... }; Box<double>b1(13.5); Box<>b2(5);// This is Box<int>
Some languages additionally offer a form of constraining these type parameters, called type classes. C++ offers concepts and extends and List<?>. This exists in Kotlin as well, but denoted with * instead. In Rust, a generic type parameter can be left unspecified for the compiler to interpret using _, called an "inferred type" (for example "}}'>Vec<_>).
In languages with dynamic typing, although type annotations may not be a core part of the language, some features may be provided to emulate them. For example, in Python, type variables can still be represented and specified using the class usingstd::array; template<typenameT,size_tM,size_tN> classMatrix{ private: array<array<T,N>,M>data; public: Matrix()=default; template<typenameSelf> constexprauto&&operator[](thisSelf&&self,size_trow,size_tcol){ returnstd::forward<Self>(self).data[row][col]; } };
| View original on Wikipedia | Back | FazBrowse Home |