Read Online
Download PDF
Additional resources
Revision history
Known typos/bugs
Report a bug
License terms
About the author
"node189_1.gif" "node189_2.gif" "node189_3.gif"

4.6.4  Functions with variable number of arguments

Sometimes one may need to define a function whose number of arguments is not fixed, either because it can change from one call to the other, or because there is no need to refer to the individual arguments, or both. To do this, one may use BlankSequence (__) or BlankNullSequence (___),  depending on whether or not the zero arguments case has to be included. Several built - in functions  are in fact defined on an arbitrary number of arguments, examples being Plus, Times,  Equal, Alternatives, SameQ and a few others.  

As an example, we will define our own version of Plus function :




The built - in Plus is however defined also for zero arguments (through convention) :



Since we used BlankSequence, the zero argument case is not included in our function definition :



If we want it to behave just as the built - in Plus in all cases, we have to use BlankNullSequence :


Check now :



Let us now define a function which will multiply its first argument by the sum of all others :


We have included the case when there is a single argument. Check :



There is no ambiguity in this case as to which arguments will be matched with < x_ > pattern and which with < y___ >, since < x_ > states that there should be exactly one - the first one, and all the rest are matched by < y___ > .

The other way to define the same function would be not to split arguments on the level of the definition but to do that later, in the body of the function :


This is exactly equivalent to the previous realization. The role of Apply here is to hand to Plus the interior of the list Rest[{x}], rather than the list itself. :



One has however to avoid ambiguous patterns like the following one :




This example is in fact  useful to examine the way how the pattern - matcher works: it is obvious that it starts from the left, and once it finds out that < 1 > matches < x__ >, then all the rest of the arguments match < y__ > . However, one should not rely on a particular behavior of the pattern - matcher, and neither should one use ambiguous patterns like the one above.

The more general pattern we use in a function definition, the more dangerous it is in the sense that it may match incorrectly in situations completely unforeseen by the developer. We already discussed this issue when we considered patterns and rules separately (section, but this is  as true for function definitions as it was for local  rules and patterns (since function definitions are just global rules). The less you use these patterns the safer your functions will be  - use them only when necessary.

"node189_23.gif" "node189_24.gif" "node189_25.gif"

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