# Pattern of nested functions

Suppose I have a list of elements

list = {f[b[G]],f[b],k[k[k[G]]]}


What is the pattern associated to an expression in which the function G appears at the last level of nested functions? For example, I want a pattern such that

MatchQ[list[],pattern] (*Returns: True*)
MatchQ[list[],pattern] (*Returns: False*)
MatchQ[list[],pattern] (*Returns: True*)


In general, this pattern should match an arbitrary expression of nested functions, e.g. a@b@c@d@e@f@G.

pattern1 = _?({G} == Level[#, {-2}]&);
MatchQ[pattern1]  /@ list


{True, False, True}

Alternatively, define a helper function (peel) that strips off heads around G:

peel = # //. _ @ G -> G &;


and define a pattern using peel:

pattern2 = _?(G == peel[#] &);
MatchQ[pattern2]  /@ list


{True, False, True}

An alternative way to use peel:

MatchQ[peel @ #, G]& /@ list


{True, False, True}

• What if you want extend the above method for general argument's value of G? For example, i want to get the same result for G and G or with G. So.. for any value of the argument. Jul 10, 2019 at 10:28
• @apt45, does it work if you change the definition of peel and pattern2 as peel = # //. _ @ G[_] -> G[_] &; pattern2 = _?(G[_] == peel[#] &);?
– kglr
Jul 10, 2019 at 19:16