# TagSetDelayed for spotting zero derivatives

I am trying to implement my own differential operator, d[arg_, var_], that computes the derivative of arg w.r.t. var. Now, I need to teach' Mathematica about the key properties of that operator. In particular, I want it to remove all derivatives that are obviously zero because arg is independent of var. My attempt is as follows

Clear[d];
d /: d[arg_, var_] := 0 /; (SameQ[D[arg, var], 0]);


At first, this rule seemed to work fine, because I got

d[x,x]
---> d[x,x]
d[x,y]
---> 0


Yet, if I now stack up the derivatives, the rule seems to be incorrectly applied. Indeed, I got

d[d[x+y,x],y]
---> 0


which is incorrect.

To investigate the origin of this strange behaviour, I modified the previous rule to also print its arguments when it is being applied, as such:

Clear[d];
d /: d[arg_, var_] := (Print["| ",arg, " | ", var]; 0) /; (SameQ[D[arg, var], 0]);


For the same test as before I got

d[d[x+y,x],y]
---> | #1 | #2
| d[x+y,x] | y
0


It seems therefore that the rule is being used once with the pure arguments {#1,#2}, which is likely the reason for the bug encountered.

Where does this strange evaluation come from? And how should one fix the TagSetDelayed for the rule to be applied as expected?

d /: d[arg_, var_] := 0 /; FreeQ[arg, var]

• I've had a quick look at Trace[d[d[x + y, x], y]]. I believe that Mathematica tries to derive rules for the derivatives of functions from the definitions you give. In this case, (I think) it looks at your definition of d`, ignores the condition, and concludes that its derivative is zero. Oct 31 '19 at 20:07