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=C*A@A@A@....@A and C whatever quantity. So I want a rule that will do this symbolically
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
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
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
A@A@X % /. D1_@X1_ /; (True) :> (Length[Position[D1, A]])
this gives as output 1 which should be 2.
A@A@X % /. D1_@X /; (True) :> D1 // Position[#, A] & // Length
which gives as an output 2, the correct result.
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.