# Pattern matching not going over a list when using default values

if I execute the following command in Mathematica:

{a,a^2,a^3}/.a^(n_:1)->b^(2 n)


Mathematica returns:

{b^2,b^4,b^6}


but if I enter:

{a,a^2,a^3}/.a_^(n_:1)->b^(2 n)


Mathematica only returns:

b^2


Without the default value for n, Mathematica returns in both instances (a & a_):

{a,b^4,b^6}


Could someone explain why the different behavior?

-

First try looking at:

 {a, a^12, a^13} /. a_^(n_: 1) -> b^(2 n)


b^2

You'll notice that it's not the case that it's just returning just one of the elements. What is' doing is actually replacing the whole list. This happens because anything is equal to itself to the power of 1.

 MatchQ[{4, Plot, Sin}, a_^(n_: 1)]

True


So what happens is that when you use a blank pattern _ you can match anything, and the first thing encountered is the entire list. For this particular case you can solve this by making sure you are only matching symbols and not expressions, and by checking that you aren't replacing your head of List:

 {a, a^12, a^13} /. (a_Symbol /; a =!= List)^(n_: 1) -> b^(2 n)

-
I beat you by a hair. +1 for providing an alternative. Another is: {a, a^2, a^3} /. a : Except[List | _List]^(n_: 1) :> b^(2 n) – Mr.Wizard Jan 9 '13 at 10:42

Your problem is simply that your entire left hand expression matches the pattern:

MatchQ[{a, a^2, a^3}, a_^(n_: 1)]

True


You can avoid this match is a variety of ways such as more restrictive patterns but perhaps the best is a level restriction. (We can use the _. form of Optional because the effective default is already 1.)

Replace[
{a, a^2, a^3},
a_^n_. :> b^(2 n),
1
]

{b^2, b^4, b^6}


Equivalently:

# /. a_^n_. :> b^(2 n) & /@ {a, a^2, a^3}

{b^2, b^4, b^6}


Notice that in all cases I changed -> to :>; the latter (RuleDelayed) should be used to correctly localize n.

-