Skip to main content

Collections

Types & Units covered how to declare a list, map, set, or tuple. This page covers what you actually do with one once it exists.

Lists

Push and pop from either end, index directly, or use front()/back():

lists.stof
#[main]
fn main() {
  let list = [1, 2, 3];

  list.push_back(4);
  list.push_front(0);
  pln(list);

  const last = list.pop_back();
  pln(last, list);

  pln(list.front(), list.back(), list.len());
}
Output

Searching and sorting both come built in — sort_by takes a comparator that returns -1, 0, or 1:

list-search-sort.stof
#[main]
fn main() {
  let scores = [42, 7, 19, 88, 3];

  pln(scores.contains(19), scores.index_of(88));

  scores.sort();
  pln(scores);

  scores.sort_by((a: int, b: int): int => {
      if (a > b) -1
      else if (a < b) 1
      else 0
  });
  pln(scores);
}
Output

That comparator flips the usual order — returning -1 when a > b sorts largest-first instead of the default ascending.

Maps

insert, get, remove, and contains cover most of it. Iterating a map gives you (key, value) tuples:

maps.stof
#[main]
fn main() {
  let ages = {'Ada': 30, 'Grace': 34};

  ages.insert('Linus', 28);
  pln(ages.get('Ada'), ages.contains('Grace'));

  for (const pair in ages) {
      pln(pair[0], pair[1]);
  }

  ages.remove('Grace');
  pln(str(ages.keys()), ages.values());
}
Output

Sets

Same shape as a list, but every value is unique — insert reports whether the value was actually new:

sets.stof
#[main]
fn main() {
  let tags = {'core', 'stof'};

  tags.insert('runtime');
  tags.insert('core');
  pln(str(tags), tags.contains('runtime'));

  tags.remove('stof');
  pln(str(tags));
}
Output

Sets also carry the algebra you'd expect — union, intersection, difference, and a few others:

set-algebra.stof
#[main]
fn main() {
  const a = {1, 2, 3};
  const b = {2, 3, 4};

  pln(str(a.union(b)));
  pln(str(a.intersection(b)));
  pln(str(a.difference(b)));
}
Output

Tuples

Tuples are simpler by design — fixed length, indexed access, nothing to insert or remove:

tuples.stof
row: ("alpha", 1, true)

#[main]
fn main() {
  pln(self.row.len(), self.row[0], self.row.at(1));
}
Output

Control Flow already covered iterating any of these with for...in, including the implicit index/first/last variables — that part doesn't change based on which collection you're looping over.