While and do-while loops

While and do-while loops in XY are very similar to loops in C or Python. Major difference is loops in XY can be expressions i.e. produce a value.

Void form

The void form (i.e. no value is produced) is the most basic and easiest to understand. A while loop first checks the condition, if true then the body is executed, and this repeats until the condition becomes false. Do-while loops first execute the body and then check the condition.

while (cond) {
    ... body ...
}

do {
    ... body ...
} while (cond);
  • The condition of a while or do-while loop must be a Bool. XY does not auto convert it. This avoiding many pitfalls.
  • A terminating semicolon is always required at the end of a do-while.

do-while loops are rearely used but in certain cases they produce more readable code. They are also relatively easy to implement by a compiler. For these reasons it was decided to include do-whiles in XY.

Named loops

Loops can be given a name. The name can serve two purposes:

  • Add additional information what the loops is supposed to do
  • Be used to break or continue the loop from within another loop
while loopName(cond) {
    ... body ...
}

do {
    ... body ...
} while loopName(cond);

Loops as expressions

Loops can produce a result:

while (cond) -> (res := initialValue) {
    ... body ...
}

do -> (res := initialValue) {
    ... body ...
} while(cond);

This is lowered by the compiler i.e. equivalent to

-> (res := initValue) {
    while (cond) {
        ... body ...
    }
}

-> (res := initialValue) {
    do {
        ... body ...
    } while(cond);
}

The names of the resulting variables (res in this example) can be used in the condition despite the fact it appears after the condition in the code.

Short form

In order to improve readability, XY provides a short form for loops:

while (cond) expr;

# is lowered to

-> (tmp := %expr) {
    while (cond) {
        tmp = expr;
    }
}

And similarly for do-while loops:

do expr while(cond);

# is lowered to

-> (tmp := %expr) {
    do {
        tmp = expr;
    } while (cond);
}

tmp is a variable auto-generated by the compiler which name is unknown and hidden from the program.

Break

The keyword break can be used to skip the remaining code in the current iteration and move to executing the code immediatelly after the loop. Alternatively the break keyword may be followed by the name of the loop to break.

do {
    while inner(cond2) {
        if (cond3) {
            break outer;
        }
    }
} outer(cond1);

Continue

The keyword continue can be used to skip the remaining code in the current iteration and move to reevaluating the condition. A specific loop to continue can be specified by using its name.

do {
    while inner(cond2) {
        if (cond3) {
            break outer;
        }
    }
} outer(cond1);

This site uses Just the Docs, a documentation theme for Jekyll.