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$
6
  • 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
    Commented Dec 2, 2014 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$ Commented Dec 2, 2014 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
    Commented Dec 2, 2014 at 21:00
  • 1
    $\begingroup$ Also check the thirds heading here $\endgroup$
    – Szabolcs
    Commented Dec 2, 2014 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
    Commented Dec 2, 2014 at 21:05

1 Answer 1

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 and acknowledge you have read our privacy policy.

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