为什么默认行为像这样? [英] Why does Default behave like this?
问题描述
可以为函数的参数设置一个Default
值:
One may set a Default
value for the arguments of a function:
Default[f] = 5;
然后使用:
f[a_, b_.] := {a, b}
f[1, 2]
f[1]
{1, 2}
{1, 5}
这将创建以下值:
DefaultValues[f]
DownValues[f]
{HoldPattern[Default[f]] :> 5}
{HoldPattern[f[a_, b_.]] :> {a, b}}
由此可能会认为值5
在f
的定义中不是固定的,而是针对DefaultValues
赋值.但是,如果我们更改 DefaultValues
,直接或使用:
From this one might think that the value 5
is not fixed in the definition of f
, but addresses the DefaultValues
assignment. However, if we change the DefaultValues
, either directly or using:
Default[f] = 9;
DefaultValues[f]
{HoldPattern[Default[f]] :> 9}
并再次使用 f
:
f[1]
{1, 5}
我们看到新值没有被使用.
因此,我的问题是:
为什么
f[a_, b_.] := {a, b}
使用的默认值不随DefaultValues
改变?
Why does the default value used by
f[a_, b_.] := {a, b}
not change withDefaultValues
?
真正的默认值 (5
) 存储在哪里,因为它没有出现在 DownValues
或 DefaultValues
中?
Where is the real default value (5
) stored, since it does not appear in either DownValues
or DefaultValues
?
推荐答案
不是答案,而是:
使用在重新定义函数之前保留原始默认值的行为建议一个快速的解决方法:
Not an answer, but:
Using the behaviour that the original default is kept until the function is redefined suggests a quick work-around:
在进行任何其他定义之前为 Default
定义一个全局变量.
Define a global variable for the Default
before any other definitions are made.
In[1]:= Default[f]:=$f
In[2]:= f[a_.]:=a
In[3]:= f[]
Out[3]= $f
In[4]:= $f=5; f[]
Out[5]= 5
In[6]:= $f=6; f[]
Out[7]= 6
In[8]:= $f=.; f[]
Out[9]= $f
这也适用于 Optional
In[1]:= g[a_:$g] := a
In[2]:= g[]
Out[2]= $g
In[3]:= $g=1; g[]
Out[4]= 1
这篇关于为什么默认行为像这样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!