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!

• 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
• @Xavier It seems to work! Can you write a more explanatory answer? That way I can also vote it up. Thanks! – Lior Blech Feb 8 '16 at 19:44
• Perhaps for something more detailed the answers of this post will help? – user31159 Feb 8 '16 at 19:51
• That was an illuminating post. I wonder if any mathematica books cover this strange behaviour. I started reading Leonid Shifrin's book and he talkes a little about similiar things. – Lior Blech Feb 8 '16 at 21:45