Remove goto in C - c

I want to remove goto statements in my C code. The following shows my C code.
void placeFruit(void)
{
resetfruitX:fruitX=rand()%20;
if(fruitX==0||fruitX==width)
goto resetfruitX;
resetfruitY:fruitY=rand()%20;
if(fruitY==0||fruitY==height)
goto resetfruitY;
}
Can anyone help me?

void placeFruit(void){
do fruitX=rand()%20; while(fruitX==0||fruitX==width);
do fruitY=rand()%20; while(fruitY==0||fruitY==width);
}

Use loops and perhaps improve readability a bit with an internal helper function:
static inline int place (int max)
{
int fruit=0;
while(fruit==0 || fruit==max)
fruit = rand() % 20;
return fruit;
}
void placeFruit(void)
{
fruitX = place(width);
fruitY = place(height);
}
do-while is a micro-optimization over while but works too - it doesn't matter much which one you pick. The performance bottleneck here is the rand() call. In theory this loop could go on for ever, so maybe consider a better strategy like having two containers/matrices, one with "used" coordinates and one with "free" coordinates.

Related

When is it acceptable to break prematurely out of a loop/method?

This is a question I've been facing for a while in my college class that I've been thinking about, and I need to get other people's point of views. I searched and couldn't find another question very similar to this one in terms of coding practices.
(Examples are written in Java)
When I write my code, I will generally write methods like this:
public void myMethod(int one, int two) {
if (one >= two) return;
// do things
if (two != one) return;
// do other things
}
Instead of writing methods like this:
public void myMethod(int one, int two) {
if (one < two) {
// do things
if (two != one) {
// do other things
}
}
}
Similarly, I will write my loops like this:
for (int i = 0; i < x.length; i++) {
if (x[i].getValue() > 4) continue;
// do things
if (!xConditionTwo) continue;
// do other things
}
Instead of like this:
for (int i = 0; i < x.length; i++) {
if (x[i].getValue() <= 4) {
// do things
if (xConditionTwo) {
// do other things
}
}
}
As seen here, I look at things sequentially (from top line to bottom line), and it makes sense to me to exit out of the method/loop if that something is not what we're looking for, and we don't require an else statement.
However, when I spoke to my college instructors, they all agreed that if somebody were to write code like this, they would not be hired because said person cannot figure out an algorithm that wouldn't require the use of a continue/return.
My question to everyone is: When is it acceptable to use continue/return to break like this, if at all? Why is this considered bad practice, and how can I avoid using if statements without an else to avoid extra indentation?
This is going to be a question mostly dealing with opinions, but for both of your examples I'd use the continue/return in the first line like you have it, but use an if statement for the other.
public void myMethod(int one, int two) {
if (two >= one) {
return;
}
// do things
if (two != one) {
// do other things
}
}
To me, this reads better and limits the nested if statements

"Saving" current state in foor loop to continue later

currently I'm thinking about the following problem and maybe someone can help me:
For minecraft I want to change a lot of blocks and to prevent lags I want to change only a couple of blocks at the same time. To change a cuboid I usually use a loop like this:
for(int x=t.x; x<t.X; x++)
for(int y=t.y; y<t.Y; y++)
for(int z=t.z; z<t.Z; z++) {
// ..
}
where t saves the from and to coords.
Now I want to save the current progress to continue later.
Please help me im tired of thinking about it..
Your code looks like C. In C, a process cannot return to a given stack state after leaving the calling functions. So leaving a loop and later returning to it are not possible at the language level. In other languages, things are different. E.g. in the Pypy implementation of the Python language, continuelets can be used to achieve what you describe.
However, you can achieve similar ways by using your own objects to store the last counters.
struct counters { int x, y, z; };
bool continueLoops(struct counters *ctrs) {
for (; ctrs->x < t.X; ctrs->x++) {
for (; ctrs->y < t.Y; ctrs->y++) {
for (; ctrs->z < t.Z; ctrs->z++) {
// ..
if (weWantToInterruptTheLoop)
return true;
}
ctrs->z = t.z;
}
ctrs->y = t.y;
}
return false;
}
void startLoops() {
struct counters ctrs;
ctrs.x = t.x;
ctrs.y = t.y;
ctrs.z = t.z;
while (continueLoops(&ctrs)) {
// do whatever you want to do between loops
}
}
However, I don't see much benefit in the above approach, as opposed to perform the relevant operation directly within the inner loop. So I'm not sure whether this is useful for you.

How can I goto the value of a String in C?

