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

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

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

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

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

   ---> 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:

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

For the same test as before I got

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

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?


If you want to check that one expression is free of another, I would use

d /: d[arg_, var_] := 0 /; FreeQ[arg, var]
  • $\begingroup$ Thank you very much, this seems to do the trick. Would you have a feeling why my previous attempt was failing? $\endgroup$
    – jibe
    Oct 31 '19 at 8:00
  • $\begingroup$ 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. $\endgroup$
    – mikado
    Oct 31 '19 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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