Reference · Lists

find

signature
find(list | null, fn) -> any

What it does

The first item for which the function gives a true value, or null when none does. The function takes one argument, the item, and is called in order until it says yes; the rest of the list is not looked at. null counts as an empty list.

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 find(xs, f)? stops there.

Examples

print(find([1, 2, 3], (x) => x > 1))let people = [{ id: 1, name: "Ann" }, { id: 2, name: "Bo" }]print(find(people, (p) => p.id == 2))print(find(people, (p) => p.id == 2).name)print(find(["a", "bb", "ccc"], (s) => len(s) > 1))
output
2{ id: 2, name: "Bo" }Bobb

Edge cases

print(find([1, 2, 3], (x) => x > 5), find([], (x) => true), find(null, (x) => true))print(find([1, 2], (x) => x > 5) ?? "none")print(find([1, 2, 3], (x) => { print("trying", x)    x == 2 }))print(find([null, 1], (x) => x == null), any([null, 1], (x) => x == null))
output
null null nullnonetrying 1trying 22null true

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. An error inside the function stops the request. A missing match is not an error: it is null.

this one fails
print(find("abc", (c) => c == "b"))
output
line 1: `find` expects a list as argument 1, got str
this one fails
print(find([1, 2], 2))
output
line 1: `find` expects a function as argument 2, got int

Chaining

In a pipeline the list comes first: xs | find(f). A field of the result can be read at once; when nothing was found that field is null too, since a field of null is null.

let users = [{ id: 1, name: "Ann" }, { id: 2, name: "Bo" }]print(users | find((u) => u.id == 1) | get("name"))print((users | find((u) => u.id == 9)).name)print(users | map((u) => u.name) | find((n) => starts_with(n, "B")))
output
AnnnullBo

See also

filter, any, first, index_of, contains

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

Thread 0 posts

On find(): 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