I'm completely puzzled by the following codes:
Clear[func, f]
a = x^2 + z;
func[k_] := Block[{f}, (f[x_] := Evaluate[(a /. {z -> k})]; f[1])]
func[2]
2+x^2
But I think it should be 3
, i.e., 2+1^2=3
.
Actually for the following code:
f[x_] := Evaluate[(a /. {z -> k})]; f[1]
The output is 3.
Can you explain the evaluation inside the Block
?
Taking Simon Woods' advice, for
func[k_] :=
Block[{f, tmp}, (tmp = Evaluate[a /. z -> k]; f[x_] = tmp; f[1])]
Trace[func[2]]
gives,
{func[2],Block[{f,tmp},tmp = Evaluate[a /. z -> 2],f[x_] = tmp; f[1]],...}
But, for the codes
func[k_] := Block[{f}, (f[x_] = Evaluate[a /. z -> k]; f[1])]
Trace[func[2]]
gives,
{func[2],Block[{f},f[x$_] = Evaluate[a /. z -> 2];f[1],...}
I notice that the arguments of f
inside the Block
are different in these two cases, and that is the reason.
But why is the difference?
func[k_] := Block[{y = (a /. {z -> k}), f}, (f[x_] = y; f[1])]
. $\endgroup$Trace[func[2]]
$\endgroup$