Reference

Collection Methods

Look up array elements and map keys, keep insertion order, and choose between copied results and changes to existing collections.

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.

TOPAZ
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.

Output
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

TaskCallResult
Read an array position that may be absentitems.get(index)Option<T>, with None for an invalid index
Read a position that must existitems[index]T, or a fault for an invalid index
Find a map keyvalues.get(key)Option<V>
Use a default when the key is absentvalues.getOr(key, default)V
Check whether a set contains a valuevalues.contains(value)bool
Copy map keys, values, or entries in orderkeys, values, entriesA snapshot in insertion order
Transform or sort elementsmap, filter, sortedA new collection
Change an existing collectionA mutating method on a let mut bindingThe 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.

CollectionMethods that change itMethods that return a new collection
Mapinsert, remove, clear, updatemapValues, filter
Setadd, remove, clearunion, 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) or x in map.keys. The checker rejects x in map.
  • For a string's scalar count, use text.scalars().length. Strings have no .length property.
  • If a mutating method is rejected on an immutable binding, declare that binding with let mut when 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.
  • Map and Set have 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.