Back: Programming
Previous: Compound expressions, conditionals
Next: Module, Block, With

Programming in Mathematica

Contexts: local vs. global variables

Conflict of symbols

Illustrating the conflict

powers[x_] := Table[x^i, {i,5}]

powers[2]

	{2, 4, 8, 16, 32}

powers[t]

	{7, 49, 343, 2401, 16807}

powers[i]

	{5, 25, 125, 625, 3125}


How can this be avoided?

The variable i appears in two contexts which conflict; we need to use i in a private context in defining the function.

Full names of symbols include "Context"


??i

	Global`i
	i = 5


{  Context[i],   Context[Pi],   Context[ABC]  }

	{Global`, Global`, Global`}


$ContextPath

	{Global`, System`}


Global`Pi = 3.14

	Pi:: shdw:  Warning: Symbol Pi appears in multiple contexts
	    {Global`, System`}; definitions in context Global`
	    may shadow or be shadowed by other definitions.

	3.14


Using a private context; an example


Remove[powers,i]
powers[x_] := Table[x^Private`i, {Private`i, 5}]

powers[2]

	{2, 4, 8, 16, 32}

powers[t]

	{7, 49, 343, 2401, 16807}

powers[i]

	     2   3   4   5
	{i, i , i , i , i }

powers[Private`j]

	                     2           3           4           5
	{Private`j, Private`j , Private`j , Private`j , Private`j }

powers[Private`i]

	{1, 4, 27, 256, 3125}