Sometimes when I am programming, I find that some particular control structure would be very useful to me, but is not directly available in my programming language. I think my most common desire is something like a "split while" (I have no idea what to actually call this):
{
foo();
} split_while( condition ) {
bar();
}
The semantics of this code would be that foo()
is always run, and then the condition is checked. If true, then bar()
is run and we go back to the first block (thus running foo()
again, etc). Thanks to a comment by reddit user zxqdms, I have learned that Donald E. Knuth writes about this structure in his paper "Structured programming with go to
statements" (see page 279).
What alternative control structures do you think are a useful way of organizing computation?
My goal here is to give myself and others new ways of thinking about structuring code, in order to improve chunking and reasoning.
Note: I'm not asking about how to generalize all possible control structures, whether by using jne
, if
/goto
, Lisp macros, continuations, monads, combinators, quarks, or whatever else. I'm asking what specializations are useful in describing code.
Labeled loops are something I find myself missing sometimes from mainstream languages. e.g.,
Yes, I can usually simulate this with a
goto
, but an equivalent forcontinue
would require you to move the increment to the end of loop body after the label, hurting the readability. You can also do this by setting a flag in the inner loop and checking it at each iteration of the outer loop, but it always looks clumsy.(Bonus: I'd sometimes like to have a
redo
to go along withcontinue
andbreak
. It would return to the start of the loop without evaluating the increment.)You can accomplish that pretty easily using a regular
while
:I do that pretty frequently now that I got over my irrational distaste for
break
.Sometimes, I need to have a foreach loop with an index. It could be written like this:
(I'm not particularly fond of this syntax, but you get the idea)
I think I should mention CityScript (the scripting language of CityDesk) which has some really fancy looping constructs.
From the help file: