Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Usually we define a function with default values by the syntax x_:default, but there is another technique to do this by registering a global default value with Default. In the Document, there are three ways to use Default, two of which have confused me.

The document tells that

Default[f,i] gives the default value to use when _. appears as the i-th argument of f

, while

Default[f,i,n] gives the default value for the i-th argument out of a total of n arguments

. Therefore, I have tried the following comparison:

Default[f, 1] = a1;
Default[f, 2] = a2;
Default[f, 3] = a3;
f[x_., y_., z_.] := {x, y, z}
{f[], f[1], f[1, 2], f[1, 2, 3]}

The result is {{a1, a2, a3}, {1, a2, a3}, {1, 2, a3}, {1, 2, 3}}.

ClearAll[f];
Default[f, 1, 3] = a1;
Default[f, 2, 3] = a2;
Default[f, 3, 3] = a3;
f[x_., y_., z_.] := {x, y, z}
{f[], f[1], f[1, 2], f[1, 2, 3]}

This give the same result.

It seems that there is no difference between these two ways to use Default. If there were no difference, why would the document list the two ways?

I'd appreciate it if someone could provide some information.

share|improve this question

1 Answer 1

up vote 5 down vote accepted

The third parameter allows control of Optional behavior for multiple function definitions. It is not attached to the number of actual arguments passed to the function but rather to the number of arguments that appear in the function definition itself. Consider this example:

ClearAll[f];

Default[f, 1, 3] = a1;
Default[f, 2, 3] = a2;
Default[f, 3, 3] = a3;
f[x_., y_., z_.] := {x, y, z}

Default[f, 1, 2] = Q;
Default[f, 2, 2] = R;
f[x_., Optional[y_Symbol]] := foo[x, y]

Now:

{f[], f[1], f[1, 2], f[1, 2, 3]}
{foo[Q, R], foo[1, R], {1, 2, a3}, {1, 2, 3}}
share|improve this answer
    
Thanks for your help! –  Z-Y.L Apr 10 at 10:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.