Home > BCL, C# 4.0 > Zip and Tuple Neatness

Zip and Tuple Neatness

In BCL 4.0, there’s still no Unfold method (boooo), but at least there’s a Zip extension method to keep us warm as winter draws on.

I played with it thusly:

    var list1 = new[] { 1, 2, 3 };
    var list2 = new[] { "a", "b", "c" };
    var both = list1.Zip(list2, (first, second) => new { first, second });
    foreach (var item in both)

Then I thought, what about these new fangled tuples? Shouldn’t there be an overload of Zip that only takes two lists and is smart enough to return a binary tuple?

Then I realised there’s not really much need, because you can ask for that to happen very succinctly already:

var both = list1.Zip(list2, Tuple.Create);

This is not technically that astounding, because it’s just an example of a pre-defined function happening to fit the delegate required by some method. No big deal.

But in another way, it is a big deal, because of the generality of it. Suppose you have a generic method that accepts a delegate as one of its parameters, and that delegate must accept some fixed number of parameters of specific types, but can return any type. Sometimes you just want to be able to say “Oh, whatever they are, just stick them together and I’ll figure out what to do with them later”. Well, now that wish has a name, and it’s name is Tuple.Create. And this is applicable for any method that takes a delegate that takes up to 8 parameters and can return a value of unconstrained type.

Sometimes I just want to cry at the beauty of functions-as-first-class-objects.

(Just occasionally.)

Categories: BCL, C# 4.0 Tags: ,
  1. October 24, 2009 at 10:24 am

    Amen brother!

  2. John
    March 13, 2010 at 8:55 am

    Not in the BCL, but the there’s a Generate method available off the EnumerableEx extension methods to System.Linq (in the Reactive Extensions)

    • earwicker
      March 16, 2010 at 12:10 pm

      Great, I must look at that stuff properly.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: