To my mind the only reason for the existence of For[]
loops in Mathematica is to allow new users with some experience in procedural programming languages to write simple Mathematica programs. The real problem is that sometimes such a user do not dive deeper and as a consequence he has 1) ugly and unreliable code and 2) a belief that "Mathematica has a C-like syntax".
It is hard for me to imagine a situation when For[]
cannot be effectively and more cleanly replaced by Table
, Map
, anything else or Do
at least. Am I wrong? Should we really recommend beginners to avoid For[]
loops?
SUMMARY
There are actually two great answers. The first answer is the accepted one and the second answer is this question. I wish I could accept it as well.
Answer
To my mind, there are at least two cases when For
loops are ok:
- Inside
Compile
, or in code which is being written withCompile
in mind - When your inner loops are vectorized or made efficient by some other means, so that each iteration of the
For
loop is sufficiently intensive computationally
Many efficient algorithms are procedural by nature and gain their efficiency by side effects and local mutations. When those algorithms contain nested loops, what matters the most is to speed up innermost loop(s). While we mostly tend to move away from For
loops, I have no problem with a For
loop being an outer loop in a program, as long as innermost loops are optimized. Also, For
loops are more flexible than Map
or Scan
because you can use Break
and Continue
, and generally are not forced to iterate over all of the elements in a list in a prescribed order.
That said, I think we should recommend beginners to avoid For
loops, just because this would allow them to change their mindset and get to the better understanding of Mathematica programming sooner. I'd say, it is ok to occasionally use For
loops for experienced users, but beginners would be better off avoiding them entirely, until they get more experience with the language.
Comments
Post a Comment