4

I am having some difficulties with the ReplaceAll function. When I write:

{1, 2, 3, 4, 5} /. x_?OddQ -> x^2

I expect:

{1,2,9,4,25}

But if I write:

x = 1;
{1, 2, 3, 4, 5} /. x_?OddQ -> x^2

I have:

{1,2,1,4,1}

How can I avoid this? I mean, even using:

x = 1;
Module[{x},{1, 2, 3, 4, 5} /. x_?OddQ -> x^2]

The output still:

{1,2,1,4,1}

Thanks in advance!

Edit: Thanks again! I never quite understood this RuleDelayed.

Kuba
  • 136,707
  • 13
  • 279
  • 740
Pedro
  • 129
  • 1
  • 3

1 Answers1

7

Just use :> (that is RuleDelayed) instead of -> (Rule). Indeed, the Rule will evaluate the right-hand side of the rule immediately, that means it will use the x = 1 value before to define the rule itself. On the other hand, RuleDelayed will evaluate the right-hand side only after the rule itself is created and then the x is that inside the rule and not the Global one.

x = 1;
{1, 2, 3, 4, 5} /. x_?OddQ :> x^2
{1, 2, 9, 4, 25}
Kuba
  • 136,707
  • 13
  • 279
  • 740
bobknight
  • 2,037
  • 1
  • 13
  • 15