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?
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.
$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$
"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$
$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$
$Pre
defined... try evaluating $Pre =.
and then repeat your experiment. I get 1.
$\endgroup$