"do ... while" loop equivalent in Mathematica
While While[procedure; test]
works, it looks very similar to While[test, procedure]
. The only difference is ;
vs ,
. While
is not the most commonly used construct, so when used like this there's a high chance of misunderstanding/misreading.
If readability/reliability is a concern (for example a collaboratively developed published package), I'd use the longer but clearer
While[True,
procedure;
If[Not[test], Break[]]
]
The only argument here is readability and "defensive programming" (extra effort to avoid accidental problems). Readability is subjective. If you are the only person who writes/reads the code and you get used to this use of While
(and thus always pay special attention to the ,
vs ;
) then this argument doesn't apply.
Why not write your own and place it in your init.m file?
SetAttributes[DoWhile, HoldAll];
DoWhile[procedure_, test_] := While[procedure; test]
Here's another way to write your own:
SetAttributes[doWhile, HoldAll];
doWhile[expr_, test_] := CompoundExpression[expr, While[test, expr]]
Or just:
doWhile[expr_, test_] := (expr; While[test, expr])