This question already has an answer here:

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[]
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:= a**b
Out:= a b

Works, but:

In:= 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!