I am programming a robot in C, and I have run into a problem I can't seem to figure out.
The only way to solve this problem would be to use a lot of goto statements.
I am trying to figure out a way to save myself writing over 100 goto points and statements and if statements, etc. and am wondering if there is a way to goto the value of a string. for example-
string Next = "beginning";
goto Next;
beginning:
Is there any way to goto the value of Next, or to substitute in the value of Next into the goto statement?
If there is a way to do this, then I will be able to just change the value of Next for each driving command, and then goto whatever the value of the string Next is.
In other words, just converting the string to a goto identifier, or substituting it in place of one.
Thanks for the help!
-EDIT-
A lot of you guys are suggesting the use of switch statements. I am not sure this would work because of how i have it programmed. The structure of the program is here--
by the way this code only includes a little of what i actually have, my real code is over 500 lines so far. Also, the driving commands are majorly simplified. but the basic concept is here, easier to understand than what i wouldve had.
task main()
{
//integer list
int forwardDrivingSelector = 0;
int backwardDrivingSelector = 0;
int rightRotatingSelector = 0;
string nextCommand;
int waitTime = 0;
int countup = 0;
//driving commands
driveForward:
while(forwardDrivingSelector == 1)
{
motor[leftMotor] = 127;
motor[rightMotor] = 127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
driveBackward:
while(backwardDrivingSelector == 1)
{
motor[leftMotor] = -127;
motor[rightMotor] = 127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
rightRotate:
while(rightRotatingSelector == 1)
{
motor[leftMotor] = 127;
motor[rightMotor] = -127;
countup++;
wait1Msec(1);
if(countup == waitTime)
{
countup = 0;
goto nextCommand;
}
}
//autonomous driving code
//first command, drive forward for 1000 milliseconds
forwardDrivingSelector = 1;
nextCommand = "secondCommand";
waitTime = 1000;
goto driveForward;
secondCommand:
forwardDrivingSelector = 0;
//second command, rotate right for 600 milliseconds
rightRotatingSelector = 1;
nextCommand = "thirdCommand";
waitTime = 600;
goto rightRotate;
thirdCommand:
rightRotatingSelector = 0;
//third command, drive backwards for 750 milliseconds
backwardDrivingSelector = 1;
nextCommand = "end";
waitTime = 750;
goto driveBackward;
end:
backwardDrivingSelector = 0;
}
so. how this works.
i have a list of integers, including driving command selectors, the countup and waitTime integers, and the string that i was talking about, nextCommand.
next comes the driving commands. in my real code, i have about 30 commands, and they are all hooked up to a remote control and its over 400 lines for just the driving commands.
next comes the autonomous code. the reason i set it up like this is so that the autonomous code part would be, short, simple, and to the point. pretty much to add a command to the driving code, you turn on the selector, tell the nextCommand string what the next command is, set the waitTime (which is how long it does the command, in milliseconds), then you make the code goto the driving command which you are putting in. the driving command drives for the amount of time you put in, then does goto nextCommand;
This would all theoretically work if there was a way to make the goto statement 'interpret' the string as an identifier so it can be changed.
There are about 4 simple ways i can think of right now that could get past this easily, but they would make the code really really long and cluttered.
Now that you have a better understanding of my question, any more input? :)
btw - i am using a program called robotC, and i am programming a vex robot. so i HAVE to use plain, basic, C, and i cant use any addons or anything... which is another reason this is complicated because i cant have multiple classes and stuff like that...
As an extension to the C language, GCC provides a feature called computed gotos, which allow you to goto a label computed at runtime. However, I strongly recommend you reconsider your design.
Instead of using gotos with over a hundred labels (which will easily lead to unmaintainable spaghetti code), consider instead using function pointers. The code will be much more structured and maintainable.
Instead of goto's, I'd call one of 100 functions. While C won't handle the conversion from string to function for you, it's pretty easy to use a sorted array of structs:
struct fn {
char name[whatever];
void (*func)(void);
};
Then do (for example) a binary search through the array to find the function that matches a string.
Also note that many real systems provide things like GetProcAddress (Windows) or dlsym (Unix/Linux) to handle some of the work for you.
You're thinking about this the wrong way. Each of the actions you need to call should be a function, then you can choose which function should be called next by inspecting a "next" variable.
This could be a string as you've mentioned, but you might be best using a enumerated type to make readable, but more efficient code.
The alternative, though probably overkill, would be to ensure your functions all use the same parameters and return types, and then use a function pointer to track which piece of code should be executed next.
Small tip: If you ever think you need more than 1 goto statement to achieve a certain goal you're probably not looking at the best solution.
You need to step back and consider other solutions for the problem you are trying to solve. One of them might look like this:
void DoSomething() {
printf("Something\n");
}
void DoSomethingElse() {
printf("Something else\n");
}
void (*nextStep)(void) = NULL;
nextStep = DoSomething;
nextStep();
nextStep = DoSomethingElse;
nextStep();
See it in action.
How about a switch? Either use an int/enum/whatever or inspect the value of the string (loop over it and strcmp, for instance) to figure out the destination.
const char *dsts[n_dsts] = {"beginning","middle",...};
...
int i;
for(i = 0; i < n_dsts; i++) if(strcmp(dsts[i]) == 0) break;
switch(i) {
case 0: // whatever
case 1: // whatever
...
break;
default: // Error, dest not found
}
Firstly, let me preface this by agreeing with everyone else: this is probably not the right way to go about what you're trying to do. In particular, I think you probably want a finite-state machine, and I recommend this article for guidelines on how to do that.
That said . . . you can more or less do this by using a switch statement. For example:
Next = BEGINNING;
HelperLabel:
switch(Next)
{
case BEGINNING:
.
.
.
Next = CONTINUING;
goto HelperLabel;
case ENDING:
.
.
.
break;
case CONTINUING:
.
.
.
Next = ENDING;
goto HelperLabel;
}
(Note that a switch statement requires integers or integer-like values rather than strings, but you can use an enum to create those integers in a straightforward way.)
See http://en.wikipedia.org/wiki/Duff's_device for the original, canonical example of using switch/case as a goto.
#define GOTO_HELPER(str, label) \
if (strcmp(str, #label) == 0) goto label;
#define GOTO(str) do { \
GOTO_HELPER(str, beginning) \
GOTO_HELPER(str, end) \
} while (0)
int main (int argc, char ** argv) {
GOTO("end");
beginning:
return 1;
end:
return 0;
}

How to make external Mathematica functions interruptible?

I had an earlier question about integrating Mathematica with functions written in C++.
This is a follow-up question:
If the computation takes too long I'd like to be able to abort it using Evaluation > Abort Evaluation. Which of the technologies suggested in the answers make it possible to have an interruptible C-based extension function? How can "interruptibility" be implemented on the C side?
I need to make my function interruptible in a way which will corrupt neither it, nor the Mathematica kernel (i.e. it should be possible to call the function again from Mathematica after it has been interrupted)
For MathLink - based functions, you will have to do two things (On Windows): use MLAbort to check for aborts, and call MLCallYieldFunction, to yield the processor temporarily. Both are described in the MathLink tutorial by Todd Gayley from way back, available here.
Using the bits from my previous answer, here is an example code to compute the prime numbers (in an inefficient manner, but this is what we need here for an illustration):
code =
"
#include <stdlib.h>
extern void primes(int n);
static void yield(){
MLCallYieldFunction(
MLYieldFunction(stdlink),
stdlink,
(MLYieldParameters)0 );
}
static void abort(){
MLPutFunction(stdlink,\" Abort \",0);
}
void primes(int n){
int i = 0, j=0,prime = 1, *d = (int *)malloc(n*sizeof(int)),ctr = 0;
if(!d) {
abort();
return;
}
for(i=2;!MLAbort && i<=n;i++){
j=2;
prime = 1;
while (!MLAbort && j*j <=i){
if(i % j == 0){
prime = 0;
break;
}
j++;
}
if(prime) d[ctr++] = i;
yield();
}
if(MLAbort){
abort();
goto R1;
}
MLPutFunction(stdlink,\"List\",ctr);
for(i=0; !MLAbort && i < ctr; i++ ){
MLPutInteger(stdlink,d[i]);
yield();
}
if(MLAbort) abort();
R1: free(d);
}
";
and the template:
template =
"
void primes P((int ));
:Begin:
:Function: primes
:Pattern: primes[n_Integer]
:Arguments: { n }
:ArgumentTypes: { Integer }
:ReturnType: Manual
:End:
";
Here is the code to create the program (taken from the previous answer, slightly modified):
Needs["CCompilerDriver`"];
fullCCode = makeMLinkCodeF[code];
projectDir = "C:\\Temp\\MLProject1";
If[! FileExistsQ[projectDir], CreateDirectory[projectDir]]
pname = "primes";
files = MapThread[
Export[FileNameJoin[{projectDir, pname <> #2}], #1,
"String"] &, {{fullCCode, template}, {".c", ".tm"}}];
Now, here we create it:
In[461]:= exe=CreateExecutable[files,pname];
Install[exe]
Out[462]= LinkObject["C:\Users\Archie\AppData\Roaming\Mathematica\SystemFiles\LibraryResources\
Windows-x86-64\primes.exe",161,10]
and use it:
In[464]:= primes[20]
Out[464]= {2,3,5,7,11,13,17,19}
In[465]:= primes[10000000]
Out[465]= $Aborted
In the latter case, I used Alt+"." to abort the computation. Note that this won't work correctly if you do not include a call to yield.
The general ideology is that you have to check for MLAbort and call MLCallYieldFunction for every expensive computation, such as large loops etc. Perhaps, doing that for inner loops like I did above is an overkill though. One thing you could try doing is to factor the boilerplate code away by using the C preprocessor (macros).
Without ever having tried it, it looks like the Expression Packet functionality might work in this way - if your C code goes back and asks mathematica for some more work to do periodically, then hopefully aborting execution on the mathematica side will tell the C code that there is no more work to do.
If you are using LibraryLink to link external C code to the Mathematica kernel, you can use the Library callback function AbortQ to check if an abort is in progress.

Useful alternative control structures?

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.
One that's fairly common is the infinite loop. I'd like to write it like this:
forever {
// ...
}
Sometimes, I need to have a foreach loop with an index. It could be written like this:
foreach (index i) (var item in list) {
// ...
}
(I'm not particularly fond of this syntax, but you get the idea)
Most languages have built-in functions to cover the common cases, but "fencepost" loops are always a chore: loops where you want to do something on each iteration and also do something else between iterations. For example, joining strings with a separator:
string result = "";
for (int i = 0; i < items.Count; i++) {
result += items[i];
if (i < items.Count - 1) result += ", "; // This is gross.
// What if I can't access items by index?
// I have off-by-one errors *every* time I do this.
}
I know folds can cover this case, but sometimes you want something imperative. It would be cool if you could do:
string result = "";
foreach (var item in items) {
result += item;
} between {
result += ", ";
}
Loop with else:
while (condition) {
// ...
}
else {
// the else runs if the loop didn't run
}
{
foo();
} split_while( condition ) {
bar();
}
You can accomplish that pretty easily using a regular while:
while (true) {
foo();
if (!condition) break;
bar();
}
I do that pretty frequently now that I got over my irrational distaste for break.
If you look at Haskell, although there is special syntax for various control structures, control flow is often captured by types. The most common kind of such control types are Monads, Arrows and applicative functors. So if you want a special type of control flow, it's usually some kind of higher-order function and either you can write it yourself or find one in Haskells package database (Hackage) wich is quite big.
Such functions are usually in the Control namespace where you can find modules for parallel execution to errorhandling. Many of the control structures usually found in procedural languages have a function counterpart in Control.Monad, among these are loops and if statements. If-else is a keyworded expression in haskell, if without an else doesn't make sense in an expression, but perfect sense in a monad, so the if statements without an else is captured by the functions when and unless.
Another common case is doing list operation in a more general context. Functional languages are quite fond of fold, and the Specialized versions like map and filter. If you have a monad then there is a natural extension of fold to it. This is called foldM, and therefor there are also extensions of any specialized version of fold you can think of, like mapM and filterM.
This is just a general idea and syntax:
if (cond)
//do something
else (cond)
//do something
also (cond)
//do something
else
//do something
end
ALSO condition is always evaluated. ELSE works as usual.
It works for case too. Probably it is a good way to eliminate break statement:
case (exp)
also (const)
//do something
else (const)
//do something
also (const)
//do something
else
//do something
end
can be read as:
switch (exp)
case (const)
//do something
case (const)
//do something
break
case (const)
//do something
default
//do something
end
I don't know if this is useful or simple to read but it's an example.
With (lisp-style) macros, tail-calls, and continuations all of this is quaint.
With macros, if the standard control flow constructs are not sufficient for a given application, the programmer can write their own (and so much more). It would only require a simple macro to implement the constructs you gave as an example.
With tail-calls, one can factor out complex control flow patters (such as implementing a state machine) into functions.
Continuations are a powerful control flow primitive (try/catch are a restricted version of them). Combined with tail-calls and macros, complex control flow patterns (backtracking, parsing, etc.) become straight-forward. In addition, they are useful in web programming as with them you can invert the inversion of control; you can have a function that asks the user for some input, do some processing, asks the user for more input, etc.
To paraphrase the Scheme standard, instead of piling more features onto your language, you should seek to remove the limitations that make the other features appear necessary.
if not:
unless (condition) {
// ...
}
while not:
until (condition) {
// ...
}
Labeled loops are something I find myself missing sometimes from mainstream languages. e.g.,
int i, j;
for outer ( i = 0; i < M; ++i )
for ( j = 0; j < N; ++j )
if ( l1[ i ] == l2[ j ] )
break outer;
Yes, I can usually simulate this with a goto, but an equivalent for continue 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 with continue and break. It would return to the start of the loop without evaluating the increment.)
I propose the "then" operator. It returns the left operand on the first iteration and the right operand on all other iterations:
var result = "";
foreach (var item in items) {
result += "" then ", ";
result += item;
}
in the first iteration it adds "" to the result in all others it adds ", ", so you get a string that contains each item separated by commas.
if (cond)
//do something
else (cond)
//do something
else (cond)
//do something
first
//do something
then
//do something
else (cond)
//do something
else
//do something
end
FIRST and THEN blocks runs if any of 3 conditionals are evaluated to true. FIRST block runs before the conditional block and THEN runs after the conditional block has ran.
ELSE conditional or final write following FIRST and THEN statement are independent from these blocks.
It can read as :
if (cond)
first()
//do something
then()
else (cond)
first()
//do something
then()
else (cond)
first()
//do something
then()
else (cond)
//do something
else
//do something
end
function first()
//do something
return
function then()
//do something
return
These functions are just a form to read. They wouldn't create scope. It's more like a gosub/return from Basic.
Usefulness and readability as matter of discussion.
How about
alternate {
statement 1,
statement 2,
[statement 3,...]
}
for cycling through the available statements on each successive pass.
Edit: trivial examples
table_row_color = alternate(RED, GREEN, BLUE);
player_color = alternate(color_list); // cycles through list items
alternate(
led_on(),
led_off()
);
Edit 2: In the third example above the syntax is maybe a bit confusing as it looks like a function. In fact, only one statement is evaluated on each pass, not both. A better syntax might be something like
alternate {
led_on();
}
then {
led_off();
}
Or something to that effect. However I do like the idea that the result of which ever is called can be used if desired (as in the color examples).
D's scope guards are a useful control structure that isn't seen very often.
I think I should mention CityScript (the scripting language of CityDesk) which has some really fancy looping constructs.
From the help file:
{$ forEach n var in (condition) sort-order $}
... text which appears for each item ....
{$ between $}
.. text which appears between each two items ....
{$ odd $}
.. text which appears for every other item, including the first ....
{$ even $}
.. text which appears for every other item, starting with the second ....
{$ else $}
.. text which appears if there are no items matching condition ....
{$ before $}
..text which appears before the loop, only if there are items matching condition
{$ after $}
..text which appears after the loop, only of there are items matching condition
{$ next $}
Also note that many control structures get a new meaning in monadic context, depending on the particular monad - look at mapM, filterM, whileM, sequence etc. in Haskell.
ignoring - To ignore exceptions occuring in a certain block of code.
try {
foo()
} catch {
case ex: SomeException => /* ignore */
case ex: SomeOtherException => /* ignore */
}
With an ignoring control construct, you could write it more concisely and more readably as:
ignoring(classOf[SomeException], classOf[SomeOtherException]) {
foo()
}
[ Scala provides this (and many other Exception handling control constructs) in its standard library, in util.control package. ]
I'd like to see a keyword for grouping output. Instead of this:
int lastValue = 0;
foreach (var val in dataSource)
{
if (lastValue != val.CustomerID)
{
WriteFooter(lastValue);
WriteHeader(val);
lastValue = val.CustomerID;
}
WriteRow(val);
}
if (lastValue != 0)
{
WriteFooter(lastValue);
}
how about something like this:
foreach(var val in dataSource)
groupon(val.CustomerID)
{
startgroup
{
WriteHeader(val);
}
endgroup
{
WriteFooter(val)
}
}
each
{
WriteRow(val);
}
If you have a decent platform, controls, and/or reporting formatting you won't need to write this code. But it's amazing how often I find myself doing this. The most annoying part is the footer after the last iteration - it's hard to do this in a real life example without duplicating code.
Something that replaces
bool found = false;
for (int i = 0; i < N; i++) {
if (hasProperty(A[i])) {
found = true;
DoSomething(A[i]);
break;
}
}
if (!found) {
...
}
like
for (int i = 0; i < N; i++) {
if (hasProperty(A[i])) {
DoSomething(A[i]);
break;
}
} ifnotinterrupted {
...
}
I always feel that there must be a better way than introducing a flag just to execute something after the last (regular) execution of the loop body. One could check !(i < N), but i is out of scope after the loop.
This is a bit of a joke, but you can get the behavior you want like this:
#include <iostream>
#include <cstdlib>
int main (int argc, char *argv[])
{
int N = std::strtol(argv[1], 0, 10); // Danger!
int state = 0;
switch (state%2) // Similar to Duff's device.
{
do {
case 1: std::cout << (2*state) << " B" << std::endl;
case 0: std::cout << (2*state+1) << " A" << std::endl; ++state;
} while (state <= N);
default: break;
}
return 0;
}
p.s. formatting this was a bit difficult and I'm definitely not happy with it; however, emacs does even worse. Anyone care to try vim?
Generators, in Python, are genuinely novel if you've mostly worked with non-functional languages. More generally: continuations, co-routines, lazy lists.
This probably doesn't count, but in Python, I was upset there was no do loop.
Anto ensure I get no upvotes for this answer, I wind up annoyed at any language I work in for any period of time that lacks goto's.
for int i := 0 [down]to UpperBound() [step 2]
Missing in every C-derived language.
Please consider before you vote or write a comment:
This is not redundant to for (int i = 0; i <= UpperBound(); i++), it has different semantics:
UpperBound() is evaluated only once
The case UpperBound() == MAX_INT does not produce an infinite loop
This is similar to the response by #Paul Keister.
(mumble, mumble) years ago, the application I was working on had lots of variations of so-called control-break processing -- all that logic that goes into breaking sorted rows of data into groups and subgroups with headers and footers. As the application was written in LISP, we had captured the common idioms in a macro called WITH-CONTROL-BREAKS. If I were to transpose that syntax into the ever-popular squiggly form, it might look something like this:
withControlBreaks (x, y, z : readSortedRecords()) {
first (x) : { emitHeader(x); subcount = 0; }
first (x, y) : { emitSubheader(x, y); zTotal = 0; }
all (x, y, z) : { emitDetail(x, y, z); ztotal += z; }
last (x, y) : { emitSubfooter(x, y, zTotal); ++subCount; }
last (x) : { emitFooter(x, subcount); }
}
In this modern era, with widespread SQL, XQuery, LINQ and so on, this need does not seem to arise as much as it used to. But from time to time, I wish that I had that control structure at hand.
foo();
while(condition)
{
bar();
foo();
}
How about PL/I style "for" loop ranges? The VB equivalent would be:
' Counts 1, 2, ... 49, 50, 23, 999, 998, ..., 991, 990
For I = 1 to 50, 23, 999 to 990 Step -1
The most common usage I can see would be to have a loop run for a list of indices, and then throw in one more. BTW, a For-Each usage could also be handy:
' Bar1, Bar2, Bar3 are an IEnum(Wazoo); Boz is a Wazoo
For Each Foo as Wazoo in Bar1, Bar2, Enumerable.One(Boz), Bar3
This would run the loop on all items in Bar1, all items in Bar2, Boz, and Bar3. Linq would probably allow this without too much difficulty, but intrinsic language support might be a little more efficient.
One of the control structures that isn't available in many languages is the case-in type structure. Similar to a switch type structure, it allows you to have a neatly formatted list of possible options, but matches the first one that's true (rather then the first one that matches the input). A LISP of such such (which does have it):
(cond
((evenp a) a) ;if a is even return a
((> a 7) (/ a 2)) ;else if a is bigger than 7 return a/2
((< a 5) (- a 1)) ;else if a is smaller than 5 return a-1
(t 17)) ;else return 17
Or, for those that would prefer a more C-like format
cond
(a % 2 == 0):
a; break;
(a > 7):
a / 2; break;
(a < 5):
a - 1; break;
default:
17; break;
It's basically a more accurate representation of the if/elseif/elseif/else construct than a switch is, and it can come in extremely handing in expressing that logic in a clean, readable way.
How about iterating with a moving window (of n elements instead of 1) through a list?
This is tangentially related #munificent's answer, I think.
Something like
#python
#sum of adjacent elements
for x,y in pairs(list):
print x + y
def pairs(l):
i=0
while i < len(l)-1:
yield (l[i],l[i+1])
i+=1
It is useful for certain types of things. Don't get me wrong, this is easy to implement as a function, but I think a lot of people try to bring out for and while loops when there are more specific/descriptive tools for the job.

Resources