8
$\begingroup$

I need a behaviour provided by:

x = 2;
Block[{x = HoldForm[x]}, x]
x

FrontEnd marks this syntax as not quite correct.

enter image description here

It has not caused me any troubles so far so my question is: could it be a problem?

$\endgroup$
2
  • 2
    $\begingroup$ I don't think it's a problem; the front end produces this coloring as a hint to the user that there could be a scoping inconsistency, not to say that the code is necessarily erroneous. The greater question in my mind is why does the FE apply the coloring in this particular case, which to me looks rather benign. (For others' reference, the FE is saying that x will go out of scope before being used. I must admit I don't understand what this even means for HoldForm.) $\endgroup$ Commented May 23, 2014 at 23:55
  • $\begingroup$ The notebook code editor is far from perfect. It produces strange coloration in many other situations. $\endgroup$
    – m_goldberg
    Commented May 24, 2014 at 2:26

1 Answer 1

7
$\begingroup$

The FE only looks at the structure of your code for colouring. It doesn't evaluate anything. This means two things: (1) it can only guess that there might be a problem, because by looking at the structure, it doesn't know whether your code really evaluates to something you might not want. (2) You can easily trick the FE by changing the structure into something equivalent which looks different. With this you can easily trick the FE into whatever colouring you prefer. Here are only some examples of exactly the same code:

Mathematica graphics

Mathematica graphics

Mathematica graphics

Mathematica graphics

Mathematica graphics

$\endgroup$
6
  • 1
    $\begingroup$ Or: Block[{x=HoldForm@x},x] $\endgroup$ Commented May 24, 2014 at 6:27
  • $\begingroup$ @RolfMertig Included! $\endgroup$
    – halirutan
    Commented May 24, 2014 at 8:28
  • $\begingroup$ @halirutan So do you think it is only artifact/preventive behaviour and not an idication of any subtle cases that I may face one day? $\endgroup$
    – Kuba
    Commented May 24, 2014 at 8:36
  • 2
    $\begingroup$ There is one issue: It seems you cannot remove the HoldForm wrapper inside the Block. If you use x=HoldForm[a] instead, everything works as expected. Look at the output of this and then replace a by x. $\endgroup$
    – halirutan
    Commented May 25, 2014 at 1:28
  • $\begingroup$ I stumbled over this when I was trying to mess with the scoping by releasing the hold of x. I wanted to see what happens because the x inside the HoldForm is the global x. Obviously they prevented it. What consequences this has for your code, I don't know. $\endgroup$
    – halirutan
    Commented May 25, 2014 at 1:30

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.