4
$\begingroup$

Suppose I have a list of elements

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

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

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

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

$\endgroup$
5
$\begingroup$
pattern1 = _?({G[1]} == Level[#, {-2}]&);
MatchQ[pattern1]  /@ list

{True, False, True}

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

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

and define a pattern using peel:

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

{True, False, True}

An alternative way to use peel:

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

{True, False, True}

$\endgroup$
  • $\begingroup$ 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[1] and G[4] or with G[100]. So.. for any value of the argument. $\endgroup$ – apt45 Jul 10 at 10:28
  • $\begingroup$ @apt45, does it work if you change the definition of peel and pattern2 as peel = # //. _ @ G[_] -> G[_] &; pattern2 = _?(G[_] == peel[#] &);? $\endgroup$ – kglr Jul 10 at 19:16

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.