Wednesday, June 23, 2004

Language enhancements

What will I code at the moment when I'd obtain my copy of new C#? First I'll try to use templates and anonymous delegates at their full potential. First I'd like to have a class

class Range<Type T>
{
public T Left, Right;
public virtual void Each( T step,
delegate bool body( T ) )
{
for( T t = Left; t < Right; t += step )
if( !body( t ) ) break;
}
}

Please, note that the delegate body has been declared as bool. The purpose is to allow complete mirroring of foreach statement.

Range<double> dr( 0.0, 100.0 );
double max = 66.0;
double min = 33.0;
double sum = 0.0;
dr.Each( 3.14, \(double i)
{
if( i > max ) break;
if( i < min ) continue;
sum += i;
}

break statement is meaningless in this case unless it was equivalent to return false. Reciprocally contiunue would be equivalent to return true. While the example was not very practical, it's illustrative. Certainly the anonymous delegate should return true by default.

Another feature would be a statement for instantiation of a template. Just like in C++

typedef Range<int> Int32Range;

I work on a class library which requires this feature.

Next I'd like to be able to restrict the use the template on ordered and additive types only:

class Range<Type T : IAdditive, IComparable>

Next a variation of Each method

class Range<Type T : IAdditive, IComparable>
{
public virtual void Each(
delegate T step(T),
delegate bool body(T))
{
for( T t = Left; t < Right; t = step(t) )
if( !body(t) ) break;
}
}

Or this could be declared as

public virtual void Each(delegate step(ref T),
delegate bool body(T))

Then DiscontinuousRange<Type T, T step> could be declared to provide Each method with default step etc.

Let's return to IAdditive and IComparable. It would be good if the classification was a little bit complicated. For example, let's declare IOrdered. Then IContinuous:IOrdered, IDiscontinuous:IOrdered, and IAlternative:IOrdered. Finally declare Int32 as IDiscontinuous, Double as IContinuous, Boolean as IAlternative. This will provide an opportunity to define

class DiscontinuousRange<Type T:IDiscontinuous> : Range<T>
{
public void Each( delegate bool body(T) )
{
T t = Left;
while( T.MoveNext(ref t) ) )
if( !body(t) ) ) break;
}
}

The Range class is especially useful in defining ranges of continuous data such as DateTime.

One more piece of sugar:

interface IList<Type ItemType,
Type IndexType : IDiscontinuous>;
class DicontinuousRange<Type T : IDiscontinuous>:Range<T>
{
public template <Type ItemType>
static ItemType [] operator *(
IList<ItemType,T> list,
DicontinuousRange<T>)
{
ArrayList<ItemType> result = new ArrayList<ItemType>();
Each( \(t)
{
Result.Add( list[t] );
});
retun result.ToArray();
}
}


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?