22.	Modularity and the Naming of Symbols

2016-06-27

$Version

Mathematica normally assumes that all the variables one introduces are global. There are exceptions in loops. However, in functions definitions, the variables listed at the left hand side of the definition marked by an underscore must be free of assignments; 
otherwise the assignmment is taken over into the function definition as for example:

x = Pi;

f[x_] = Sin[a x]

f[y]

Clear[f,x]
f[x_]=Sin[a x]

f[y]

x = Pi;
Sum[x, {x,3}]

x

x

It is often desirable to have local variables or values in different parts of a  Mathematica  program. This can be accomplished by  Module,   Block  and  Contexts.

22.1	Modules and Local Variables

Module[{x,y,...}, body]		a module with local variables   x,y ...

Variables contained in the list at the beginning of    Module   are local. Below the global variable   t   is assigned the value  17.  It keeps this value as the name  t   is used in the  Module. This  t   is a completely independent variable local to the Module.

t = 17

Module[ {t}, t = 8; Print[t] ]

t

Remove[f,v,a,b]

f[v_] := Module[{t}, t = (1 + v)^2; Expand[t] ]

f[a + b]

t

Expand[ (1 + t)^3 ]

FullForm[%]

Head[%%]

t

Length[ Expand[ (1 + t)^3 ] ]

Module[ {t},  Length[ Expand[ (1 + t)^3 ] ] ]

fac3[k_] := 
Module[{f,n}, f[1]= 1; f[n_] := k + n f[n -1]; f[3] ]

fac3[0]

This value results from the recursion defined above:

f[3] = 0 + 3 f[2] = 3 ( 0 + 2 f[1]) = 3 2 1 = 6

fac3[Pi]

p = 33

Module[ {t},   t = 8 + p; Print[t] ]

Module[ {t,p}, t = 8 + p; Print[t] ]

p

Module{ {x = x0, y = y0, ...}, body]

					a module with initial values for local variables

If any of the variables occuring in left hand parts of  the list of has been assigned a global value this may shadow the value at the corresponding right hand side.

t = 17

facn[u_] := Module[ {t = u}, f[1] = 1; 
					f[n_] := t + n f[n-1]; f[3] ]

facn[Pi]

The following function   contains a command in C++. Mathematica understands and
executes this since Mathematica itself is programmed in C.

Clear[g]; Remove[g];
g[u_] := Module[ {t = u}, t += t/(1 + u) ]

g[a]

Module[ {t = 6, u = t}, u^2]

17^2

The global value for  t  is taken as initial value, even though   t   is declared  local !

22.1.1	How Modules Work

Modules generate symbols with names of the form    x$nnn    to represent  each local variable. nnn  is increased by unity each time  Module  is called.

Module[ {t}, Print[t] ]

Module[ {t,u}, Print[t]; Print[u]  ]

$ModuleNumber

t

Module[ {t,u}, Print[t]; Print[u]  ]

22.2  Blocks and Local Variables

Modules in Mathematica  allow one to treat the names as local. When one uses Block  then the names are global, but the values are local.

Block[{x,y,...}, body] evaluate   expr  using local values  for  x,y, ...

Block[{x=x0,y=y0,...}, body]	assign initial values to  x,y; and evaluate ... as above

Block[] is automatically used to localize values of iterators in iteration constructs such as Do, Sum and Table. 
Block[] may be used to pack several expressions into one unity.

Clear[x,t,a]

x^2 + 3

Block[ {x = a + 1}, %]

x

t = 17

Module[ {t}, Print[t] ]

t

Block[ {t}, Print[t] ]

la = {33,17};

Block[ {t}, Print[la[[1]] t^2 + la[[2]] t + 7]]

%

Block[ {t}, la[[1]] t^2 + la[[2]] t + 7]

la[[1]] t^2 + la[[2]] t + 7

Block[ {}, Print[la[[1]] t^2 + la[[2]] t + 7]]

Block[ {t= 6}, Print[la[[1]] t^2 + la[[2]] t + 7]]

t

Block[ {t}, t = 6;la[[1]] t^2 + la[[2]] t + 7]

t

li1 = {1.1,2.2,3.5,4.3};
li2 = {0,1.5,2.5,3.2,5};
li = {li1,li2};

