Delayed Rule right-hand-side mis-evaluation

Outline

I am trying to create a rule that will give me a minus sign if the number of times A is applied on X is odd where A is some οperator and X a random quantity.

Some of the configurations of interest: A@X,A@A@X,C*A@A@A@A@X etc, in general a term will be of the form D1@X where D1=C*A@A@A@....@A and C whatever quantity. So I want a rule that will do this symbolically

A@X---->-A@X

A@A@X----->+A@A@X

D1@X----->((-1)^n)*D1@X where n = number of operators A included in D1.

Specific realization I really want the (Delayed) rule to be of the form

D1_@X_/;(True):>Power[-1,Length@Position[D1,A]]*D1@X


where Length@Position[D1,A]] just counts how many times A is applied on X and (True) is for any Condition that will always be true for our examples.

Problem of the above realization

Try as input

A@A@X
% /. D1_@X_ /; (True) :> (D1@X)*((-1)^(Length[Position[D1, A]]))


this gives as output

-A[A[X]]


which is obviously wrong since we have only 2 instances of A applied on X and it should give +A[A[X]].

Source of the problem I guess the problem lies in how the variables are "hidden" into functions in the right-hand-side of the rule. I tried

FAILED EXAMPLE:

A@A@X
% /. D1_@X1_ /; (True) :> (Length[Position[D1, A]])


this gives as output 1 which should be 2.

Corrected EXAMPLE:

A@A@X
% /. D1_@X /; (True) :> D1 // Position[#, A] & // Length


which gives as an output 2, the correct result.

QUESTIONS/RECAP

1)Is there a way of fixing Power[-1,Length@Position[D1,A]] in the right-hand-side in order to actually work? Even Power[-1,D1 // Position[#, A] & // Length] does not work as per Corrected EXAMPLE.

2)Could someone explain what exactly is going on? There must be some general idea of how you can include complicated operations on the right-hand-side of a (delayed) rule that actually work and get evaluated correctly.

3)Alternative (as general as possible) approaches to the problem are welcome.

• Something like a[a[x]] /. c_. (f : a[arg_]) :> c (-1)^(Depth[f] - 1) f? – J. M.'s discontentment Nov 19 '19 at 11:56
• This is close, but I really need to have explicit X in the rule because I will impose conditions on it. Like D1_@X_ /; (Condition on X(TRUE)) :> (D1@X)*((-1)^(Length[Position[D1, A]])) – Viktor Gakis Nov 19 '19 at 12:14
• Well, I gave enough for you to start with, namely that you should look into Depth[] and not Length[]. – J. M.'s discontentment Nov 19 '19 at 12:17