Grav v1.14.0

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, set and indexing xs[i] are O(1) (adding is O(1) on average: the buffer doubles when full).
  • insert, removeAt and remove move the elements after the position: O(n).
  • Every index is checked: an index outside 0..size() throws IndexError.
  • [1, 2, 3] builds an Array wherever one is expected.
grav
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)
}
Output
[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.

grav
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))
}
Output
[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 for capacity elements before the first reallocation.

Methods

  • fn reserve(capacity: int) — Make room for at least capacity elements 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, or fallback when 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 before index (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 to item; reports whether one was found.
  • fn removeWhere(pred: fn(T) -> bool) -> int — Removes every element matching pred (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 to item.
  • fn indexOf(item: T) -> int — The index of the first element equal to item (==), or -1.
  • fn lastIndexOf(item: T) -> int — The index of the last element equal to item (==), or -1.
  • fn contains(item: T) -> bool — Whether some element equals item (==).
  • 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 which keep returns 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 — Whether pred holds for at least one element.
  • fn all(pred: fn(T) -> bool) -> bool — Whether pred holds for every element (true when empty).
  • fn countWhere(pred: fn(T) -> bool) -> int — How many elements pred holds for.
  • fn findIndex(pred: fn(T) -> bool) -> int — Index of the first element matching pred, or -1.
  • fn findFirst(pred: fn(T) -> bool, fallback: T) -> T — The first element matching pred, or fallback.
  • 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 by cmp (throws StateError when empty).
  • fn minBy(cmp: fn(T, T) -> int) -> T — The smallest element by cmp (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 first n elements (all of them when there are fewer), as a new array.
  • fn drop(n: int) -> Array<T> — Everything after the first n elements, as a new array.
  • fn takeWhile(keep: fn(T) -> bool) -> Array<T> — The elements from the start for as long as keep holds.
  • fn dropWhile(skip: fn(T) -> bool) -> Array<T> — The elements after the leading run for which skip holds.
  • 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 by sep: [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 which keep holds, 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 passes pred.
  • 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 of size (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.)

Edit this page on GitHub