Generalization to AllTrue, AnyTrue and NoneTrue
Select
is fairly close to this already, notably including early exit behavior, so perhaps:
someTrue[list_, pred_, {m_} | n_] :=
n + m == Length @ Select[list, pred, 1 n + m]
Test:
someTrue[Range@10, PrimeQ, 3]
someTrue[Range@10, PrimeQ, 5]
someTrue[Range@10, PrimeQ, {4}]
someTrue[Range@10, PrimeQ, {2}]
True False True False
The code above is me trying to be clever with vanishing patterns. The longer but more legible form:
someTrue[list_, pred_, n_] := n == Length @ Select[list, pred, n]
someTrue[list_, pred_, {n_}] := n == Length @ Select[list, pred, n + 1]
Here's a way to implement this without Select
, but with VectorQ
. If you don't want to duplicate memory, then Select
could be dangerous.
My idea was to count the number of times pred
was true and exit once it hit's the specified threshold.
SomeTrue[list_, pred_, n_Integer] := Module[{i = 0},
!VectorQ[list, (If[pred[#], i++]; i < n)&]
]
SomeTrue[list_, pred_, {n_Integer}] := Module[{i = 0},
VectorQ[list, (If[pred[#], i++]; i < n+1)&] && i == n
]