2
$\begingroup$

Modified code from the help file on $Pre:

$PreRead =.

SetAttributes[saveinputs, HoldAll];
inputs = {};
saveinputs[new_] := (inputs = {inputs, HoldForm[new]}; new);
$PreRead = saveinputs;

Evaluating:

<>

then

Flatten[inputs]

{<>,8.,RowBox[{Flatten,[,inputs,]}]}

If you look at the Cell Expression for the 8. it is actually a TagBox

TagBox["8.`", HoldForm]

Why does a syntax error cause this?

Example where this causes a problem in code:

$PreRead =.

SetAttributes[saveinputs, HoldAll];
inputs = {};
saveinputs[new_] := (inputs = {inputs, HoldForm[new]};
  If[Unevaluated[new],
   new,
   new);
$PreRead = saveinputs;

When evaluating pretty much anything you get:

ToExpression::esntx: Could not parse 8.` as Mathematica input.

If the test clause of the if statement in the above code does not depend on new then it runs fine.

$PreRead =.

SetAttributes[saveinputs, HoldAll];
inputs = {};
saveinputs[new_] := (inputs = {inputs, HoldForm[new]};
  If[True,
   new,
   new);
$PreRead = saveinputs;

The above works fine.

How am I changing new in the test clause to cause this to fail?

$\endgroup$
0

1 Answer 1

3
$\begingroup$

"How am I changing new in the test clause to cause this to fail?"

With three arguments, If[condition,t,f], If remains unevaluated, i.e., it returns If[condition,t,f], if the condition is neither True nor False.

Using the four-arguments form, If[condition,t,f,u] gives u if condition evaluates to neither True nor False as in your case with Unevaluated[new] as the test clause.

So if you change your code to

$PreRead =.

SetAttributes[saveinputs, HoldAll];
inputs = {};
saveinputs[new_] := (inputs = {inputs, HoldForm[new]};If[whatever, new, new, new]);
$PreRead = saveinputs;

it works like the example in the docs.

$\endgroup$
1
  • $\begingroup$ Sure enough, just needed a TrueQ to make sure it turned out a boolean. $\endgroup$
    – Davorak
    Commented Aug 24, 2012 at 7:18

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.