dotnet / vblang

The home for design of the Visual Basic .NET programming language and runtime library.
290 stars 64 forks source link

Numeric Constraint for Generics #214

Open AdamSpeight2008 opened 6 years ago

AdamSpeight2008 commented 6 years ago

Proposal

Add a new Attribute / Constraint to Generic Parameters to restrict the type to those that are considered numeric. How to define what is numeric is another discussion.

Definition of "Numeric"

For the purpose of this proposal we are using the definition as define in the grammar as NumericTypeName Spec: Primitive Types

Benefits

Since we now know the type is constrained to be numeric, we can permit the usage of operator within the generic operator being defined.

Structure Range(Of <Numeric> Tx, <Numeric> Sx )
   Public ReadOnly X As Tx
   Public ReadOnly Y As Tx
   Public ReadOnly S As Sx
   Public Sub New ( X As Tx, Y As Tx, S As Sx)
     Me.X = X : Me.Y = Y : Me.S = S
   End Sub

   Public Function GetEnumerator() As IEnumerable(Of Tx)
     Return If( X <= Y , Ascending(), Descending() )
   End Function

   Private Iterator Function Ascending() As IEnumerable(Of Tx)
     Dim Current = X
     Dim Last = Y - S
     While Current <= Last
       Yield Current
       Current += S
     End While
     Yield Current
   End Function

   Private Iterator Function Ascending() As IEnumerable(Of Tx)
     Dim Current = X
     Dim Last = Y - S
     While Current >= Last
       Yield Current
       Current += S
     End While
     Yield Current
   End Function

End Structure
AdamSpeight2008 commented 6 years ago

@AnthonyDGreen Also we can currently can not write this usage of an attribute in VBnet, so we could look into it.

xieguigang commented 6 years ago

How to define what is numeric is another discussion.

numeric type means it should be a structure type, and have implemented the interface of IComparable, IComparable(Of ), IEquatable(Of ) for sort by its value?

xieguigang commented 6 years ago

In current version of VisualBasic language, the code template or numeric constrain is not allowed, so that the possible solutions for implements a generic operator is using Object type or Code Copy for each numeric type. For implements a generic operator for numeric types such as the +-*/ (PrimitiveTypes/Core.vb#L283), I'm using the Object type for implements a generic numeric operator like PrimitiveTypes/Core.vb#L155 currently, but the using object type maybe brings some performance issues due to the reason of boxing or unboxing;

By introducing the numeric constrain feature, can makes such job more easier. v