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

ContentsFunctions as Procedures

1.7.1 Defining Functions

In this part of the book, we have seen many examples of functions that are built into Mathematica. In this section, we discuss how you can add your own simple functions to Mathematica. Part 2 will describe in much greater detail the mechanisms for adding functions to Mathematica.

As a first example, consider adding a function called f which squares its argument. The Mathematica command to define this function is f[x_] := x^2. The _ (referred to as "blank") on the left-hand side is very important; what it means will be discussed below. For now, just remember to put a _ on the left-hand side, but not on the right-hand side, of your definition.

This defines the function f. Notice the _ on the left-hand side.

In[1]:= f[x_] := x^2

f squares its argument.

In[2]:= f[a+1]

Out[2]=

The argument can be a number.

In[3]:= f[4]

Out[3]=

Or it can be a more complicated expression.

In[4]:= f[3x + x^2]

Out[4]=

You can use f in a calculation.

In[5]:= Expand[f[(x+1+y)]]

Out[5]=

This shows the definition you made for f.

In[6]:= ?f

Defining a function in Mathematica.

The names like f that you use for functions in Mathematica are just symbols. Because of this, you should make sure to avoid using names that begin with capital letters, to prevent confusion with built-in Mathematica functions. You should also make sure that you have not used the names for anything else earlier in your session.

Mathematica functions can have any number of arguments.

In[7]:= hump[x_, xmax_] := (x - xmax)^2 / xmax

You can use the hump function just as you would any of the built-in functions.

In[8]:= 2 + hump[x, 3.5]

Out[8]=

This gives a new definition for hump, which overwrites the previous one.

In[9]:= hump[x_, xmax_] := (x - xmax)^4

The new definition is displayed.

In[10]:= ?hump

This clears all definitions for hump.

In[11]:= Clear[hump]

When you have finished with a particular function, it is always a good idea to clear definitions you have made for it. If you do not do this, then you will run into trouble if you try to use the same function for a different purpose later in your Mathematica session. You can clear all definitions you have made for a function or symbol f by using Clear[f].

ContentsFunctions as Procedures