Back: Programming
Previous: Contexts: local vs. global variables
Next: Packages

Programming in Mathematica

Control of local values: Module, Block, With

Preliminary definitions



Remove[t,u,x,m,b,w];
t = 7;
u := t^2 + x^3
ShowGlobalT := Print["Global t is ", t]


Module[ {privatelist}, expr ]


m[a_] := Module[ {t=a, x},
        	Print["This is a Module."];
        	ShowGlobalT;
        	Print["Local variable `x' is ",x];
        	Print["Local t is ", t];
        	StringJoin[ToString[u], "  = u"]
          ]

m[3]

	This is a Module.
	Global t is 7
	Local variable `x' is x$44
	Local t is 3

	      3
	49 + x  = u

{x,t,u}

	             3
	{x, 7, 49 + x }


Block[ {privatelist}, expr ]


b[a_] := Block[{t=a, x},
     	   Print["This is a Block."];
      	   ShowGlobalT;
      	   Print["Local variable `x' is ",x];
      	   Print["Local t is ", t];
      	   StringJoin[ToString[u], "  = u"]
        ]

b[3]

	This is a Block.
	Global t is 3
	Local variable `x' is x
	Local t is 3

	     3
	9 + x  = u


{x,t,u}

	             3
	{x, 7, 49 + x }


With[ {privatelist}, expr ]


w[a_] := With[ {t=a, x=17},
        	Print["This is a Module."];
        	ShowGlobalT;
        	Print["Local variable `x' is ",x];
        	Print["Local t is ", t];
        	StringJoin[ToString[u], "  = u"]
        ]

w[3]

	This is a Module.
	Global t is 7
	Local variable `x' is 17
	Local t is 3

	      3
	49 + x  = u


{x,t,u}

	             3
	{x, 7, 49 + x }