Array.last
func Array.last[T](xs: Array[T]): T | nullArray.last returns the last element of xs, or null when xs is empty.
Details
- Does not change
xs. To remove the last element, use Array.pop.
Basic examples
Array.last([10, 20, 30]) // 30
Array.last(["a", "b"]) // "b"An empty array gives null. Annotate it so that T is known:
let empty: Array[int] = []
Array.last(empty) // nullCall it through . on any array:
let history = ["open", "edit", "save"]
history.last() // "save"Scope
An array of one element gives that element:
[42].last() // 42An array of records gives the last record. Read a field of it with ?., which yields null for an empty array:
type Commit = { hash: string, message: string }
let commits = [Commit{ hash: "a1f", message: "init" }, Commit{ hash: "9c2", message: "fix typo" }]
let none: Array[Commit] = []
commits.last() // Commit{ hash: "9c2", message: "fix typo" }
commits.last()?.hash // "9c2"
none.last()?.hash // null
none.last()?.hash ?? "no commits" // "no commits"A nested array gives its last inner array, and ?.[i] indexes into it:
let rows = [[1, 2], [3, 4, 5]]
rows.last() // [3, 4, 5]
rows.last()?.[0] // 3Elements of a union keep their tag, so is tells which member came last:
type Passed = { value: int }
type Failed = { reason: string }
type Step = Passed | Failed
let steps: Array[Step] = [Passed{ value: 1 }, Failed{ reason: "timeout" }]
steps.last() // Failed{ reason: "timeout" }
steps.last() is Failed // trueAn array of functions gives a function, which ?.(…) calls when it is there:
let handlers: Array[func(string): string] = [{ x.toUpper() }, { "<${x}>" }]
let empty: Array[func(string): string] = []
handlers.last()?.("hi") // "<hi>"
empty.last()?.("hi") // nullFor the last character of a string, split it into graphemes first, so that a character built from several code points stays whole:
"bonjour 👋🏽".graphemes().last() // "👋🏽"The keys of a map and the values of a set are arrays in insertion order, so Array.last gives the one inserted last:
Map{ b: 2, a: 1 }.keys().last() // "a"
Set.of([3, 1, 2]).values().last() // 2A map value that may be missing can default to [] with ??. The [] takes the type of the value, so it needs no annotation:
let visits = Map{ ann: ["home", "cart"] }
(visits["ann"] ?? []).last() // "cart"
(visits["bob"] ?? []).last() // nullIn a pipe, the array is the first argument:
"src/lib/geo.ant" | String.split("/") | Array.last() // "geo.ant"Applications
Take the file name from a path:
func baseName(path: string): string {
path.split("/").last() ?? ""
}
println(baseName("docs/lib/Array/last.md"))
println(baseName("README.md"))last.md
README.mdString.split always returns at least one piece, so the ?? "" only satisfies the string | null type.
Read the top of a stack and leave the stack as it was:
let stack = ["main", "parse", "expr"]
let top = stack.last()
if top != null {
println("in ${top}, depth ${stack.length()}")
}in expr, depth 3Keep the latest reading from a series, and report when there is none:
type Reading = { at: string, celsius: float64 }
func latest(rs: Array[Reading]): string {
let r = rs.last() ?? return "no data"
"${r.celsius} at ${r.at}"
}
println(latest([Reading{ at: "09:00", celsius: 14.5 }, Reading{ at: "12:00", celsius: 19.0 }]))
println(latest([]))19.0 at 12:00
no dataPanic when an array that must have elements is empty:
let results: Array[int] = []
results.last() ?? panic("no results") // panic: no resultsProperties and relations
Array.last agrees with Array.get at the last index, with indexing on a non-empty array, with Array.findLast given a function that accepts everything, and with Array.first of the reversed array:
for xs in [[4, 5, 6], [7], []] {
assert(xs.last() == xs.get(xs.length() - 1))
assert(xs.last() == xs.findLast({ true }))
assert(xs.last() == xs.reverse().first())
if !xs.isEmpty() {
assert(xs.last() == xs[xs.length() - 1])
}
}After Array.push, the pushed value is the last element:
let xs = [1, 2]
xs.push(3)
assert(xs.last() == 3)When the element type does not include null, the result is null exactly when the array is empty:
for xs in [["a"], []] {
assert((xs.last() == null) == xs.isEmpty())
}Possible issues
The result is T | null, not T, so using it as a T is a compile error:
let xs = [3, 1, 2]
println(xs.last() + 1) // error: + needs both operands of one type, got int | null and intGive a default with ??, or narrow a local:
let xs = [3, 1, 2]
(xs.last() ?? 0) + 1 // 3Testing the call itself does not narrow a second call, because only locals, parameters, and top-level lets narrow:
let xs = [3, 1, 2]
if xs.last() != null {
println(xs.last() * 2) // error: * needs both operands of one type, got int | null and int
}Bind the result to a local and test that:
let xs = [3, 1, 2]
let tail = xs.last()
if tail != null {
println(tail * 2)
}4When the element type includes null, a null result does not tell an empty array from one whose last element is null. Ask the array with Array.isEmpty instead:
let answers: Array[string | null] = ["yes", null]
answers.last() // null
answers.isEmpty() // falseIndexing with [-1] does not count from the end. It panics, as any index outside the array does:
let xs = [1, 2, 3]
xs.last() // 3
xs[-1] // panic: index -1 out of range for an array of length 3See also
Array.first · Array.pop · Array.get · Array.findLast · Array.push · Array.isEmpty · Array.slice · ?? operator · ?. operator · Null guide
