How to | Create Definitions for Variables and Functions

The Wolfram Language has a very general notion of functions, as rules for arbitrary transformations. Values for variables are also assigned in this manner. When you set a value for a variable, the variable becomes a symbol for that value.

Here is a simple transformation rule. It says: whenever you see , replace it by 3:

In[1]:=
Click for copyable input
Out[1]=

The variable has a value of 3.

Whenever you evaluate an expression, 3 is substituted for :

In[2]:=
Click for copyable input
Out[2]=

You can remove the rule by defining a new one:

In[3]:=
Click for copyable input
Out[3]=

The new rule says: whenever you see , replace it by . So far there are no rules associated with , so its value is itself.

Assign a value to :

In[4]:=
Click for copyable input
Out[4]=

Now if you evaluate , the rule for says to replace by , and the rule for says to replace by 4, so the result is , or 16:

In[5]:=
Click for copyable input
Out[5]=

If you change the value of , then the value of changes:

In[6]:=
Click for copyable input
Out[6]=
In[7]:=
Click for copyable input
Out[7]=

Now assign a value to , like this:

In[8]:=
Click for copyable input
Out[8]=

Since has already been assigned the value 3, the rule you have defined is "replace by 9", not "replace by ". So does not depend on :

In[9]:=
Click for copyable input
Out[9]=
In[10]:=
Click for copyable input
Out[10]=

This happened because when a rule is defined using (Set), the right-hand side is evaluated before the rule is defined.

You can also define rules using (SetDelayed), like this:

In[11]:=
Click for copyable input

When a rule is defined with the right-hand side is not evaluated before the rule is defined. So even if already has a value, this new rule says: whenever you see , replace it with . So in this case, depends on :

In[12]:=
Click for copyable input
Out[12]=
In[13]:=
Click for copyable input
Out[13]=
In[14]:=
Click for copyable input
Out[14]=

Functions in the Wolfram Language are defined by rules that act on patterns. Here is a simple one:

In[15]:=
Click for copyable input

is a pattern in which stands for any expression (which is represented on the right-hand side by the name ). The rule says: if you have of any expression, replace it by that expression squared:

In[16]:=
Click for copyable input
Out[16]=
In[17]:=
Click for copyable input
Out[17]=

Here is a function with two arguments:

In[18]:=
Click for copyable input
In[19]:=
Click for copyable input
Out[19]=

Always use to define functions, otherwise the variables on the right-hand side may not represent the associated expressions on the left-hand side, since they will be evaluated before the rule is defined:

In[20]:=
Click for copyable input
Out[20]=

That happened because is 9 and is 3. This rule says that anything matching the pattern is replaced by 90:

In[21]:=
Click for copyable input
Out[21]=