Proposal: Concepts #9720
Unanswered
hez2010
asked this question in
Language Ideas
Replies: 2 comments 4 replies
-
So it's an alias for type constraint combinations. The name "concept" may imply something more in different context. There hasn't been a practice for exposing alias in compiled assembly in C#. The |
Beta Was this translation helpful? Give feedback.
3 replies
-
Is there a reason for this to be in the IL at all? It's effectively just an alias |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Motivation
With the introduction of virtual static methods, we are now using more and more generic programming with generic constraints. This leads to an issue where you have to repeat the generic constraints again over again which leads to a lot of bloats.
Take an example in .NET BCL: https://github.com/dotnet/runtime/blob/6bbf3520b7232e19c2d1c4d59631a318199f847d/src/libraries/System.Numerics.Tensors/src/System/Numerics/Tensors/netcore/Tensor.op_Multiply.cs#L6
We end up duplicating the generic constraints
where T : IMultiplyOperators<T, T, T>, IMultiplicativeIdentity<T, T>
again and again, which produces to a lot of boilerplate code.A solution is to create yet another interface
interface IMultiplyOperatorsWithMultiplicativeIdentity<T> : IMultiplyOperators<T, T, T>, IMultiplicativeIdentity<T, T>
, and useIMultiplyOperatorsWithMultiplicativeIdentity<T>
instead.However, it's really not a solution as it immediately requires all the types to implement the new interface, otherwise you cannot pass it to a generic parameter that is constrained by the new constraint.
Proposal: Concepts
Concepts are an alias of a set of operations. Unlike interfaces, concepts don't have the type identity, and they can only be used as generic constraints.
We use
concept Name<TypeParams> = TypeList
to declare a concept:while I'm here just throwing an example, the final syntax doesn't have to be like this. But I chose this syntax because it can express conjunction relation with
&
explicitly while also reserving the space for future update in case we want to extend it to support disjunctive relation with|
in the future.We can also "extend" an existing concept by:
Then to use a concept, we simply do:
Lower strategy
Definitions
For concept definitions, we can lower it to some unspeaking types. For example,
gets lowered to
and
gets lowered to
Uses: Concepts flatten
A naive method is to flatten all concepts at compile time. So that
gets lowered to
This allows a more structural way of constraints instead of the nominal way we have today. And also, this allows us to replacing existing sets of generic constraints with concepts, without any breaking change.
Beta Was this translation helpful? Give feedback.
All reactions