Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 6 down vote accepted

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.

share|improve this answer
    
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? –  VF1 Oct 23 '12 at 4:11
    
@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;] –  rm -rf Oct 23 '12 at 4:38
    
@rm-rf Thanks for the clarification. –  VF1 Oct 23 '12 at 4:42
    
@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? –  VF1 Oct 23 '12 at 14:18
    
@VF1 I suspect you already had $Pre defined... try evaluating $Pre =. and then repeat your experiment. I get 1. –  rm -rf Oct 23 '12 at 14:24
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.