3
$\begingroup$

I thought I know With and Module until I see this example on Wolfram Documentation.

Below is a demo code:

Clear["*"];
With[{x = a}, x = 5;]
a (* Oupput new value: 5 *)
Clear["*"];
a = 8
With[{x = a}, x = 5;]
a (* Oupput old value: 8 *)

I always though the x in the first With structure is guaranteed to be a constant(With's main function). To my surprise, Not only the x's value is changed, it also give the global variable a a new value! What's more strange is that after the global a is already defined, like what it is the case in the second With structure, the same With expression cannot affect a's value anymore!

Things are a little more understandable with Module:

Clear["*"];
Module[{x = a}, x = 5;]
a (* Output undefined symbol: a *)
Clear["*"];
a = 8;
Module[{x = a}, x = 5;]
a (* Oupput old value: 8 *)

Can anyone please explain to me how this happened?

$\endgroup$
5
$\begingroup$

This is expected behavior, although perhaps confusing at first; it is the power of With :-)

With will inject values into held expressions, so it will inject the value a for x everywhere inside it, and particularly before the Set expression is evaluated.

Look at the results of Trace for your first With expression:

Trace@With[{x = a}, x = 5;]

(* Out: {With[{x = a}, x = 5;], a = 5;, {a = 5, 5}, Null} *)

When you write With[{x = a}, x = 5;] this becomes a = 5, which then assigns the value 5 to global variable a.

$\endgroup$
4
  • $\begingroup$ Then how come the second With statement didn't modified the value of 'a' to 5? $\endgroup$
    – Murphy Ng
    May 4 '20 at 0:15
  • $\begingroup$ @MurphyNg because a already had a value, so x=5 would become 8=5, which doesn’t work and throws an error. Did you not see the error message “Set: can not assign to raw object 8”? $\endgroup$
    – MarcoB
    May 4 '20 at 1:05
  • $\begingroup$ I missed it. The way Wolfram language works really is different from other programming language. It's damn hard making the transit to thinking variable assignment as expression substitution rather than stuff like memory address and so on. $\endgroup$
    – Murphy Ng
    May 5 '20 at 18:30
  • $\begingroup$ @MurphyNg Agreed. It really is a different paradigm, and With is perhaps one of the weirder ones out there. $\endgroup$
    – MarcoB
    May 5 '20 at 18:45

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.