Reference · Lists
find
find(list | null, fn) -> anyWhat 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))2{ id: 2, name: "Bo" }BobbEdge cases
- Nothing found, an empty list or
nullgivesnull. Give a default with??. - Only the first match comes back; for all of them use filter.
- The search stops at the first match: the function is not called for the items after it.
- A
nullitem that matches givesnulltoo, which cannot be told from "not found". Use any when the question is only whether it is there.
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))null null nullnonetrying 1trying 22null trueErrors
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.
print(find("abc", (c) => c == "b"))line 1: `find` expects a list as argument 1, got strprint(find([1, 2], 2))line 1: `find` expects a function as argument 2, got intChaining
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")))AnnnullBoSee also
filter, any, first, index_of, contains
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