MathGroup Archive 2010

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

Search the Archive

Re: local variables - Module, For loop

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113115] Re: local variables - Module, For loop
  • From: Pierre Albarede <pa.news at free.fr>
  • Date: Wed, 13 Oct 2010 12:40:19 -0400 (EDT)
  • References: <i8ukij$o9s$1@smc.vnet.net>

Hello,

On Oct 11, 11:14 am, Sebastian Schmitt <sschm... at physi.uni-
heidelberg.de> wrote:

> 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).

Your impression is correct !

> If I have a For loop in a function like this:
>
> In[39]:= f[x_] := Module[{},
>   For[i = 0, i != x, i++,
>    Print[i]
>    ]
>   ]
>

You do not need Print to see something.  Print is a side-effect.  You
should use normal output, because it can be used inside expressions,
while Print is a dead end (only good for visualizing).

The best way to avoid problem with variables is to eliminate them,
with functional programming.

Your f already exists in Mathematica : it is Range.  You should always
try to use what is already available.

If Range did not exist, you could define it like this :

range[x_Integer] := Table[i, {i, x}]

where x is a constant and i a local variable

or, without any constant or variable to worry about :

range = MapIndexed[First@#2 &, Table[_, {#}]] &

Good luck.



  • Prev by Date: Re: C-pointers from Mathematica
  • Next by Date: Re: something nice I found today, return multiple values from a function
  • Previous by thread: Re: local variables - Module, For loop
  • Next by thread: Re: local variables - Module, For loop