Mathematica wraps any expression with some boxing code before showing the evaluation result in the front-end. Unfortunately, the wrapping algorithm and its position in the Mathematica end-to-end flow are not described in the official documentation. Surprisingly, this stuff can affect the evaluation of the expressions. Please, see an UpValues
-based approach to problem of removing head X
by head Y
:
UpValues[Y] = {};
UpValues[X] =
{HoldPattern[(head: __)[a___, X[b__], c___]] :> Hold[head[a, Y[b], c]]};
1 + X[432] + A[2] (* ==> Hold[1 + A[2] + Y[432] *)
X[X[545]] (* ==> Hold[Hold[Y[Y[545]]]] *)
Hold
/HoldPattern
were used in the transformation pattern to keep expression unevaluated but transformed by UpValues[X]
. So it works. Now I want this transformation rule to work only if pattern head
is not X
:
UpValues[Y] = {};
UpValues[X] =
{HoldPattern[(head: Except[X])[a___, X[b__], c___]] :> Hold[head[a, Y[b], c]]};
1 + X[432] + A[2] (* ==> Hold[1 + A[2] + Y[432] *)
X[X[545]]
(* ==>
Hold[
If[False,
Y[X[545]],
With[{OutputSizeLimit`Dump`boxes$ =
Block[{$RecursionLimit = Typeset`$RecursionLimit},
MakeBoxes[X[X[545]], StandardForm]
]},
OutputSizeLimit`Dump`loadSizeCountRules[];
If[TrueQ[BoxForm`SizeCount[OutputSizeLimit`Dump`boxes$, 1048576]],
OutputSizeLimit`Dump`boxes$,
OutputSizeLimit`Dump`encapsulateOutput[X[X[545]], $Line, $SessionID, 5]
]
],
X[X[545]]
]
] *)
It seems, that pattern object Except[X]
captures wrapping code that Mathematica uses to adopt any expression for the front-end needs. As for me it is a surprise because the case using general pattern object __
works well. So, my claim is that code wrapping used for front-end needs can affect the evaluation process in the Mathematica core.
Resulting,
- Where can I read about Mathematica's end-to-end in details? I mean something like "The TeXbook" by D. Knuth for TeX.
- Is the described behaviour a bug? Probably, it corresponds to features of implicit end-to-end flow.
- Probably, the code above is not the only case. What technique can help me to avoid such behaviour?
If
. So,Except[X | If]
$\endgroup$