I'm looking for the pattern patt[head] that will match any expression expr in which head occurs as a head anywhere within expr. (Ideally, the matching would stop as soon as a matching subexpression is found.)

For example,

Cases[{f, f[0], h[f[e[d[c[a]]]]], p[q[r[f]]], f[2][3][4], x[y[z[0,f[5][6],1,2]]]},

should evaluate to

{f[0], h[f[e[d[c[a]]]]], f[2][3][4], x[y[z[0,f[5][6],1,2]]]}

The answers given to a less general question produce the result

{f[0], f[2][3][4]}

I can't figure out how to adapt those answers to this more general problem.

  • 2
    $\begingroup$ How about patt[head]:= x_ /; ! FreeQ[x, _f]? $\endgroup$
    – Fabian
    Jan 16, 2015 at 13:40

1 Answer 1

FirstCase[{f, f[0], h[f[e[d[c[a]]]]], p[q[r[f]]], f[2][3][4], x[y[z[0, f[5][6], 1, 2]]]},
   _?(! FreeQ[#, f[___]] &)]

(* f[0] *)

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.