5

Why does

{x, x^2, x^3, a, b} /. x^n_ -> f[n]

result in

{x, f[2], f[3], a, b}

when -> is supposed to be evaluated immediately? Shouldn't it produce something like

{x, f[n], f[n], a, b}

with :> (RuleDelayed) producing {x, f[2], f[3], a, b}? Note that :> also gives {x, f[2], f[3], a, b} (as expected).

Excuse the silly question, but I am rather baffled.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
d125q
  • 437
  • 3
  • 9
  • I think that's because n is on both sides of ->, so it's treated like a function. So for x^2, the rules says, make it a function, with 2 as its input. – Chen Stats Yu Jan 03 '15 at 02:02

2 Answers2

8

The use of Rule (->) does cause the right-hand-side to be evaluated but if a pattern Symbol (such as n) remains its left-hand-side match will still be substituted in. Observe what happens when f[n] evaluates to different expressions.

No n present in evaluated form:

f[n] = 7;

{x, x^2, x^3, a, b} /. x^n_ -> f[n]
{x, 7, 7, a, b}

Note that only literal f[n] evaluates to 7; f[2] or f[3] will remain unevaluated.

Multiple instances of n present in evaluated form:

f[z] = n^2 + Sin[n];

{x, x^2, x^3, a, b} /. x^n_ -> f[z]
{x, 4 + Sin[2], 9 + Sin[3], a, b}

Note again that this is not f[n_] := . . .. First f[z] evaluates to n^2 + Sin[n] and then each appearance of n is replaced with the LHS match.

Note also that further evaluation of the RHS is not immediately performed after filling with LHS matches:

Hold[x, x^2, x^3, a, b] /. x^n_ -> f[z]
Hold[x, 2^2 + Sin[2], 3^2 + Sin[3], a, b]

Here 2^2 and 3^2 remain unevaluated due to Hold.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
1

I think that's because n is on both sides of ->, so it's treated like a function. So for x^2, the rules says, make it a function, with 2 as its input.

{x, x^2, x^3, a, b} /. x^n_ -> f[n]

{x, f[2], f[3], a, b}

{x, x^2, x^3, a, b} /. x^n_ :> f[n]

{x, f[2], f[3], a, b}

Now we define the function f[z_]

f[z_] := Sqrt[z] // N

{x, x^2, x^3, a, b} /. x^n_ -> f[n]

{x, Sqrt[2], Sqrt[3], a, b}

{x, x^2, x^3, a, b} /. x^n_ :> f[n]

{x, 1.41421, 1.73205, a, b}

enter image description here

Chen Stats Yu
  • 4,986
  • 2
  • 24
  • 50