Edsger Dijkstra ha fatto una nota su !=
rispetto a <
nel capitolo 8 della sua "Disciplina della programmazione" , pagina 56:
Prior to my getting used to these formal developments I would always have used "j < n"
as the guard for this repetitive construct, a habit I still have to unlearn, for in case like this, the guard "j != n"
is certainly to be preferred. The reason for the preference is twofold. The guard "j != n"
allows us to conclude "j = n"
upon termination without an appeal to the invariant relation P and thus simplifies the argument about what the whole construct achieves for us compared with the guard "j < n"
. Much more important, however, is that the guard "j != n"
makes termination dependent upon (part of) the invariant relation, viz. "j <= n"
, and is therefore to be preferred for reasons of robustness. If the addition "j := j + 1"
would erroneously increase j
too much and would establish "j > n"
, then the guard "j < n"
would give no alarm, while the guard "j != n"
would at least prevent proper termination. Even without taking machine malfunctioning into account, this argument seems valid.
Ho prontamente smesso di usare <
nelle condizioni di terminazione del loop dopo aver letto questa nota circa 25 anni fa.
EDIT questa nota segue una discussione di un programma che trova un massimo di una funzione f(k)
nell'intervallo [0..n)
:
k, j := 0, 1;
do j != n --> if f(k) >= f(j) --> j := j + 1
[] f(k) <= f(j) --> k, j := j, j + 1 fi od
Questa notazione insolita adottata nel suo libro corrisponde grosso modo a questo programma:
int k = 0, j = 1;
while (j != n) {
if (f(k) <= f(j)) k = j;
j++;
}