3
$\begingroup$

Algebra is so much fun but I'm struggling to understand how MMA executes local variables within Module. Reading the Module documentation page I suspect it has something to do with "Before evaluating expr, Module substitutes new symbols for each of the local variables that appear anywhere in expr except as local variables in scoping constructs". But as I work through possible examples of how this works, the output behaviour continues to unpredictable. For example, what is causing the difference in output below? How would you explain this to a kindergartener? Or one's great grandmother?

In1= x=2;y=x+2;y+x

6

in2= Module[{a=2,b=a+2},a+b]

4+a

$\endgroup$
  • 2
    $\begingroup$ I'd have written the second one as Module[{a = 2, b}, b = a + 2; a + b]; the way you wrote it will not have b inherit the value of a. $\endgroup$ – J. M. is in limbo Sep 29 '17 at 4:58
  • $\begingroup$ sigh... hadn't tried that combo yet (or considered it). It's just like learning a new language. $\endgroup$ – BBirdsell Sep 29 '17 at 5:16
  • $\begingroup$ Personally, I'd remove "just like" from the last sentence of your comment, and it'd be accurate. $\endgroup$ – J. M. is in limbo Sep 29 '17 at 5:19
3
$\begingroup$

Look at the syntax coloring:

enter image description here

Note that the a in b = a + 2 (blue) is colored differently than the a in a = 2. (green). That is because they are different variables. The a in b = a + 2 references the variable Global`a (usually displayed as just a). You can also Trace the evaluation to see this:

Trace[Module[{a=2,b=a+2},a+b]]

{Module[{a=2,b=a+2},a+b],{a\$40801=2,2},{a+2,2+a},{b\$40801=2+a,2+a},{{a\$40801,2},{b\$40801,2+a},2+(2+a),2+2+a,4+a},4+a}

$\endgroup$
  • 1
    $\begingroup$ Interestingly, my MMA Online notebook is not showing that: It's green across the board. This is difficult. Thanks so much for your time. $\endgroup$ – BBirdsell Sep 29 '17 at 5:15

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.