Read Online
Download PDF
Additional resources
Revision history
Known typos/bugs
Report a bug
License terms
About the author
"node169_1.gif" "node169_2.gif" "node169_3.gif"

4.4.3    On the necessity of patterns

So, the name of the function is its Head  - the symbol outside the square brackets in its definition, which contains a pattern. We may ask if it is possible to define a function without a pattern. The answer is that it is possible but the object so defined will not be a function in the normal sense and will have a behavior different from what we  probably  want. Here is an example:


This definition does not contain a pattern (no underscore or other pattern ingredients). Let us check it:



Since we did not have a pattern, the class of expressions on which the corresponding rule will match has been narrowed down to just literal f[x]. In particular, it will not work on any other parameters :



Moreover, if we then define the global value for an < x > variable, it will not work on < x > either :



(We should already be able to understand the last result : x evaluated to 5 before f had any chance to "look" at it).

The object f[x] here could be interpreted as an indexed variable (section 2.2.4) rather than a function, but  even in this interpretation, it is a very error - prone practice to use symbols as indices in indexed variables. In any case, it has nothing to do with the  behavior of the real function.

This behavior explains why we need patterns to define functions: patterns widen the class of expressions on which the rule will match. In particular, when we write


the pattern < x_ > means "any expression" and < x > here becomes a name attached to a placeholder where the actual input parameter will be placed. When we later call the function, normally the input parameters are evaluated first, and then the action of the function is to  replace them with whatever the action of the r.h.s. of the corresponding rule should be.


"node169_13.gif" "node169_14.gif" "node169_15.gif"

Created by Wolfram Mathematica 6.0  (05 February 2009) Valid XHTML 1.1!