# NonCommutativeMultiply syntax question

I define:

Unprotect[NonCommutativeMultiply];
NonCommutativeMultiply[left___, HoldPattern[Times[u[x_], p : (a[k_] | SuperDagger[a][k_])]],
right___] := u[x] NonCommutativeMultiply[left, p, right]
Protect[NonCommutativeMultiply];


since I want the function u[x_] to commute with a[k_], SuperDagger[a][k_]

Now if i try

In:= a[k] ** u[k]*a[q]
Out= a[q] a[k] ** u[k]    (*  which is not the desired output*)


if i try

In:= a[k] ** (u[k] a[q])
Out= a[k] ** a[q] u[k]


which is better but still it's not u[k] a[k] ** a[q]

I can't figure out why my definition isn't working. What am I missing?

• The problem is that ** distributes over *. That means: a[k] ** u[k]*a[q] is interpreted as: (a[k] ** u[k]) * ( a[k] **a[q]). If you write: a[k] ** (u[k]*a[q]) you get: a[k] ** a[q] u[k] – Daniel Huber Dec 20 '20 at 12:27
• @DanielHuber I thought my rule would take care of that? Even with a[k] ** (u[k] a[q]) the output places u[k] after a[k] ** a[q]  not before. How should I change it to have the desired output? – geom Dec 20 '20 at 12:32
• "Times" has the attribute "Orderless". Therefore MMA will rearrange the expression according to its own rules (I think, lexicographically, but I am not sure) – Daniel Huber Dec 20 '20 at 12:47
• @DanielHuber Geez, you are right. Even if I add orderless to NonCommutativeMultiply nothing changes.The order is decided by Sort which orders symbols by their names, and in the event of a tie, by their contexts. Please post your comments as an answer. They are helpful. – geom Dec 20 '20 at 13:08

The problem is that NonCommutativeMultiply (**) distributes over Times.
That means: a[k] ** u[k]*a[q] is interpreted as: (a[k] ** u[k]) * (a[k] ** a[q]). If you write: a[k] ** (u[k]*a[q]) you get: a[k] ** a[q] u[k]
Furthermore, Times has the attribute Orderless. Therefore MMA will rearrange the expression according to its own rules (I think lexicographically, but I am not sure).