2.6.9 Loops and Control Structures
The execution of a Mathematica program involves the evaluation of a sequence of Mathematica expressions. In simple programs, the expressions to be evaluated may be separated by semicolons, and evaluated one after another. Often, however, you need to evaluate expressions several times, in some kind of "loop".
Simple looping constructs.
This evaluates Print[i^2], with i running from 1 to 4.
In[1]:= Do[Print[i^2], {i, 4}]
This executes an assignment for t in a loop with k running from 2 to 6 in steps of 2.
In[2]:= t = x; Do[t = 1/(1 + k t), {k, 2, 6, 2}]; t
Out[2]=
The way iteration is specified in Do is exactly the same as in functions like Table and Sum. Just as in those functions, you can set up several nested loops by giving a sequence of iteration specifications to Do.
This loops over values of i from 1 to 4, and for each value of i, loops over j from 1 to i1.
In[3]:= Do[Print[{i,j}], {i, 4}, {j, i1}]
Sometimes you may want to repeat a particular operation a certain number of times, without changing the value of an iteration variable. You can specify this kind of repetition in Do just as you can in Table and other iteration functions.
This repeats the assignment t = 1/(1+t) three times.
In[4]:= t = x; Do[t = 1/(1+t), {3}]; t
Out[4]=
You can put a procedure inside Do.
In[5]:= t = 67; Do[Print[t]; t = Floor[t/2], {3}]
Applying functions repetitively.
Do allows you to repeat operations by evaluating a particular expression many times with different values for iteration variables. Often, however, you can make more elegant and efficient programs using the functional programming constructs discussed in Section 2.2.2. Nest[f, x, n], for example, allows you to apply a function repeatedly to an expression.
This nests f three times.
In[6]:= Nest[f, x, 3]
Out[6]=
By nesting a pure function, you can get the same result as in the example with Do above.
In[7]:= Nest[ Function[t, 1/(1+t)], x, 3 ]
Out[7]=
Nest allows you to apply a function a specified number of times. Sometimes, however, you may simply want to go on applying a function until the results you get no longer change. You can do this using FixedPoint[f, x].
FixedPoint goes on applying a function until the result no longer changes.
In[8]:= FixedPoint[Function[t, Print[t]; Floor[t/2]], 67]
Out[8]=
You can use FixedPoint to imitate the evaluation process in Mathematica, or the operation of functions such as expr //. rules. FixedPoint goes on until two successive results it gets are the same. NestWhile allows you to go on until an arbitrary function no longer yields True.
Nonlocal control of evaluation.
When the Throw is encountered, evaluation stops, and the current value of i is returned as the value of the enclosing Catch.
In[9]:= Catch[Do[Print[i]; If[i > 3, Throw[i]], {i, 10}]]
Out[9]=
Throw and Catch provide a flexible way to control the process of evaluation in Mathematica. The basic idea is that whenever a Throw is encountered, the evaluation that is then being done is stopped, and Mathematica immediately returns to the nearest appropriate enclosing Catch.
Scan applies the function Print to each successive element in the list, and in the end just returns Null.
In[10]:= Scan[Print, {7, 6, 5, 4}]
The evaluation of Scan stops as soon as Throw is encountered, and the enclosing Catch returns as its value the argument of Throw.
In[11]:= Catch[Scan[(Print[#]; If[# < 6, Throw[#]])&, {7, 6, 5, 4}]]
Out[11]=
The same result is obtained with Map, even though Map would have returned a list if its evaluation had not been stopped by encountering a Throw.
In[12]:= Catch[Map[(Print[#]; If[# < 6, Throw[#]])&, {7, 6, 5, 4}]]
Out[12]=
You can use Throw and Catch to divert the operation of functional programming constructs, allowing for example the evaluation of such constructs to continue only until some condition has been met. Note that if you stop evaluation using Throw, then the structure of the result you get may be quite different from what you would have got if you had allowed the evaluation to complete.
Here is a list generated by repeated application of a function.
In[13]:= NestList[1/(# + 1)&, 2.5, 6]
Out[13]=
Since there is no Throw encountered, the result here is just as before.
In[14]:= Catch[ NestList[1/(# + 1)&, 2.5, 6] ]
Out[14]=
Now the evaluation of the NestList is diverted, and the single number given as the argument of Throw is returned.
In[15]:= Catch[ NestList [If[# > 1, Throw[#], 1/(# + 1)]&, 2.5, 6] ]
Out[15]=
Throw and Catch operate in a completely global way: it does not matter how or where a Throw is generated—it will always stop evaluation and return to the enclosing Catch.
The Throw stops the evaluation of f, and causes the Catch to return just a, with no trace of f left.
In[16]:= Catch[ f[ Throw[ a ] ] ]
Out[16]=
This defines a function which generates a Throw when its argument is larger than 10.
In[17]:= g[x_] := If[x > 10, Throw[overflow], x!]
No Throw is generated here.
In[18]:= Catch[ g[4] ]
Out[18]=
But here the Throw generated inside the evaluation of g returns to the enclosing Catch.
In[19]:= Catch[ g[40] ]
Out[19]=
In small programs, it is often adequate to use Throw[value] and Catch[expr] in their simplest form. But particularly if you write larger programs that contain many separate pieces, it is usually much better to use Throw[value, tag] and Catch[expr, form]. By keeping the expressions tag and form local to a particular piece of your program, you can then ensure that your Throw and Catch will also operate only within that piece.
Here the Throw is caught by the inner Catch.
In[20]:= Catch[ f [ Catch[ Throw[x, a], a ] ], b ]
Out[20]=
But here it is caught only by the outer Catch.
In[21]:= Catch[ f [ Catch[ Throw[x, b], a ] ], b ]
Out[21]=
You can use patterns in specifying the tags which a particular Catch should catch.
In[22]:= Catch[ Throw[x, a], a  b ]
Out[22]=
This keeps the tag a completely local.
In[23]:= Module[{a}, Catch[ Throw[x, a], a] ]
Out[23]=
You should realize that there is no need for the tag that appears in Throw to be a constant; in general it can be any expression.
Here the inner Catch catches all throws with tags less than 4, and continues the Do. But as soon as the tag reaches 4, the outer Catch is needed.
In[24]:= Catch[ Do[ Catch[ Throw[i^2, i], n_ /; n < 4], {i, 10} ], _]
Out[24]=
When you use Catch[expr, form] with Throw[value, tag], the value returned by Catch is simply the expression value given in the Throw. If you use Catch[expr, form, f], however, then the value returned by Catch is instead f[value, tag].
Here f is applied to the value and tag in the Throw.
In[25]:= Catch[ Throw[ x, a ], a, f ]
Out[25]=
If there is no Throw, f is never used.
In[26]:= Catch[ x, a, f ]
Out[26]=
General loop constructs.
Functions like Do, Nest and FixedPoint provide structured ways to make loops in Mathematica programs, while Throw and Catch provide opportunities for modifying this structure. Sometimes, however, you may want to create loops that even from the outset have less structure. And in such cases, you may find it convenient to use the functions While and For, which perform operations repeatedly, stopping when a specified condition fails to be true.
The While loop continues until the condition fails.
In[27]:= n = 17; While[(n = Floor[n/2]) != 0, Print[n]]
The functions While and For in Mathematica are similar to the control structures while and for in languages such as C. Notice, however, that there are a number of important differences. For example, the roles of comma and semicolon are reversed in Mathematica For loops relative to C language ones.
This is a very common form for a For loop. i++ increments the value of i.
In[28]:= For[i=1, i < 4, i++, Print[i]]
Here is a more complicated For loop. Notice that the loop terminates as soon as the test i^2 < 10 fails.
In[29]:= For[i=1; t=x, i^2 < 10, i++, t = t^2 + i; Print[t]]
In Mathematica, both While and For always evaluate the loop test before evaluating the body of the loop. As soon as the loop test fails to be True, While and For terminate. The body of the loop is thus only evaluated in situations where the loop test is True.
The loop test fails immediately, so the body of the loop is never evaluated.
In[30]:= While[False, Print[x]]
In a While or For loop, or in general in any Mathematica procedure, the Mathematica expressions you give are evaluated in a definite sequence. You can think of this sequence as defining the "flow of control" in the execution of a Mathematica program.
In most cases, you should try to keep the flow of control in your Mathematica programs as simple as possible. The more the flow of control depends for example on specific values generated during the execution of the program, the more difficult you will typically find it to understand the structure and operation of the program.
Functional programming constructs typically involve very simple flow of control. While and For loops are always more complicated, since they are set up to make the flow of control depend on the values of the expressions given as tests. Nevertheless, even in such loops, the flow of control does not usually depend on the values of expressions given in the body of the loop.
In some cases, however, you may need to construct Mathematica programs in which the flow of control is affected by values generated during the execution of a procedure or of the body of a loop. One way to do this, which fits in with functional programming ideas, is to use Throw and Catch. But Mathematica also provides various functions for modifying the flow of control which work like in languages such as C.
Control flow functions.
The Break[ ] causes the loop to terminate as soon as t exceeds 19.
In[31]:= t = 1; Do[t *= k; Print[t]; If[t > 19, Break[]], {k, 10}]
When k < 3, the Continue[ ] causes the loop to be continued, without executing t += 2.
In[32]:= t = 1; Do[t *= k; Print[t]; If[k < 3, Continue[]]; t += 2, {k, 10}]
Return[expr] allows you to exit a particular function, returning a value. You can think of Throw as a kind of nonlocal return which allows you to exit a whole sequence of nested functions. Such behavior can be convenient for handling certain error conditions.
Here is an example of the use of Return. This particular procedure could equally well have been written without using Return.
In[33]:= f[x_] := (If[x > 5, Return[big]]; t = x^3; Return[t  7])
When the argument is greater than 5, the first Return in the procedure is used.
In[34]:= f[10]
Out[34]=
This function "throws" error if its argument is negative.
In[35]:= h[x_] := If[x < 0, Throw[error], Sqrt[x]]
No Throw is generated here.
In[36]:= Catch[ h[6] + 2 ]
Out[36]=
But in this case a Throw is generated, and the whole Catch returns the value error.
In[37]:= Catch[ h[6] + 2 ]
Out[37]=
Functions like Continue[ ] and Break[ ] allow you to "transfer control" to the beginning or end of a loop in a Mathematica program. Sometimes you may instead need to transfer control to a particular element in a Mathematica procedure. If you give a Label as an element in a procedure, you can use Goto to transfer control to this element.
This goes on looping until q exceeds 6.
In[38]:= (q = 2; Label[begin]; Print[q]; q += 3; If[q < 6, Goto[begin]])
Note that you can use Goto in a particular Mathematica procedure only when the Label it specifies occurs as an element of the same Mathematica procedure. In general, use of Goto reduces the degree of structure that can readily be perceived in a program, and therefore makes the operation of the program more difficult to understand.
