7
$\begingroup$

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.

$\endgroup$
6
$\begingroup$

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}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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