Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Arrays and slices

Array<T> is Pepper's growable list. Beyond append, indexing and sort, it has the everyday algorithms, and slice gives a function "some of the elements" without copying them:

total(values: ArrayView<int>): int {
    var sum = 0;
    for (var x in values) {
        sum = sum + x;
    }
    return sum;
}

main(): int {
    # Searching a sorted array.
    var sorted = [1, 3, 3, 5, 8];
    assert(sorted.is_sorted(), "sorted");
    assert(sorted.binary_search(5).value() == 3, "found at 3");
    assert(sorted.binary_search(4).is_empty(), "no 4");
    assert(sorted.upper_bound(3) - sorted.lower_bound(3) == 2, "two 3s");

    # Changing elements in place.
    var a = [4, 4, 1, 2, 2, 7];
    a.dedup();
    assert(a == [4, 1, 2, 7], "adjacent repeats removed");
    a.retain((x) => x % 2 == 0);
    assert(a == [4, 2], "odd elements removed");
    a.resize(4, 0);
    assert(a == [4, 2, 0, 0], "padded with 0");
    var tail = a.split_off(2);
    assert(a == [4, 2] && tail == [0, 0], "split in two");
    tail.fill(9);
    assert(tail == [9, 9], "filled");

    # Reshaping.
    var digits = [1, 2, 3, 4, 5];
    digits.rotate(2);
    assert(digits == [3, 4, 5, 1, 2], "rotated");
    var drained = digits.drain(1, 3);
    assert(digits == [3, 1, 2] && drained == [4, 5], "drained");
    digits.remove_if((x) => x > 2);
    digits.extend_from(drained.slice(0, 1));
    assert(digits == [1, 2, 4], "filtered and extended");

    # Ordering without a full stable sort.
    var scores = [40, 95, 12, 77, 63, 8];
    scores.select_nth(2);
    assert(scores[2] == 40, "the third smallest");
    scores.partial_sort(2);
    assert(scores[0] == 8 && scores[1] == 12, "the two smallest, in order");
    scores.sort_unstable((x, y) => y - x);
    assert(scores == [95, 77, 63, 40, 12, 8], "descending");
    assert([1, 2, 3].compare([1, 3]) < 0, "lexicographic");

    # A slice views part of an array without copying it.
    var numbers = [1, 2, 3, 4, 5];
    var middle = numbers.slice(1, 4);
    assert(middle.count == 3 && middle[0] == 2, "views [2, 3, 4]");
    assert(total(middle) == 9, "passed to a function");
    assert(middle.to_array() == [2, 3, 4], "copied out");
    var (head, rest) = middle.split_at(1);
    assert(head.count == 1 && rest[0] == 3, "split in two");
    var pairs = 0;
    for (var pair in numbers.chunks(2)) {
        pairs = pairs + pair.count;   # [1, 2], [3, 4], [5]
    }
    assert(pairs == 5, "every element in some chunk");
    var rises = 0;
    for (var pair in numbers.windows(2)) {
        rises = rises + (pair[1] > pair[0] ? 1 : 0);
    }
    assert(rises == 4, "each neighbor is larger");
    assert(numbers.slice(0, 2) == [9, 1, 2].slice(1, 3), "equal elements");
    return 0;
}

Searching a sorted array

  • binary_search(item) returns the index of the first element equal to item as a ulong?, in O(log count). The element type must be Comparable (every number, char and String is), and the array sorted in its compare order.
  • binary_search_by(order) searches with a function that says whether an element sorts before (negative), at (0) or after (positive) the target.
  • lower_bound(item) and upper_bound(item) are the first and last places item could be inserted to keep the array sorted; the elements between them equal item.
  • is_sorted() reports whether the array is in that order.

Changing elements in place

  • fill(value) sets every element to value.
  • retain(keep) removes each element keep returns false for, keeping the order of the rest. keep must not change the array; if it does, retain panics with Array modified during retain.
  • dedup() removes each element equal (==) to the one before it; on a sorted array that removes every duplicate.
  • resize(count, value) shortens the array, or appends copies of value.
  • split_off(index) moves the elements from index on into a new array, and drain(start, end) moves out the elements in between.
  • remove_if(remove) is the opposite of retain.
  • rotate(count) moves the first count elements to the end.
  • extend_from(slice) appends the elements of a slice, which may be a slice of the same array.

Each counts as modifying the array, so a for loop over it panics on its next step.

Ordering

  • sort_unstable() sorts with pattern-defeating quicksort: no scratch buffer, and O(count) on input that is already sorted or all equal, but equal elements may change places. sort() is the stable sort.
  • select_nth(nth) puts the element a sort would put at nth there, with smaller elements before it and larger ones after (C++'s nth_element), in O(count) on average: the median without a full sort.
  • partial_sort(count) sorts only the count smallest elements into the front.
  • a.compare(b) orders two arrays lexicographically: by the first elements that differ, else the shorter first. == compares element by element.

Each takes a comparer too (sort_unstable((a, b) => b - a)) for an order other than the elements' own, or for elements that are not Comparable.

Slices

a.slice(start, end) is an ArrayView<T> (formerly ArraySlice<T>, a name that still works, with a deprecation warning): a read-only view of the elements from start up to but not including end. It has count, is_empty, indexing, for loops, slice, to_array, find, contains and the searches above, plus:

  • split_at(index), which returns two slices: the elements before index, and those from it on.
  • chunks(size), which visits runs of size elements side by side, as slices; the last run is shorter when size does not divide the count.
  • windows(size), which visits every run of size neighbors, each starting one element after the one before.
  • == and, for Comparable elements, the lexicographic compare, which compare the elements, not where they are.

Array has chunks and windows too, over all its elements. Neither copies an element: each run is a slice of the same array.

var rises = 0;
for (var pair in [1, 3, 2, 5].windows(2)) {
    if (pair[1] > pair[0]) {
        rises = rises + 1;   # 2 in all
    }
}

A slice is safe by construction:

  • It holds a reference to its array, so the array lives as long as the slice does.
  • It is fail-fast, like an iterator. Once the array changes (any store, append, remove_at, sort, ...), every later use of the slice panics with Array modified while a slice of it is in use, so it can never read an element that moved or a buffer that was freed. Make a new slice after changing the array.
  • It never holds a pointer into the array's buffer, only the array and a range, so even growing the array (which moves the buffer) cannot leave it pointing at freed memory. The runs chunks and windows give are slices too, and follow the same rules.

An Array is never null

Unlike other struct types, an Array is never null. A variable, field or element of an array type that was not given a value holds an empty array, and so does __default<u8[]>(). Storing one (append, resize, an assignment) stores an array, so comparing with __null says nothing useful:

u8[] none;
var buckets = Array<u8[]>();
buckets.resize(4, none);   # one empty array, four times; no nulls

When "no array" must differ from "an empty array", say so in the type with Optional: u8[]?, empty until it is given an array.

Not yet

  • Slices are read-only; there is no slice that writes through to its array, and no a[1..4] syntax: write a.slice(1, 4) (the compiler says so: cannot index 'Array<int>' with a value of type 'Range<int>').
  • An Array is not itself Comparable, so < between arrays and sort() on an array of arrays need compare: rows.sort((a, b) => a.compare(b)).
  • String has no slice type; substr copies.