Functions and Programs

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:
f squares its argument:
The argument can be a number:
Or it can be a more complicated expression:
You can use f in a calculation:
This shows the definition you made for f:
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:
You can use the hump function just as you would any of the builtin functions:
This gives a new definition for hump, which overwrites the previous one:
The new definition is displayed:
This clears all definitions for 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 Wolfram Language session. You can clear all definitions you have made for a function or symbol f by using Clear[f].
Clears all definitions for f:
No definitions are displayed for f:
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:
This does the same thing, but with four terms:
This defines a function exprod which constructs a product of n terms, then expands it out:
Every time you use the function, it will execute the Product and Expand operations:
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:
This "runs" the procedure:
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 cex defined above is not a module, so the value of t "escapes", and exists even after the function returns:
Clear the variable t:
This function is defined as a module with the variable t made local:
The function gives the same result as before:
Now, however, the value of t does not escape from the function:
Manipulating Options
There are a number of functions built into the Wolfram Language which, like Plot, have various options you can set. The Wolfram Language provides some general mechanisms for handling such options.
If you do not give a specific setting for an option to a function like Plot, then the Wolfram Language will automatically use a default value for the option. The function Options[function,option] allows you to find out the default value for a particular option. You can reset the default using SetOptions[function,option->value]. Note that if you do this, the default value you have given will stay until you explicitly change it.
Options[function]
give a list of the current default settings for all options
Options[function,option]
give the default setting for a particular option
SetOptions[function,option->value,]
reset defaults
Manipulating default settings for options.
Here is the default setting for the PlotRange option of Plot:
This resets the default for the PlotRange option. The semicolon stops the Wolfram Language from printing out the rather long list of options for Plot:
Until you explicitly reset it, the default for the PlotRange option will now be All:
The graphics objects that you get from Plot or Show store information on the options they use. You can get this information by applying the Options function to these graphics objects.
Options[plot]
show all the options used for a particular plot
Options[plot,option]
show the setting for a specific option
AbsoluteOptions[plot,option]
show the absolute form used for a specific option, even if the setting for the option is Automatic or All
Getting information on options used in plots.
Here is a plot, with default settings for all options:
The setting used for the PlotRange option was All:
AbsoluteOptions gives the absolute automatically chosen values used for PlotRange:
While it is often convenient to use a variable to represent a graphic as in the above examples, the graphic itself can be evaluated directly. The typical ways to do this in the notebook interface are to copy and paste the graphic or to simply begin typing in the graphical output cell, at which point the output cell will be converted into a new input cell.
When a plot created with no explicit ImageSize is placed into an input cell, it will automatically shrink to more easily accommodate input.
The following input cell was created by copying and pasting the graphical output created in the previous example:
Restore Plot to its default option settings:
Repetitive Operations
In using the Wolfram Language, you sometimes need to repeat an operation many times. There are many ways to do this. Often the most natural is in fact to set up a structure such as a list with many elements, and then apply your operation to each of the elements.
Another approach is to use the Wolfram Language function Do, which works much like the iteration constructs in languages such as C and Fortran. Do uses the same Wolfram Language iterator notation as Sum and Product, described in "Sums and Products".
Do[expr,{i,imax}]
evaluate expr with i running from 1 to imax
Do[expr,{i,imin,imax,di}]
evaluate expr with i running from imin to imax in steps of di
Print[expr]
print expr
Table[expr,{i,imax}]
make a list of the values of expr with i running from 1 to imax
Implementing repetitive operations.
This prints out the values of the first five factorials:
It is often more useful to have a list of results, which you can then manipulate further:
If you do not give an iteration variable, the Wolfram Language simply repeats the operation you have specified, without changing anything:
Transformation Rules for Functions
"Values for Symbols" discussed how you can use transformation rules of the form x->value to replace symbols by values. The notion of transformation rules in the Wolfram System is, however, quite general. You can set up transformation rules not only for symbols, but for any Wolfram System expression.
Applying the transformation rule x->3 replaces x by 3:
You can also use a transformation rule for f[x]. This rule does not affect f[y]:
f[t_] is a pattern that stands for f with any argument:
Probably the most powerful aspect of transformation rules in the Wolfram System is that they can involve not only literal expressions, but also patterns. A pattern is an expression such as f[t_] which contains a blank (underscore). The blank can stand for any expression. Thus, a transformation rule for f[t_] specifies how the function f with any argument should be transformed. Notice that, in contrast, a transformation rule for f[x] without a blank, specifies only how the literal expression f[x] should be transformed, and does not, for example, say anything about the transformation of f[y].
When you give a function definition such as f[t_]:=t^2, all you are doing is telling the Wolfram System to automatically apply the transformation rule f[t_]->t^2 whenever possible.
You can set up transformation rules for expressions of any form:
This uses a transformation rule for x^p_:
"Patterns" and "Transformation Rules and Definitions" explain in detail how to set up patterns and transformation rules for any kind of expression. Suffice it to say here that in the Wolfram System all expressions have a definite symbolic structure; transformation rules allow you to transform parts of that structure.