If I define an expression , and evaluate it in With function, replace rule does not work.
sumT = TA + TE;
With[
{TA = 0.1, TE = 0.2},
{TA + TE, sumT}
]
output
{0.3, TA + TE}
try this:
sumT = TA + TE;
With[
{TA = 0.1, TE = 0.2},
Evaluate@{TA + TE, sumT}
]
With
has the attribute HoldAll
$\endgroup$
Commented
Nov 19, 2023 at 19:14
Replace With
with Block
:
sumT = TA + TE;
Block[{TA = 0.1, TE = 0.2}, {TA + TE, sumT}]
{0.3, 0.3}
Block[{TA = 0.1, TE = 0.5}, {TA + TE, sumT}]
{0.6, 0.6}
From its Documentation
details:
"Block
allows you to set up an environment in which the values of variables can temporarily be changed."
In answer to
Could you give some explanation ?
Just follow the evaluation process
With[ {TA = 0.1, TE = 0.2}, {TA + TE, sumT} ]
{0.1 + 0.2, sumT}
{0.3,sumT}
{0.3, TA + TE}
The way With
works is that it holds everything unevaluated, performs the substitutions "formally", and then "goes away" and lets the resulting expression continue evaluating. You can think of the TA
and TE
inside of the With
as local variables if you want. Once the With
has been handled (step 2), we're now back at the main scope, and sumT
will be replaced according to its OwnValues
.