2

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 {}?

  • 5
    See FullForm[Sqrt[x]]. It returns Power[x, Rational[1, 2]] which corresponds to x^(1/2), and either you have to prevent evaluation or match this form. – kirma Apr 30 '21 at 12:14
  • 1
    Related: https://mathematica.stackexchange.com/a/29219, https://mathematica.stackexchange.com/q/114685 – Michael E2 Apr 30 '21 at 16:30
  • Also: https://mathematica.stackexchange.com/q/221369, https://mathematica.stackexchange.com/q/22948 – Michael E2 Apr 30 '21 at 16:41

3 Answers3

5

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)}
Daniel Huber
  • 51,463
  • 1
  • 23
  • 57
4

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]

I.M.
  • 2,926
  • 1
  • 13
  • 18
3

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

AsukaMinato
  • 9,758
  • 1
  • 14
  • 40