The Ordering of Definitions

When you make a sequence of definitions in the Wolfram System, some may be more general than others. The Wolfram System 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 "Making Definitions for Functions". Regardless of the order in which you entered them, the Wolfram System will always put the rule for the special case ahead of the rule for the general case . This means that when the Wolfram System looks for the value of an expression of the form f[n], it tries the special case first, and only if this does not apply, it tries the general case . As a result, when you ask for , the Wolfram System will keep on using the general rule until the "end condition" rule for applies.

The Wolfram System tries to put specific definitions before more general definitions.

Treatment of definitions in the Wolfram System.

If the Wolfram System 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 was ahead of the rule for , then even when the Wolfram System tried to evaluate , it would use the general rule, and it would never find the special rule.

Here is a general definition for .
In[1]:=
Click for copyable input
Here is a definition for the special case .
In[2]:=
Click for copyable input
Out[2]=
The Wolfram System puts the special case before the general one.

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, the Wolfram System simply tries the rules in the order you give them.

These rules have no definite ordering in generality.
In[4]:=
Click for copyable input
The Wolfram System stores the rules in the order you gave them.
This rule is a special case of the rule for .
In[6]:=
Click for copyable input
The Wolfram System puts the special rule before the more general one.

Although in many practical cases, the Wolfram System 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, the Wolfram System stores rules in the order you give them.