A rule for $x^0$ will never be applied if x^_
is not there in the original equation.
(Note: You can do this for $x^1$: 4 - 3 x + 2 x^2 - x^5 /. {x^p_ :> f@p, Power@x -> f@1}
, cf. OneIdentity
attribute that is assigned to Power
.)
CoefficientList
will probably be the best choice for you:
In[1]:= With[{c = CoefficientList[#, x]}
, c.(f /@ (Range@Length@c - 1)) ]&[4 - 3 x + 2 x^2 - x^5]
Out[1]= 4 f[0] - 3 f[1] + 2 f[2] - f[5]
However, you can always define your own structures. For example, you could introduce power
that never evaluates. To make it printed the way the original is printed, you can do the following:
In[2]:= MakeBoxes[power[x_, p_], tag_] ^:=
With[{boxes = MakeBoxes[Power[x, p], tag]}
, InterpretationBox[boxes, power[x, p]]]
Now you can have a transformer for polynomials [of one variable]
In[3]:= toLazyPowers[poly_, x_] /; PolynomialQ[poly, x] :=
With[{c = CoefficientList[poly, x]}
, c.(power[x, #] & /@ (Range@Length@c - 1))]
that returns expressions with explicit “powers”, only those powers don't have any definitions associated with them:
In[4]:= toLazyPowers[4 - 3 x + 2 x^2 - x^5, x]
Out[4]= 4 x^0 - 3 x^1 + 2 x^2 - x^5
Then you will be able to perform replacements with $x^0$:
In[5]:= toLazyPowers[4 x^0 - 3 x^1 + 2 x^2 - x^5, x] /. power[x, p_] :> f@p
Out[5]= 4 f[0] - 3 f[1] + 2 f[2] - f[5]
To go back, replace your power
with original Power
:
In[6]:= Out@4 /. power -> Power
Out[6]= 4 - 3 x + 2 x^2 - x^5
which can be formalised, e.g., this way:
In[7]:= toEagerPowers@expr_ := expr /. power -> Power
Note: Sure, you can enrich power
with definitions like
power[power[expr_, n_Integer], m_Integer] := power[expr, n m]
but prior to doing that, it's better to ask yourself what exactly you need this symbol for. In the example above it's actually used for printing polynomials, and not much for anything else. For “regular representations” of polynomials in terms of Mathematica's data structures you don't need powers at all; coefficients lists, maybe combined with a custom head, would do.
1 + x + x^2 + x^4 /. x^p_. :> f[p]
notice thep_.
pattern. This now returns1 + f[1] + f[2] + f[4]
see reference.wolfram.com/mathematica/guide/Patterns.html $\endgroup$Replace
for 1. $\endgroup$z^4 + z^2 + 4 /. z^(a_Integer) -> x^(1/2 a)
and use1 + z + z^2 /. z^(a_Integer) -> f[a]
, you can see it doesn't work for 1 and z, and that is exactly where my question is. $\endgroup$