4
$\begingroup$

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}
$\endgroup$

3 Answers 3

5
$\begingroup$

try this:

sumT = TA + TE;
With[
 {TA = 0.1, TE = 0.2},
  Evaluate@{TA + TE, sumT}
 ]
$\endgroup$
2
  • 1
    $\begingroup$ Could you give some explanation ? $\endgroup$
    – eason
    Commented Nov 19, 2023 at 19:08
  • 1
    $\begingroup$ With has the attribute HoldAll $\endgroup$
    – Bob Hanlon
    Commented Nov 19, 2023 at 19:14
3
$\begingroup$

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."

$\endgroup$
1
  • $\begingroup$ In fact, I have a bit complex function , I combine With in Block. Because I first get a lot of formulas , then I verify them by passing real number. $\endgroup$
    – eason
    Commented Nov 19, 2023 at 19:09
3
$\begingroup$

In answer to

Could you give some explanation ?

Just follow the evaluation process

  1. With[ {TA = 0.1, TE = 0.2}, {TA + TE, sumT} ]
  2. {0.1 + 0.2, sumT}
  3. {0.3,sumT}
  4. {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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.