qsharp icon indicating copy to clipboard operation
qsharp copied to clipboard

Bounded polymorphism

Open bamarsha opened this issue 1 year ago • 2 comments

From microsoft/qsharp-language#149:

Is your feature request related to a problem? Please describe. When writing a polymorphic function in Q#, the type variables are fully general. They are opaque types with no properties that the function can rely on.

But there are many cases where a function needs a type to have certain properties. For example, a function may need its type variables to be equatable or comparable to store/retrieve them from a list or map. Arithmetic functions may also require that the types are numeric.

Describe the solution you'd like Q# needs some form of bounded polymorphism to be able to write functions that are valid for only certain types. I believe type classes are the best solution for this: they are very flexible and fit with Q#'s functional style.

Describe alternatives you've considered Overloading functions based on type (microsoft/qsharp-compiler#29) would solve the naming problem (e.g. PlusI, PlusD, PlusL could be overloaded to Plus), but this solution doesn't scale. Because the numeric types are not formally grouped, there is no way to write a single polymorphic function that calls the right Plus automatically - it similarly needs to be overloaded for each numeric type, creating unnecessary code duplication.

bamarsha avatar Jul 20 '23 17:07 bamarsha