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

Making Definitions for FunctionsImmediate and Delayed Definitions

2.4.7 The Ordering of Definitions

When you make a sequence of definitions in Mathematica, some may be more general than others. Mathematica follows the principle of trying to put more general definitions after more specific ones. This means that special cases of rules are typically tried before more general cases.

This behavior is crucial to the factorial function example given in the previous section. Regardless of the order in which you entered them, Mathematica will always put the rule for the special case f[1] ahead of the rule for the general case f[n_]. This means that when Mathematica looks for the value of an expression of the form f[n], it tries the special case f[1] first, and only if this does not apply, it tries the general case f[n_]. As a result, when you ask for f[5], Mathematica will keep on using the general rule until the "end condition" rule for f[1] applies.

Treatment of definitions in Mathematica.

If Mathematica did not follow the principle of putting special rules before more general ones, then the special rules would always be "shadowed" by more general ones. In the factorial example, if the rule for f[n_] was ahead of the rule for f[1], then even when Mathematica tried to evaluate f[1], it would use the general f[n_] rule, and it would never find the special f[1] rule.

Here is a general definition for f[n_].

In[1]:= f[n_] := n f[n-1]

Here is a definition for the special case f[1].

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


Mathematica puts the special case before the general one.

In[3]:= ?f

In the factorial function example used above, it is clear which rule is more general. Often, however, there is no definite ordering in generality of the rules you give. In such cases, Mathematica simply tries the rules in the order you give them.

These rules have no definite ordering in generality.

In[4]:= log[x_ y_] := log[x] + log[y] ; log[x_^n_] := n log[x]

Mathematica stores the rules in the order you gave them.

In[5]:= ?log

This rule is a special case of the rule for log[x_ y_].

In[6]:= log[2 x_] := log[x] + log2

Mathematica puts the special rule before the more general one.

In[7]:= ?log

Although in many practical cases, Mathematica can recognize when one rule is more general than another, you should realize that this is not always possible. For example, if two rules both contain complicated /; conditions, it may not be possible to work out which is more general, and, in fact, there may not be a definite ordering. Whenever the appropriate ordering is not clear, Mathematica stores rules in the order you give them.

Making Definitions for FunctionsImmediate and Delayed Definitions