Skip to main content

bugs - Dispatch displays rules incorrectly and evaluates when displaying


Bug introduced in 10.0.0 and fixed in 10.0.1





Consider this


a = 3;
disp = Dispatch[Unevaluated[{a -> 2}]]


enter image description here



We see the rule 3 -> 2, rather than a -> 2. However, we have


Unevaluated[a] /. disp



2 (*not 3*)

So that indeed the rule in the dispatch table was a -> 2. Note however that


Unevaluated[a] /. Normal[disp]


3

As Normal[disp] intermediately evaluates to a -> 2 which evaluates to 3 -> 2. a does not match 3, so there is no replacement. So at first sight it may seem reasonable that Dispatch displays the table this way. However, this may lead to side effects



Side effects


Consider the following example. First we just set disp2, without displaying it.


disp2 = Dispatch[Unevaluated[{Print["hello"] -> 2}]];


 Null (*prints nothing, note the semicolon*)

but when we do display the Dispatch table, the message is printed.


enter image description here


Note that we can still use the Dispatch table however.



Unevaluated[Print["hello"]] /. disp2


2

This seems quite weird to me. To me it seems reasonable to put any expression in a Dispatch table. But it is not nice at all that such expressions would be evaluated when we display the Dispatch table. I suppose the way around this is to use HoldPattern, but that is disappointing to me, because really this should not be necessary.


Comparison with Association


To see why this is disappointing, consider Association. Here it is crucial that we use Unevaluated, as it is not an option to use HoldPattern, as the following does not work.


(*b has no value*)
Association[HoldPattern[b] -> 2][b]



Missing["KeyAbsent", b]

For a, which does have a value, we would have to do


Association[Unevaluated[a -> 2]][Unevaluated[a]]


2


Quick fix


Note that evaluating the following will prevent this issue.


Unprotect[Dispatch];
Clear@Dispatch;
Protect[Dispatch];

This only clears the rules that determine how Dispatch tables are displayed.


Question


So all in all it's nothing too major, I just wanted to share this. It is not nice that Dispatch can have side effects when used in this reasonable way. Is this a bug?


A perfect answer would "spelunk" to where to code is evaluated.





Comments