Array.find
func Array.find[T](xs: Array[T], f: func(T): bool): T | nullArray.find returns the first element of xs that f accepts, or null when there is none.
Details
- Returns
nullwhenfaccepts no element, so an empty array givesnull. - Calls
ffrom the first element and stops at the first elementfaccepts. - When
Tincludesnull, anullresult does not tell a missing element from a foundnull; use Array.findIndex. - The result is the element in
xs, not a copy.
Basic examples
Find the first number above 2:
Array.find([1, 2, 3, 4], { x > 2 }) // 3When no element matches, the result is null:
Array.find([1, 2, 3], { x > 5 }) // nullFind a record by a field, and read a field of the result with ?.:
type User = { id: int, name: string }
let users = [User{ id: 1, name: "Ann" }, User{ id: 7, name: "Bob" }]
users.find({ x.id == 7 })?.name // "Bob"
users.find({ x.id == 9 })?.name // nullScope
An empty array has no element to find. Annotate it so that T is known:
let empty: Array[string] = []
empty.find({ true }) // nullOnly the first match counts, even when later elements match too:
["fig", "plum", "pear", "lime"].find({ x.length() == 4 }) // "plum"f runs from the first element and stops at the first match. A callback that records each call shows it never sees 12:
let seen: Array[int] = []
let found = [3, 8, 5, 12].find({
seen.push(x)
x > 4
})
println(found)
println(seen)8
[3, 8]Pass a named function instead of a lambda:
func isEven(n: int): bool {
n % 2 == 0
}
[3, 5, 8, 10].find(isEven) // 8A lambda can use the local variables around it:
let limit = 10
let prices = [4, 12, 7, 30]
prices.find({ x > limit }) // 12Search the graphemes of a string by splitting it with String.graphemes first:
String.graphemes("🐜🐝🐞") | Array.find({ x != "🐜" }) // "🐝"Find a member of a union by its type with is. The result type stays Shape | null, not Square | null; test it with is again to read side:
type Circle = { radius: float64 }
type Square = { side: float64 }
type Shape = Circle | Square
let shapes: Array[Shape] = [Circle{ radius: 1.0 }, Square{ side: 2.0 }, Square{ side: 3.0 }]
shapes.find({ x is Square }) // Square{ side: 2.0 }
let s = shapes.find({ x is Square })
if s is Square { s.side } // 2.0Find in a nested array:
[[1, 2], [], [3]].find({ x.isEmpty() }) // []Call it through . or in a pipe:
[5, 10, 15].find({ x % 2 == 0 }) // 10
[5, 10, 15] | Array.find({ x % 3 == 0 }) // 15Applications
Look up a record and fall back to a default with ??:
type User = { id: int, name: string }
let users = [User{ id: 1, name: "Ann" }, User{ id: 7, name: "Bob" }]
func nameOf(id: int): string {
users.find({ x.id == id })?.name ?? "anonymous"
}
println(nameOf(7))
println(nameOf(9))Bob
anonymousNarrow the result with != null to work with the whole record:
type Item = { name: string, stock: int }
let items = [Item{ name: "nut", stock: 0 }, Item{ name: "bolt", stock: 4 }]
let item = items.find({ x.stock > 0 })
if item != null {
println("${item.name}: ${item.stock} in stock")
}bolt: 4 in stockFind the first line that is not blank:
let text = "\n \nTitle\nBody"
text.split("\n").find({ x.trim() != "" }) // "Title"Return early from a function when nothing matches, with ?? return:
type Route = { path: string, handler: string }
func handle(routes: Array[Route], path: string): string {
let route = routes.find({ x.path == path }) ?? return "404 not found"
"200 ${route.handler}"
}
let routes = [Route{ path: "/", handler: "home" }, Route{ path: "/about", handler: "about" }]
println(handle(routes, "/about"))
println(handle(routes, "/missing"))200 about
404 not foundProperties and relations
Array.find gives the first element of Array.filter, and the element at Array.findIndex:
let xs = [4, 9, 16, 25]
let f: func(int): bool = { x > 5 }
assert(xs.find(f) == xs.filter(f).first())
let i = xs.findIndex(f)
assert(i != null && xs.find(f) == xs[i])It finds something exactly when Array.some holds, for an element type without null:
let xs = [1, 3, 5]
assert((xs.find({ x > 4 }) != null) == xs.some({ x > 4 }))
assert((xs.find({ x > 9 }) != null) == xs.some({ x > 9 }))On a reversed array, it gives what Array.findLast gives on the original:
let xs = [2, 7, 4, 9, 6]
assert(xs.reverse().find({ x > 5 }) == xs.findLast({ x > 5 }))The element it returns is the one in the array, so a change to it shows in the array:
type Item = { name: string, stock: int }
let items = [Item{ name: "nut", stock: 0 }]
let item = items.find({ x.name == "nut" })
if item != null {
item.stock = 10
}
assert(items[0].stock == 10)Possible issues
The result may be null, so reading a field of it without narrowing is a compile error:
type User = { id: int, name: string }
let users = [User{ id: 1, name: "Ann" }]
println(users.find({ x.id == 1 }).name)
// error: User | null has no field name: narrow the value firstUse ?., ??, or a test against null first, as in the examples above.
When the element type includes null, a found null and no match look the same. Use Array.findIndex to tell them apart:
let scores: Array[int | null] = [90, null, 75]
scores.find({ x == null }) // null
scores.find({ x == 100 }) // null
scores.findIndex({ x == null }) // 1
scores.findIndex({ x == 100 }) // nullf must return a bool. Ant has no truthy values, so a number is not a test:
let xs = [1, 2, 3]
println(xs.find({ x - 2 })) // error: cannot use int where bool is expectedArray.find takes a predicate, not a value. To look for a value by ==, use Array.contains or Array.indexOf, or compare in the lambda:
[1, 2, 3].find({ x == 2 }) // 2
[1, 2, 3].contains(2) // true
[1, 2, 3].indexOf(2) // 1See also
Array.findIndex · Array.findLast · Array.findLastIndex · Array.filter · Array.some · Array.contains · Array.indexOf · Array.first · ?. operator · ?? operator
