What is the correct way to match a function in an expression in the way that
Cases[Sin[x] Cos[x], _Sin | _Cos, {0, Infinity}]
matches Sin
and Cos
?
How can I match those functions without list all function names? The following code not only matches functions, but also List,
Plus` and so on.
Cases[Sin[x] Cos[x], _?(MatchQ[Head@#, _Symbol] &), Infinity]
Should I express this question as matching a function not in a list such as {List, Plus, Times, ...}
?
Answer
Cases[Sin[x] Cos[x], _@_, {0, Infinity}]
(* {Cos[x], Sin[x]} *)
Cases[Sin[x] Cos[x], h_@_ :> h, {0, Infinity}]
(* {Cos, Sin} *)
Note: watch out for expressions that "look like" functions with a single argument:
Cases[Sqrt[x ] Times[Sin[x], w], h_@_ :> h, {0, Infinity}]
(* {Sin} *)
because
Sqrt[x] // FullForm
(* Power[x,Rational[1,2]] *)
Comments
Post a Comment