Array.pop
func Array.pop[T](xs: Array[T]): T | nullArray.pop removes and returns the last element of xs, or returns null when xs is empty. It mutates xs.
Details
- Removes and returns the last element, changing
xsin place. Every name that shares the array sees the shorter array. - Returns
nullwhenxsis empty. WhenTincludesnull, that does not tell an empty array from a poppednull; ask withArray.isEmpty.
Basic examples
Pop the last element, and the array is one shorter:
let xs = [10, 20, 30]
xs.pop() // 30
xs // [10, 20]An empty array gives null. Annotate it so that T is known:
let empty: Array[string] = []
Array.pop(empty) // null
empty // []Each call removes one more element, until none is left:
let tasks = ["write", "test"]
tasks.pop() // "test"
tasks.pop() // "write"
tasks.pop() // nullScope
An array of records gives the last record. Read a field of it with ?.:
type Frame = { name: string, line: int }
let trace = [Frame{ name: "main", line: 3 }, Frame{ name: "parse", line: 41 }]
trace.pop()?.name // "parse"
trace // [Frame{ name: "main", line: 3 }]Elements of a union keep their tag, so is tells which member came off:
type Push = { value: int }
type Clear = {}
type Op = Push | Clear
let ops: Array[Op] = [Push{ value: 1 }, Clear{}]
ops.pop() is Clear // true
ops.pop() // Push{ value: 1 }A nested array gives its last inner array, which ?.[i] indexes into:
let rows = [[1, 2], [3, 4, 5]]
rows.pop()?.[2] // 5
rows // [[1, 2]]An array of functions gives a function, which ?.(…) calls:
let undo: Array[func(int): int] = [{ x + 1 }, { x * 10 }]
undo.pop()?.(4) // 40
undo.length() // 1An array bound by let can still lose elements:
let queue = ["a", "b"]
queue.pop() // "b"
queue // ["a"]Every name that shares the array sees the change, including the caller of a function that pops:
func dropLast(xs: Array[int]) {
xs.pop()
}
let a = [1, 2, 3]
let b = a
dropLast(b)
println(a)[1, 2]A copy made with spread is a separate array, which Array.pop leaves alone:
let original = [1, 2, 3]
let copy = [...original]
copy.pop() // 3
original // [1, 2, 3]In a pipe, the array is the first argument:
let words = "a b c".split(" ")
words | Array.pop() // "c"
words // ["a", "b"]Applications
Use an array as a stack: Array.push adds to the top, and Array.pop takes from it. Check that brackets match:
func balanced(s: string): bool {
let pairs = Map{ ")": "(", "]": "[", "}": "{" }
let open: Array[string] = []
for c in s.graphemes() {
if c == "(" || c == "[" || c == "{" {
open.push(c)
} else if pairs.has(c) {
if open.pop() != pairs.get(c) {
return false
}
}
}
open.isEmpty()
}
println(balanced("f(a[1], {b: 2})"))
println(balanced("(]"))
println(balanced("(("))true
false
falseDrain a stack with a while loop, and stop at null with ?? break:
let pending = ["a.ant", "b.ant", "c.ant"]
while true {
let file = pending.pop() ?? break
println("check ${file}")
}
println(pending.length())check c.ant
check b.ant
check a.ant
0Walk a tree depth first without recursion:
type Node = { name: string, children: Array[Node] }
let root = Node{
name: "/",
children: [Node{ name: "bin", children: [] }, Node{ name: "src", children: [Node{ name: "lib", children: [] }] }],
}
let stack = [root]
while true {
let node = stack.pop() ?? break
println(node.name)
for child in node.children.reverse() {
stack.push(child)
}
}/
bin
src
libUndo the last edit, and report when there is nothing to undo:
type Edit = { text: string }
func undo(history: Array[Edit]): string {
let last = history.pop() ?? return "nothing to undo"
"undid ${last.text}"
}
let history = [Edit{ text: "insert a" }, Edit{ text: "delete b" }]
println(undo(history))
println(undo(history))
println(undo(history))undid delete b
undid insert a
nothing to undoProperties and relations
Array.pop returns what Array.last returned, and the length drops by one:
let xs = [4, 5, 6]
let before = xs.length()
let peek = xs.last()
assert(xs.pop() == peek)
assert(xs.length() == before - 1)Array.pop undoes Array.push:
let xs = ["a", "b"]
xs.push("c")
assert(xs.pop() == "c")
assert(xs == ["a", "b"])On a non-empty array, it agrees with Array.removeAt at the last index:
let a = [1, 2, 3]
let b = [1, 2, 3]
assert(a.pop() == b.removeAt(b.length() - 1))
assert(a == b)What remains equals the slice without the last element:
let xs = [7, 8, 9]
let rest = xs.slice(0, xs.length() - 1)
xs.pop()
assert(xs == rest)Popping every element gives them in reverse order:
let xs = [1, 2, 3]
let out: Array[int] = []
while true {
out.push(xs.pop() ?? break)
}
assert(out == [3, 2, 1])
assert(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.pop() + 1) // error: + needs both operands of one type, got int | null and intGive a default with ??, or bind it to a local and narrow that:
let xs = [3, 1, 2]
(xs.pop() ?? 0) + 1 // 3Testing the result of one call and then popping again removes two elements, not one:
let xs = [1, 2, 3]
if xs.pop() != null {
println(xs.pop())
}
println(xs)2
[1]Bind the result to a local, and narrow that. The array loses one element:
let xs = [1, 2, 3]
let top = xs.pop()
if top != null {
println(top + 1)
}
println(xs)4
[1, 2]When the element type includes null, a null result does not tell an empty array from a popped null. Ask Array.isEmpty first:
let answers: Array[string | null] = ["yes", null]
answers.pop() // null
answers.isEmpty() // falsePopping one shared array from two goroutines without synchronization is a data race, a program error with no guaranteed result. Guard each pop with a Mutex:
let work = [1, 2, 3, 4]
let done: Array[int] = []
let mu = Mutex.new()
let wg = WaitGroup.new()
for _ in [1, 2] {
wg.add(1)
go {
defer { wg.done() }
while true {
let n = mu.withLock({ work.pop() }) ?? break
mu.withLock({ done.push(n * n) })
}
}
}
wg.wait()
println(done.sort())
println(work)[1, 4, 9, 16]
[]Array.pop takes from the end. To take from the front, as a queue does, use Array.removeAt at index 0, which panics on an empty array:
let line = ["first", "second"]
line.removeAt(0) // "first"
line // ["second"]See also
Array.push · Array.last · Array.removeAt · Array.insert · Array.isEmpty · Array.slice · ?? operator · ?. operator · Null guide
