Generic programming: Difference between revisions

Content deleted Content added
WP:REFerence WP:CITation parameters: adds, fills, reorders, respaces, update-standardizes. WP:LINKs: needless WP:PIPEs > WP:NOPIPEs, update-standardizes, underscores > spaces, adds. WP:COPYEDITs WP:EoS: WP:TERSE, clarify. Template:Quote, Template:Main article updates > Template:Blockquote, Template:Main. MOS:FIRSTABBReviation define before WP:ABBR. Cut needless carriage return in paragraphs. WP:SLASHes > comma+space.
Line 3:
{{Use dmy dates|date=November 2020}}
{{Programming paradigms}}
'''Generic programming''' is a style of [[computer programming]] in which [[algorithm]]s are written in terms of [[data type|types]]s ''to-be-specified-later'' that are then ''instantiated'' when needed for specific types provided as [[parameter (computer programming)|parameters]]. This approach, pioneered by the [[ML (programming language)|ML]] programming language in 1973,<ref name="Lee2008">
{{cite book
| last=Lee
Line 12:
| publisher=Springer Science & Business Media
| isbn=978-0-387-79422-8
| pages=9–10}}</ref><ref>{{cite conference |last1=Milner |first1=R. |last2=Morris |first2=L. |last3=Newey |first3=M. |year=1975 |title=A Logic for Computable Functions with Reflexive and Polymorphic Types |author1=Milner, R. |author2=Morris, L. |author3=Newey, M. | book-title=Proceedings of the Conference on Proving and Improving Programs | year=1975}}</ref> permits writing common [[function (computer science)|functions]] or [[type (computer science)|type]]s that differ only in the set of types on which they operate when used, thus reducing [[duplicate code|duplication]].
 
Generics was introduced to the main-stream programming with Ada in 1977 and then with ''[[Template (C++)|templatetemplates]]s'' in [[C++]] it became part of the repertoire of professional library design. The techniques were further improved and ''parameterized types'' were introduced in the influential 1994 book ''[[Design Patterns (book)|Design Patterns]]''.<ref name="GoF">
{{cite book |last1 = Gamma
|first1 = Erich
|last2 = Helm
|first2 = Richard
|last3 = Johnson
|first3 = Ralph
|last4 = Vlissides
|first4 = John
|date = 1994
|title = Design Patterns
|date = 1994
|publisher = Addison-Wesley
|isbn = 0-201-63361-2
|url-access = registration
|url = https://archive.org/details/designpatternsel00gamm
}}</ref>
 
New techniques were introduced by [[Andrei Alexandrescu]] in his 2001 book, [[Modern C++ Design|Modern C++ Design]]: Generic Programming and Design Patterns Applied]] book in 2001. Subsequently, [[D (programming language)|D]] implemented the same ideas.
 
