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 which squares its argument. The Wolfram Language command to define this function is . The (referred to as "blank") on the lefthand side is very important; what it means will be discussed below. For now, just remember to put a on the lefthand side, but not on the righthand side, of your definition.

This defines the function . Notice the on the lefthand side.
Click for copyable input
squares its argument.
Click for copyable input
The argument can be a number.
Click for copyable input
Or it can be a more complicated expression.
Click for copyable input
You can use in a calculation.
Click for copyable input
This shows the definition you made for .
Click for copyable input
f[x_]:=x^2define the function
?fshow the definition of
Clear[f]clear all definitions for

Defining a function in the Wolfram Language.

The names like 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.
Click for copyable input
You can use the function just as you would any of the builtin functions.
Click for copyable input
This gives a new definition for , which overwrites the previous one.
Click for copyable input
The new definition is displayed.
Click for copyable input
This clears all definitions for .
Click for copyable input

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].

Translate this page: