# Custom substitution in a polynomial

I'm a beginner with Mathematica, hope this is an interesting question.

Basically I would like to write a function that takes a 3-variable polynomial as input and linearly maps it in an another expression based on the degrees of each monomial.

I give you an example. Suppose I've a function:

f[a_,b_,c_] = some expression depending on a,b,c


Now I want to define a Mathematica function $$g$$ such that:

$$g(\alpha x^ay^bz^c + \beta x^dy^ez^f) = \alpha f(a,b,c) + \beta f(d,e,f)$$

Some practical example:

$$g(xy+yx+z) = 2f(1,1,0) + f(0,0,1)$$

$$g(xz^3y^2 + xyxz^2) = f(1,2,3) + f(2,1,2)$$

I have no idea how to do such a thing. I was thinking to use the /. operator, but I've realised soon that is not the correct instrument since I'm not able to make it work in general.

I appreciate also a reference from where I can extract the answer, if replying is too complicated. Thanks in advance!

• Something like Total[KeyValueMap[#2 Apply[f, #1] &, Association @ CoefficientRules[x y^2 z^3 + x y x z^2]]]? Commented Jun 8, 2022 at 16:48

You need to use Replace rather than ReplaceAll (aka /.), which allows you finer control. Here's what I came up with:

expr = 2 x z^3 y^2 + x y x z^2
Total[Replace[CoefficientRules[expr, {x, y, z}], {Rule -> Times, List -> f}, {2, 3}, Heads -> True]]


Step by step:

• CoefficientRules[expr, {x, y, z}] returns {{2, 1, 2} -> 1, {1, 2, 3} -> 2}, or (if we apply FullForm)

List[Rule[List[2,1,2],1],Rule[List[1,2,3],2]]

• If we can replace the innermost Lists with fs and the Rules with multiplication, then we've got what we want. This is what the Replace command does: replace {Rule -> Times, List -> f}, but only at levels {2,3}, and allow Mathematica to replace the Heads of expressions. This yields

List[f[2,1,2],Times[2,f[1,2,3]]]

• Finally, Total adds up all the elements of this list, yielding

2 f[1, 2, 3] + f[2, 1, 2]

• Best answer I could ever get! It works and there is a detailed explanation of why
– L.A.
Commented Jun 9, 2022 at 7:31