Such software entities are known as ''generics'' in [[Ada (programming language)|Ada]], [[C Sharp (programming language)|C#]], [[Delphi (programming languagesoftware)|Delphi]], [[Eiffel (programming language)|Eiffel]], [[F Sharp (programming language)|F#]], [[Java (programming language)|Java]], [[Nim_Nim (programming_languageprogramming language)|Nim]], [[Python (programming language)|Python]], [[Go (programming language)|Go]], [[Rust (programming language)|Rust]], [[Swift (programming language)|Swift]], [[TypeScript]], and [[Visual Basic .NET]]. They are known as ''[[parametric polymorphism]]'' in [[ML (programming language)|ML]], [[Scala (programming language)|Scala]], [[Julia (programming language)|Julia]], and [[Haskell (programming language)|Haskell]] (the Haskell communityterminology also uses the term "generic" for a related but somewhat different concept).
 
 
The term "generic programming" was originally coined by [[David Musser]] and [[Alexander Stepanov]]{{sfn|Musser|Stepanov|1989}} in a more specific sense than the above, to describe a programming paradigm whereby fundamental requirements on data types are abstracted from across concrete examples of algorithms and [[data structuresstructure]]s and formalized as [[Concept (generic programming)|concepts]], with [[generic function]]s implemented in terms of these concepts, typically using language genericity mechanisms as described above.
 
== Stepanov–Musser and other generic programming paradigms ==
 
Generic programming is defined in {{harvtxt|Musser|Stepanov|1989}} as follows,
{{Blockquote
{{Quote
| text = Generic programming centers around the idea of abstracting from concrete, efficient algorithms to obtain generic algorithms that can be combined with different data representations to produce a wide variety of useful software.
| author = Musser, David R.; Stepanov, Alexander A.
| source = Generic Programming<ref>{{cite book | url=https://stepanovpapers.com/genprog.pdf | title=Generic Programming |author1=Musser, David R. |author2=Stepanov, Alexander A. }}</ref>}}
 
The "generic programming" paradigm is an approach to software decomposition whereby fundamental requirements on types are abstracted from across concrete examples of algorithms and data structures and formalized as [[Concept (generic programming)|concepts]], analogously to the abstraction of algebraic theories in [[abstract algebra]].<ref>{{cite book|author1 =Alexander Stepanov |author2 =Paul McJones|title=Elements of Programming|publisher=Addison-Wesley Professional |date=19 June 2009|isbn=978-0-321-63537-2}}</ref> Early examples of this programming approach were implemented in Scheme and Ada,<ref>{{cite journal | doi=10.1145/317500.317529 | title=A library of generic algorithms in Ada |author1=Musser, David R. |author2=Stepanov, Alexander A. | journal=Proceedings of the 1987 Annual ACM SIGAda International Conference on Ada | pages=216–225| year=1987 | isbn=0897912438 | citeseerx=10.1.1.588.7431 | s2cid=795406 }}</ref> although the best known example is the [[Standard Template Library]] (STL),<ref>Alexander Stepanov and Meng Lee: The Standard Template Library. HP Laboratories Technical Report 95-11(R.1), 14 November 1995</ref><ref>Matthew H. Austern: Generic programming and the STL: using and extending the C++ Standard Template Library. Addison-Wesley Longman Publishing Co., Inc. Boston, MA, USA 1998</ref> which developed a theory of [[iterator]]s that is used to decouple sequence data structures and the algorithms operating on them.
 
For example, given ''N'' sequence data structures, e.g. singly linked list, vector etc., and ''M'' algorithms to operate on them, e.g. <code>find</code>, <code>sort</code> etc., a direct approach would implement each algorithm specifically for each data structure, giving {{nowrap|''N'' × ''M''}} combinations to implement. However, in the generic programming approach, each data structure returns a model of an iterator concept (a simple value type that can be dereferenced to retrieve the current value, or changed to point to another value in the sequence) and each algorithm is instead written generically with arguments of such iterators, e.g. a pair of iterators pointing to the beginning and end of the subsequence or ''range'' to process. Thus, only {{nowrap|''N'' + ''M''}} data structure-algorithm combinations need be implemented. Several iterator concepts are specified in the STL, each a refinement of more restrictive concepts e.g. forward iterators only provide movement to the next value in a sequence (e.g. suitable for a singly linked list or a stream of input data), whereas a random-access iterator also provides direct constant-time access to any element of the sequence (e.g. suitable for a vector). An important point is that a data structure will return a model of the most general concept that can be implemented efficiently—[[Analysis of algorithms|computational complexity]] requirements are explicitly part of the concept definition. This limits the data structures a given algorithm can be applied to and such complexity requirements are a major determinant of data structure choice. Generic programming similarly has been applied in other domains, e.g. graph algorithms.<ref>Jeremy G. Siek, Lie-Quan Lee, Andrew Lumsdaine: The Boost Graph Library: User Guide and Reference Manual. Addison-Wesley 2001</ref>
 
Note that althoughAlthough this approach often utilizesuses language features of [[compile-time]] genericity/ and templates, it is in fact independent of particular language-technical details. Generic programming pioneer Alexander Stepanov wrote,
{{Blockquote
{{Quote
| text = Generic programming is about abstracting and classifying algorithms and data structures. It gets its inspiration from [[Donald Knuth|Knuth]] and not from type theory. Its goal is the incremental construction of systematic catalogs of useful, efficient and abstract algorithms and data structures. Such an undertaking is still a dream.
| author = Alexander Stepanov
| source = Short History of STL <ref>{{cite book |last=Stepanov |first=Alexander |url=https://stepanovpapers.com/history%20of%20STL.pdf | title=Short History of STL | author=Stepanov, Alexander}}</ref><ref name = "stroustrup2007">{{cite book |last=Stroustrup |first=Bjarne |url=https://www.stroustrup.com/hopl-almost-final.pdf | title=Evolving a language in and for the real world: C++ 1991-2006 | author=Stroustrup, Bjarne | doi=10.1145/1238844.1238848 | s2cid=7518369 }}</ref> }}
 
{{Blockquote
{{Quote
| text = I believe that iterator theories are as central to Computer Science as theories of [[Ring (mathematics)|rings]] or [[Banach space]]s are central to Mathematics.
| author = Alexander Stepanov
| source = An Interview with A. Stepanov<ref name=stepanov2011>{{cite web | url =https://www.stlport.org/resources/StepanovUSA.html |title=An Interview with A. Stepanov |last=Lo Russo |first=Graziano}}</ref>}}
 
[[Bjarne Stroustrup]] noted,
{{Blockquote
{{Quote
| text = Following Stepanov, we can define generic programming without mentioning language features: Lift algorithms and data structures from concrete examples to their most general and abstract form.
| author = Bjarne Stroustrup
| source = Evolving a language in and for the real world: C++ 1991-2006<ref name="stroustrup2007" />}}
 
Other programming paradigms that have been described as generic programming include ''Datatype generic programming'' as described in "Generic Programming – an Introduction".<ref>{{cite book |last1=Backhouse url|first1=Roland |last2=Jansson |first2=Patrik |last3=Jeuring |first3=Johan |last4=Meertens |first4=Lambert |author4-link=Lambert Meertens |year=1999 |url=https://www.cse.chalmers.se/~patrikj/poly/afp98/genprogintro.pdf| |title= Generic Programming – an Introduction |author1 =Roland Backhouse |author2 =Patrik Jansson |author3 =Johan Jeuring |author4 =Lambert Meertens | year=1999 }}</ref> The {{em | Scrap your [[Boilerplate code|boilerplate]]}} approach is a lightweight generic programming approach for Haskell.<ref>{{cite web | url=https://www.microsoft.com/en-us/research/wp-content/uploads/2003/01/hmap.pdf | title=Scrap Your Boilerplate: A Practical Design Pattern for Generic Programming |last1=Lämmel publisher|first1=MicrosoftRalf |last2=Peyton accessJones |first2=Simon |author2-datelink=16Simon OctoberPeyton 2016Jones |author1date=Lämmel,January Ralf2003 |author2publisher=PeytonMicrosoft Jones,|access-date=16 SimonOctober 2016}}</ref>
 
In this article we distinguish the high-level [[programming paradigm]]s of ''generic programming'', above, from the lower-level programming language ''genericity mechanisms'' used to implement them (see [[#Programming language support for genericity|Programming language support for genericity]]). For further discussion and comparison of generic programming paradigms, see.<ref>{{cite web |url=https://lcsd05.cs.tamu.edu/papers/dos_reis_et_al.pdf |title=What is Generic Programming? (preprint LCSD'05) |author1last1=Gabriel Dos Reis |author2first1=JaakkoGabriel |last2=Ja ̈rvi |first=Jaakko |year=2005 |url-status=dead |archive-url=https://web.archive.org/web/20051225114849/https://lcsd05.cs.tamu.edu/papers/dos_reis_et_al.pdf |archive-date=25 December 2005}}</ref>
 
==Programming language support for genericity==
Genericity facilities have existed in high-level languages since at least the 1970s in languages such as [[ML (programming language)|ML]], [[CLU (programming language)|CLU]] and [[Ada (programming language)|Ada]], and were subsequently adopted by many [[objectObject-based programminglanguage|object-based]] and [[objectObject-oriented programming|object-oriented]] languages, including [[BETA (programming language)|BETA]], [[C++]], [[D (programming language)|D]], [[Eiffel (programming language)|Eiffel]], [[Java (programming language)|Java]], and [[Digital Equipment Corporation|DEC]]'s now defunct [[Trellis-Owl]] language.
 
Genericity is implemented and supported differently in various programming languages; the term "generic" has also been used differently in various programming contexts. For example, in [[Forth (programming language)|Forth]] the [[compiler]] can execute code while compiling and one can create new ''compiler keywords'' and new implementations for those words on the fly. It has few ''words'' that expose the compiler behaviour and therefore naturally offers ''genericity'' capacities that, however, are not referred to as such in most Forth texts. Similarly, dynamically typed languages, especially interpreted ones, usually offer ''genericity'' by default as both passing values to functions and value assignment are type-indifferent and such behavior is often utilizedused for abstraction or code terseness, however this is not typically labeled ''genericity'' as it's a direct consequence of the dynamic typing system employed by the language.{{citation needed|date=August 2015}} The term has been used in [[functional programming]], specifically in [[Haskell (programming language)|Haskell]]-like]] languages, which use a [[structural type system]] where types are always parametric and the actual code on those types is generic. These usagesuses still serve a similar purpose of code-saving and the rendering of an abstraction.
 
[[Array data type|Arrays]] and [[struct (C programming language)|structs]] can be viewed as predefined generic types. Every usage of an array or struct type instantiates a new concrete type, or reuses a previous instantiated type. Array element types and struct element types are parameterized types, which are used to instantiate the corresponding generic type. All this is usually built-in in the [[compiler]] and the syntax differs from other generic constructs. Some [[extensible programming|extensible programming languages]] try to unify built-in and user defined generic types.
 
A broad survey of genericity mechanisms in programming languages follows. For a specific survey comparing suitability of mechanisms for generic programming, see.<ref>{{citeCite citeseerxCiteSeerX | title=An extended comparative study of language support for generic programming (preprint)| |author1=R. Garcia |author2 =J. Ja ̈rvi |author3 =A. Lumsdaine |author4 =J. Siek |author5 =J. Willcock |year=2005 |citeseerx = 10.1.1.110.122}}</ref>
 
===In object-oriented languages===
Line 110:
</syntaxhighlight>
 
The C++ <code>template</code> construct used above is widely cited{{Citation needed|date=May 2010}} as the genericity construct that popularized the notion among programmers and language designers and supports many generic programming idioms. The D programming language also offers fully generic-capable templates based on the C++ precedent but with a simplified syntax. The Java programming language has provided genericity facilities syntactically based on C++'s since the introduction of [[Java Platform, Standard Edition|J2SE]] (J2SE) 5.0.
 
[[C Sharp (programming language)|C#]] 2.0, [[ChromeOxygene (programming language)|Oxygene 1.5]] (also known asformerly Chrome) and [[Visual Basic .NET|Visual Basic .NET]] 2005]] have constructs that take advantage ofexploit the support for generics present in theMicrosoft [[.NET Framework|Microsoft .NET Framework]] since version 2.0.
 
====Generics in Ada====
Line 179:
</syntaxhighlight>
 
=====Advantages and limitationslimits=====
 
The language syntax allows precise specification of constraints on generic formal parameters. For example, it is possible to specify that a generic formal type will only accept a modular type as the actual. It is also possible to express constraints ''between'' generic formal parameters; for example:
Line 198:
* the compiler can implement ''shared generics'': the object code for a generic unit can be shared between all instances (unless the programmer requests inlining of subprograms, of course). As further consequences:
** there is no possibility of code bloat (code bloat is common in C++ and requires special care, as explained below).
** it is possible to instantiate generics at run-time, as well asand at compile time, since no new object code is required for a new instance.
** actual objects corresponding to a generic formal object are always considered to be non-static inside the generic; see [[wikibooks:Ada Programming/Generics#Generic formal objects|Generic formal objects]] in the Wikibook for details and consequences.
* all instances of a generic being exactly the same, it is easier to review and understand programs written by others; there are no "special cases" to take into account.
Line 205:
 
====Templates in C++====
{{Main article|Template (C++)}}
C++ uses templates to enable generic programming techniques. The C++ Standard Library includes the [[Standard Template Library]] or STL that provides a framework of templates for common data structures and algorithms. Templates in C++ may also be used for [[template metaprogramming]], which is a way of pre-evaluating some of the code at compile-time rather than [[Run time (program lifecycle phase)|run-time]]. Using template specialization, C++ Templates are considered [[Turing complete]].
 
Line 246:
 
=====Advantages and disadvantages=====
Some uses of templates, such as the <code>max()</code> function, were previously filled by function-like [[preprocessor]] [[Macro (computer science)|macros]] (a legacy of the [[C (programming language)|C programming]] language]]). For example, here is a possible implementation of such macro:
 
<syntaxhighlight lang="Cpp">
Line 252:
</syntaxhighlight>
 
Macros are expanded (copy pasted) by [[preprocessor]], before compilationcompiling proper; templates are actual real functions. Macros are always expanded inline; templates can also be [[inline function]]s when the compiler deems it appropriate.
 
However, templates are generally considered an improvement over macros for these purposes. Templates are type-safe. Templates avoid some of the common errors found in code that makes heavy use of function-like macros, such as evaluating parameters with side effects twice. Perhaps most importantly, templates were designed to be applicable to much larger problems than macros.
Line 261:
# Many compilers historically had poor support for templates, thus the use of templates could have made code somewhat less portable. Support may also be poor when a C++ compiler is being used with a [[Linker (computing)|linker]] that is not C++-aware, or when attempting to use templates across [[Library (computer science)#Shared libraries|shared library]] boundaries.
# Compilers can produce confusing, long, and sometimes unhelpful error messages when errors are detected in code that uses SFINAE.<ref>[https://www.stroustrup.com/N1522-concept-criteria.pdf Stroustrup, Dos Reis (2003): Concepts - Design choices for template argument checking]</ref> This can make templates difficult to develop with.
# Finally, the use of templates requires the compiler to generate a separate ''instance'' of the templated class or function for every type parameters used with it. (This is necessary because types in C++ are not all the same size, and the sizes of data fields are important to how classes work.) So the indiscriminate use of templates can lead to [[code bloat]], resulting in excessively large executables. However, judicious use of template specialization and derivation can dramatically reduce such code bloat in some cases:{{quoteBlockquote|So, can derivation be used to reduce the problem of code replicated because templates are used? This would involve deriving a template from an ordinary class. This technique proved successful in curbing code bloat in real use. People who do not use a technique like this have found that replicated code can cost megabytes of code space even in moderate size programs.|[[Bjarne Stroustrup]]|The Design and Evolution of C++, 1994<ref name="Stroustrup94Design">{{cite book|last=Stroustrup|first=Bjarne|author-link=Bjarne Stroustrup|title=The Design and Evolution of C++|year=1994|publisher=Addison-Wesley|___location=Reading, Massachusetts|isbn=978-81-317-1608-3|pages=346–348|chapter=15.5 Avoiding Code Replication|bibcode=1994dec..book.....S}}</ref>}}
# Templated classes or functions may require an ''explicit specialization'' of the template class which would require rewriting of an entire class for a specific template parameters used by it.
The extra instantiations generated by templates can also cause some debuggers to have difficulty working gracefully with templates. For example, setting a debug breakpoint within a template from a source file may either miss setting the breakpoint in the actual instantiation desired or may set a breakpoint in every place the template is instantiated.
Line 269:
====Templates in D====
 
The [[D (programming language)|D]] language supports templates based in design on C++. Most C++ template idioms carry over to D without alteration, but D adds some functionality:
Most C++ template idioms will carry over to D without alteration, but D adds some additional functionality:
 
* Template parameters in D are not restricted to just types and primitive values (as it was in C++ before C++20), but also allow arbitrary compile-time values (such as strings and struct literals), and aliases to arbitrary identifiers, including other templates or template instantiations.
* Template constraints and the <code>static if</code> statement provide an alternative to respectively C++'s [[Concepts (C++)|C++ concepts]] and <code>if constexpr</code>.
* The <code>is(...)</code> expression allows speculative instantiation to verify an object's traits at compile time.
* The <code>auto</code> keyword and the <code>[[typeof]]</code> expression allow [[type inference]] for variable declarations and function return values, which in turn allows "Voldemort types" (types that do not have a global name).<ref>{{cite web |last1last=Bright |first1first=Walter |title=Voldemort Types in D | url =https://www.drdobbs.com/cpp/voldemort-types-in-d/232901591 |website=Dr. Dobbs |access-date=3 June 2015}}</ref>
 
Templates in D use a different syntax than in C++: whereas in C++ template parameters are wrapped in angular brackets (<code>Template<param1, param2></code>),
Line 314 ⟶ 313:
 
* The <code>import</code> expression allows reading a file from disk and using its contents as a string expression.
* Compile-time reflection allows enumerating and inspecting declarations and their members during compilationcompiling.
* User-defined [[Attribute (computing)|attributes]] allow users to attach arbitrary identifiers to declarations, which can then be enumerated using compile-time reflection.
* [[Compile-time function execution|Compile-Time Function Execution]] (CTFE) allows a subset of D (restricted to safe operations) to be interpreted during compilationcompiling.
* String mixins allow evaluating and compiling the contents of a string expression as D code that becomes part of the program.
 
Line 340 ⟶ 339:
====Genericity in Eiffel====
 
Generic classes have been a part of [[Eiffel (programming language)|Eiffel]] since the original method and language design. The foundation publications of Eiffel,<ref>''Object-Oriented Software Construction,'' Prentice Hall, 1988, and ''Object-Oriented Software Construction, second edition,'' Prentice Hall, 1997.</ref><ref>''Eiffel: The Language,'' Prentice Hall, 1991.</ref> use the term ''genericity'' to describe the creationcreating and use ofusing generic classes.
 
=====Basic/Unconstrained, unconstrained genericity=====
Generic classes are declared with their class name and a list of one or more ''formal generic parameters''. In the following code, class <code lang=Eiffel>LIST</code> has one formal generic parameter <code lang=Eiffel>G</code>
 
Line 381 ⟶ 380:
 
====Generics in Java====<!-- This section is linked from [[Comparison of Java and C++]] -->
{{Main article|Generics in Java}}
 
{{Main article|Generics in Java}}
 
Support for the ''generics'', or "containers-of-type-T" was added to the [[Java (programming language)|Java programming language]] in 2004 as part of J2SE 5.0. In Java, generics are only checked at compile time for type correctness. The generic type information is then removed via a process called [[type erasure]], to maintain compatibility with old [[Java virtual machine|JVM]] implementations, making it unavailable at runtime.{{sfn|Bloch|2018|loc=§Item 28: Prefer lists to arrays|p=126}} For example, a <code>List&lt;String&gt;</code> is converted to the raw type <code>List</code>. The compiler inserts [[Type conversion|type casts]] to convert the elements to the <code>String</code> type when they are retrieved from the list, reducing performance compared to other implementations such as C++ templates.
Line 388 ⟶ 386:
====Genericity in .NET [C#, VB.NET]====
 
Generics were added as part of [[.NET Framework#.NET Framework 2.0|.NET Framework 2.0]] in November 2005, based on a research prototype from Microsoft Research started in 1999.<ref>[https://docs.microsoft.com/en-us/archive/blogs/dsyme/netc-generics-history-some-photos-from-feb-1999 .NET/C# Generics History: Some Photos From Feb 1999]</ref> Although similar to generics in Java, .NET generics do not apply [[type erasure]],{{sfn|Albahari|2022}}{{rp|208-209}} but implement generics as a first class mechanism in the runtime using [[Reification (computer science)|reification]]. This design choice provides additional functionality, such as allowing [[ReflectionReflective (computer science)programming|reflection]] with preservation of generic types, as well asand alleviating some of the limitationslimits of erasure (such as being unable to create generic arrays).<ref>[https://www.ondotnet.com/pub/a/dotnet/2005/10/17/interview-with-anders-hejlsberg.html C#: Yesterday, Today, and Tomorrow: An Interview with Anders Hejlsberg]</ref><ref>[https://www.artima.com/intv/generics2.html Generics in C#, Java, and C++]</ref> This also means that there is no performance hit from runtime [[Type conversion|casts]] and normally expensive [[Boxing (computer science)|boxing conversions]]. When primitive and value types are used as generic arguments, they get specialized implementations, allowing for efficient generic [[Collection class|collections]] and methods. As in C++ and Java, nested generic types such as Dictionary<string, List<int>> are valid types, however are advised against for member signatures in code analysis design rules.<ref>[https://msdn.microsoft.com/en-us/library/ms182144.aspx Code Analysis CA1006: Do not nest generic types in member signatures]</ref>
 
.NET allows six varieties of generic type constraints using the <code>where</code> keyword including restricting generic types to be value types, to be classes, to have constructors, and to implement interfaces.<ref>[https://msdn2.microsoft.com/en-us/library/d5x73970.aspx Constraints on Type Parameters (C# Programming Guide)]</ref> Below is an example with an interface constraint:
Line 461 ⟶ 459:
 
====Genericity in Delphi====
[[Delphi (programming languagesoftware)|Delphi's]] [[Object Pascal]] dialect acquired generics in the Delphi 2007 release, initially only with the (now discontinued) .NET compiler before being added to the native code in the Delphi 2009 release. The semantics and capabilities of Delphi generics are largely modelled on those had by generics in .NET 2.0, though the implementation is by necessity quite different. Here's a more or less direct translation of the first C# example shown above:
 
<syntaxhighlight lang="Delphi">
Line 506 ⟶ 504:
</syntaxhighlight>
 
As with C#, methods as well asand whole types can have one or more type parameters. In the example, TArray is a generic type (defined by the language) and MakeAtLeast a generic method. The available constraints are very similar to the available constraints in C#: any value type, any class, a specific class or interface, and a class with a parameterless constructor. Multiple constraints act as an additive union.
 
====Genericity in Free Pascal====
[[Free Pascal]] implemented generics before Delphi, and with different syntax and semantics. However, since FPC version 2.6.0, the Delphi-style syntax is available when using the {$mode Delphi} language mode. Thus, Free Pascal programmerscode are able to usesupports generics in whichevereither style they prefer.
 
Delphi and Free Pascal example:
Line 611 ⟶ 609:
 
====Genericity in Haskell====
The [[type class]] mechanism of [[Haskell]] supports generic programming. Six of the predefined type classes in Haskell (including <code>Eq</code>, the types that can be compared for equality, and <code>Show</code>, the types whose values can be rendered as strings) have the special property of supporting ''derived instances.'' This means that a programmer defining a new type can state that this type is to be an instance of one of these special type classes, without providing implementations of the class methods as is usually necessary when declaring class instances. All the necessary methods will be "derived" – that is, constructed automatically – based on the structure of the type. For example, the following declaration of a type of [[binary tree]]s states that it is to be an instance of the classes <code>Eq</code> and <code>Show</code>:
The [[type class]] mechanism of [[Haskell (programming language)|Haskell]] supports generic programming.
Six of the predefined type classes in Haskell (including <code>Eq</code>, the types that can be compared for equality, and <code>Show</code>, the types whose values can be rendered as strings) have the special property of supporting ''derived instances.'' This means that a programmer defining a new type can state that this type is to be an instance of one of these special type classes, without providing implementations of the class methods as is usually necessary when declaring class instances. All the necessary methods will be "derived" – that is, constructed automatically – based on the structure of the type.
For instance, the following declaration of a type of [[binary tree]]s states that it is to be an instance of the classes <code>Eq</code> and <code>Show</code>:
 
<syntaxhighlight lang="Haskell">
Line 625 ⟶ 621:
 
===== PolyP =====
PolyP was the first generic programming language extension to [[Haskell (programming language)|Haskell]]. In PolyP, generic functions are called ''polytypic''. The language introduces a special construct in which such polytypic functions can be defined via structural induction over the structure of the pattern functor of a regular datatype. Regular datatypes in PolyP are a subset of Haskell datatypes. A regular datatype t must be of [[kindKind (type theory)|kind]] ''* → *'', and if ''a'' is the formal type argument in the definition, then all recursive calls to ''t'' must have the form ''t a''. These restrictions rule out higher-kinded datatypes as well asand nested datatypes, where the recursive calls are of a different form.
The flatten function in PolyP is here provided as an example:
 
Line 646 ⟶ 642:
 
=====Generic Haskell=====
Generic Haskell is another extension to [[Haskell (programming language)|Haskell]], developed at [[Utrecht University]] in the [[Netherlands]]. The extensions it provides are:
*''Type-indexed values'' are defined as a value indexed over the various Haskell type constructors (unit, primitive types, sums, products, and user-defined type constructors). In addition, we can also specify the behaviour of a type-indexed values for a specific constructor using ''constructor cases'', and reuse one generic definition in another using ''default cases''.
The resulting type-indexed value can be specialized to any type.
Line 673 ⟶ 669:
====Clean====
 
[[Clean (programming language)|Clean]] offers generic programming based {{slink|[[#PolyP|PolyP}}]] and the {{slink|[[#Generic Haskell|Generic Haskell}}]] as supported by the GHC ≥ 6.0. It parametrizes by kind as those but offers overloading.
 
===Other languages===
Line 680 ⟶ 676:
A [[Verilog]] module may take one or more parameters, to which their actual values are assigned upon the instantiation of the module. One example is a generic [[Hardware register|register]] array where the array width is given via a parameter. Such an array, combined with a generic wire vector, can make a generic buffer or memory module with an arbitrary bit width out of a single module implementation.<ref>Verilog by Example, Section ''The Rest for Reference''. Blaine C. Readler, Full Arc Press, 2011. {{ISBN|978-0-9834973-0-1}}</ref>
 
[[VHDL]], being derived from Ada, also has generic capabilitiesabilities. <ref>https://www.ics.uci.edu/~jmoorkan/vhdlref/generics.html VHDL Reference</ref>
 
[[C (programming language)|C]] supports "type-generic expressions" using the {{c-lang|_Generic}} keyword:<ref name="N1516">[https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1516.pdf WG14 N1516 Committee Draft — October 4, 2010]</ref>
Line 700 ⟶ 696:
{{refbegin}}
* {{cite book |last=Albahari |first=Joseph |title= C# 10 in a Nutshell |publisher= O'Reilly |isbn= 978-1-098-12195-2|edition=First|year=2022}}
*{{cite book | title= "Effective Java: Programming Language Guide" |last=Bloch| first=Joshua| publisher=Addison-Wesley | edition=third | isbn=978-0134685991| year=2018}}
* {{Cite book | last1 = Musser | first1 = D. R. | author-link1 = David Musser | last2 = Stepanov | first2 = A. A. | author-link2 = Alexander Stepanov| chapter = Generic programming | doi = 10.1007/3-540-51084-2_2 | title = Symbolic and Algebraic Computation: International symposium ISSAC 1988 | editor = P. Gianni | editor-link = Patrizia Gianni | series = Lecture Notes in Computer Science | volume = 358 | pages = 13–25 | year = 1989 | isbn = 978-3-540-51084-0 }}
* {{cite conference | url =https://www.research.att.com/~bs/hopl-almost-final.pdf |title=Evolving a language in and for the real world: C++ 1991-2006 |author-link=Bjarne Stroustrup |last=Stroustrup |first=Bjarne |conference=ACM HOPL 2007 |year=2007}}
* {{cite book |title=Design Patterns: Elements of Reusable Object-Oriented Software |first1=Erich |last1=Gamma |first2=Richard |last2=Helm |first3=Ralph |last3=Johnson |first4=John |last4=Vlissides |year=1994 |publisher=Addison-Wesley |isbn=0-201-63361-2 |bibcode=1995dper.book.....G |url-access=registration |url=https://archive.org/details/designpatternsel00gamm }}
{{refend}}
 
== Further reading ==
* Gabriel Dos Reis and Jaakko Järvi, ''[https://www.elegantcoding.com/2012/04/what-is-generic-programming.html What is Generic Programming?],'' [https://lcsd05.cs.tamu.edu LCSD 2005] {{Webarchive|url=https://web.archive.org/web/20190828045251/https://lcsd05.cs.tamu.edu/ |date=28 August 2019 }}.
* {{cite conference | first = Jeremy | last = Gibbons | author-link = Jeremy Gibbons | citeseerx = 10.1.1.159.1228 | title = Datatype-generic programming
| editor1-last = Backhouse | editor1-first = R. | editor2-last = Gibbons | editor2-first = J. | editor3-last = Hinze | editor3-first = R.
| editor4-last = Jeuring | editor4-first = J.
| conference = Spring School on Datatype-Generic Programming 2006 | series = Lecture Notes in Computer Science | volume = 4719 | pages = 1–71
| publisher = Springer | ___location = Heidelberg | year = 2007 }}
* {{cite book|doi=10.1145/28697.28738|chapter=Genericity versus inheritance|title=Conference proceedings on Object-oriented programming systems, languages and applications - OOPSLA '86|pages=391–405|year=1986|last1=Meyer|first1=Bertrand|isbn=0897912047|s2cid=285030|author-link1=Bertrand Meyer}}
 
Line 719 ⟶ 715:
* Alexander A. Stepanov, [https://www.stepanovpapers.com/ Collected Papers of Alexander A. Stepanov] (creator of the [[Standard Template Library|STL]])
 
;C++/, D
* Walter Bright, ''[https://www.digitalmars.com/d/templates-revisited.html Templates Revisited].''
* David Vandevoorde, Nicolai M Josuttis, ''C++ Templates: The Complete Guide'', 2003 Addison-Wesley. {{ISBN|0-201-73484-2}}
 
;C#/, .NET
* Jason Clark, "[https://msdn.microsoft.com/msdnmag/issues/03/09/NET/ Introducing Generics in the Microsoft CLR]," September 2003, ''MSDN Magazine'', Microsoft.
* Jason Clark, "[https://msdn.microsoft.com/msdnmag/issues/03/10/NET/ More on Generics in the Microsoft CLR]," October 2003, ''MSDN Magazine'', Microsoft.
* M. Aamir Maniar, [https://codeplex.com/Wiki/View.aspx?ProjectName=genericsnet Generics.Net]. An open source generics library for C#.
 
;Delphi/, Object Pascal
* Nick Hodges, "[https://edn.embarcadero.com/article/38757 Delphi 2009 Reviewers Guide]," October 2008, ''Embarcadero Developer Network'', Embarcadero.
* Craig Stuntz, "[https://web.archive.org/web/20090131211440/https://blogs.teamb.com/craigstuntz/2008/08/29/37832/ Delphi 2009 Generics and Type Constraints]," October 2008
Line 756 ⟶ 752:
 
{{Data types}}
 
{{Authority control}}