Please explain this behavior with C, Block and Module

Good afternoon,

I am a little puzzled by this:

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]} 

The same thing happens if I use Block or Module instead of With .

I expected the last DownValues[f] give: {HoldPattern[f[x_]]:>ff[x]} . But this is not so. Please explain.

+4
source share
1 answer

From the documentation With .

With the replacement of characters in expr only when they are not found as local variables in scoping constructs.

The module and block are simply not designed for this.

Modify to clarify Module and Block . The reason symbol is not replaced, so it is that it is not evaluated. The block and module do not perform syntactic replacement operations. Try

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

and then evaluate f[z] .

Alternatively, you can execute the initial strategy by first using the construct without specifying a scope:

 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]} 
+2
source

Source: https://habr.com/ru/post/1342993/


All Articles