Skip to main content

Collections

Stof has four kinds of collections: lists, maps, sets, and tuples. Each has its own library of functions, called as methods: list.push_back(4). This page covers the common ones. The full lists are in the List, Map, Set, and Tuple libraries.

Lists​

A list is an ordered sequence of any values:

lists.stofPlayground ↗
#[main]
fn main() {
  const queue = ['b', 'c'];
  queue.push_back('d');
  queue.push_front('a');
  pln(queue);

  pln(queue[0]);
  pln(queue.len());
  pln(queue.pop_back());
  pln(queue.contains('c'));
  pln(queue.join(', '));
}
Output

sort() sorts in place. sort_by takes a function that compares two items and returns a negative number, zero, or a positive number:

sort.stofPlayground ↗
#[main]
fn main() {
  const scores = [42, 7, 19, 88];
  scores.sort();
  pln(scores);

  scores.sort_by((a: int, b: int): int => b - a);    // largest first
  pln(scores);
}
Output

Maps​

A map holds values by key. Keys can be any value, but they're usually strings:

maps.stofPlayground ↗
#[main]
fn main() {
  const limits = {'calls': 100, 'seats': 5};
  limits.insert('storage', 10GB);

  pln(limits.get('calls'));
  pln(limits.contains('seats'));
  limits.remove('seats');

  for (const (key, value) in limits) {
      pln(`${key}: ${value}`);
  }
}
Output

Sets​

A set holds each value once:

sets.stofPlayground ↗
#[main]
fn main() {
  const tags = {'core', 'stof'};
  tags.insert('runtime');
  tags.insert('core');        // already there
  pln(tags.len());

  const other = {'stof', 'docs'};
  pln(str(tags.intersection(other)));
  pln(tags.union(other).len());
}
Output

Tuples​

A tuple is a fixed group of values, read by position:

tuples.stofPlayground ↗
#[main]
fn main() {
  const release = ('beta', 0.5.2, true);
  pln(release[0]);
  pln(release.len());

  const (name, version, _) = release;
  pln(`${name} ${version}`);
}
Output

Braces: Object, Map, or Set?​

Braces mean different things in different places, and it's worth knowing which:

  • In the document itself, and inside new { ... }, braces make an object: server: { port: 8080 }.
  • In an expression inside a function, braces make a map ({'a': 1}) or a set ({1, 2}).

So inside a function, create objects with new:

braces.stofPlayground ↗
#[main]
fn main() {
  const settings = new { theme: 'dark', size: 12 };    // an object
  const counts = {'dark': 3, 'light': 1};              // a map
  pln(typeof settings);
  pln(typeof counts);
  pln(settings.theme);
}
Output

Collections are shared, not copied, when you assign them. See Copied or Shared. Next, Null & Initialization.