# Algebra, Local variables and the Module function

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

• 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. – J. M. is in limbo Sep 29 '17 at 4:58
• sigh... hadn't tried that combo yet (or considered it). It's just like learning a new language. – BBirdsell Sep 29 '17 at 5:16
• Personally, I'd remove "just like" from the last sentence of your comment, and it'd be accurate. – J. M. is in limbo Sep 29 '17 at 5:19 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 Globala (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}