I feel a bit uneasy about posting tangential commentary as answers but since this is too long for Comments here are my thoughts on m_goldberg's post.
I absolutely agree that procedural coding has its place in Mathematica. Nevertheless I feel that the example given is misleading. First a Do
loop is already a level of abstraction above For
and it is used quite often by experienced users. (It is not representative of procedural code that people typically argue against.) Second Continue[]
is quite pointless in this example; one would instead just write:
r = 0;
Do[If[i > 8, Break[], If[OddQ[i], r += i]], {i, 10}]
r
The Break
condition itself is also not really valid as it depends solely on the Do
iterator which is never directly manipulated. A more realistic example would be a condition on r
, e.g.
r = 0;
Do[If[r > 5, Break[], If[OddQ[i], r += i]], {i, 10}]
r (* 9 *)
This could be written with NestWhile
in several ways:
NestWhile[If[OddQ[++i], # + i, #] &, i = 0, # <= 5 &]
NestWhile[# + i*Boole@OddQ[i++] &, i = 0, # <= 5 &]
NestWhile[# + i*Mod[i++, 2] &, i = 0, # <= 5 &]
I do not feel that the Do
/Break
code is objectively clearer here.
Of course this whole example is still contrived and I one could just write Tr @ Range[1, 8, 2]
or Sum[i, {i, 1, 8, 2}]
in actuality.
I know it is difficult to contrive an example that is simple enough without being too simple and I do not mean to attack a straw man, but examples should still actually exemplify what they purport to if at all possible, and I feel that this one does not.