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, ...}?

  • $\begingroup$ Since List is a function, a pattern that matches all functions must match List. If you want to exclude certain functions, such as List from matching, look at Except. $\endgroup$ – m_goldberg Jun 2 '15 at 11:30
  • $\begingroup$ Maybe Cases[Sin[x] Cos[x], _@_, {0, Infinity}] for single-argument functions? $\endgroup$ – kglr Jun 2 '15 at 11:32
  • 1
    $\begingroup$ There's no general way to tell what is a function in Mathematica. $\endgroup$ – Szabolcs Jun 2 '15 at 11:32
  • $\begingroup$ @m_goldberg So this is a silly question. I must define what function I want to match or what I do not want to match, before I can match them. $\endgroup$ – Kattern Jun 2 '15 at 11:34
  • 1
    $\begingroup$ There is really no way of doing what you want without formulating a definition of what heads are to classified as 'functions` or what heads are to be excluded. The second may be easier, which is why I recommended looking at Exclude. $\endgroup$ – m_goldberg Jun 2 '15 at 11:44
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} *)


Sqrt[x] // FullForm
(* Power[x,Rational[1,2]] *)

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.