May 07, 2011

Evolution of the FOR loop

The history of FOR loop is long and interesting. Nearly every high-level programming language has developed an own variant of the FOR loop, for making it easy for the programmer to iterate a variable through numeric sequences and ranges. Here we are going to compare how each programming language has done it, and we will see that the syntax has not necessarily always gone to a better direction.

One interesting point is that nearly all languages also have some kind of implementation of foreach - means to iterate through a list. But this syntax seems to differ very little between languages. Maybe the reason for that is that when talking about foreach, it is quite obvious what the programmer is up to, whereas with regular for, it is not that clear.

Let's have a look how COBOL did it.

   PERFORM VARYING A FROM 0 BY 1 UNTIL A=99
      ...
   END-PERFORM

Now the syntax is a disaster. There is an awful lot of typing for the simplest thing. This loops variable a from 0 to 99, and - after a quick count - it takes 53 keypresses to achieve that simple loop.

Now what do we have in C ?
for(int a; a<100; ++a)
        { ... }

A lot more compact, have to admit. But logically, it is a mess. I never really understood the reason for including for loop into C language anyway. It looks like misters Kernighan and Ritchie had added this syntax the last day before publishing their book in a terrible hurry. You can write perfectly good code without it. The syntax is nothing but a handy access to a regular while loop, adding some extra complexity and removing readability. Syntax like this requires the programmer to know EXACTLY in which phases of the loop the different segments are evaludated. Stupid syntax, and should be deprecated.

Python does the same thing like this:

for a in range(0, 100):
        ...

Now I can't think of anything to improve in here. First of all, it is easy to write and easy to understand. And there is one more very important point about the syntax: Python combines here the for and foreach syntaxes in one. If the programmer wants a regular loop, he will just need to create an instant throwaway array to iterate through. So Python has avoided the "unclear for loop problem" by removing the regular for keyword completely, offering only a foreach -type of solution, and then a function to support "regular" looping when user just wants to repeat something. From programmer's point of view this is most esthetic, and if this can be optimized, an extremely elegant solution.

No comments:

Post a Comment