# Encode expression into a list

I have an expression of the form:

$$c {\partial^{k+l} \Phi(\theta,\phi,n) \over \partial \theta^k \partial \phi^l}$$

$$n,k,l$$ are (positive) integers. $$c$$ is some constant. It is also possible that $$c$$ appears by itself. I would like a function, myExprToList that takes such an expression as input and outputs in an array: {c,k,l,n}, or just {c} if the constant is by itself.

As an example, suppose I have the two expressions:

expr1 = 42 D[D[\[CapitalPhi][\[Theta], \[Phi], 10], {\[Theta], 2}], {\[Phi], 3}]
expr2 = -1


I would then want respectively:

 myExprToList[expr1] (* Out: {42,2,3,10} *)
myExprToList[expr2] (* Out: {-1} *)


My first instinct was to use the function PolynomialRemainder, but since the $$k,l,n$$ are a prior unknown, I would need to use patterns and I am not sure how this would work.

This seems to work, also for c=1 :

myExprToList[
c_.  Derivative[k_, l_, _][_][_, _, n_]
]:= {c, k, l, n};
myExprToList[c_. ] := {c};

• Pretty good. It fails however if $c=1$ or if the function is undifferentiated. Dec 8, 2021 at 10:38
• There will also need to be a case needed for when the function appears undifferentiated Jan 24 at 14:04

You can do this using a pattern:

pat=c_ D[D[\[CapitalPhi][\[Theta], \[Phi], n_ : 0], {\[Theta],
l_ : 0}], {\[Phi], k_ : 0}] -> {c, k, l, n}


Then the examples:

expr1 = 42 D[D[\[CapitalPhi][\[Theta], \[Phi], 10], {\[Theta], 2}], {\[Phi], 3}];
expr2 = -1;

expr1 /. pat
(*{42, 3, 2, 10}*)

expr2 /. pat
(* -1 *)

• This does not work if c=1 or if the function appears undifferentiated. Jan 24 at 14:06
• To make it work for c=1 give a default value to c: c_:1 Jan 24 at 16:28
ClearAll[exprToList]

exprToList[expr_, headparts_: {1, 2}, argparts_: {3}] :=
expr /. a_. Derivative[b__][_][c__] :> Flatten[{a, {b}[[headparts]], {c}[[argparts]]}]


Examples:

expr1 = 42 D[D[Φ[θ, ϕ, 10], {θ, 2}], {ϕ, 3}] Extract parameters {1, 2} from the operator head and part {3} from the arguments (default):

exprToList @ expr1

{42, 2, 3, 10}


Extract parameters {1, 3} from the operator head and parts {1, 2, 3} from the arguments:

exprToList[expr1, {1, 3}, All]

{42, 2, 0, θ, ϕ, 10}

expr2 = D[D[Φ[θ, ϕ, 10], {θ, 2}], {ϕ, 3}] exprToList @ expr2

{1, 2, 3, 10}

expr3 = 500 Derivative[3, 1, 2, 2, 1][Φ][θ, ϕ, ψ, λ, ρ] exprToList[expr3, All, All]

{500, 3, 1, 2, 2, 1, θ, ϕ, ψ, λ, ρ}

expr4 = -1

exprToList @ expr4

-1

• Does not work if function is undifferentiated Jan 24 at 14:07