LEVIATHAN vd52e79c4 · d52e79c486

leviathan-lang.com / docs / learn

Collections

Arrays, maps, and sets as values with in-place verbs; iterating with for..in; lazy pipelines with Seq.

Collections are values

Array, Map, and Set are values. Imperative methods (add, set, remove, clear) change the variable you call them on and return nothing; prepositional ones (with, without, concat) return a new collection. This is what makes them safe to pass around: no one can change your array behind your back, because a function only ever gets its own copy.

Arrays

use io::console;
use std;

Array<int> nums = [1, 2, 3, 4, 5, 6];
Array<int> even = nums.where((n) => n % 2 == 0);       // [2, 4, 6]
Array<int> doubled = nums.map((n) => n * 2);           // [2, 4, 6, 8, 10, 12]
Array<string> labels = nums.map(string (n) => "#" + n); // a written return type picks map's result
int total = std::sum(nums);                            // 21
console.writeln(even);
console.writeln(doubled);
console.writeln(labels);
console.writeln(total);

nums.add(7);        // in place: "nums" now ends with 7
int first;
first = nums.first();  // 1
console.writeln(nums);
console.writeln(first);
[2, 4, 6]
[2, 4, 6, 8, 10, 12]
[#1, #2, #3, #4, #5, #6]
21
[1, 2, 3, 4, 5, 6, 7]
1

Maps

Map<K, V> is insertion-ordered and a value like an array. The vocabulary is at to read, set / remove to change in place, with / without for a new map, or bracket sugar, where m[k] = v stores in place; m.set(k, v) and m.remove(k) are the verbs.

Maps

use io::console;

Map<string, int> ages;      // bare declaration -> empty map
ages.set("Ada", 36);
ages["Alan"] = 41;           // stores in place, like ages.set("Alan", 41)

int a;
a = ages.at("Ada");            // 36  (throws if missing)
int b;
b = ages.atOr("Grace", 0);     // 0   (default if missing)
console.writeln(a);
console.writeln(b);
console.writeln(ages.at("Alan"));
36
0
41

Iterating

Iterate with for..in over ranges, arrays, and map entries:

for..in over ranges, keys, and entries

use io::console;

Map<string, int> ages;
ages.set("Ada", 36);
ages["Alan"] = 41;

for (int i in 1..3) { console.writeln(i); }          // 1, 2, 3 (inclusive)

for (string k in ages.keys()) { console.writeln(k); }

for (Pair<string, int> e in ages) {                   // entries as Pair<K, V>
    console.writeln("${e.first} is ${e.second}");
}
1
2
3
Ada
Alan
Ada is 36
Alan is 41

Lazy pipelines

For big pipelines that should stay lazy, bridge into a Seq with asSeq(). Nothing runs until a terminal operation pulls:

A lazy Seq pipeline

use io::console;

Array<int> nums = [1, 2, 3, 4, 5, 6];
Array<int> r = nums.asSeq()
    .map(int (x) => x * x)
    .where((x) => x % 2 == 1)
    .take(3)
    .toArray();    // squares computed only for the 3 kept elements
console.writeln(r);
[1, 9, 25]

The full method lists are on the library pages for Array, Map, and Seq.