When working with symbolic matrix operations or other objects which don't have commutative multiplication, it would be nice to not have to constantly switch out times for NonCommutativeMultiply (**). So I was wondering if there is a way to do something like
matrix /: Times[pre___, a_matrix, post___] := NonCommutativeMultiply[pre, a, post]
a = matrix["a"];
b = matrix["b"];
and then have it replaced automatically. However since Times is orderless, this doesn't preserve the order. In general, is it impossible to get the order of inputs when doing this kind of "overloading" though upvalues of an orderless function?
Answer
Well, you can sort of do this, by creating something like a continuation. This requires playing games with the Stack, and I don't claim that it is robust, but it may represent some theoretical interest, particularly to those of us looking for ways to implement continuations in Mathematica. Here is the code (edit please note that I had to add Update[matrix] to address some improper behavior noted in the comments end edit):
ClearAll[matrix, inMatrix];
matrix /: HoldPattern[Times[pre___, a_matrix, post___]] :=
(
Update[matrix];
ReleaseHold[NonCommutativeMultiply @@@ $stack]
);
matrix[args__] /; ! TrueQ[inMatrix] :=
Block[{inMatrix = True},
Update[matrix];
$stack = Stack[_][[-5]];
matrix[args]]
It combines UpValues, Villegas-Gayley trick to redefine a function, and manipuations with Stack. What happens is that first, of course, the attributes of Times are applied, I can't fight that. Then, the DownValues of matrix are applied, and at this point I record the relevant part of the Stack. Then, UpValues of matrix are applied, and at that point I communicate the recorded part of the stack, where the attributes of Times weren't yet applied, and Times gets replaced with NonCommutativeMultiply, after which I re-evaluate this, as if it was not evaluated before. The Update sommand is used to prevent caching the values for the $stack, as this is inappropriate here and resulted in some erroneous behavior noted in the comments.
Here are some examples:
a = matrix["a"];
b = matrix["b"];
a*c*b
matrix[a]**c**matrix[b]
f[g[1 + c*a*d*b*e]]
f[g[1 + c ** matrix["a"] ** d ** matrix["b"] ** e]]
I would not probably recommend such tricks for serious use, it is just interesting that you can use them to divert evaluation sequence in ways which seem to be impossible otherwise.
Comments
Post a Comment