# How to define action of derivative (D) on a user-defined operator f

I have a symbolic function (which is in fact an operator) f[expr, x] where the second argument is a local variable for f (kind of like how Integrate[expr, x] is set up).

How do I make analysis functions like D act on f[expr, x] similar to how D acts on Inactive[Integrate]:

D[Inactive[Integrate][Sin[p x^2], x], p]

Inactive[Integrate][x^2 Cos[p x^2], x]

D[f[Sin[p x^2], x], p]

x^2 Cos[p x^2] Derivative[1, 0][f][Sin[p x^2], x] (*Wrong*)


This output is wrong because x^2 Cos[p x^2] has incorrectly been pulled out of f.

Edit: It should work if f appears arbitrarily deep inside expr. Another test case that needs to work:

D[a * f[Sin[p x^2], x], p]


with the desired result:

a*f[x^2*Cos[p*x^2], x] (*Desired*)

• You can overload D on f with e.g. f /: D[_f, x_] := someOperation[f, x] -- do you mean something else? – Mr.Wizard Jun 17 '16 at 15:14
• I should have written f /: D[body_f, x_] := someOperation[body, x] – Mr.Wizard Jun 17 '16 at 15:24

I think this is good case for TagSetDelayed. Rather than redefining D, you associate f with the desired upvalue.

f /: D[f[exp_, x_], p_] := f[D[exp, p], x]

D[f[Sin[p x^2], x], p]
(* f[x^2 Cos[p x^2], x] *)

• This is nice; but if D doesn't directly wrap f, it doesn't seem to work: for example D[a * f[Sin[p x^2], x], p]. Can you suggest a workaround? – QuantumDot Jun 17 '16 at 15:36
• @Quantum, is f supposed to be a linear operator, or not? It should not be too hard to modify chuy's answer to incorporate a linearity property, if so. – J. M.'s ennui Jun 17 '16 at 16:12
• @QuantumDot You can use NonConstants -> {f} option. This will prevent D from using built in chain rule on expressions with head f and result will contain D[f[...], ...], so no matter how deep f is inside differentiated expression its D-overriding UpValues will be used. You'll also need to change p_ to p__, so that D with more than two arguments (including options) will be matched. – jkuczm Jun 17 '16 at 22:08
• @jkuczm NonConstants solved my problem. Please post as answer and I will accept. – QuantumDot Jun 18 '16 at 5:56

Using jkuczm comment together with chuy's answer, I have a satisfactory solution.

Consider the following example expression (f is a symbolic operator introduced in OP's question):

expr = Cos[ f[Sin[p x^2], x] ]

1. When using D, set option NonConstants->{f} to prevent it from operating on f. This works for any expression where f appears arbitrarily deep. (jkuczm)

D[expr, p, NonConstants -> {f}]

(*  -D[f[Sin[p x^2], x], p, NonConstants -> {f}] Sin[f[Sin[p x^2], x]] *)

2. Then, define a rule specifying how D should act on f (chuy):

f /: D[f[exp_, x_], p_, NonConstants -> {f}] :=
f[D[exp, p, NonConstants -> {f}], x]


Now we have:

D[expr, p, NonConstants -> {f}]

(* -f[x^2 Cos[p x^2], x] Sin[f[Sin[p x^2], x]] *)


as desired.