count
Counts the number of elements with a certain property in a container.
Syntax
-
count(X, p)
-
X
is a container -
p
is a predicate
-
-
count(X, x[, ε])
-
X
is a container -
x
is an object -
ε
is a positive number
-
Description
If X
is a container and p
a predicate, then count(X, p)
returns the number of elements x
in X
for which p(x)
is true
.
If X
is a container and x
an object, then count(X, x)
returns the number of elements in X
that are equal to x
. count(X, x, ε)
does the same, but uses the specified epsilon when comparing floating-point numbers. Both overloads compare mathematical values, so, for instance, the integer 5
is equal to the real number 5.0
. However, only the latter overload, with an appropriate ε, is guaranteed to consider sin(π)
and 0
to be equal.
Examples
ℙ ≔ compute(prime(n), n, 1, 1000000);
count(ℙ, p ↦ sum(digits(p)) = 10)
1121
count(ℙ, p ↦ (d ≔ digits(p); ∑(d) = ∏(d)))
23
count(ℙ, p ↦ (s ≔ string(p); s = reverse(s)))
781
count(digits(2^50), 5)
1
s ≔ ExampleData("Alice in Wonderland");
count(s, ChrIsPunctuation) / #s
0.0563018101844 (=1664/29555)