# How to write a pattern that matches all functions

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

• 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. Jun 2, 2015 at 11:30
• Maybe Cases[Sin[x] Cos[x], _@_, {0, Infinity}] for single-argument functions?
– kglr
Jun 2, 2015 at 11:32
• There's no general way to tell what is a function in Mathematica. Jun 2, 2015 at 11:32
• @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. Jun 2, 2015 at 11:34
• 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. Jun 2, 2015 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} *)


because

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