# Non-commutative multiplication sign and constant treatment

By default, non-commutative multiplication behaves as

(-W) ** (4 R) //FullForm


NonCommutativeMultiply[Times[-1,W],Times[4,R]]

while I would like it to simplify as follows, for any object involved that is not a symbol:

(-W) ** (4 R) //FullForm


Times[-4,NonCommutativeMultiply[W,R]]

I could write a set of substitution rules, but I suspect that would be very slow for large number of operations. How should one set this property the most efficient way? Perhaps there is a proper Attribute one can set for NonCommutativeMultiply?

EDIT

Since in my case only products of two operators appear at a time, I use the following as a workaround

Unprotect[NonCommutativeMultiply];
NonCommutativeMultiply[Times[x1_,y1_],Times[x2_,y2_]]:= Times[x1,x2,NonCommutativeMultiply[y1,y2]]


Mathematica seems to order Times as constants first then symbols, which is why this works.

Still wondering how a better more efficient solution would look like.

• Try Times @@ MapThread[Apply, {{Times, NonCommutativeMultiply}, Transpose[FactorTermsList /@ {-W, 4 R}]}]. Generalization ought to be straightforward. – J. M. will be back soon Mar 4 '18 at 17:24
• @J.M. Wow, that line of code looks quite busy... I wonder if that would be the most efficient way for large inputs? – Kagaratsch Mar 4 '18 at 17:27
• How large are we talking? – J. M. will be back soon Mar 4 '18 at 17:29
• @J.M. Millions of operations. Preferably per second... – Kagaratsch Mar 4 '18 at 17:32
• You might want to add a constraint like Times[x1_?NumericQ, y1_] for safety. – J. M. will be back soon Mar 4 '18 at 17:59