Scope

2010 October 28 by Joshua R. Davis

Although you probably don't know Mathematica, you can probably understand the basic idea of the code below. To run the code, just click anywhere on the code and then press the Enter key (or Shift-Return --- not Return).

Clear[x, y, myFunction];
y = 5;
myFunction[x_] = x + y;
myFunction[3]
y = 11;
myFunction[3]

Execute the following code as well. What is the difference between it and the previous code, and what is the effect of this difference? Feel free to add your own statements to try things out.

Clear[x, y, myFunction];
y = 5;
myFunction[x_] := x + y;
myFunction[3]
y = 11;
myFunction[3]

The following two examples are similar, but the variable x is assigned a value at the top level of the code. How does this change things?

Clear[x, y, myFunction];
x = 20;
y = 5;
myFunction[x_] = x + y;
myFunction[3]
y = 11;
myFunction[3]

Clear[x, y, myFunction];
x = 20;
y = 5;
myFunction[x_] := x + y;
myFunction[3]
y = 11;
myFunction[3]

When the function myFunction is defined, is x stored as a value or as a variable? Is y stored as a value or as a variable? What effect does this choice have? These questions may be easier to answer after you execute the following code. This clears all definitions of x, y, and myFunction. Once you've done this, Mathematica will color-code all of the code above. Can you determine the meaning of the color coding?

Clear[x, y, myFunction];