A simple problem about a Rule example
Pattern matching is performed based on the form of an expression, not its (mathematical) meaning. Using jargon, pattern matching is performed syntactically, not semantically.
Specifically, here x^1
is evaluated/simplified first to be x
. The latter no longer has the form of "one thing raised to the power of another thing", so it will not be matched when applied the rule afterward.
Consequently, if you want the first one to be matched, you can stop it from evaluation by using Hold
or HoldForm
and ReleaseHold
in the end.
{HoldForm[x^1], x^2, x^3, a, b} /. x^n_ -> f[n] // ReleaseHold
{f[1], f[2], f[3], a, b}
To see the function of ReleaseHold
, evaluate
{HoldForm[x^1], x^2, x^3, a, b} /. x^n_ -> f[n] // InputForm
and you obtain
{HoldForm[f[1]], f[2], f[3], a, b}
You see that HoldForm
is still there, but usually in the OutputForm
it is invisible and ReleaseHold
can remove it.
Another more concise way is to use Default
in the pattern (the dot following the underscore):
{x, x^2, x^3, a, b} /. x^n_. -> f[n]
{f[1], f[2], f[3], a, b}
My recommendation is to look at the FullForm
of the expression and the replacement.
FullForm[{x^1, x^2, x^3, a, b}]
List[x, Power[x,2], Power[x,3], x, b]
and
FullForm[x^n_]
Power[x, Pattern[n, Blank[]]]
This makes it clear that the first element of the list doesn't match the pattern.