4

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[];
d125q
  • 437
  • 3
  • 9
  • 2
    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: http://reference.wolfram.com/language/guide/ScopingConstructs.html. In particular look at "Learning Resources". – mfvonh Dec 02 '14 at 20:41
  • 1
    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. – Daniel Lichtblau Dec 02 '14 at 20:48
  • @d125q I've added an answer but there's a good chance someone will provide a better one or a good link to a previous answer. Worth waiting before you accept. – mfvonh Dec 02 '14 at 20:55
  • 2
    @mfvonh Actually Table & related functions use the same type of scoping as Block (not like With). Try Table[i = 1; Print[i], {i, 5}]. – Szabolcs Dec 02 '14 at 21:00
  • 1
    Also check the thirds heading here – Szabolcs Dec 02 '14 at 21:02
  • 3
    for entertainment ask a "c" programmer what this does.. i = {4, 5}; Do[Do[ Print[ i ] , {i, i}], {i, i}] – george2079 Dec 02 '14 at 21:05

1 Answers1

5

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}

mfvonh
  • 8,460
  • 27
  • 42