3
$\begingroup$

I came across this case:

expr = {x, Cos[Exp[x]], x^a}

Cases[expr, Power[__], -1]
(*{x,E,x,E^x,Cos[E^x],x,a,x^a}*)

Level[expr, -1]
(*{x,E,x,E^x,Cos[E^x],x,a,x^a}*)

What is going on here? Why Power[__] (or Power[_] ) Works like Level?

Thanks

$\endgroup$

2 Answers 2

5
$\begingroup$

Very simply Power[__] evaluates to __ and __ matches any expression:

expr = {x, Cos[Exp[x]], x^a};

Power[__]

Cases[expr, __, -1]
__

{x, E, x, E^x, Cos[E^x], x, a, x^a}
$\endgroup$
2
  • $\begingroup$ Hmm, Indeed very simply. Although I have came across such thing in the past and all I need to do to check is use Trace, I have missed that. Thinking of finding something new blinded me to realize the reality. what a shame ! I think I need to reconsider my ability in MMA :( $\endgroup$ Commented Dec 20, 2014 at 14:29
  • 1
    $\begingroup$ @Algohi We all get surprises from Mathematica. It's just a matter of having a good set of diagnostic methods to determine the reason for the behavior. $\endgroup$
    – Mr.Wizard
    Commented Dec 20, 2014 at 17:00
3
$\begingroup$

_^_ instead of Power[__] may give you the result you desire. The issue is that all expressions strictly match themselves to the first power!

MatchQ[x, Power[__]]

True

MatchQ[x, Power[_, 1]]

True

MatchQ[x, _^_]

False

Considering you example...

 expr = {x, Cos[Exp[x]], x^a}

 Cases[expr, _^_, -1] // InputForm

{E^x, x^a}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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