# Define a derivative-like function

I would like to define a function Cd[a_][expr_] which takes an arbitrary argument a and acts on the expression expr by following a chain rule, in a way that resembles derivatives.

Let's consider two examples.

If expr = p G[x], for some constant p, I would like to get Cd[a][expr] = Cd[a][p] G[x]+p Cd[a][G[x]]

If expr = I p G[x], for some constant p, I would like to get Cd[a][expr] = Cd[a][I] p G[x]+I Cd[a][p] G[x]+I p Cd[a][G[x]]

One possible definition of this function is

Cd[a_][expr_?((Head[#] == Times) &)] := Module[{listexpr}, listexpr = List @@ expr;
Table[Cd[a][listexpr[[i]]] Times @@ DeleteCases[listexpr, listexpr[[i]]],
{i, 1,Length[listexpr]}] // Total // Return]
Cd[a_][b_?NumberQ] = 0;


However, I wonder whether this definition can be simplified. Any suggestion? Thanks!

• I don't really follow your examples. Also I is reserved for the imaginary constant $\sqrt{-1}$. Do you simply mean you want to define an operator $X$ such that $X[f\circ g](x)=X[f](g(x))\times X[g](x)$ ? Dec 5, 2020 at 14:05
• @flinty I know that I is reserved for the imaginary constant, I don't want to modify its definition. I just took two examples where I have one or two constants. Yes, I want to define an operator as you said. Dec 5, 2020 at 14:18
• Slightly better than deleting I think is just to divide out an element. In:= cd[a_][ee_Times] := Total[Table[cd[a][ee[[j]]]*ee/ee[[j]], {j, Length[ee]}]] In:= cd[a][I p G[x]] Out= p G[x] cd[a][I] + I G[x] cd[a][p] + I p cd[a][G[x]] Dec 5, 2020 at 15:22

A recursive definition could work:

Cd[a_][u_*v_] := Cd[a][u]*v + u*Cd[a][v]

Cd[a][p*G[x]]
(*    G[x]*Cd[a][p] + p*Cd[a][G[x]]    *)

Cd[a][I*p*G[x]]
(*    p*G[x]*Cd[a][I] + I*(G[x]*Cd[a][p] + p*Cd[a][G[x]])    *)


Keep in mind that ratios of the form u/v == Times[u, 1/v] also have the head Times:

Cd[a][u/v]
(*    Cd[a][u]/v + u Cd[a][1/v]    *)