# How to create an operator which is a composition of a sequence of operators?

Suppose I have a sequence of operators $$\partial_x$$, $$\partial_x^2$$,..., $$\partial_x^n$$. I want to define an operator which is a composition of these $$D_x^{(n)}=\partial_x\circ\partial_x^2\circ\cdot\cdot\cdot\circ \partial_x^n$$

Something like Diffn[f,x,n].

The $$D_x^{(n)}$$ should take a function, a variable x (differentiation with respect to x) and n.

The operator which I want is a bit more complicated but it will be just an extension of this. I tried

Apply[Composition, Array[Sin &, n]][x]


It is based on an example on the mathematica website where one may put sin function and it gives a composition of n such functions, but I am a bit confused how to use derivative operator here and put an index for the order of the derivative. (since operators and functions are mathematically different entities)

There is another example on the mathematica website for the derivatives but I can't specify the order of differentiation by an index.

(* get our operators like this: *)
n=3;
operators = Array[Function[{y}, D[y, {x, #}]] &, n]

(** returns: {Function[{y}, D[y, {x, 1}]], Function[{y}, D[y, {x, 2}]], Function[{y}, D[y, {x, 3}]]} **)

(* Apply composition to put them together *)
composed = Composition@@operators;

(* try it out: *)
composed[x^6]
(* 720 *)

(* verify it matches this handwritten form *)
D[D[D[x^6, {x, 3}], {x, 2}], {x, 1}]

• In case it isn't clear, # the index filled from the Array. This is easier than using Table as there's some kind of Hold-ing going on and the table index doesn't evaluate how you'd expect. Jul 7, 2021 at 15:26

As an alternative you could use Fold

Diffn1[f_, x_Symbol, n_Integer?Positive] :=
Fold[D[#1, {x, #2}] &, f, Range[n, 1, -1]]

Diffn1[f[x], x, 3]

(* Derivative[f][x] *)


Or it can be simplified as

Diffn2[f_, x_Symbol, n_Integer?Positive] := D[f, {x, n (n + 1)/2}]


These are equivalent

And @@ Table[Diffn1[f[x], x, n] == Diffn2[f[x], x, n],
{n, 1, 20}]

(* True *)