# A problem with Cases and Pattern recognition: unexpected behavior

I need the following command (to isolate exponents and variables):

F[X_] := Cases[ X , G[x_]^m0_. -> {x, m0}]


This example gives the correct answer:

In:= F[G[a]^4 G[b]^3]

Out:= {{a, 4}, {b, 3}}


Good. But this second example

In:= F[G[a]^3]

Out:= {{a, 1}}


is incorrect! Curiously

In:= F[2 G[a]^3]

Out:= {{a, 3}}


is correct! What is going on? I can see that the Heads of the first and third cases are the same (Times) while the second is different (Power). But, how can I get Mathematica to deliver the right output in the second case?

• Your first and third cases work only because the expressions inside F[] have head Times[]. For the second, you need something like Cases[G[a]^3, G[x_]^m0_. :> {x, m0}, {0}]. May 20, 2020 at 5:31

This is an idiosyncrasy of Cases I always found annoying. You could, until a better solution comes along, do this

Clear["Global*"];
Cases[X, G[x_]^m0_. :> {x, m0}],
Cases[{X}, G[x_]^m0_. :> {x, m0}]
]


Alternative way to do the above is as suggested by JM in the comment below, is to change the level spec, either {0} or {1}, based on the head

F[X_] := Cases[X, G[x_]^m0_. :> {x, m0},
If[MatchQ[Head[X], Plus | Times], {1}, {0}]]


Both these definitions achieve the same thing:

And now

 F[G[a]^4*G[b]^3]


 F[G[a]^3]


 F[2 G[a]^3]


   F[G[a]^4 + G[b]^3]


If you want to keep your original function instead, then you'd have to change F[G[a]^3] to F[{G[a]^3}] and then it will work. But the above definition does it automatically inside.

• An equivalent formulation: Cases[X, G[x_]^m0_. :> {x, m0}, If[MatchQ[Head[X], Plus | Times], {1}, {0}]]`. May 20, 2020 at 6:10
• @J.M. thanks. This is good way to do it. May 20, 2020 at 6:15