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?
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?
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].
Withmakes a "literal" replacement of the instances ofxthat appear in the code that follows the list. When the code isy, there is "literally" noxpresent. So no substitution is made, and *then*yis evaluated, thexappears, but the replacement time is over. – Michael E2 Aug 14 '19 at 23:10Block[{x = 1}, y]. @A.G., see https://mathematica.stackexchange.com/questions/559/what-are-the-use-cases-for-different-scoping-constructs – Michael E2 Aug 14 '19 at 23:12Tracecan be a good tool to use and be familiar with. TryWith[{x = 1}, y] // Trace– Michael E2 Aug 14 '19 at 23:15