Categories: .Net, Patterns Posted by mheydt on 1/30/2007 2:34 AM | Comments (0)

Take the following code snippet to iterate across an array:

        int[] ia = new int[] { 5, 4, 3, 2, 1};
        for (int i=0; i<ia.Length; i++)
        {
            Console.WriteLine(ia[i]);
        }
 

What'sthe problem with this code?   Well, its just too verbose.  I have asimple idea here, and I have to type way too much.  All I want to do isdo something to every element in the array (in this case, it's print iton the console, but the process can be arbitrarily complex).  To dothis, I have to say 'for', and then create a variable that I have toinitialize, increment and check for a completion state.  I then have touse that variable to select the particular element of the array toprocess.

I can't tell you how many times I've had to type thisboiler plate, and it kills me every time as I have a simple idea, dosomething with each of the items, and I have to do a lot of problematictyping to get it done (I wont get into the reasons for problems - thathas been documented elsewhere quite well).

C# nicely has gone and made this a little simpler:

        int[] ia = new int[] { 5, 4, 3, 2, 1};
        foreach (int i in ia)
        {
            Console.WriteLine(i);
        }

Atleast with the foreach construct, I don't have the initialization ofthe index variable, incrementation, termination comparison to type andget messed up.  I still do need to have a variable to hold the currentitem, and the other boiler plate code around it (the 'foreach' andsuch).

Can't this be still simpler?  How about the following:

        int[] ia = new int[] { 5, 4, 3, 2, 1};
        iterate ia |i| { Console.WriteLine(i) };

Theiterate keyword means just that - iterate across something.  You figureout how to, Mr. computer.  I'm just interested in doing something witheach item, which I'll refer to as the symbol inside of the pipes. Isn't this nice?

Yes, I know this is quite literally Ruby, but Ijust wanted to resolve this down to its essence for expositorypurposes.  And also why I like Ruby, but more can also be accomplished,and this is another core concept of P#...

Technorati Tags:

Comments