wolfram-mathematica - 为什么默认行为像这样?

标签 wolfram-mathematica

可以设置一个 Default函数参数的值:

Default[f] = 5;

然后使用:
f[a_, b_.] := {a, b}

f[1, 2]
f[1]
   {1, 2}
   {1, 5}

This creates the following Values:

DefaultValues[f]
DownValues[f]
   {HoldPattern[Default[f]] :> 5}
   {HoldPattern[f[a_, b_.]] :> {a, b}}

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}

and use f again:

f[1]

{1, 5}

我们看到没有使用新值。

因此,我的问题是:
  • 为什么f[a_, b_.] := {a, b}使用的默认值不随 DefaultValues 改变?
  • 实际默认值 ( 5 ) 存储在哪里,因为它没有出现在 DownValues 中或 DefaultValues ?
  • 最佳答案

    不是答案,而是:
    使用在重新定义函数之前保留原始默认值的行为建议快速解决方法:

    Default 定义一个全局变量在做出任何其他定义之前。

    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
    

    关于wolfram-mathematica - 为什么默认行为像这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6337753/

    相关文章:

    wolfram-mathematica - 将声音导出为 WAV 文件

    wolfram-mathematica - 优化大型模型 - 尝试利用并行性

    wolfram-mathematica - "Tag Part in (...) is Protected"

    wolfram-mathematica - 如何中止对输入序列的评估?

    progress-bar - 更新Mathematica中的进度条

    wolfram-mathematica - 增加 Mathematica 函数插值精度/域

    wolfram-mathematica - 列表列表中此 ReplaceAll 的正确语法是什么?

    wolfram-mathematica - 为什么 InverseFunction[0 &]@0 返回 33/10?

    wolfram-mathematica - 在mathematica中操作列表中的一个元素

    java - 坚持一些角度算术