5.7.17  Mythryl for Loop

SML suffers from a paucity of iterative constructs. Only while is standard, and it is almost never used.

Mythryl implements a C-flavored for loop construct:

    for (i = 0; i < 10; ++i) {
        printf "Loop %d\n" i;

That looks disturbingly imperative at first blush, but is in fact a derived form which expands into a recursive function as pure as the driven snow. The general form is

    for ( i = expressioni, j = expressionj ...; conditional; loop_increments; result_expression) {
        loop body

which the compiler expands internally into code like

    let fun loop (i, j, ...) = {
            if (conditional)
                loop body;
                loop( i, j, ...);
        loop (expressioni, expressionj, ...);

You will note that the former version is one-quarter the length of the latter: Using the for construct can make iterative code considerably shorter and clearer!

Incidentally, the ++i and --j syntax expand into harmless pure i = i + 1; and j = j - 1; statements.

So there you are, the best of both worlds: clean loop syntax without guilt!

By the way, the old while loop is still available as

    for (expression) {
        loop body

The point of the keyword substitution is to return while to the general identifier pool: The fewer reserved words, the better.

Comments and suggestions to: