wolfram-mathematica – 请解释With,Block和Module的这种行为

美好的一天,

我对此感到困惑:

In[1]:= f[x_]:=With[{xx=x},f[xx_]:=ff[xx]]
DownValues[f]
f[1]
DownValues[f]
Out[2]= {HoldPattern[f[x_]]:>With[{xx=x},f[xx_]:=ff[xx]]}
Out[4]= {HoldPattern[f[xx_]]:>ff[xx]}

如果我使用Block或Module而不是With,也会发生同样的情况.

我期望最后的DownValues [f]将给出:{HoldPattern [f [x _]]:> ff [x]}.但事实并非如此.请解释.

最佳答案 从With的文档.

With replaces symbols in expr only when they do not occur as local variables inside scoping constructs.

模块和块根本就不是这样做的.

编辑以详细说明模块和块. `原因符号未被替换,是因为它没有被评估.块和模块不进行语法替换操作.尝试

f[x_] := Block[{xx = x}, f[xx_] = ff[xx]]

然后评估f [z].

或者,您可以通过首先使用非作用域构造来执行初始策略:

f[x_] := With[{xx = x}, 
  Hold[{f[xx_], ff[xx]}] /. {Hold[{a_, b_}] :> SetDelayed[a, b]}]

In[117]:= DownValues[f]

Out[117]= {HoldPattern[f[x_]] :> 
  With[{xx = x}, 
   Hold[{f[xx_], ff[xx]}] /. {Hold[{a_, b_}] :> (a := b)}]}

In[118]:= f[z]

In[119]:= DownValues[f]

Out[119]= {HoldPattern[f[z_]] :> ff[z]}
点赞