This is documentation for Mathematica 5, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)

Documentation / Mathematica / The Mathematica Book / A Practical Introduction to Mathematica / Functions and Programs /

1.7.2 Functions as Procedures

In many kinds of calculations, you may find yourself typing the same input to Mathematica 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]:= Expand[ Product[x + i, {i, 3}] ]


This does the same thing, but with four terms.

In[2]:= Expand[ Product[x + i, {i, 4}] ]


This defines a function exprod which constructs a product of n terms, then expands it out.

In[3]:= exprod[n_] := Expand[ Product[ x + i, {i, 1, n} ] ]

Every time you use the function, it will execute the Product and Expand operations.

In[4]:= exprod[5]


The functions you define in Mathematica 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]:= cex[n_, i_] := ( t = exprod[n]; Coefficient[t, x^i] )

This "runs" the procedure.

In[6]:= cex[5, 3]


Constructing procedures.

When you write procedures in Mathematica, 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 cex defined above is not a module, so the value of t "escapes", and exists even after the function returns.

In[7]:= t


This function is defined as a module with local variable u.

In[8]:= ncex[n_, i_] :=
Module[{u}, u = exprod[n]; Coefficient[u, x^i]]

The function gives the same result as before.

In[9]:= ncex[5, 3]


Now, however, the value of u does not escape from the function.

In[10]:= u