3
$\begingroup$

I just noticed that

With[{x = 1}, If[x == 0, 0, 1]]

returns 1 (as I expected) but

y := If[x == 0, 0, 1];
With[{x = 1}, y]

returns an unevaluated form:

If[x == 0, 0, 1]

Can someone explain what is going on?

$\endgroup$
  • 4
    $\begingroup$ With makes a "literal" replacement of the instances of x that appear in the code that follows the list. When the code is y, there is "literally" no x present. So no substitution is made, and then y is evaluated, the x appears, but the replacement time is over. $\endgroup$ – Michael E2 Aug 14 at 23:10
  • 3
    $\begingroup$ @kglr I might suggest Block[{x = 1}, y]. @A.G., see mathematica.stackexchange.com/questions/559/… $\endgroup$ – Michael E2 Aug 14 at 23:12
  • 1
    $\begingroup$ For these short examples, Trace can be a good tool to use and be familiar with. Try With[{x = 1}, y] // Trace $\endgroup$ – Michael E2 Aug 14 at 23:15
5
$\begingroup$

Mathematica is an expression rewriting language. With[{x = 1}, y] rewrites y with every x replaced by 1. With has the HoldAll attribute, so y is left unevaluated before the rewrite takes place.

But y contains no x, so the the result is simply y. Then, since y has an ownvalue, it gets rewritten as If[x == 0, 0, 1].

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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