Functions as Procedures

In many kinds of calculations, you may find yourself typing the same input to the Wolfram Language over and over again. You can save yourself a lot of typing by defining a function that contains your input commands.

This constructs a product of three terms, and expands out the result.
In[1]:=
Click for copyable input
Out[1]=
This does the same thing, but with four terms.
In[2]:=
Click for copyable input
Out[2]=
This defines a function which constructs a product of n terms, then expands it out.
In[3]:=
Click for copyable input
Every time you use the function, it will execute the Product and Expand operations.
In[4]:=
Click for copyable input
Out[4]=

The functions you define in the Wolfram Language are essentially procedures that execute the commands you give. You can have several steps in your procedures, separated by semicolons.

The result you get from the whole function is simply the last expression in the procedure. Notice that you have to put parentheses around the procedure when you define it like this.
In[5]:=
Click for copyable input
This "runs" the procedure.
In[6]:=
Click for copyable input
Out[6]=
expr1;expr2; a sequence of expressions to evaluate
Module[{a,b,},proc]a procedure with local variables a, b,

Constructing procedures.

When you write procedures in the Wolfram Language, it is usually a good idea to make variables you use inside the procedures local, so that they do not interfere with things outside the procedures. You can do this by setting up your procedures as modules, in which you give a list of variables to be treated as local.

The function defined above is not a module, so the value of "escapes", and exists even after the function returns.
In[7]:=
Click for copyable input
Out[7]=
This function is defined as a module with local variable .
In[8]:=
Click for copyable input
The function gives the same result as before.
In[9]:=
Click for copyable input
Out[9]=
Now, however, the value of does not escape from the function.
In[10]:=
Click for copyable input
Out[10]=