Array
import "std/collections" (included in import "std") · namespace std.collections
Array<T> is the general-purpose list: elements in order, indexed from 0, growing as you add. It is the collection to reach for first.
push/add,pop,get,setand indexingxs[i]are O(1) (adding is O(1) on average: the buffer doubles when full).insert,removeAtandremovemove the elements after the position: O(n).- Every index is checked: an index outside
0..size()throwsIndexError. [1, 2, 3]builds anArraywherever one is expected.
import "std"
fn main() {
let xs: Array<int> = [5, 3, 8]
xs.push(1)
xs.insert(0, 9)
print(xs)
print("${xs[0]} ${xs.first()} ${xs.last()} ${xs.size()}")
xs[1] = 50
print(xs.removeAt(2))
print(xs.indexOf(8))
print(xs.contains(42))
print(xs[1..3])
let evens = xs.filter(fn(n) => n % 2 == 0)
print(evens)
print(xs.map(fn(n) => n * 2))
print(xs.reduce(0, fn(sum, n) => sum + n))
print(xs.mapTo(fn(n) => "#${n}"))
print(xs.maxBy(fn(a, b) => a - b))
xs.sortBy(fn(a, b) => a - b)
print(xs)
xs.removeWhere(fn(n) => n > 10)
print(xs)
}[9, 5, 3, 8, 1]
9 9 1 5
3
2
false
[50, 8]
[50, 8]
[18, 100, 16, 2]
68
["#9", "#50", "#8", "#1"]
50
[1, 8, 9, 50]
[1, 8, 9]Methods that build a new collection (filter, map, mapTo, slice, copy, toArray) return a copy, so changing the result never changes the original. indexOf, contains and remove compare with == (an object's operator== when it has one). See Arrays and collections.
Slicing and reshaping
take(n), drop(n), takeWhile, dropWhile, distinct, reversed() and sorted(cmp) (copies; reverse() and sortBy work in place), flatMap, join(sep), sumBy, partition (a pair of arrays), zip (pairs of elements), none and indices. The function chunked(xs, n) splits an array into groups.
import "std"
fn main() {
let xs: Array<int> = [5, 1, 4, 1, 5, 9, 2, 6]
print(xs.take(3))
print(xs.distinct())
print(xs.sorted(fn(a, b) => a - b))
print(chunked(xs, 3))
print(xs.join(" + "))
let (even, odd) = xs.partition(fn(x) => x % 2 == 0)
print("${even} ${odd}")
let names: Array<string> = ["ann", "bob"]
let scores: Array<int> = [90, 85]
print(names.zip(scores))
print(xs.flatMap(fn(x) -> Array<int> { return [x, -x] }).take(4))
}[5, 1, 4]
[5, 1, 4, 9, 2, 6]
[1, 1, 2, 4, 5, 5, 6, 9]
[[5, 1, 4], [1, 5, 9], [2, 6]]
5 + 1 + 4 + 1 + 5 + 9 + 2 + 6
[4, 2, 6] [5, 1, 1, 5, 9]
[("ann", 90), ("bob", 85)]
[5, -5, 1, -1]When a flatMap lambda returns an array literal, give it a result type (fn(x) -> Array<int> { ... }) so the element type is known.
API
class Array<T>
Constructors
new Array()new Array(capacity: int)— Pre-sized: room forcapacityelements before the first reallocation.
Methods
fn reserve(capacity: int)— Make room for at leastcapacityelements in total.fn size() -> int— The number of elements.fn length() -> int— The number of elements (same as size()).fn isEmpty() -> bool— Whether the array has no elements.fn clear()— Removes every element.fn get(i: int) -> T— The element at index i; an index out of range throws IndexError.fn set(i: int, item: T)— Replaces the element at index i; an index out of range throws IndexError.fn operator[](i: int) -> T—xs[i]: the element at index i (IndexError when out of range).fn operator[]=(i: int, item: T)—xs[i] = v: replaces the element at index i.fn first() -> T— The first element; an empty array throws IndexError.fn last() -> T— The last element; an empty array throws IndexError.fn getOr(i: int, fallback: T) -> T— The element at index i, orfallbackwhen i is out of range.fn push(item: T)— Appends an element at the end (amortized O(1)).fn add(item: T)— Appends an element at the end (same as push).fn addAll(other: Array<T>)— Appends every element of another array.fn pop() -> T— Removes and returns the last element; an empty array throws StateError.fn insert(index: int, item: T)— Inserts an element beforeindex(0..size()); later elements move up.fn removeAt(index: int) -> T— Removes and returns the element at index; later elements move down.fn remove(item: T) -> bool— Removes the first element equal toitem; reports whether one was found.fn removeWhere(pred: fn(T) -> bool) -> int— Removes every element matchingpred(keeping order); returns how many.fn swap(i: int, j: int)— Exchanges the elements at indexes i and j.fn fill(item: T)— Sets every element toitem.fn indexOf(item: T) -> int— The index of the first element equal toitem(==), or -1.fn lastIndexOf(item: T) -> int— The index of the last element equal toitem(==), or -1.fn contains(item: T) -> bool— Whether some element equalsitem(==).fn reverse()— Reverses the order of the elements in place.fn copy() -> Array<T>— A new array with the same elements (a shallow copy).fn toString() -> string— As text: [1, 2, 3] (strings in quotes).fn toArray() -> Array<T>— A new array with the same elements (same as copy()).fn slice(start: int, end: int) -> Array<T>— Elements [start, end) as a new array (bounds are clamped).fn dispose()— Releases the elements and the buffer now, leaving the array empty.fn forEach(f: fn(T))— Calls f on each element, in order.fn forEachIndexed(f: fn(int, T))— Calls f with each index and element, in order.fn map(f: fn(T) -> T) -> Array<T>— A new array of f(x) for each element x (same element type; see mapTo for another).fn filter(keep: fn(T) -> bool) -> Array<T>— A new array of the elements for whichkeepreturns true.fn reduce(init: T, f: fn(T, T) -> T) -> T— Combines the elements left to right: f(f(init, x0), x1)...fn any(pred: fn(T) -> bool) -> bool— Whetherpredholds for at least one element.fn all(pred: fn(T) -> bool) -> bool— Whetherpredholds for every element (true when empty).fn countWhere(pred: fn(T) -> bool) -> int— How many elementspredholds for.fn findIndex(pred: fn(T) -> bool) -> int— Index of the first element matchingpred, or -1.fn findFirst(pred: fn(T) -> bool, fallback: T) -> T— The first element matchingpred, orfallback.fn mapTo<U>(f: fn(T) -> U) -> Array<U>— Map into another element type.fn fold<A>(init: A, f: fn(A, T) -> A) -> A— Reduce into an accumulator of any type.fn maxBy(cmp: fn(T, T) -> int) -> T— The largest element bycmp(throws StateError when empty).fn minBy(cmp: fn(T, T) -> int) -> T— The smallest element bycmp(cmp(a, b) < 0 means a is smaller); empty throws IndexError.fn sortBy(cmp: fn(T, T) -> int)— Stable sort (TimSort, lib/core/timsort.grav):cmp(a, b)< 0 puts a first. O(n log n), and close to O(n) on input that is mostly in order.fn take(n: int) -> Array<T>— The firstnelements (all of them when there are fewer), as a new array.fn drop(n: int) -> Array<T>— Everything after the firstnelements, as a new array.fn takeWhile(keep: fn(T) -> bool) -> Array<T>— The elements from the start for as long askeepholds.fn dropWhile(skip: fn(T) -> bool) -> Array<T>— The elements after the leading run for whichskipholds.fn distinct() -> Array<T>— Each element once, in first-seen order (compared with ==; O(n²), fine for small arrays).fn reversed() -> Array<T>— A new array in reverse order (reverse() reverses this one in place).fn sorted(cmp: fn(T, T) -> int) -> Array<T>— A sorted copy (sortBy sorts this one in place).fn flatMap<U>(f: fn(T) -> Array<U>) -> Array<U>— f applied to every element, with the resulting arrays joined into one.fn join(sep: string) -> string— The elements as text joined bysep: [1, 2, 3].join(", ") == "1, 2, 3".fn sumBy(f: fn(T) -> float) -> float— The sum of f(x) over the elements.fn partition(keep: fn(T) -> bool) -> Pair<Array<T>, Array<T>>— The elements for whichkeepholds, and those for which it does not.fn zip<U>(other: Array<U>) -> Array<Pair<T, U>>— Pairs of elements at the same position, as long as the shorter array.fn none(pred: fn(T) -> bool) -> bool— Whether no element passespred.fn indices() -> Array<int>— The positions 0..size() as an array.
Functions
fn mapTo<T, U>(xs: Array<T>, f: fn(T) -> U) -> Array<U>— Free-function forms (kept for compatibility; prefer xs.mapTo(f) / xs.fold(init, f)).fn fold<T, A>(xs: Array<T>, init: A, f: fn(A, T) -> A) -> A— Folds an array into a value of another type: f(f(init, x0), x1)...fn chunked<T>(xs: Array<T>, size: int) -> Array<Array<T>>— The elements in groups ofsize(the last group may be shorter): chunked([1,2,3,4,5], 2) is [[1, 2], [3, 4], [5]]. ValueError when size < 1. (A function rather than a method, because an Array<T> method returning Array<Array<T>> would make every array type need the next one up.)