What is the idiomatic way of counting the number of elements matching a predicate?

Is there a better way to count the number of elements for which the predicate function is true, other than this:

PredCount[lst_, pred_] := Length@Select[lst, pred];

I ask because it is not possible to build a subset of lstc Select[], but because it Count[]only works with templates. In my case, the function PredCountis called many times with a large one lst.

+3
source share
2 answers

You can often do this by turning your predicate into a conditional template. For instance:

Count[list, x_/;x>5]

will count the number of items in the list that are greater than 5.

+7
source

I would use PatternTest

PredCount = Count[#, _?#2] &;

PredCount[Range@30, PrimeQ]
(*out*) 10

This template is simple enough for you to use directly Count.

+2

All Articles