DocsLanguage Guide
Arrays and Collections
The array family, slices, ranges as places, dictionaries, and the library collections.
Sable gives you two kinds of collection in the language itself: arrays, ordered runs of values of one type, and dictionaries, which map keys to values. Both are value types, like strings. A copy of an array or a dictionary is a collection of its own, and the two share their storage until one of them changes; only then is anything copied.
Where Swift has one Array and Rust has Vec and fixed arrays, Sable has a small family of array types, written with suffixes on the element type. Each says how the array may change: whether it can grow, whether it can shrink, whether its elements live inline. Choosing the right one documents your intent and lets the compiler keep references to elements valid. Other collections, such as sets, lists, deques and queues, come from the Sable.Collections library.
The Array Family#
Every array type is written as its element type followed by a suffix in brackets:
| Type | Meaning | Resizable | Stable references |
|---|---|---|---|
T[k] |
exactly k elements, known at compile time, stored inline |
no | yes |
T[] |
a size fixed when the array is made | no | yes |
T[..k] |
room for k elements inline; grows and shrinks within it |
within k |
yes |
T[..] |
inline room, its size inferred | within it | yes |
T[>..] |
grow-only: the common case | yes | yes |
T[>..<] |
grows and shrinks: stacks, queues, heaps | yes | no |
T[:] |
a slice: a view of a run of another array's elements | no | shares the array's buffer |
The suffixes read as pictures of the array: >.. is "can only get longer", >..< is "can get longer and shorter", ..k is "up to k".
let primes: Int[] = [2, 3, 5, 7, 11] // five, for goodvar log: String[>..] = [] // grows as you appendvar undo: Int[>..<] = [] // pushed onto and popped fromvar rgb: U8[3] = [255, 128, 0] // three bytes, inlinevar recent: Int[..8] = [] // at most eight, inlineMost of the time you want T[>..] for an array you build up, and T[] for one that is made once and only read. The grow-only kind is the default for good reason: since its elements never move up or down within it, a reference to one stays meaningful, which is what "stable references" in the table means. How the compiler checks references into arrays is covered in Memory and Ownership.
Array Literals#
An array literal is a list of values in square brackets: [1, 2, 3]. A literal has no array kind of its own; like a number literal, it takes the type its context asks for:
let fixed: Int[] = [1, 2, 3]var growing: Int[>..] = [1, 2, 3]let inline: Int[3] = [1, 2, 3]With nothing to say otherwise, a literal is a T[], an array of fixed size. So if you mean to append, say so:
var names = ["ann", "bob"] // String[]names.append("cy") // error: a String[] cannot growvar guests: String[>..] = ["ann", "bob"]guests.append("cy") // fineThe elements' type is inferred from the elements, or from the context: [0x54, 0x5A, version] with version: U8 is an array of U8. An empty literal, [], has nothing to infer from and needs a type annotation. A growable array can also be made by calling its type: Int[>..]() is an empty one, and Int[>..](repeating: 0, count: 3) is [0, 0, 0].
Reading and Changing an Array#
Every array has a count and an isEmpty, and is read by an integer index starting at zero. An index outside 0..<count traps.
var shelf: String[>..] = ["lamp", "desk", "chair"]print(shelf.count) // 3print(shelf[0]) // lampshelf[1] = "table" // a 'var' array's elements can be setprint(shelf.first ?? "") // lampprint(shelf.last ?? "") // chairA let array cannot be changed at all, elements included. A var array of any kind but a slice can have its elements replaced. What else it can do depends on its kind.
Growing and Shrinking#
A grow-only T[>..] grows at its end and nowhere else. It has append, append(contentsOf:), capacity and reserveCapacity, and at the end removeLast and clear:
var readings: F64[>..] = []readings.reserveCapacity(100)readings.append(20.5)readings.append(contentsOf: [21.0, 21.5])let latest = readings.removeLast() // 21.5print(readings.count) // 2T[>..<] has the same members. T[..k] grows within its room with append, removeLast and clear; an append past the room traps. Fixed arrays have none of them.
Neither growable kind inserts or removes in the middle. That would move every element after the place, which a grow-only array never does. For insertion and removal anywhere, use List from Sable.Collections (see Lists below).
Iterating#
A for-in loop goes through an array's elements in order. When you also want each position, enumerated() gives pairs of an offset and an element:
let tasks: String[] = ["pack", "label", "ship"]for (i, task) in tasks.enumerated() { print("\(i + 1). \(task)")}1. pack2. label3. shipLoops are covered fully in Control Flow.
What Every Array Can Do#
Every kind of array can be viewed as a slice, T[:], and the members of T[:] are therefore every array's. They fall into two groups: those that read, and those that reorder the elements in place without changing how many there are.
The readers include first, last, firstIndex(of:), contains, starts(with:), ends(with:), count(of:), min(), max(), partitionPoint(where:), binarySearch(for:), split(where:), chunks(of:), windows(of:) and toArray(), plus the sequence algorithms every collection has: map, filter, reduce, first(where:), allSatisfy, sorted(), and the rest.
let scores: Int[] = [72, 95, 88, 61, 95]print(scores.contains(88)) // trueprint(scores.firstIndex(of: 95) ?? -1) // 1print(scores.max() ?? 0) // 95let passing = scores.filter { $0 >= 70 } // [72, 95, 88, 95], an Int[>..]let total = scores.reduce(0) { $0 + $1 } // 411The reorderers are swapAt, reverse(), rotate(left:), rotate(right:), fill, copy(from:), partition(by:), selectNth, sort(), which is stable (a merge sort), and sortUnstable(), which sorts in place without allocating (an introsort). Each has a form taking an ordering, such as sort(by:).
var queue: Int[>..] = [5, 3, 9, 1]queue.sort() // [1, 3, 5, 9]queue.reverse() // [9, 5, 3, 1]queue.swapAt(0, 3) // [1, 5, 3, 9]let ascending = queue.sorted() // a new Int[>..]; 'queue' is unchangedsort() and reverse() change the array they are called on; sorted() and reversed() leave it alone and give a new T[>..]. Sorting belongs to the arrays: there are no free sort and sorted functions.
Some element types have members of their own that are chosen over the generic ones: U8[:]'s contains, firstIndex(of:) and count(of:), for example, are the runtime's vectorised byte search, and Int[:] has a sum() that cannot overflow partway. You can add members to every array, or to arrays of one element type, as described in Extensions.
Arrays Are Equatable, Hashable and Comparable#
An array, of any kind, is Equatable when its element is, Hashable when its element is, and Comparable when its element is, in lexicographic order. So arrays can be compared with == and <, and used as dictionary keys:
let a: Int[] = [1, 2, 3]let b: Int[>..] = [1, 2, 3]print(a == b) // true: different kinds, same elementsprint([1, 2] < [1, 3]) // truevar seen: [Int[]: Bool] = [:]seen[[1, 2]] = trueConverting Between Kinds#
as converts between a growable array and a fixed one in either direction. The elements are the same and are shared until either array changes:
var building: String[>..] = []building.append("north")building.append("south")let done = building as String[] // finished: no more growthSlices#
A slice, T[:], is a view of a run of an array's elements: the array's buffer, where the run starts, and how many elements it has. You get one by subscripting an array with a range, and taking one copies nothing.
let week: String[] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]let workdays = week[0..<5] // a String[:] of fivelet midweek = workdays[1..<4] // a slice of a slice: tue, wed, thuprint(midweek[0]) // tueA slice's indices start at zero and are checked against its own count, whatever lies beyond it in the buffer. Any kind of array can be passed where a T[:] parameter is wanted, so a function that only reads should usually take a slice:
fn average(_ values: F64[:]) -> F64 { var sum = 0.0 for v in values { sum += v } return values.isEmpty ? 0.0 : sum / F64(values.count)}let temps: F64[>..] = [18.0, 21.0, 24.0]print(average(temps)) // 21.0print(average(temps[1...])) // 22.5A slice is a value like the others: you can store it and return it, and it may outlive the array it came from, because it holds a reference to the buffer. It is not a borrow that freezes the array, as a Rust slice would be. Instead the two follow copy-on-write: the array copies its buffer on its next write while a slice shares it, and a write through a slice copies the slice's run. Neither sees the other's later changes.
var stock: Int[>..] = [10, 20, 30]let snapshot = stock[0..<2]stock[0] = 99 // the array copies its buffer firstprint(snapshot[0]) // 10A slice never changes its count. toArray() copies a slice's elements into a T[>..] of their own.
Ranges of an Array as Places#
A range of an array's elements is also a place you can write to. Calling a reordering member on a range changes those elements of the array, and passing a range inout lets a function change them:
fn sortAll(_ s: inout Int[:]) { s.sort()}var xs: Int[>..] = [5, 4, 3, 2, 1]sortAll(&xs[1..<4]) // [5, 2, 3, 4, 1]xs[^2...].reverse() // [5, 2, 3, 1, 4]The range is read out and written back, as a property with accessors is. The function gets a view of the range sharing the array's buffer; when it returns, the slice's elements are stored over the range, in place, and nothing is stored if the function wrote nothing. The whole array can be passed the same way, sortAll(&xs), with nothing copied at all. (inout and & are covered in Functions.)
Because the array is in use for the length of the call, passing two overlapping ranges of one array, swapRuns(&xs[0..<2], &xs[1..<3]), is an error (S3062), just as passing two elements of one array inout is.
You can also assign to a range. For most arrays the value must have as many elements as the range; a growable array can have a range replaced by any number of elements:
var fixed: Int[] = [1, 2, 3, 4]fixed[1..<3] = [8, 9] // [1, 8, 9, 4]; storing [8] here would trapvar grow: Int[>..] = [5, 2, 3, 1, 4]grow[1..<3] = [7] // [5, 7, 1, 4]: two elements replaced by oneA slice that comes back from a function with a different count than its range traps, whatever kind of array it came from, since the range is written back element by element.
Indexing From the End#
Prefix ^n is a position counted back from a collection's end: ^1 is the last element, ^2 the one before it, and ^0 the end itself. It is C#'s "hat" operator. It binds more tightly than any binary operator, so it can be a range bound without parentheses:
let xs: Int[] = [10, 20, 30, 40, 50]print(xs[^1]) // 50print(xs[^3...]) // [30, 40, 50]print(xs[1..<^1]) // [20, 30, 40]: all but the first and lastprint(xs[..<^1]) // [10, 20, 30, 40]print(xs[^2...^1]) // [40, 50]A position from the end is a FromEnd value, and a range with either bound written ^n is a RelativeRange, which each collection resolves against its own end. You can hold one and use it on several collections: let last = ^1. On an array, neither value exists at run time once optimised: what remains is arithmetic on the count and the bounds check.
A mutable collection can be written through a position from the end too:
var ys: Int[>..] = [1, 2, 3, 4]ys[^1] = 9 // [1, 2, 3, 9]ys[^2] += 1 // [1, 2, 4, 9]ys[1..<^1] = [7] // [1, 7, 9]^0 is a bound, never an element: xs[^0] is an error (S3090), and reaching it as the program runs traps. A position from the end outside the collection traps with a message such as index ^5 is out of range for count 3. Unlike Python's negative indices, counting from the end is part of the type, so a computed index that goes negative by mistake traps rather than quietly counting from the other end.
There is no unbounded range like Swift's xs[...]; the whole of an array is just xs, or xs[..<^0] as a slice.
Inline Arrays#
T[k] and T[..k] have no buffer. Their elements are wherever the array is: in a local variable's frame, in a struct field, in a class's field, in a closure's capture. An inline array is a value as a struct is. Copying it copies its elements, and there is no copy-on-write because nothing is shared.
struct Pixel { var channels: U8[4] // four bytes inside every Pixel}var recent: Int[..4] = []recent.append(1)recent.append(2)print(recent.count) // 2An inline array's size is part of its type: Int[4] and Int[5] are different types. It may take at most 64 KiB (S7004), since it is copied whole and may live on the stack. Every member of T[:] works on an inline array, which lends itself to the member where it is, so recent.sort() sorts in place with nothing copied. The full story, including how inline arrays behave inside @inline_layout types, is in Inline Layout.
A slice of plain values can also be viewed as a slice of another plain type, with nothing copied: points.reinterpreted(as: F32.self) sees an array of 3-float structs as floats, and xs.bytes sees any such array as U8s. That too is covered in Inline Layout.
Dictionaries#
A dictionary maps keys to values. Its type is written [Key: Value], short for Dictionary<Key, Value>, and its key type must be Hashable. A dictionary literal lists key-value pairs:
var stock: [String: Int] = ["lamp": 4, "desk": 2]The empty dictionary is [:] where its type is known, or [String: Int]() by calling its type:
var counts: [String: Int] = [:]var prices = [String: F64]()Note
Sable's dictionary keeps its keys in the order they were first added, unlike Swift's and Rust's, whose order is unspecified. Setting an existing key changes its value, not its place. If keys are removed, a key added later takes the place of the last one removed; OrderedDictionary keeps the order whatever is removed.
Reading and Writing#
Subscripting by a key gives an optional, none if the key is missing. Assigning a value adds or replaces it, and assigning none removes the key:
var ages: [String: Int] = ["ann": 31]ages["bob"] = 27print(ages["ann"] ?? 0) // 31print(ages["cy"] == none) // trueages["bob"] = none // removedprint(ages.count) // 1The default: subscript reads a fallback for a missing key, and writing through it updates the stored value, which makes counting easy:
var wordCounts: [String: Int] = [:]for word in "the cat and the hat".split(" ") { wordCounts[word, default: 0] += 1}print(wordCounts["the"] ?? 0) // 2Other members include contains(key), updateValue(_:forKey:) (which gives back the old value), remove(key), removeAll(), merge(_:uniquingKeysWith:), mapValues, compactMapValues, filter and retain(where:). Dictionary(grouping:by:) builds a dictionary of arrays from a sequence.
Iterating Over a Dictionary#
Iterating gives (key, value) pairs, in the dictionary's order, which you can take apart in the loop:
let menu: [String: F64] = ["tea": 2.5, "cake": 4.0, "soup": 6.0]for (dish, price) in menu { print("\(dish:<6)\(price:>6.2)")}tea 2.50cake 4.00soup 6.00Other Collections#
Sable.Collections provides the collections that are not built in. Import it with import Sable.Collections. Note which are structs, with value semantics like arrays, and which are classes, shared by reference (see Structures and Classes).
| Collection | Kind | What it is for |
|---|---|---|
List<T> |
struct | insert and remove anywhere: Swift's Array, Rust's Vec |
Set<T> |
struct | distinct values by hash, in insertion order |
OrderedSet<T>, OrderedDictionary<K, V> |
class | insertion order kept whatever is removed |
SortedSet<T>, SortedDictionary<K, V> |
struct | kept in key order, with floor, ceiling and ranges |
SmallVec<T, N> |
struct | up to N elements inline, then moves to the heap |
ArrayVec<T, N> |
struct | up to N elements inline, never more |
Deque<T> |
class | add and remove at both ends in constant time |
Queue<T>, Stack<T> |
class | enqueue/dequeue, push/pop |
PriorityQueue<T>, Heap<T> |
class | the first element by order; a heap gives both least and greatest |
BitSet |
class | small non-negative integers, a bit each |
LinkedList<T> |
struct | a doubly linked list |
FrozenSet, FrozenDictionary |
struct | built once, then looked up as fast as possible |
ImmutableList, ImmutableSet, … |
struct | persistent: copies that change cheaply share most of their structure |
Sets#
A Set holds distinct values. It has the usual set algebra:
import Sable.Collectionsvar odd = Set<Int>([1, 3, 5, 7])let small = Set<Int>([1, 2, 3])print(odd.contains(3)) // trueprint(odd.intersection(small).toArray()) // [1, 3]print(odd.union(small).toArray()) // [1, 3, 5, 7, 2]odd.insert(9)print(small.isSubset(of: odd)) // falseThere are also subtracting, symmetricDifference, the mutating formUnion, formIntersection and subtract, and isSuperset(of:), isDisjoint(with:) and their strict forms.
Lists#
List<T> is the growable array that can change anywhere: insert(_:at:), remove(at:), removeAll(where:), retain(where:), dedup(), truncate(to:), drain, replaceSubrange and swapRemove(at:). It is a struct holding a T[>..], and converts to and from one without copying:
import Sable.Collectionsvar list = List<Int>([1, 2, 4])list.insert(3, at: 2)let removed = list.remove(at: 0) // 1let array = list.toArray() // [2, 3, 4], an Int[>..], shared until changedSplitting the middle-of-the-array operations out into List is deliberate. A grow-only array is the common case and the one whose element references stay valid; making insertion a different type means you only pay for moving elements, and lose reference stability, when you ask for it.
All of these are ordinary library types built from what this book covers, mostly from arrays and Generics; none of them is special to the compiler.