2
$\begingroup$

I'm trying to understand how Cases work in Mathematica, and I'm a bit curios why i't wont pick up the Sqrt function?

Consider the following expressions

Cases[Erfc[b], _Erfc, Infinity]
Cases[a*Erfc[b], _Erfc, Infinity]
Cases[a*Sqrt[b], _Sqrt, Infinity]
Cases[a*Sqrt[b], _Sqrt, Infinity]
Cases[a*Sqrt[a]*Erfc[b], _Erfc, Infinity]
Cases[a*Sqrt[a]*Erfc[b], _Sqrt, Infinity]

they give respectively

{}
{Erfc[b]}
{}
{}
{Erfc[b]}
{}

Why does Cases fail in the cases that give {}?

$\endgroup$
3

3 Answers 3

5
$\begingroup$

In the first case:

Cases[Erfc[b], _Erfc, Infinity]

"Infinity" means: {1,Infinity}. But Erfc[b] is at level 0. Therefore, you need:

Cases[Erfc[b], _Erfc, {0,Infinity}]

Further, the next problem:

Cases[a*Sqrt[b], _Sqrt, Infinity]

The full form of Sqrt[b] is Power[..] (You may use "FullForm" to see the full form). Therefore, you need:

Cases[a*Sqrt[b], _Power,  Infinity]

To get:

{Sqrt[b]}

Then the case of:

Cases[a*Sqrt[a]*Erfc[b], _Sqrt, Infinity]

Because arguments are evaluated before sending them to functions, a*Sqrt[a] is simplified to a^(3/2) and by:

Cases[a*Sqrt[a]*Erfc[b], _Power, Infinity]

you get:

{a^(3/2)}
$\endgroup$
4
$\begingroup$

Check FullForm, arg of Cases is evaluated before matching:

FullForm[a*Sqrt[b]]
Cases[HoldForm[a*Sqrt[b]], _Sqrt, Infinity]

MatchQ[f[x], f[x]]
Symbol === Head[f]
Cases[f[x], _f, Infinity]
Cases[{f[x]}, _f, Infinity]
$\endgroup$
3
  • $\begingroup$ Does this also explain why Cases[Erfc[b], _Erfc, Infinity] gives {}? $\endgroup$ Commented Apr 30, 2021 at 13:31
  • $\begingroup$ @MikaelFremling, no, this seems to be related to expression Head being a symbol, see the edit, not sure why $\endgroup$
    – I.M.
    Commented Apr 30, 2021 at 15:31
  • 2
    $\begingroup$ @MikaelFremling Try Cases[Erfc[b], _Erfc, {0, Infinity}]. The level spec Infinity is equivalent to {1, Infinity}. $\endgroup$
    – Michael E2
    Commented Apr 30, 2021 at 16:46
3
$\begingroup$

Try HoldForm

Cases[HoldForm[ Erfc[b]], _Erfc, Infinity]
Cases[HoldForm[ a*Erfc[b]], _Erfc, Infinity]
Cases[HoldForm[ a*Sqrt[b]], _Sqrt, Infinity]
Cases[HoldForm[ a*Sqrt[b]], _Sqrt, Infinity]
Cases[HoldForm[ a*Sqrt[a]*Erfc[b]], _Erfc, Infinity]
Cases[HoldForm[ a*Sqrt[a]*Erfc[b]], _Sqrt, Infinity]

enter image description here

$\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.