I want to define a new Product but for NonCommutativeMultiply, which I do something like this:

NCMProduct[expr_, iterator_] := NonCommutativeMultiply @@ Table[expr, iterator]

Is there any way for Mathematica to Block the iterator automatically to the scope of NCMProduct like it would for Product?

So then I could use things like:

i = 3; NCMProduct[f[i], {i, 5}] Product[f[i], {i, 5}]

In this case, Product will Block out i and the fact that I have assigned to i doesn't matter, but NCMProduct doesn't know that i is going to be Blocked inside its definition, and hence I get Table::itraw, which isn't the behaviour I want. I'd also like to have nice syntax highlighting for my NCMProduct showing that i is Blocked in the front end if possible!


1 Answer 1


Your problem is an evaluation leak, which is fixed with:

SetAttributes[NCMProduct, HoldAll];

NCMProduct[expr_,iterator_] := NonCommutativeMultiply @@ Table[expr, iterator]

Your example:

i = 3;
NCMProduct[f[i], {i, 5}]

f[1] ** f[2] ** f[3] ** f[4] ** f[5]

As for syntax coloring, the easiest thing to do is to copy the syntax information for Product:

SyntaxInformation[NCMProduct] = SyntaxInformation[Product];

Here is a screen shot showing the syntax coloring:

enter image description here

  • $\begingroup$ Excellent thanks! $\endgroup$
    – Jojo
    Jan 25, 2018 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.