0
$\begingroup$

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?

$\endgroup$
1
  • 1
    $\begingroup$ 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}]. $\endgroup$ May 20, 2020 at 5:31

1 Answer 1

1
$\begingroup$

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

Clear["Global`*"];
F[X_] := If[Head@X === Times || Head@X === Plus, 
             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]

Mathematica graphics

 F[G[a]^3]

Mathematica graphics

 F[2 G[a]^3]

Mathematica graphics

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

Mathematica graphics

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.

$\endgroup$
3
  • 1
    $\begingroup$ An equivalent formulation: Cases[X, G[x_]^m0_. :> {x, m0}, If[MatchQ[Head[X], Plus | Times], {1}, {0}]]. $\endgroup$ May 20, 2020 at 6:10
  • $\begingroup$ @J.M. thanks. This is good way to do it. $\endgroup$
    – Nasser
    May 20, 2020 at 6:15
  • $\begingroup$ Thank you ! Very useful comments (and I am glad my question made sense) $\endgroup$
    – MaxB
    May 20, 2020 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.