2
$\begingroup$

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]]]},
      patt[f]]

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.

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

1 Answer 1

3
$\begingroup$
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] *)
$\endgroup$

Your Answer

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

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