I am wondering if there is a natural Mathematica way to generalize those functions. To be specific, All three functions AllTrue
, AnyTrue
and NoneTrue
return a Boolean value when a list of length L
contains certain number of elements satisfying a predicate.
For example, AllTrue
returns true when the number of elements satisfying the predicate is L
while NoneTrue
returns true when the number is 0
.
On the contrary, AnyTrue
returns true when the number is at least 1
.
I am considering the generalization SomeTrue[ list, pred, n]
that
it returns true when the number is at least n
.
Another generalization might be SomeTrue[ list, pred, {n}]
that
it returns true when the number is exactly n
.
One natural way I can think of is just using Count
function to calculate the number and compare the criterion but it does not allow the early exit(i.e., every element should be checked even for the case where the result is determined in the early stage).
For people like me migrating from procedural language, the algorithm might be obvious using For
loop with counters and early return
statements.
It would be nice if you can show some examples with truly Mathematica way to attack such problems.
BooleanCountingFunction
. Unfortunately it doesn't appear applicable here as I cannot think of a way to give it early-exit behavior, so one might as well useCount
. $\endgroup$While
myself. One could useScan
andTHrow/Catch
, say. But really I don't see an early exit method that does not, at heart, emulate procedural code. $\endgroup$