Type class is simply a public abstract generic class, which contains some abstract or virtual methods and properties. Here's an example of Eq-like type class from Haskell:

[TypeClass]
public abstract class Eq<T>
{
  public abstract bool op_Equality(T a, T b);
  public virtual bool op_Inequality(T a, T b)
  {
    return !op_Equality(a, b);
  }
}

Member names for equality and inequality refer to C#'s operator== and operator!= names.
I've declared inequality virtual rather than abstract to provide default implementation for it via equality. This implementation will be used in case T will only provide equality.

Note, that current NTypeClasses's version does not differentiate static and instance members at all. E.g. any type T with instance method bool op_Equality(T other) will meet Eq's constraints.

As I've said before, type classes also support properties. Here's an example that requires type to have static Zero property.
[TypeClass]
public abstract class TypeWithZero<T>
{
  public abstract T Zero{ get; }
}

Actually, you don't need to mark a class with TypeClassAttribute to make a type class work, but this is strongly recommended to do so since type classes feature may be introduced in your or other .NET language in the future, so their compilers would need to distinguish type class from ordinary class.

Last edited Nov 19, 2010 at 5:37 PM by LostTheBlack, version 1

Comments

No comments yet.