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!

  • $\begingroup$ 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)$ ? $\endgroup$
    – flinty
    Dec 5, 2020 at 14:05
  • $\begingroup$ @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. $\endgroup$
    – apt45
    Dec 5, 2020 at 14:18
  • $\begingroup$ Slightly better than deleting I think is just to divide out an element. In[468]:= cd[a_][ee_Times] := Total[Table[cd[a][ee[[j]]]*ee/ee[[j]], {j, Length[ee]}]] In[469]:= cd[a][I p G[x]] Out[469]= p G[x] cd[a][I] + I G[x] cd[a][p] + I p cd[a][G[x]] $\endgroup$ Dec 5, 2020 at 15:22

1 Answer 1


A recursive definition could work:

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

(*    G[x]*Cd[a][p] + p*Cd[a][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 + u Cd[a][1/v]    *)

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.