This is essentially a follow-up to the question/answer here: How to define a differential operator?

Suppose I wish to define an operator DiffOp, e.g.,

DiffOp[t_]:=D[#,t]+4t D[#,{t,2}]&;

but in such a way that the function can read in the argument without having to state it explicitly. Can this be done? If so, how?

In code, what I'd like (using the example above) is a definition that would give


(* f'[x]+4x f''[x] *)



(* 10x+Cos[x]-4x Sin[x] *)

Note that I'm not explicitly calling the function as DiffOp[x][...].


Edit: I changed the example expression to be more complicated to test.


2 Answers 2


This works:

diffOp[a_] := Module[{sym},
  sym = DeleteDuplicates@Cases[a, _Symbol, Infinity];
   Length@sym == 1,
   Return[D[a, First@sym] + 4 First@sym D[a, {First@sym, 2}]]


diffOp[y^2 + Sin[y]]

2 y + Cos[y] + 4 y (2 - Sin[y])


Perhaps you can use the undocumented internal function Reduce`FreeVariables to determine the free variables:

DiffOp[expr_] := Replace[Reduce`FreeVariables[expr],
    {} -> expr,
    {x_} :> D[expr, x],
    x_List :> D[expr, {x}]

A couple examples:

DiffOp[x^2+Sin[Subscript[y, 1]]^2]

2 x + Cos[x]

{2 x, 2 Cos[Subscript[y, 1]] Sin[Subscript[y, 1]]}

The latter example shows that Reduce`FreeVariables thinks that subscripted variables can be free variables as well as just ordinary symbols.

  • $\begingroup$ What exactly does Reduce`FreeVariables do? I seem to be getting drastically different results for these two similar expressions: Reduce`FreeVariables[ f[g[d[rho]],g[d[s[rho, m, n]]]]*(-x[0,a^2,u,v,m]-2*a*x[1,a^2,u,v,m])] versus Reduce`FreeVariables[ f[g[d[rho]],g[d[s[rho, m, n]]]]*(-x[0,a^2,u,v,m]-2*x[1,a^2,u,v,m])]. $\endgroup$
    – QuantumDot
    Jan 1, 2020 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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