patternModerate
What is the use case for multi-type-parameter generics?
Viewed 0 times
casethemultiwhattypeforgenericsuseparameter
Problem
In C#, one can define a class/method/function with multiple type parameters. For example,
I understand how to use it, but I don't understand why I need it. So I'm hoping someone can answer the following questions:
1) What is the use case for multiple type parameters?
2) Based on the use case given in Question 1, what are the alternative solutions for that use case if multiple type parameters is not a feature of the language in use?
// function
void foo(T1 x, T2 y) { /*body*/}
// class
class Bar { /*body*/ }I understand how to use it, but I don't understand why I need it. So I'm hoping someone can answer the following questions:
1) What is the use case for multiple type parameters?
2) Based on the use case given in Question 1, what are the alternative solutions for that use case if multiple type parameters is not a feature of the language in use?
Solution
Some use cases for multiple type arguments include
If we did not have multiple type arguments, or any other way to emulate multiple argument types (e.g. nested parametric classes
Of course, a programming language could disallow generic classes and still have a specific primitive type for some of the examples above. For instance,
- maps/dictionaries
Map, where you have one key parameter and one value parameter
- product types
Pair
- sum types, AKA variants
Variant, which represent a value which might be either of typeAor of typeB
- Function-like types
Funcrepresenting a function fromAtoB
- "Visitor" objects for parametric types. I.e. a visitor for
ListisListVisitorwhereRis the return type of the visitor.
If we did not have multiple type arguments, or any other way to emulate multiple argument types (e.g. nested parametric classes
class T { class U { ... which are a sort-of curried version of the two-arguments class), we could not express the examples above in a generic way.Of course, a programming language could disallow generic classes and still have a specific primitive type for some of the examples above. For instance,
Func could be a primitive type, instead of a user/library-defined class type.Context
StackExchange Computer Science Q#95280, answer score: 17
Revisions (0)
No revisions yet.