The source code of a computer program necessarily speaks to two different audiences, the computers whom it commands, and the humans who would read and amend those commands. The for loop construct is addressed especially to the human audience. The for loop in PostScript is stylish, but I would have good use for a subtly different version of it.
To use the for loop in PostScript you push four values onto the stack,
the initial value of the counter, the increment, the limit, and finally the
procedure itself. The for command causes the procedure to be
executed repeatedly, with a different value on the top of the stack each time.
So 7 2 12 f for causes the evaluation of f(7),f(9),f(11).
The number of times the function is evaluation is a natural number,0,1,2,3,
···
If memory serves, the Pascal programming language takes this as
a justification for restricting the type of the loop variable to be ordinal.
This is a poor fit to the task of describing pages.
For example, my program for printing blank music sheets needs to draw batches of
five lines to form the staves. It seems natural to express this
bottom_line
line_spacing
top_line
draw line
for
Postscript permits floating point numbers, which is natural if the
start and the increment represent physical distances.
But this has its own problem, because floating point arithmetic is not exact.
The first version of my program would sometimes draw five lines, and other times four.
It all depending on the details of how the rounding error accumulated. If
bottom_line+4line_spacing > top_linethe top line is lost.
One could admit that Wirth was right, loop counts should be
natural numbers. One codes the stave as 1 1 5 draw linefor
and calculates the position on the page of line i with the formula
bottom_line+(i-1)*line_spacing inside the draw line routine.
This works, even with languages
like PostScript that use floating point, because, if the base of the exponent is
a positive integer power of the base used to represent the mantissa,
the arithmetic of small integers is exact.
Or one could bump the limit up a little to make sure that the calculation of the position of the fifth line comes in below the limit despite rounding error. Adjusting it by half the increment gives maximum protection against rounding error.
But for a page description language, one would really like a for loop which takes
a floating point initial value, a floating point increment, and an integer count,
so that x dx 3 f for causes the evaluation of f(x),f(x+dx),f(x+2dx).
This is better than the Pascal solution, because it achieves a top down
decompostion. Personifying the draw line routine, it just wants to be told where to
draws its line, it would rather not know about which line in the stave it is.
And it is better that the PostScript solution because it doesn't set a
trap using the subtlies of floating point arithmetic.
| Single column | Two columns | Three columns |