for ever young

musings about for loops

An Alice 90 homecomputer
for loops are found in many programming languages

This article is part of a series about polyglot programming madness. Today we will take a look at one way to do things repeatedly. That is, using for loops.

Let’s tart with BASIC. …yess. BASIC. Probably the most used programming language by hobbyists in the early 80s. ;-)

The FOR keyword defines both start and end values. Anything that follows until the NEXT keyword is executed repeatedly, in my example, that means just printing a number. Have you noticed the loop variable after NEXT? Most BASIC dialects allow to omit it. Take a look at this one:

Loops can of course be nested. Each NEXT has a corresponding FOR, so here I have omitted the variable. The STEP keyword is used to change the increment or decrement value. Please note that start, end and increment value are computed prior to the execution of the loop.

Now, back to the future. Here is (one of several ways) how JavaScript handles for loops:

This surely looks familiar to C, Java and C# developers. There is a nice alternative usage, this time written in Java:

If we translate this into JavaScript, we get something like:

If we run it, we get… the numbers 0 to 3.

Oh my.

In defense of JavaScript I should say that I misused in. The for … in statement is meant to be used to iterate over object properties. To get my above example working as intended, we have to use of instead of in:

Now let’s turn to Swift. Take a look at the following code fragment.

This resembles my JavaScript example. But please not the missing parenthesis. To count from 1 to 10 is as simple as:

However, counting down from 10 to 1 has a caveat. Using 10…1, the code will crash. To achieve this, we can use the reversed() instance method:

Next: Dart:

Looks familiar, right? As Dart is greatly influenced by C-like languages, the three-part variant works as well:

Finally, let as turn to Kotlin. The basic usage is like this:

This resembles Swift, but we have to use parenthesis, yet write .. instead of and trying three dots does not work, of course. Counting down looks like this:

So, quite similar yet subtly different. This is polyglot programming heaven. :-) That’s it for today. Stay tuned.

A previous (less complete) version of this article was published 2017/05/14 on my blog Tommis Blog. I deleted the weblog in the wake of the GDPR (General Data Protection Regulation), so the original post is no longer available (or only through the Wayback machine of the Internet Archive).

If not stated otherwise images are © Thomas Künneth