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 toitemas aulong?, in O(log count). The element type must beComparable(every number,charandStringis), and the array sorted in itscompareorder.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)andupper_bound(item)are the first and last placesitemcould be inserted to keep the array sorted; the elements between them equalitem.is_sorted()reports whether the array is in that order.
Changing elements in place
fill(value)sets every element tovalue.retain(keep)removes each elementkeepreturns false for, keeping the order of the rest.keepmust not change the array; if it does,retainpanics withArray 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 ofvalue.split_off(index)moves the elements fromindexon into a new array, anddrain(start, end)moves out the elements in between.remove_if(remove)is the opposite ofretain.rotate(count)moves the firstcountelements 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 atnththere, with smaller elements before it and larger ones after (C++'snth_element), in O(count) on average: the median without a full sort.partial_sort(count)sorts only thecountsmallest 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 beforeindex, and those from it on.chunks(size), which visits runs ofsizeelements side by side, as slices; the last run is shorter whensizedoes not divide the count.windows(size), which visits every run ofsizeneighbors, each starting one element after the one before.==and, forComparableelements, the lexicographiccompare, 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 withArray 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
chunksandwindowsgive 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: writea.slice(1, 4)(the compiler says so:cannot index 'Array<int>' with a value of type 'Range<int>'). - An
Arrayis not itselfComparable, so<between arrays andsort()on an array of arrays needcompare:rows.sort((a, b) => a.compare(b)). Stringhas no slice type;substrcopies.