# How to define custom differential operator using the arguments of the expression?

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

DiffOp[f[x]]

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


and

DiffOp[x^2+Sin[x]]

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


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

Thanks!

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

This works:

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


then

diffOp[y^2 + Sin[y]]


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

Perhaps you can use the undocumented internal function ReduceFreeVariables to determine the free variables:

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


A couple examples:

DiffOp[x^2+Sin[x]]
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 ReduceFreeVariables` thinks that subscripted variables can be free variables as well as just ordinary symbols.