My goal right now is to implement some rules like linearity etc for noncommuting operators (arbitrary matrices etc). This is partly an exercise for me to understand MMA better so giving me a package like NCAlgebra is not really helping. My code is:

EmptyQ[__] := False
EmptyQ[] := True

ConstQ[args_Times] := And @@ ConstQ /@ List @@ args
ConstQ[args_Plus] := And @@ ConstQ /@ List @@ args
ConstQ[args_NonCommutativeMultiply] := And @@ ConstQ /@ List @@ args
ConstQ[args_Integrate] := And @@ ConstQ /@ List @@ args[[1]]
ConstQ[args_Operator] := False
ConstQ[_] := True

Unprotect[NonCommutativeMultiply];
a___ ** (b_?ConstQ x_) ** c___ := b (a ** x ** c)
a___ ** (x_ + y_) ** c___ := a ** x ** c + a ** y ** c
a___ ** b_?ConstQ ** c___ := b a ** c /; ! EmptyQ[a, c]

NonCommutativeMultiply[x_] := x
Protect[NonCommutativeMultiply];


Trying

In[1]:= a**b
Out[1]:= a b


Works, but:

In[2]:= Operator[y] ** Operator[x]


gives me

"\$IterationLimit::itlim: Iteration limit of 4096 exceeded. >>"


I've tried working with MatchQ and ReplaceAll to try and manually see what happens but I can't figure out what rule (and why) is getting applied over and over (if that's even what's happening).

The question is similiar to this this this this and this but by reading these I couldn't understand where the bug is coming from. Also some of them may have workarounds but I really want to understand how to write good MMA code down the line.

Thanks!

## marked as duplicate by MarcoB, m_goldberg, user9660, ubpdqn, Yves KlettFeb 15 '16 at 6:51

• This is probably due to the Flat attribute of NonCommutativeMultiply which fires in the pattern matching when your last DownValues is invoked. You can remove it by adding Attributes[NonCommutativeMultiply] = {}; right after the line of code Unprotect[...]. – user31159 Feb 8 '16 at 19:26