exoteric said:

More about tuples. I see in .Net 4.0 beta 2 they are implemented as classes. How about this?

 

public struct STuple<a>
{
    private readonly a x;
    public a Item
    {
        get { return x; }
    }
    public STuple(a a)
    {
        x = a;
    }
}
public struct STuple<a, b>
{
    private readonly a x;
    private readonly STuple<b> s;
    public a Item
    {
        get { return x; }
    }
    public STuple<b> Rest
    {
        get { return s; }
    }
    public STuple(a a, b b)
    {
        x = a;
        s = new STuple<b>(b);
    }
}
public struct STuple<a, b, c>
{
    private readonly a x;
    private readonly STuple<b, c> s;
    public a Item
    {
        get { return x; }
    }
    public STuple<b, c> Rest
    {
        get { return s; }
    }
    public STuple(a a, b b, c c)
    {
        x = a;
        s = new STuple<b, c>(b, c);
    }
}
public struct STuple<a, b, c, d>
{
    private readonly a x;
    private readonly STuple<b, c, d> s;
    public a Item
    {
        get { return x; }
    }
    public STuple<b, c, d> Rest
    {
        get { return s; }
    }
    public STuple(a a, b b, c c, d d)
    {
        x = a;
        s = new STuple<b, c, d>(b, c, d);
    }
}
public struct STuple<a, b, c, d, e>
{
    private readonly a x;
    private readonly STuple<b, c, d, e> s;
    public a Item
    {
        get { return x; }
    }
    public STuple<b, c, d, e> Rest
    {
        get { return s; }
    }
    public STuple(a a, b b, c c, d d, e e)
    {
        x = a;
        s = new STuple<b, c, d, e>(b, c, d, e);
    }
}

 

As you can see they are recursively constructed structs. Their definition is much like linked lists, only here defined statically as heterogeneous nested structs.

 

It looks quite elegant and I'd expect more efficient for what tuples will often be used for than a class based implementation. There is no interface compatibility because C# forbids it. Also in this form the code is not FxCop compatible (lower-case type parameters and sins like that).

 

Now how to make these semantics better? It would be cool if the following was possible

  • an (s)tuple of a higher dimension extends an (s)tuple of a lower dimension (structural matching between lower- and higher-dimensional (s)tuples)
  • an (s)tuple is an IEnumerable<dynamic> when heterogeneous
  • an (s)tuple is an IEnumerable<T> when homogeneous

These ideas will require an extension of the generic type system for C#. For examples in C# there is no struct inheritance or  struct interface inheritance.

 

Thoughts?

 

[2nd revision]

how is a.Rest.Rest.Rest.Rest.Item more readable than a.Item4?