Reference · Lists

count

signature
count(list | null, fn=) -> int

What 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))
output
321

Edge cases

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))
output
0 0 0true410

Errors

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.

this one fails
print(count("abc"))
output
line 1: `count` expects a list as argument 1, got str
this one fails
print(count([1, 2], 5))
output
line 1: `count` expects a function as argument 2, got int

Chaining

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)
output
422

See also

len, filter, any, all, sum, group_by

Thread
8Useful? Like it, or add to its thread below.

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