Generic function: Difference between revisions

Content deleted Content added
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags
mNo edit summary
 
(2 intermediate revisions by 2 users not shown)
Line 1:
{{Distinguish|Generalized function}}
{{Polymorphism}}
 
In [[computer programming]], a '''generic function''' is a function defined for [[Polymorphism (computer science)|polymorphism]].
Line 53 ⟶ 54:
=== Comparison to other languages ===
Generic functions correspond roughly to what [[Smalltalk]] terms [[Method (computer science)|methods]], with the notable exception that, in Smalltalk, the receiver's class is the sole determinant of which body of code is called: the types or values of the arguments are irrelevant ([[single dispatch]]). In a programming language with [[multiple dispatch]] when a generic function is called, method dispatch occurs on the basis of all arguments, not just one which is privileged. [[Flavors (programming language)|New Flavors]] also provided generic functions, but only single dispatch.
 
In JavaScript, a generic function is a function that can work with values of different types, rather than a specific type. This is achieved through the use of type parameters or by dynamically checking the type of the value being operated on. One common use case for generic functions in JavaScript is to create reusable functions that can work with different data types, such as arrays, strings, or objects. JavaScript's dynamic typing system makes it particularly suited for the creation of generic functions, as values can be easily coerced or converted to different types as needed.
 
<!-- i moved this earlier because i think it's the more common definition. C++, Java, C#, ML , Rust,
another, completely separate definition of '''generic function''' is a function that uses [[parametric polymorphism]]. This is the definition used when working with a language like [[OCaml]]. An example of a generic function is
Line 59 ⟶ 63:
</syntaxhighlight>
which takes an argument of any type and returns something of that same type. -->
 
== References ==
{{Reflist}}