4
$\begingroup$

Why does

Block[{$Pre = ( 1 + #) &}, 1]

produce 1 while

Block[{$PreRead = Print["hi"]}, 1]

produces

"hi"
1

? In the Block block, shouldn't the expression have it's Pre evaluation as well?

$\endgroup$

1 Answer 1

6
$\begingroup$

No, $Pre and $PreRead cannot be set within a "line" of code and apply to that same "line" as well. Your example with $PreRead is a false result because you did not make it a function.

Consider:

Block[{$PreRead = (Print["hi"]; #) &}, 1]
1

If outside Block you set:

$PreRead = (Print["<<", #, ">>"]; #) &;

and then evaluate a Block:

Block[{x},
 1;
 2;
 3;
]
 <<RowBox[{Block,[,RowBox[{RowBox[{{,x,}}],,,RowBox[{1,;,2,;,3,;}]}],]}]>>

You see that the entire "line" (I can't think of a better term at the moment) of code is sent to $PreRead, not individual parts of it.

$\endgroup$
5
  • $\begingroup$ That is unfortunate. If I ever have to use $Pre or $Post, I have to evaluate them in a separate line, do my calculation on a second, and then remove their values on a third! Also, when you say "false result," I don't quite understand. What does the fact that it isn't a function have to do with it being evaluated? $\endgroup$
    – VF1
    Commented Oct 23, 2012 at 4:11
  • $\begingroup$ @VF1 Because the "hi" you're seeing is just because the Print statement evaluated, and not as a result of $PreRead being correctly set. If it indeed were set correctly, as you had hoped, you should've seen two "hi" statements for the following Block[{$PreRead = Print["hi"]}, 1; 1;] $\endgroup$
    – rm -rf
    Commented Oct 23, 2012 at 4:38
  • $\begingroup$ @rm-rf Thanks for the clarification. $\endgroup$
    – VF1
    Commented Oct 23, 2012 at 4:42
  • $\begingroup$ @rm-rf Actually, if the rhs of the expression $PreRead is evaluated, I would assume that $PreRead has been set. Anyways, regarding the fact that setting it doesn't change the first line - $Pre = 1 + # &; 1 returns 2. Why is CompoundExpression special and Block not? $\endgroup$
    – VF1
    Commented Oct 23, 2012 at 14:18
  • $\begingroup$ @VF1 I suspect you already had $Pre defined... try evaluating $Pre =. and then repeat your experiment. I get 1. $\endgroup$
    – rm -rf
    Commented Oct 23, 2012 at 14:24

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.