Collections and sequences
Arrays
Section titled “Arrays”T[] is an array of T, growing at the end. Its methods take functions,
written as lambdas, x => x * 2:
import weaver.io.print
fn main() { var scores = [12, 7, 19, 3] scores.push(10) print("${scores.len()} scores, the first is ${scores[0]}") print("doubled: ${scores.map(s => s * 2)}") print("above 9: ${scores.filter(s => s > 9)}") print("sorted: ${scores.sorted()}, total ${scores.sum()}") print("any zero? ${scores.any(s => s == 0)}")}5 scores, the first is 12doubled: [24, 14, 38, 6, 20]above 9: [12, 19, 10]sorted: [3, 7, 10, 12, 19], total 51any zero? falseAn index is checked: scores[9] stops the program rather than read
outside the array. A named function is passed with ::,
words.map(::capitalize), or a method with its type, Char::isAsciiDigit.
Map<K, V>, in weaver.collections, maps keys to values. Reading a key
gives an optional, since the key may be missing:
import weaver.io.printimport weaver.collections.Map
fn main() { val text = "the cat saw the dog and the bird" var counts = Map<String, Int>() for word in text.split(" ") { counts[word] = (counts[word] ?? 0) + 1 } print("the: ${counts["the"] ?? 0}, fish: ${counts["fish"] ?? 0}") for word in counts.keys().sorted() { if (counts[word] ?? 0) == 1 { print("once: ${word}") } }}the: 3, fish: 0once: andonce: birdonce: catonce: dogonce: sawOrderedMap keeps the order of insertion, and Set holds values without
duplicates. A map literal is written ["ada": 36, "alan": 41], and [:]
is the empty map.
Lazy sequences
Section titled “Lazy sequences”map and filter on an array build a new array at each step. A
sequence, xs.seq(), does the work lazily instead: the steps are fused
into a single loop, as fast as one written by hand, with no intermediate
array.
import weaver.io.print
fn main() { val xs = [5, 8, 13, 21, 34, 55] val total = xs.seq().filter(x => x % 2 == 1).map(x => x * x).fold(0, (acc, x) => acc + x) print("sum of odd squares: ${total}")
val firsts = (1..).map(n => n * n).take(4).collect() print("${firsts}")
for (i, x) in xs.enumerated() { if i < 2 { print("#${i}: ${x}") } }}sum of odd squares: 3660[1, 4, 9, 16]#0: 5#1: 81.. is an open range: the sequence is infinite, and take(4) stops it.
Closures
Section titled “Closures”A lambda captures the variables it uses by value. To let it modify one,
name it in brackets, [var total]: the lambda then cannot outlive the
call it is passed to.
import weaver.io.print
fn main() { val factor = 3 val tripled = [1, 2, 3].map(x => x * factor)
var total = 0 tripled.seq().forEach([var total] x => total += x) print("${tripled}, total ${total}")}[3, 6, 9], total 18