Array.findLast
func Array.findLast[T](xs: Array[T], f: func(T): bool): T | nullArray.findLast returns the last 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 last element back and stops at the first elementfaccepts. - When
Tincludesnull, anullresult does not tell a missing element from a foundnull; use Array.findLastIndex.
Basic examples
Find the last even number:
Array.findLast([1, 4, 7, 8, 9], { x % 2 == 0 }) // 8When no element matches, the result is null:
Array.findLast([1, 3, 5], { x % 2 == 0 }) // nullCall it through . on any array:
let words = ["ant", "bee", "beetle", "wasp"]
words.findLast({ x.startsWith("b") }) // "beetle"Scope
An empty array has no last match. Annotate it so that T is known:
let empty: Array[string] = []
empty.findLast({ x != "" }) // nullWhen every element matches, the result is the last element:
[3, 1, 2].findLast({ x > 0 }) // 2f can test a record's fields:
type Order = { id: int, total: float64 }
let orders = [Order{ id: 1, total: 9.5 }, Order{ id: 2, total: 42.0 }, Order{ id: 3, total: 7.25 }]
orders.findLast({ x.total > 8.0 }) // Order{ id: 2, total: 42.0 }A test with is finds the last member of one type in a union. The result has type Shape | null, not Circle | null: the test inside f does not narrow the result:
type Circle = { radius: float64 }
type Square = { side: float64 }
type Shape = Circle | Square
let shapes: Array[Shape] = [Circle{ radius: 1.0 }, Square{ side: 2.0 }, Circle{ radius: 3.0 }]
shapes.findLast({ x is Circle }) // Circle{ radius: 3.0 }
shapes.findLast({ x is Square }) // Square{ side: 2.0 }A named function works as well as a lambda:
func isVowel(s: string): bool {
"aeiou".contains(s)
}
"rhythm and blues".graphemes().findLast(isVowel) // "e"A lambda can read local variables:
let limit = 10
[4, 12, 9, 15, 3].findLast({ x < limit }) // 3In a pipeline, the array is the first argument:
"a,bb,ccc,dd" | String.split(",") | Array.findLast({ x.length() == 2 }) // "dd"A callback that records its argument shows the order: from the last element back, stopping at the first match:
let tested: Array[int] = []
let found = [1, 4, 7, 8, 9].findLast({
tested.push(x)
x % 2 == 0
})
println(found)
println(tested)8
[9, 8]With no match, f sees every element, last first:
let tested: Array[int] = []
let found = [1, 3, 5].findLast({
tested.push(x)
x % 2 == 0
})
println(found)
println(tested)null
[5, 3, 1]Both parameters can be named, in any order:
Array.findLast(f: { x > 1 }, xs: [1, 2, 3]) // 3Applications
Find the most recent error in a log:
type LogLine = { level: string, message: string }
let log = [
LogLine{ level: "info", message: "start" },
LogLine{ level: "error", message: "disk full" },
LogLine{ level: "info", message: "retry" },
LogLine{ level: "error", message: "timeout" },
LogLine{ level: "info", message: "done" },
]
log.findLast({ x.level == "error" })?.message ?? "no errors" // "timeout"Read the last value a setting was given, where later lines override earlier ones:
let lines = ["port=80", "host=localhost", "port=8080"]
let port = lines.findLast({ x.startsWith("port=") })
if port != null {
println(port.trimPrefix("port="))
}8080Find the last stop on a route within driving range:
type Stop = { name: string, km: int }
let route = [Stop{ name: "Ash", km: 40 }, Stop{ name: "Birch", km: 95 }, Stop{ name: "Cedar", km: 160 }]
let range = 120
let stop = route.findLast({ x.km <= range })
println(stop?.name ?? "stay home")BirchProperties and relations
Array.findLast on an array gives what Array.find gives on its reverse:
let xs = [5, 2, 8, 3, 6]
for limit in [0, 4, 7, 10] {
assert(xs.findLast({ x > limit }) == xs.reverse().find({ x > limit }))
}It agrees with Array.findLastIndex and with the last element of Array.filter:
let xs = [5, 2, 8, 3, 6]
for limit in [0, 4, 7, 10] {
let i = xs.findLastIndex({ x < limit })
let v = xs.findLast({ x < limit })
assert(v == (if i != null { xs[i] } else { null }))
assert(v == xs.filter({ x < limit }).last())
}f runs once for each element from the end through the match, so it runs length − i times when the match is at index i, and length times when there is none:
let xs = [5, 2, 8, 3, 6]
for limit in [0, 4, 7, 10] {
var calls = 0
xs.findLast({
calls += 1
x < limit
})
let i = xs.findLastIndex({ x < limit })
assert(calls == xs.length() - (i ?? 0))
}The result is null exactly when Array.some is false, as long as T does not include null:
let xs = ["ant", "bee", "wasp"]
for n in [2, 3, 4, 5] {
assert((xs.findLast({ x.length() == n }) != null) == xs.some({ x.length() == n }))
}Possible issues
The result may be null, so using it as a T is a compile error:
let last = [1, 2, 3].findLast({ x > 1 })
println(last + 1) // error: + needs both operands of one type, got int | null and intNarrow it first, or give a fallback with ??:
let last = [1, 2, 3].findLast({ x > 1 })
(last ?? 0) + 1 // 4When the element type includes null, a null result does not say whether f found a null or found nothing. Use Array.findLastIndex, whose result is an index:
let readings: Array[int | null] = [3, null, 5]
readings.findLast({ x == null }) // null
readings.findLast({ x == 7 }) // null
readings.findLastIndex({ x == null }) // 1
readings.findLastIndex({ x == 7 }) // nullArray.findLast takes a predicate, not a value. To look for a value by ==, use Array.lastIndexOf or Array.contains:
let xs = [1, 2, 3]
println(xs.findLast(2)) // error: cannot use int where func(int): bool is expectedSee also
Array.find · Array.findLastIndex · Array.findIndex · Array.last · Array.filter · Array.some · Array.lastIndexOf · ?? operator · ?. operator
