Skip to main content

list manipulation - Generalization to AllTrue, AnyTrue and NoneTrue


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.




Answer



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]

Comments