I've found myself thinking lately about loops.
Specifically, how do you terminate a loop? I see two basic sorts
of thing here:
-
There is a reasonably knowable number of iterations when you start.
For example, "given this list of items, do the following once for
each item". The for loop can count as a special case of this;
BASIC's FOR I = 1 TO 10 can be expressed as foreach my $i (1 .. 10)
in Perl.
-
You don't know how many iterations you have: you want to loop until
a condition changes. This takes various forms: in BBC BASIC it was
REPEAT...UNTIL, and in Perl it's usually while (condition) { block }; languages may allow a test at the beginning or the end of
the loop, depending on whether you want it to be executed at least
once or not.
But while fiddling with PostScript, which doesn't have a while
operator, I realised that start and end tests are just special cases:
the test can be anywhere, taking the form "if (terminating
condition), leave the loop and go on to the next thing". And indeed
you can have multiple tests at different places.
You can extend this thinking to more sophisticated languages (Perl has
last to terminate a loop, C-like languages have break). (Generally
there's also some way to say "abandon this iteration of the loop and
carry on with the next one".) My Rust these days often has an infinite
loop { } with explicit termination conditions where I want them.
Except that functional languages don't want you to do that. In Scala
you can by design not break out of a loop. So I at least find myself
constructing scaffolding around it: have an exit-flag as part of the
while test, and if I set it mid-way through loop processing I must
explicitly skip over the rest of the loop body to go straight to the
test point. I'm sure that people who understand functional programming
can explain why it's important to have to do this.
Note that I will only approve comments that relate to the blog post itself, not ones that relate only to previous comments. This is to ensure that the blog remains outside the scope of the UK's Online Safety Act (2023).
Your submission will be ignored if any field is left blank, but your email address will not be displayed. Comments will be processed through markdown.