6
$\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$

3 Answers 3

6
$\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$
2
  • $\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
    Commented Jul 10, 2019 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
    Commented Jul 10, 2019 at 19:16
0
$\begingroup$

An alternative way to do this using FoldList:

f = First @@ (Rest@FoldList[Level[#1, {#2}] &, {#}, {Depth[#] - 1}]) &;

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

{True, False, True}

$\endgroup$
0
$\begingroup$

Use FixedPoint is also a choice.

{f[b[G[1]]],f[b[1]],k[k[k[G[1]]]]} //
Map[FixedPoint[Function[expr, expr /. x_[y_[z_]] -> y[z]], #]&] //
Map[# === G[1] &]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.