I am symbolically working with matrix commutators (
comm) and face the following issue: There are nested commutators in my final results, defined as
NestedComm[mat1_, mat2_, n_] /; n > 1 := comm[NestedComm[mat1, mat2, n - 1], mat2]; NestedComm[mat1_, mat2_, 1] := comm[mat1, mat2]; NestedComm[mat1_, mat2_, 0] := mat1;
which due to the nature of the algorithm appear for instance as
comm[comm[comm[a,b],b],b] in my final expressions. Note that the level of nesting
n can in principle be anything from one to infinity. In order to make the results more readable, I am looking for a pattern or something else that would transform
comm[comm[comm[a, b], b], b] to
nestedComm[a,b,3] (the lowercase letter would be intended to avoid evaluation of the actual definition and to avoid the need of messing around with
Hold and the like). The pattern should of course only apply if it is really a nested commutator according to the definition of
NestedComm - there are also terms like
comm[comm[comm[a,b],c],b] which should stay untouched by the transformation.
Is it somehow possible to automatically recognize this type of
Nested functions and the corresponding level of nesting in order to replace them with a shorthand notation?
Update: It has not been clear from the question, that I do not want the nested
commobjects to simplify automatically everywhere. Actually, my algorithm relies on them not being transformed to
nestedComm throughout many steps of computation. But since the expressions may become quite involved and long, I would like to use a replacement rule/function/... on the final result, so that the nested objects are only simplified where I want them to be.