fi[nnn_]:=Block[{t},gr1=ListPlot[li[[nnn]]];gf=Fit[li[[nnn]],{1,t,(t^2),(t^3)},t];gr2=Plot[gf,{t,1,5},PlotStyle->Hue[nnn 0.3`]];Show[gr1,gr2]]

fi[2]

t

Block  allows to set up "environments" in which the values of variables may be changed temporarily. Expressions being evaluated at any point during the execution of a block will use the values of the variables currently defined for variables in the block. This is true wether the expressions appear directly as part of  the body of the block, or are produced at any point in its evaluation.

t

Clear[u,x]; u := x^2 + t^2

u

Block[ {t = 5}, u + 7]

x^2 + 25 + 7

u

Block[ {t = 5, u}, u + 7 ]

Block[ {t = 5}, u + 7]

Block[  {t}, u + 7]

x^2 + 17^2 + 7

u

Module[ {t = 5}, u + 7]

Module[ {t,u}, u + 7 ]

Module[ {t = 2, u}, u + 7 ]

t = 17

Expand[(1 + t)^3]

Length[Expand[(1 + t)^3] ]

Expand[(1 + t)^3] //FullForm

Head[%]

Module[ {t}, Length[Expand[(1 + t)^3]]  ]

Expand[ (1 + x)^3] //FullForm

Block[ {t}, Length[Expand[(1 + t)^3]] ]

Module[ {t}, Expand[(1 + t)^3]  ] //FullForm

Block[ {t}, Expand[(1 + t)^3]  ] //FullForm

Block[ {x}, Expand[(1 + x)^3]  ] //FullForm

Block[{x = t}, Expand[(1 + x)^3]  ] //FullForm

22.3	Contexts

The mechanism that Mathematica provides for keeping the variables used in a package different from those used in the main session is called contexts.  As each symbol is read from the terminal or from a file Mathematica  checks  to see whether this symbol has already been used before.  If it has been encountered before, the new instance is made to refer to that previously  defined. If the symbol has not been encountered before, a new entry in the symbol table is created.

Each symbol belongs to a certain context. Within one context the names of symbols are unique, but the same name can occur  in two differnt contexts. After one has started a Mathematica session  all new symbols that one defines are put in the context  Global` (all context names end with ` ).by default.
The context   Global` is that of the main  Mathematica session.

The full name of a symbol is broken into two parts: a context and a short name:

context`short

Contexts in Mathematica work somewhat like the directories in many operating systems. One can always specify a particular file by giving its complete name, including its directory. But at any given point, there is usually a current  directory, analogous to the current Mathematica context. Files that are in this directory can then be specified by giving their short names.

a`x

aaa`x

%^2 - %

a`b`x

$Context

Clear[x]
{x, Global`x}

$ContextPath

Context[Pi]

Context[s]			the context of a symbol

	$Context			the current context of a Mathematica session

	$ContextPath			the current context search path

	Contexts			a list of all contexts

Contexts[ ]

context`name  		a symbol in an explicitlly specified context
c1`c2`..`name

`name			a symbol in the current context

`context`name 		a symbol in a specified context relative to the current context
`c1`c2`..`name	
		 
name			a symbol in the current context. or found on the context search path

The following command yields the directory housing the file one is working with:

SetDirectory[ToFileName[
Extract["FileName"/.NotebookInformation[EvaluationNotebook[]],{1},FrontEnd`FileName]]]

22.3.1	Clearing and Removing Symbols

Clear[s]		Clear the values of symbol  s

Remove[s]		Remove the symbol  s  from the system

Clear["s*"]	Clear the values of  all symbols whose names start with the letter    s

Remove["s*"] 	Remove all symbols  whose names start  with the letter  s  				from the system

ClearAll[]		Clears everything

ClearAll[]

Protected symbols cannot be cleared:

x = 5;

Protect[x]

Clear[x]

Clear::wrsym: "Symbol \!\(x\) is Protected. \!\(\*ButtonBox[\"»\", ButtonStyle->\"Link\", ButtonFrame->None, ButtonData:>\"paclet:ref/message/General/wrsym\", ButtonNote -> \"Clear::wrsym\"]\)"

x

Unprotect[x]
Clear[x]

