# Match first n elements where n is matched before

Can we use a matched integer to determine how many elements in a sequence should be matched?

In other words, do you think it is possible to generalize foo for any n?

isM = MemberQ[{m1, m2, m3, m4}, #] &;
foo[expr_] := expr /.
{
F[_, n_?(# == 2 &)][_?isM, _?isM, ___] :> 0,
F[_, n_?(# == 3 &)][a_, b_, c_, ___] :>
0 /; Count[{a, b, c}, _?isM] >= 2,
F[_, n_?(# == 4 &)][a_, b_, c_, d_, ___] :>
0 /; Count[{a, b, c, d}, _?isM] >= 2,
F[_, n_?(# == 5 &)][a_, b_, c_, d_, e_, ___] :>
0 /; Count[{a, b, c, d, e}, _?isM] >= 2,
F[_, n_?(# == 6 &)][a_, b_, c_, d_, e_, f_, ___] :>
0 /; Count[{a, b, c, d, e, f}, _?isM] >= 2,
F[_, n_?(# == 7 &)][a_, b_, c_, d_, e_, f_, g_, ___] :>
0 /; Count[{a, b, c, d, e, f, g}, _?isM] >= 2,
F[_, n_?(# == 8 &)][a_, b_, c_, d_, e_, f_, g_, h_, ___] :>
0 /; Count[{a, b, c, d, e, f, g, h}, _?isM] >= 2
}


F[a, 3][m2, x, m3, y, z] (should be matched, i.e. =0)

F[a, 3][m2, x, y, m3, z] (should not match)

• Might want to use the 2-arg form of Repeated for this. Commented Feb 13, 2023 at 21:38

foo[expr_] :=