Two responses show how one might do this. Here is a third, and it shows what went awry in the original attempt.
First note that With
holds all its arguments.
In[298]:= Attributes[With]
(* Out[298]= {HoldAll, Protected} *)
The practical consequence is that there is no x
in the second argument until after it is evaluated. And this happens (as it happens) after the macro-style substitution of 10
for x
in that second argument. To force the expression in the second argument to be x^2/2
, simply use Evaluate
.
In[299]:= With[{x = 10}, Evaluate@a]
Out[299]= 50
This next shows a bit more detail about the evaluation sequence for the example.
In[302]:= a = Integrate[x, x];
Trace[With[{x = 10}, a]]
Trace[With[{x = 10}, Evaluate@a]]
(* Out[303]= {HoldForm[With[{x = 10}, a]], HoldForm[a], HoldForm[x^2/2]}
Out[304]= {{HoldForm[a], HoldForm[x^2/2]},
HoldForm[With[{x = 10}, x^2/2]], HoldForm[10^2/2],
{HoldForm[10^2], HoldForm[100]}, HoldForm[100/2], HoldForm[50]} *)
I will remark that similar issues arise with Plot
and related functions that hold their arguments.