Thursday, November 5, 2009

Functional .Net : Tuple

Tuple's really don't have a lot to do with functional programming, they are a common concept in many language that for some reason are only making their way in the .Net on version 4.0. One could argue that you could have always easily constructed your own Tuple class but unnecessary duplication of such a simple type has obviously become apparent to the BCL team. This is good. Simple classes like this should be present in the framework. :)

So what is a Tuple? It is basically a container of a finite list of objects; a Point could be described as a list of 2 values Tuple<int, int> where the int values could be the X and The Y coordinates of a point. A Date could be described as Turple<int,int,int> with the values being Year, Month & Day. It is not a list in that your would typically enumerate through the items but you would reference them by index. You may be ask why is this different to an Array eg int[3]? Well with a Tuple the list length is set at compile time and the type of each index point is also set. Tuple<int,string,DateTime> forces you to always have the DateTime as the 3rd item. This is all pretty under-whelming to be honest, but like anything cool its the simplicity that is its strength and also why it pops up in functional styled programming a lot. Future demos are likely to include Tuples :)

3 comments:

Anonymous said...

Tuples would be a lot more useful if a special syntax was added for them.

Something like this would be nice:

(int, int, int) GetDate()
{
return (5, 10, 1984);
}

Wolfbyte said...

I recently added Tuple behavior to a .NET 3.5 app I'm working on. I based my implementation on the BCL 4.0 version so that when we upgrade I can just delete my classes and move on. I was hoping to use it to return multiple values (without using out and ref parameters which I hate) similar to the way arrays tend to be used in ruby.

Unfortunately without some special syntax this is worse than useless. Even looking back on the ruby syntax it's a little suspect. You can't easily provide names for the elements which means that even though there IS a strict order of the elements, it's not really encoded anywhere.

i.e. Point IS a Tuple as X comes before Y but returning a Tuple is pointless here as YOU as a developer have to remember which is X and which is Y. You are better off with the actual Tuple class. In most places where I'd use a Tuple I suspect that this will be the case.

Wolfbyte said...

Whoops, "You are better off with the actual Tuple class" should read "Point class". I can't think of a situation where a Tuple could be used that a more specific type wouldn't be better