leviathan-lang.com / docs / learn
Collections
Arrays, maps, and sets as pure values; iterating with for..in; lazy pipelines with Seq.
Collections are pure values
Array, Map, and Set are pure values. Every "changing" method returns a new collection;
you rebind to "change." This is what makes them safe to pass around: no one can mutate your array
behind your back.
Arrays
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]
int total = std::sum(nums); // 21
console.writeln(even);
console.writeln(doubled);
console.writeln(total);
nums = nums.add(7); // rebind: "nums" now ends with 7
int first = nums.first(); // 1
console.writeln(nums);
console.writeln(first);
[2, 4, 6]
[2, 4, 6, 8, 10, 12]
21
[1, 2, 3, 4, 5, 6, 7]
1
Maps
Map<K, V> is insertion-ordered and equally pure. Because get and set are keywords, the
vocabulary is at / with / without, or bracket sugar, where m[k] = v rebinds.
Maps
Map<string, int> ages; // bare declaration -> empty map
ages = ages.with("Ada", 36);
ages["Alan"] = 41; // rebind sugar
int a = ages.at("Ada"); // 36 (throws if missing)
int 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
Map<string, int> ages;
ages = ages.with("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 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
Array<int> nums = [1, 2, 3, 4, 5, 6];
Array<int> r = nums.asSeq()
.map((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.