Defining Functions

There are many functions that are built into the Wolfram Language. This tutorial discusses how you can add your own simple functions to the Wolfram Language.

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

This defines the function f. Notice the _ on the lefthand side.
 In[1]:=
f squares its argument.
 In[2]:=
 Out[2]=
The argument can be a number.
 In[3]:=
 Out[3]=
Or it can be a more complicated expression.
 In[4]:=
 Out[4]=
You can use f in a calculation.
 In[5]:=
 Out[5]=
This shows the definition you made for f.
 In[6]:=
 f[x_]:=x^2 define the function f ?f show the definition of f Clear[f] clear all definitions for f

Defining a function in the Wolfram Language.

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

Wolfram Language functions can have any number of arguments.
 In[7]:=
You can use the hump function just as you would any of the builtin functions.
 In[8]:=
 Out[8]=
This gives a new definition for hump, which overwrites the previous one.
 In[9]:=
The new definition is displayed.
 In[10]:=
This clears all definitions for hump.
 In[11]:=

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 Wolfram Language session. You can clear all definitions you have made for a function or symbol f by using Clear[f].