Why don't we have a "Repeat" loop?

Computer programming has many different kinds of loops.

We have the while loop:

while(condition) {
    //do action
}

We have the for loop:

for(var i = 0; i < n; i++) {
 //do action
}

We have the do-while loop, a variant of the while loop that checks the conditions at the end of execution:

do {
    //action
} while(condition);

We have the foreach loop, a distant relative of the for loop:

foreach(var item in collection) {
    //do action, presumably to item
}

But there's a very common loop operation in computer programming that's not supported by any kind of syntactic sugar, and the more I think about it, the less I can figure out why. This is actually the same operation I used for my example of a for loop above; that's how basic it is. The operation is "repeat an action N times".

Obviously you can express this with a while loop, using a counter that increments in the loop body and a condition to detect the end, like so:

var i = 0;

while(i < n) {
    //do action
    i++;
}

You can do the same with a for, or a do-while, or even a foreach if you really finagled things (by for example instantiating an array of size n and iterating through it). But the whole point of syntactic sugar is to make common operations easy to write and to grok! Otherwise we'd all still be out here writing Assembly. So here's what a repeat loop should look like:

repeat(n) {
    //do action
}

That's it. That's the whole thing. That's how you should be able to tell a computer "now repeat this action n times". Nothing more should be necessary. The only nice-to-have feature would be a way to give the programmer access to the current (0-indexed, obviously) iteration number, within the scope of the loop.

Anyway, I don't write any programming languages (yet?) but here's a user-defined way to do it in C#:

public static void Repeat(int n, Action action) {
    for(var i = 0; i < n; i++) {
        action();
    }
}

And an overload that lets you access the iteration number:

public static void Repeat(int n, Action<int> action) {
    for(var i = 0; i < n; i++) {
        action(i);
    }
}

You can call them like so:

Repeat(5, () => { Console.WriteLine("hi"); });
Repeat(5, (n) => { Console.WriteLine(n); });

And there you are! If you ask me, all languages should implement this construct. It would be a nice and pleasing little bit of syntactic sugar!


You'll only receive email when they publish something new.

More from Tom
All posts