Mathematica Programming » Code Structure
Mathematica, being primarily a functional programming language, doesn't use standard flow-control techniques such as While
, Break
, Continue
, etc
. to the same degree that a primarily procedural language like python does.
Despite that, these are still useful things to know how to work with. We'll go through them pretty quickly, one-by-one.
While
Of all of these, While
is likely the most common to be used, although as mentioned previously it can be emulated perhaps more cleanly by Do
with Infinity
as the iterator spec.
On the other hand, particularly in the context of Compile
or other cases where a predominantly procedural paradigm is use, While
can be useful.
For
For
is never useful. Any time it could be used Table
or Do
would be a better choice.
Break / Continue / Return
As noted, For
isn't useful, which renders moot the primary use case of Break
and Continue
. They can potentially still be useful in Do
and Table
, though.
All Mathematica functions have an implicit Return
in them, which makes use of Return
infrequent, but it has its place. Especially when there are multiple possible points of exit from a function Return
can be highly useful.
It also helpfully has a second argument specifying the scope from which the value should be returned, which can allow for somewhat more targeted usage in, say Do
.
Similarly, FixedPoint
and other nested functional programming constructs provide support for Return
, Break
, and potentially Continue
.