Reference · Lists
count
count(list | null, fn=) -> intWhat it does
How many items there are, or, with a function, how many of them the function says
yes to. The function takes one argument, the item, and its result is read for truth
as if reads it: only false and null are no. null counts as an
empty list and gives 0.
An error the function gives comes back as the result: it has said neither yes nor no, and a
failed check must not look like nothing to see. So count(xs, f)? stops there.
Examples
print(count([1, 2, 3]))print(count([1, 2, 3, 4], (x) => x > 2))let people = [{ name: "Ann", admin: true }, { name: "Bo", admin: false }]print(count(people, (p) => p.admin))321Edge cases
- An empty list or
nullgives0, with or without a function. - Without a function,
count(xs)islen(xs). - With a function, a result of
falseornulldoes not count, and an error comes back; anything else does,0and""included. - Nothing matching gives
0, nevernull.
print(count([]), count(null), count(null, (x) => true))print(count([1, 2, 3]) == len([1, 2, 3]))print(count([1, 0, "", null, false, "a"], (x) => x))print(count([int("1"), int("x")], (v) => !is_err(v)))print(count([1, 2], (x) => x > 5))0 0 0true410Errors
A first argument that is not a list or null, or a second that is not a function, is
a runtime error, not an error value. A string has len, not count. An error inside
the function stops the request.
print(count("abc"))line 1: `count` expects a list as argument 1, got strprint(count([1, 2], 5))line 1: `count` expects a function as argument 2, got intChaining
In a pipeline the list comes first and the function is the only argument:
xs | count(f). It is filter and len in one step.
print(range(10) | count((x) => x % 3 == 0))print(["pear", "fig", "apple"] | count((w) => len(w) > 3))print(["pear", "fig", "apple"] | filter((w) => len(w) > 3) | len)422See also
len, filter, any, all, sum, group_by
Thread 0 posts
On count(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo