# 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
– MaxB
May 20, 2020 at 12:40
• Slightly shorter even: You can use {Boole[MatchQ[Head[x], Plus|Times]]} for the level specification Oct 22, 2022 at 22:28

Try

F[X_] := (Cases[{X /. G[a_] :> G[a]^p}, G[x_]^m0_. -> {x, m0},
Infinity] /. p :> 1 )[[2 ;; ;; 2]]


Then

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


give

{{a, 3}}
{{a, 4}, {b, 3}}
{{a, 4}, {b, 3}, {c, 7}}
{{a, 1}, {b, 3}, {c, 7}}


I think the problem is caused by the Head of X when there is only one element.

Updated

Now the function is

F[X_] := ({{something}, {something2}}~Join~
Cases[{X /. {G[a_] :> G[a]^tempVar,
G[b_]^b_ :> G[b]^tempVar2[b]}}, G[x_]^m0_. :> {x, m0},
Infinity] /. {tempVar :>  1, tempVar2[c_] :> c})[[2 ;; ;;
2]] /. {{something} :> Nothing, {something2} :> Nothing}


(For test F[G[a] G[b]^3 G[c]^c + Log[G[g]] + G[c]^7 - G[ap]^p] gives {{ap, 1}, {c, 7}, {a, 1}, {b, 3}, {c, c}, {g, 1}}`)

• Comments are not for extended discussion; this conversation has been moved to chat.
– Kuba
Oct 24, 2022 at 7:08