4
$\begingroup$

I have little to no understanding of how Mathematica handles scoping, so the question may seem a little bit funny.

What is the preferred way:

Test[] = Module[{},
   Do[Print["Hello ", i], {i, 5, 50, 5}];
   ];
Test[];

Or:

Test[] = Module[{i},
   Do[Print["Hello ", i], {i, 5, 50, 5}];
   ];
Test[];
$\endgroup$
  • 2
    $\begingroup$ First option is all you need. Mathematica handles scoping a couple of different ways. Table/Do/etc. create their own scope for an iterator, and I believe they use textual scoping just like With (but unlike Block and Module). This may help: reference.wolfram.com/language/guide/ScopingConstructs.html. In particular look at "Learning Resources". $\endgroup$ – mfvonh Dec 2 '14 at 20:41
  • 1
    $\begingroup$ One way to test such things is to use, and show, an explicit setting for your symbol. Try for example this small variation on your code: Module[{i=-20}, Do[Print["Hello ", i], {i, 5, 50, 5}]; i]. Notice that the i at the end is the Module variable and is not related to the i of the loop. $\endgroup$ – Daniel Lichtblau Dec 2 '14 at 20:48
  • 2
    $\begingroup$ @mfvonh Actually Table & related functions use the same type of scoping as Block (not like With). Try Table[i = 1; Print[i], {i, 5}]. $\endgroup$ – Szabolcs Dec 2 '14 at 21:00
  • 1
    $\begingroup$ Also check the thirds heading here $\endgroup$ – Szabolcs Dec 2 '14 at 21:02
  • 3
    $\begingroup$ for entertainment ask a "c" programmer what this does.. i = {4, 5}; Do[Do[ Print[ i ] , {i, i}], {i, i}] $\endgroup$ – george2079 Dec 2 '14 at 21:05
5
$\begingroup$

One type of scoping uses "textual" replacement, meaning the symbolic layer of evaluation is bypassed. For example:

With[{i = 1}, SymbolName[Unevaluated[i]]]

enter image description here

SymbolName[Unevaluated[1]]

This property of With makes it very handy sometimes, simply as a way to avoid evaluation where it is not wanted. I learned this myself in this question.

Compare that to:

Block[{i = 1}, SymbolName[Unevaluated[i]]]

i

Module[{i = 1}, SymbolName[Unevaluated[i]]]

i$24225

And turns out my comment above was inaccurate. Table does not use textual scoping:

Table[SymbolName[Unevaluated[i]], {i, 1, 1}]

{i}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.