x

a = 100; x1 = 2; x2 = 3; x3 = 4; x4 = 5; y = 7; z = 19;

z

a

Input				Output / Representation

x1						2

x2						3

y						7

Clear["x*"]

x1						x1

y						7

f[x_]:=x^2

Clear[f]

Clear["Global`*"]

N[Pi]

22.3.2   Removing Packages

Many packages protect the names of their symbols; thus Unprotect[] must be applied before the contexts can be removed.

Needs["Combinatorica`"]

"Combinatorica Graph and Permutations functionality has been superseded by preloaded functionality. The package now being loaded may conflict with this. Please see the Compatibility Guide for details."

V=5

Clear::"wrsym" : Symbol V is Protected. >>

V

Unprotect["Combinatorica`*"];

Remove["Combinatorica`*"]

V=5

22.3.3   Putting Symbols in Contexts

Clear[x,y,n,a]

(* This function returns the first  n  powers of  x  *)
PowerSum[x_, n_] := Sum[ x^i, {i, 1, n} ]

PowerSum[y,5]

PowerSum[i,5]

(* this function returns the first  n  terms of the
power series  sum a[i] x^i
               i                                   *)

SerSum[x_, n_] :=Sum[a[i] x^i, {i, 1, n} ]

SerSum[y,5]

SerSum[i,5]

SerSum[n,5]

Context[i]

$Context

$ContextPath

The variable  i    is captured by the variable  i   in the range of  the summation.  In place of the powers of   i   one gets numbers.

By default all new symbols that one defines are put in the context Global`. The local
variable  i  used in the defintion of the functions PowerSum  and BerSum  above is
therefore in the same context as the variable  i  used as argument to those functions
in the inputs  PowerSum[i,5] and   SerSum[i,5].

This is remedied by putting these two symbols having the same name  i  in different contexts.  This is done by the command   Module[]  or by the comand    Block[] :

PowerSumm[x_, n_] :=
Module[ {i}, Sum[ x^i, {i, 1, n} ]
]

PowerSumm[i,5]

PowerSumb[x_,n_] :=
Block[ {i}, Sum[ x^i, {i, 1, n} ]
]

PowerSumb[i,5]

The old definition of  i  is still valid and gets into the way. This does not happen if one used  Module[], which command renders the names in the  first list local.  Remember that  Block[]  renders local the values but not the names. One must either start a new Mathematica session or remove  i   by the following command:

Remove[i];
PowerSumb[i,5]

It is even better to screen off the inner part of a function or a package by giving it its own context. This is done by 
Begin["Private`"] and the corresponding   End    command. This is the common rule for packages.

PowerSummi::usage = "this function returns the first   n  
	powers of  x .	"
Begin["Private`"]					
PowerSummi[x_, n_] :=
Module[ {i}, Sum[ x^i, {i, 1, n} ]
]
End[(* "Private`" *)]

Context[i]

Contexts[]

SerSummp::usage = "  "  
Begin["Private`"]
SerSummp[x_, n_] :=
Module[{i},   Sum[ a[i] x^i, {i, 1, n} ]
]
End[]

SerSummp[i,5]

SerSumbp::usage = "  "  
Begin["Private`"]
SerSumbp[x_, n_] :=
Block[{i},   Sum[ a[i] x^i, {i, 1, n} ]
]
End[]

Remove[i];
SerSumbp[i,5]

Contexts[]

a[1] = Pi

FunSer[func_, x_, n_] := 
Module[{i}, Sum[ a[i] func[i x], {i,1,n}]]

FunSer[Cos,x,5]

FunSerm[func_, x_, n_] := 
Module[{i, a}, Sum[ a[i] func[i x], {i,1,n}]]

FunSerm[Cos,x,5]

FunSerb[func_, x_, n_] := 
Block[{i, a}, Sum[ a[i] func[i x], {i,1,n}]]

FunSerb[Cos,x,5]

22.3.4	A List of All Mathematica Commands

$Version

In view of the above removals one must start the notebook anew !

?*     gives a list with all the Mathematica commands

See yourself !

?*

The number of Mathematica commands is found in the following way:

$Version
cmdList=Names["*"];
Length[cmdList]

Above is the list contained in the file .