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

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


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.


  • 1
    $\begingroup$ 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[...]. $\endgroup$
    – user31159
    Feb 8, 2016 at 19:26
  • $\begingroup$ @Xavier It seems to work! Can you write a more explanatory answer? That way I can also vote it up. Thanks! $\endgroup$
    – Lior Blech
    Feb 8, 2016 at 19:44
  • 5
    $\begingroup$ Perhaps for something more detailed the answers of this post will help? $\endgroup$
    – user31159
    Feb 8, 2016 at 19:51
  • $\begingroup$ 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. $\endgroup$
    – Lior Blech
    Feb 8, 2016 at 21:45


Browse other questions tagged or ask your own question.