Note: this feature is subject to change

Let's assume we wanna make generic Vector3D<T> struct which supports addition. Besides the fact, that operator+ can't be made part of interface (which is one reason to use type classes here), primitive types in .NET does not support this operator at all. A call to it instead is replaced by compilers in code to a CIL instruction add. This anyway will not prevent us from making generic Vector3D<T> which will support the addition. Let's see an example:

[TypeClass]
public abstract class AddOp<T>
{
  public abstract T op_Add(T a, T b);
}

public struct Vector3D<T>
{
  static readonly AddOp<T> addop = TypeClass<AddOp<T>>.Instance;
  
  T X, Y, Z;

  public static Vector3D<T> operator+(Vector3D<T> a, Vector3D<T> b)
  {
    return new Vector3D<T>{
      X = addop.op_Add(a.X, b.X),
      Y = addop.op_Add(a.Y, b.Y),
      Z = addop.op_Add(a.Z, b.Z),
    };
  }
}

If we try to instantiate Vector3D<double> as is, at runtime this will lead to TypeLoadException since System.Double does not have operator+ defined. To handle that situation, TypeClass can scan specified types to provide custom implementation for System.Double.

[TypeExtension]
public static class DoubleImpls
{
  public static double op_Addition(double a, double b){ return a + b; }
}

static class Program
{
  static void Main()
  {
    var a = new Vector3D<double>{ X = 1 };
    var b = new Vector3D<double>{ Y = 1 };
    Console.WriteLine(a + b);
  }
}
The above code works without any exception. Note TypeExtensionAttribute applied to DoubleImpls. This attribute indicates that type class loader may scan this type to find implementations for missing methods.

Also, NTypeClasses provides some implementation for primitive types under NTypeClasses.PrimitiveTypes namespace.

Last edited Nov 24, 2010 at 11:01 PM by LostTheBlack, version 2

Comments

No comments yet.