# Replacement producing unexpected result

If I use a replacement rule like

Times[2, Plus[Times[AuRr, BuRb], Times[AuRb, BuRr]], h10] /.
{Times[r_, Plus[Times[x_, y_], Times[v_, w_]], h10] :>
r*TensorProduct[(TensorProduct[x, y] + TensorProduct[v, w]), h10]}


I get correctly

(* 2 (AuRb \[TensorProduct] BuRr + AuRr \[TensorProduct] BuRb) \[TensorProduct]h10 *)


Nevertheless, if I try to do the same thing more general, i.e. allowing for a general last coefficient, not specifically h10:

Times[2, Plus[Times[AuRr, BuRb], Times[AuRb, BuRr]], h10] /.
{Times[r_, Plus[Times[x_, y_], Times[v_, w_]], h_] :>
r*TensorProduct[(TensorProduct[x, y] + TensorProduct[v, w]), h]}


I get the wrong result

 (* 2 h10 (AuRb \[TensorProduct] BuRr + AuRr \[TensorProduct] BuRb) *)


Any ideas about what is going wrong here, would be much appreciated!

• Please don't add bugs tag until the community has conformed it. BTW it's almost impossible to find a bug in core language of Mathematica. – xzczd Dec 29 '15 at 9:27

Mathematica automatically factors out constants from TensorProducts:

TensorProduct[a, 2 b] (* returns 2 a\[TensorProduct]b *)


If you consider

Times[2, Plus[Times[AuRr, BuRb], Times[AuRb, BuRr]], h10] /.
{Times[r_, Plus[Times[x_, y_], Times[v_, w_]], h_]
:>
Echo[r]*TensorProduct[(TensorProduct[x, y] + TensorProduct[v, w]), Echo@h]
}


you will see that the pattern-matcher sets r = h10 and h = 2, which accounts for why the constants end up outside the expression. Then it ends up with a TensorProduct of an expression with 1, and that gets rid of the outermost TensorProduct.

• Thanks a lot for the explanation! I now simply add the condition /; Element[r, Reals] and everything works perfectly – jak Dec 29 '15 at 9:13