Message Boards Message Boards

0
|
3343 Views
|
1 Reply
|
2 Total Likes
View groups...
Share
Share this post:

A question about two ways to use Default function argument values

Posted 11 years ago
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}}
The other 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}
{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.
POSTED BY: Zhenyu Lu

Thanks God does the other example give the same result as the first: both definitions take three arguments. But in fact the second feature allows you to define functions with mandatory and optional arguments

In[189]:= ClearAll[g];
Default[g, 3, 5] = a3;
Default[g, 4, 5] = a4;
Default[g, 5, 5] = a5;
g[x1_, x2_, x3_., x4_., x5_.] := {x1, x2, x3, x4, x5}
{g[o1], g[o1, o2], g[o1, o2, 1], g[o1, o2, 1, 2], g[o1, o2, 1, 2, 3],  g[o1, o2, 1, 2, 3, X]}

Out[194]= {g[o1], {o1, o2, a3, a4, a5}, {o1, o2, 1, a4, a5}, {o1, o2, 1, 2, a5}, {o1, o2, 1, 2, 3}, g[o1, o2, 1, 2, 3, X]}

whereas with the f default definitions

In[171]:= ClearAll[f]
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], f[1, 2,3, x]}

Out[176]= {{a1, a2, a3}, {1, a2, a3}, {1, 2, a3}, {1, 2, 3}, f[1, 2, 3, x]}

and

In[195]:= {f[o1], f[o1, o2], f[o1, o2, 1], f[o1, o2, 1, 2],  f[o1, o2, 1, 2, 3], f[o1, o2, 1, 2, 3, X]}
Out[195]= {{o1,a2,a3},{o1, o2, a3}, {o1, o2, 1}, f[o1, o2, 1, 2], f[o1, o2, 1, 2, 3], f[o1, o2, 1, 2, 3, X]}
POSTED BY: Udo Krause
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract