MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: local variables - Module, For loop

If you look in the Help for For, you might read
"For[start,test,incr,body] executes start, then repeatedly evaluates body
incr until test fails to give True."
Thus For handles very general types of loops and conditions, and if you want

to use it for iteration of integer variables, that is your own choice, and 
Mathematica does not know that beforehand. Thus For does not know which 
variables to consider as locals. However, a better choice in this case is
Do command, and with 

f[x_] := Do[Print[i], {i, 0, x - 1}]

the variable i is considered as local (internally localized by a Block 
command). You might also consider the While command, but that also is
and does not localize the variables. If I get it right 

start; While[test, body; incr]

should behave exactly as the For[start,test,incr,body] command. The For 
command is thus superfluous, present in Mathematica to satisfy old Fortran
in the same way as the Goto command is there for old Basic programmers.

Best regards

Ingolf Dahl

> -----Original Message-----
> From: Sebastian Schmitt [mailto:sschmitt at]
> Sent: den 11 oktober 2010 11:15
> To: mathgroup at
> Subject: [mg113011] local variables - Module, For loop
> Dear all!
> (I recycle my disclaimer.)
> I'm new to Mathematica with a background mostly in C++. Many times I
> have the impression that my style is not natural-Mathematica
> (Mathematicaesque so to say).
> If I have a For loop in a function like this:
> In[39]:= f[x_] := Module[{},
>   For[i = 0, i != x, i++,
>    Print[i]
>    ]
>   ]
> In[41]:= f[2]
> During evaluation of In[41]:= 0
> During evaluation of In[41]:= 1
> In[42]:= i
> Out[42]= 2
> I was surprised to find "i" being not local to the For loop. Do I have
> to keep track of all my throw-away-variables and put them in the list of
> local variables of the Module? I find it pretty tedious. Is there a
> better way?
> Thanks in advance,
> Sebastian

  • Prev by Date: Re: What is the ESC sequence for the "Matching Double Brakets"? From
  • Next by Date: Re: Efficient Histogram Algorithm?
  • Previous by thread: Re: local variables - Module, For loop
  • Next by thread: Re: local variables - Module, For loop