Look up an element, keep a collection in order, or change its contents. Use Array for positions, Map for key-value pairs, and Set for unique elements.
Install Topaz. For collection syntax, see Collections & Comprehensions.
Use Array, Map, and Set together
Save this as collections.tpz.
import std.io
let tasks = ["draft", "check", "ship"]
let selected = tasks.get(1)
let mut scores: Map<string, int> = map {}
scores.insert("ada", 10)
scores.insert("lin", 12)
let mut labels = set { "docs" }
labels.add("tests")
io.writeLine("{selected}:{scores.get("lin")}:{scores.keys}:{labels.toArray()}")Run topaz run collections.tpz from the folder containing the file.
Some(check):Some(12):[ada, lin]:[docs, tests]tasks.get(1) finds "check", and scores.get("lin") finds 12. Each returns Some because the requested value exists. An absent index or key returns None.
scores.keys returns [ada, lin] in insertion order. labels.toArray() returns [docs, tests] in the same way. These arrays are snapshots. Adding or removing entries in the original collection does not change them.
Transform a Set or Range
Array<T> and Set<T> provide map<U>(f: (T) -> U) -> Array<U>, filter(f: (T) -> bool) -> Array<T>, and reduce<U>(initial: U, f: (U, T) -> U) -> U. Range<int> provides the same methods with T = int. Set methods use insertion order. Range methods preserve inclusive or exclusive endpoints and the written step.
The receiver and written arguments are evaluated once, from left to right, before the iterable snapshot is made. Callbacks then run sequentially until completion or the first fault. Empty reduce returns initial without invoking its callback. Map.mapValues keeps keys, and Map.filter passes both key and value to its predicate.
Choose the operation by task
| Task | Call | Result |
|---|---|---|
| Read an array position that may be absent | items.get(index) | Option<T>, with None for an invalid index |
| Read a position that must exist | items[index] | T, or a fault for an invalid index |
| Find a map key | values.get(key) | Option<V> |
| Use a default when the key is absent | values.getOr(key, default) | V |
| Check whether a set contains a value | values.contains(value) | bool |
| Copy map keys, values, or entries in order | keys, values, entries | A snapshot in insertion order |
| Transform or sort elements | map, filter, sorted | A new collection |
| Change an existing collection | A mutating method on a let mut binding | The original collection changes |
Safe reads, mutations, and faults
Array get and indexOf return Option. So do pop and removeAt, which also change the array and require let mut.
slice(start, end) copies elements from start up to, but excluding, end. It clamps the range to the array bounds. Direct indexing and an invalid insert position cause a runtime error (fault). Use get when an absent position is expected.
| Collection | Methods that change it | Methods that return a new collection |
|---|---|---|
Map | insert, remove, clear, update | mapValues, filter |
Set | add, remove, clear | union, intersection, difference, map, filter, reduce |
Map remove returns Option. Map containsKey, Set contains, and Set remove return bool.
Map mapValues and filter keep the order of surviving keys. Updating an existing key keeps its position. Removing and reinserting that key moves it to the end. Set union, intersection, and difference follow their specified element order.
These core collection methods do not return Result. If a file read or parser returns one, handle its Ok or Err before using the collection.
Correct a rejected operation
- For map key membership, use
map.containsKey(x)orx in map.keys. The checker rejectsx in map. - For a string's scalar count, use
text.scalars().length. Strings have no.lengthproperty. - If a mutating method is rejected on an immutable binding, declare that binding with
let mutwhen mutation is intended. - A Map key or Set element must support use as a key. This also applies to every nested payload or field. The checker rejects invalid types.
MapandSethave no general equality operation. Their lookup methods test individual keys or elements.
Callbacks run in the collection's specified iteration order. To handle absent values, continue with Null, Option, Result & Faults. Find other tasks in Standard Library Overview.
Sorting and large indices
Sorting values or keys containing NaN reports an error. A failed in-place sort leaves the array unchanged. Successful sorts preserve the input order of equal keys.
On a 32-bit target, a large index never wraps around to another element. Indexed writes reject an index that cannot address the collection. Array.get returns None for an out-of-range or unrepresentable index.