List[T] — almost always written []T — is an owned, growable sequence. It is
the workhorse collection: the higher-order surface (map, filter, fold,
sorted_by, …) lives on it directly, with no separate iterator type to opt
into.
fn main() void {
mut names: []string = ["Ada", "Grace"]
names.push("Lin")
for name in names {
println(name)
}
}Construction
A literal infers its element type from its contents. An empty literal needs
context — an annotation, a parameter type, or a later push.
fn main() void {
mut empty: []int = []
mut sized := List.new[int](64)
mut fresh := List.new[string](8)
original := [1, 2, 3]
duplicate := List.copy(original)
empty.reserve(16)
sized.push(1)
fresh.push("x")
println("${empty.len()} of ${empty.capacity()}")
println("${sized.len()} ${fresh.len()} ${duplicate.len()}")
}List.new[T](capacity) and List.with_capacity[T](capacity) both create an
empty list with room reserved; the capacity argument never changes the length,
and one past what a single block can hold stops the program with a trap.
List.copy(other) produces an independent list and never picks a capacity
smaller than the source. reserve(additional) grows the backing storage of an
existing list without changing what len() reports.
Access returns an Option
Indexing is bounds-checked, as in Rust. xs[i] answers the element and stops
the program with a trap when i is out of range; xs.get(i) answers an
Option, None past the end. The test is one compare and a branch to a trap
laid out cold, so an in-range xs[i] costs the load. The trap says
index out of range and where (see
Panics).
fn main() void {
xs := [10, 20, 30]
head: int = xs[0]
past_end: int? = xs.get(99)
println("${head} ${past_end ?? -1}")
}get is the read whose answer may be absent, so treating it as a bare value
is a type error:
fn first(xs []int) int {
return xs.get(0)
}Discharge it with ??, unwrap_or, or a match, depending on how much the
absent case deserves to be said out loud:
fn total_or_zero(xs []int) int {
return xs.get(0) ?? 0
}
fn label(xs []string) string {
match xs.first() {
Some(name) => return "first is ${name}"
None => return "empty"
}
}
fn main() void {
println("${total_or_zero([])} ${total_or_zero([7])}")
println(label([]))
println(label(["Ada"]))
}| Method | Out-of-range behavior |
|---|---|
xs[index], &xs[index] |
stops the program with a trap |
get(index), &xs.get(index) |
None |
first(), last() |
None on an empty list |
set(index, value), xs[index] = value |
stops the program with a trap — never extends the list |
try_set(index, value) |
false, list unchanged |
get_unchecked(index) |
caller must prove the index is valid |
Index arguments are usize, on a list and on a string’s bytes alike.
xs[index] also takes an int or any other integer, and so does each end
of a range, in xs[a..b] and passed to get: xs[1..xs.len() - 1] reads
as written. A negative one is out of range, and traps as one does. A method
that takes one index (get, set) needs .to_usize().
fn head_unchecked(xs []int) int {
if xs.is_empty() { return 0 }
// SAFETY: the emptiness check above covers index 0.
return unsafe { xs.get_unchecked(0) }
}
fn at(xs []int, position int) int {
return xs.get(position.to_usize()) ?? -1
}
fn main() void {
println("${head_unchecked([])} ${head_unchecked([5, 6])}")
println("${at([5, 6], 1)} ${at([5, 6], 9)}")
}Inspection methods are len, capacity, is_empty, and
is_not_empty. Mutation is push, set, try_set, reserve, and clear;
push appends, as Rust’s Vec::push does (it was push, and a call by that
name is ATOLL2114, which names push). There is no insert or remove_at.
A write past the end is a bug, as in Rust: xs.set(99, 0) or xs[99] = 0 on
a shorter list stops the program with a trap. Where an index may be out of
range, try_set answers whether it wrote:
fn main() void {
mut xs := [1, 2, 3]
xs.push(4)
xs.set(0, 10)
ok := xs.try_set(99, 0) // out of range: false, list unchanged
println("${ok} ${xs.len()} ${xs.get(0) ?? 0} ${xs.is_not_empty()}")
xs.clear() // length 0, capacity retained
println("${xs.len()} of ${xs.capacity()}")
}Removal is pop (the last element), take_at(i) (shifting the rest down) and
swap_remove(i) (moving the last element into the hole, so the order changes).
retain(keep) drops every element keep does not hold for and keeps the rest
in their order: items.retain((x &Item) => x.id != gone). Each of the first
three answers the element it took, or None when there is none — an empty list,
or an index past the end. They are the reads that move: the element leaves
the list rather than being copied out, which is how a list of values that may
not have a second name, such as tasks, is drained.
A list is written where it is: push, set and these reads find the storage
their name owns. A parameter owns what it is given, so mut rest := xs inside a
function takes the caller’s list, and a caller that goes on reading its list
after the call is refused, and passes a .clone() instead:
fn drain(xs []int) int {
mut rest := xs
mut total := 0
for Some(x) := rest.take_at(0) {
total = total * 10 + x
}
return total
}
fn main() void {
xs := [1, 2, 3]
println("${drain(xs.clone())} ${xs.len()}") // 123 3 — the caller's list is whole
mut ys := [4, 5, 6]
last := ys.pop() ?? 0
first := ys.swap_remove(0) ?? 0
println("${last} ${first} ${ys.get(0) ?? 0} ${ys.len()}") // 6 4 5 1
}Membership uses contains, index_of, and last_index_of; the two position
methods return Index?.
fn position(names &[]string, wanted string) int {
match names.index_of(wanted) {
Some(i) => return i.to_int()
None => return -1
}
}
fn main() void {
names := ["ada", "lin", "grace", "ada"]
println("${position(names, "lin")} ${position(names, "zoe")}")
println("${names.contains("ada")}")
match names.last_index_of("ada") {
Some(i) => println("last ada at ${i.to_int()}")
None => println("no ada")
}
}Mapping and filtering
map yields whatever the closure returns; filter keeps the elements the
predicate accepts. Both are lazy: they answer an iterator that does
nothing until something consumes it — a for loop, a terminal such as
sum, count or join, or collect(), which builds the list. Neither
touches the receiver. A chain consumed where it is written runs as one loop,
each element through every step in turn (see
Iteration).
struct User { id int, name string, active bool }
fn active_names(users []User) []string {
return users
.filter(u => u.active)
.map(u => u.name.clone()).collect()
}
fn main() void {
users := [
User { id: 1, name: "ada", active: true },
User { id: 2, name: "lin", active: false },
User { id: 3, name: "grace", active: true }
]
for name in active_names(users) {
println(name)
}
}flat_map maps each element to a list and yields the elements of each in
turn, which is how you flatten a one-to-many relationship in a single pass.
On a list of lists, flatten() is the same with no function.
struct Order { id int, items []string }
fn every_item(orders &[]Order) []string {
return orders.flat_map(o => o.items.clone()).collect()
}
fn merge(pages [][]int) []int {
return pages.flat_map(page => page.clone()).collect()
}
fn main() void {
orders := [Order { id: 1, items: ["bolt", "nut"] }, Order { id: 2, items: ["nut", "washer"] }]
println("${every_item(orders).len()}")
println("${every_item(orders).distinct().collect().sorted().len()}")
println("${merge([[1, 2], [3]]).len()}")
}Closures accept either the arrow form or a brace block, which reads better for a multi-line body:
fn expensive(prices []float) []float {
return prices.filter { p =>
adjusted := p * 1.2
adjusted > 100.0
}.collect()
}
fn main() void {
println("${expensive([50.0, 100.0, 200.0]).len()}")
}Pipelines
Chaining is the point. A filter narrows, a sort orders, a window bounds, and a
map renders — each step readable on its own line. The lazy steps build
nothing; sorted_by_descending needs every element at once, so the chain
collects the filtered users into a list before it, and join consumes what
follows.
struct User { name string, active bool, score int }
fn leaderboard(users []User, top int) string {
return users
.filter(u => u.active).collect()
.sorted_by_descending(u => u.score)
.take(top)
.map(u => "${u.name} (${u.score})")
.join(", ")
}
fn main() void {
users := [
User { name: "ada", active: true, score: 93 },
User { name: "lin", active: false, score: 99 },
User { name: "grace", active: true, score: 97 }
]
println(leaderboard(users, 2)) // grace (97), ada (93)
}join(sep) needs T: Display; join_of(sep, f) takes the rendering function
instead and so works on any element type. join_with(sep, f) hands f the
joined string to write each element into, fn(&T, &mut string) -> void, so
no element is rendered apart from it whatever f does:
struct User { name string, score int }
fn main() void {
users := [User { name: "ada", score: 93 }, User { name: "lin", score: 7 }]
line := users.join_with(", ", (u, out) => {
out.append(u.name)
if u.score > 50 { out.append(" (top)") }
})
println(line) // ada (top), lin
}Folding and scanning
fold and reduce are the same operation under two names: both take an
explicit initial accumulator and thread it left to right.
fn total(values []int) int {
return values.fold(0, (acc, v) => acc + v)
}
fn longest(names []string) string {
return names.fold("", (best, name) => if name.len() > best.len() { name.clone() } else { best })
}
fn main() void {
println("${total([1, 2, 3])} ${longest(["a", "abc", "ab"])}")
}A fold is not limited to scalars — it is the general way to build any summary value in one pass:
struct Stats { count int, sum float, max float }
fn summarize(samples []float) Stats {
return samples.fold(
Stats { count: 0, sum: 0.0, max: 0.0 },
(s, v) => Stats { count: s.count + 1, sum: s.sum + v, max: s.max.max(v) }
)
}
fn main() void {
s := summarize([1.5, 4.0, 2.25])
println("${s.count} ${s.sum} ${s.max}")
}scan returns every intermediate accumulator, with the initial value as its
first element — so a scan of n elements has n + 1 results.
fn running_balance(deltas []int) []int {
return deltas.scan(0, (balance, d) => balance + d).collect()
}
fn main() void {
for v in running_balance([10, -3, 5]) {
println("${v}") // 0, 10, 7, 12
}
}Predicates and search
any, all, and none short-circuit as soon as the answer is known. find
returns the first matching element as an Option, find_index returns its
position, and count(predicate) is filter(...).len() without the intermediate
list.
struct Ticket { name string, done bool, priority int }
fn next_ticket(tickets &[]Ticket) string {
return tickets
.find(t => !t.done)
.map(t => t.name.clone())
?? "nothing left"
}
fn main() void {
tickets := [
Ticket { name: "deploy", done: false, priority: 9 },
Ticket { name: "write docs", done: true, priority: 3 }
]
println("${tickets.all(t => t.done)}") // false
println("${tickets.any(t => !t.done && t.priority > 8)}") // true
println("${tickets.none(t => t.priority > 100)}") // true
println("${tickets.count(t => !t.done)} open")
println(next_ticket(tickets))
match tickets.find_index(t => !t.done) {
Some(i) => println("blocked at ${i.to_int()}")
None => println("clear")
}
}Enumerating
enumerate() and zip_with_index() both pair each element with its Index. In
a for loop the pair destructures into two bindings; used as a value it stays a
tuple with .0 and .1.
fn numbered(names []string) []string {
mut out: []string = []
for i, name in names.enumerate() {
out.push("${i + 1}. ${name}")
}
return out
}
fn main() void {
for line in numbered(["alpha", "beta"]) {
println(line)
}
for pair in ["alpha", "beta"].enumerate() {
println("${pair.0} -> ${pair.1}")
}
}zip(other) — pairing two different lists positionally — is declared but does
not lower. Walk the shorter length by index:
fn scoreboard(names []string, scores []int) []string {
mut out: []string = []
n := if names.len() < scores.len() { names.len() } else { scores.len() }
mut i := 0
for i < n {
name := names.get(i.to_usize()) ?? ""
score := scores.get(i.to_usize()) ?? 0
out.push("${name}: ${score}")
i = i + 1
}
return out
}
fn main() void {
for row in scoreboard(["ada", "lin", "grace"], [93, 88]) {
println(row) // stops after two rows
}
}Aggregates
| Method | Result | Requirement |
|---|---|---|
sum() |
T |
T: Numeric |
sum_of(f) |
R |
R: Numeric |
average() |
float (NAN when empty) |
T: Numeric |
try_average() |
float? (None when empty) |
T: Numeric |
min(), max() |
T? |
T: Comparable[T] |
min_by(f), max_by(f) |
T? |
key K: Comparable[K] |
min_of(f), max_of(f) |
K? |
key K: Comparable[K] |
min and max are optional because an empty list has neither. The _by
variants return the element with the extreme key; the _of variants return
the key itself.
struct Product { name string, price float, stock int }
fn inventory_report(products &[]Product) string {
total_value := products.fold(0.0, (acc, p) => acc + p.price * p.stock.to_float())
mut cheapest := "n/a"
match products.min_by(p => p.price) {
Some(p) => cheapest = p.name.clone()
None => {}
}
highest := products.max_of(p => p.price) ?? 0.0
return "value=${total_value} cheapest=${cheapest} max=${highest}"
}
fn main() void {
products := [
Product { name: "bolt", price: 0.25, stock: 400 },
Product { name: "gear", price: 12.5, stock: 12 }
]
println(inventory_report(products))
println("${products.count(p => p.stock > 100)} well-stocked")
println("${products.sum_of(p => p.stock)} units")
}sum_of over an int projection lowers; over a float projection the backend
currently miscompiles it, so use map(f).sum() or a fold for float totals, as
above.
Ordering
sorted, sorted_descending, sorted_by, and sorted_by_descending all
return new lists; the receiver is never reordered. sorted_by takes a key
function, not a comparator.
All four are a stable merge sort — n log n comparisons, and elements that
compare equal keep the order they had. sorted_by computes the key as it
compares, so a key that is expensive to compute is worth storing in the
elements first.
struct Employee { name string, dept string, salary int }
fn by_salary(staff &[]Employee) []&Employee {
return staff.sorted_by_descending(e => e.salary)
}
fn main() void {
staff := [
Employee { name: "lin", dept: "eng", salary: 180 },
Employee { name: "ada", dept: "eng", salary: 210 }
]
for e in by_salary(staff) {
println("${e.name} ${e.salary}")
}
for e in staff.sorted_by(e => e.name.clone()) {
println(e.name)
}
}sorted() and sorted_descending() sort elements directly, which needs
Comparable[T]. Numbers and strings have it, and so do a struct whose fields
all have it and an enum whose payloads do, field by field or variant by
variant. For a different order, write the impl:
struct Version { major int, minor int }
impl Comparable[Version] for Version {
fn compare_to(&self, other Version) Ordering {
return self.major.compare_to(other.major).then(self.minor.compare_to(other.minor))
}
}
fn main() void {
vs := [
Version { major: 1, minor: 4 },
Version { major: 2, minor: 0 },
Version { major: 1, minor: 12 }
]
for v in vs.sorted() {
println("${v.major}.${v.minor}")
}
match vs.sorted_descending().first() {
Some(v) => println("newest ${v.major}.${v.minor}")
None => println("none")
}
}reversed() returns an iterator rather than a list — walk it with for or
collect it yourself.
fn countdown(xs []int) []int {
mut out: []int = []
for v in xs.reversed() {
out.push(v)
}
return out
}
fn main() void {
for v in countdown([1, 2, 3]) {
println("${v}")
}
}Windows
take, take_last, take_while, skip, skip_last, and skip_while clamp
rather than failing when n exceeds the length. take_last and skip_last
answer a window over the list’s own elements, as xs[a..b] does, copying
nothing for elements that own no storage (clone() detaches one); the rest are
lazy iterators, and .collect() builds the list.
fn main() void {
scores := [4, 9, 1, 7]
println("${scores.sorted_descending().take(2).collect().len()}") // 2
println("${scores.take_last(2).len()}") // 2
println("${scores.skip(1).collect().len()}") // 3
println("${scores.skip_last(1).len()}") // 3
println("${scores.take_while(v => v > 0).collect().len()}") // 4
println("${scores.skip_while(v => v > 2).collect().len()}") // 3
println("${scores.take(99).collect().len()}") // 4 — clamped
lines := ["# header", "# more", "body"]
for l in lines.skip_while(l => l.starts_with("#")) {
println(l)
}
}chunked(size) cuts a list into consecutive blocks; windowed(size, step)
slides a window across it. A trailing partial chunk is kept, and a window that
would run off the end is not produced. A size (or step) of zero or less
stops the program with a trap.
fn moving_average(samples []float, width int) []float {
return samples
.windowed(width, 1)
.map(w => w.sum() / width.to_float()).collect()
}
fn main() void {
for batch in [1, 2, 3, 4, 5].chunked(2) {
println("${batch.len()}") // 2, 2, 1
}
for v in moving_average([1.0, 2.0, 3.0, 4.0], 2) {
println("${v}") // 1.5, 2.5, 3.5
}
}Slices
xs[a..b] is a half-open view over the parent’s storage, which is another
list rather than a type of its own, and xs.get(a..b) answers it as a
List[T]?. It allocates nothing, so List.copy is what makes the bytes
outlive the parent.
fn middle_sum(xs []int) int {
match xs.get(1..3) {
None => return 0
Some(view) => {
head := view.first() ?? 0
tail := view.last() ?? 0
return head + tail + view.len()
}
}
}
fn owned_copy(xs []int) []int {
match xs.get(0..2) {
None => return []
Some(view) => return List.copy(view)
}
}
fn main() void {
println("${middle_sum([1, 2, 3, 4])}")
println("${middle_sum([1])}") // 0 — range past the end
println("${owned_copy([1, 2, 3]).len()}")
}get(range) returns None when start > end or the end lies past the length, and
xs[range] stops the program there, as xs[index] does.
A range may leave an end out, as in Rust: xs[a..] runs to the end, xs[..b]
and xs[..=b] start at the first element, and xs[..] is the whole list.
Each stops the program or answers None in the same cases as the closed form
with the same bounds. A fixed array has no view, so a range of one is refused;
index its elements, or copy it into a list first.
The view is a List[T] whose cap == 0: same methods as any list, and a
grow or unique-write detaches from the parent rather than mutating it.
List.copy(view) is the owned copy. There is no Slice[T] type.
A view ends when its parent changes
A view borrows its parent, as &xs[i] does. A change to the parent ends the
borrow, and a use of the view past it is refused (ATOLL1097):
fn main() void {
mut xs: []int = [1, 2, 3]
v := xs[0..2]
xs.push(4) // the borrow ends here
println("${v.len()}") // refused: a use past the change
}What is refused is the use, not the view: one you have finished with costs
nothing, and rest = rest[1..] walks a view down without borrowing anything new.
To keep what a view shows past a change, say so with v.clone(). A view
handed to the call that writes its parent is refused too (ATOLL1113):
xs.extend(xs[0..2]) takes xs[0..2].clone().
Grouping and indexing
| Operation | Result | Status |
|---|---|---|
partition(predicate) |
([]T, []T) — matching, then non-matching |
lowers |
associate_by(key) |
Map[K, T] keyed by each element; last duplicate wins |
lowers |
distinct() |
keeps the first occurrence | lowers |
to_set() |
Set[T] |
lowers |
group_by(key) |
Map[K, []T] |
lowers |
associate(pair) |
Map[K, V] from returned (key, value) tuples |
lowers |
distinct_by(key) |
keeps the first occurrence per key | lowers |
partition returns a tuple that destructures into two bindings:
struct Record { id int, valid bool }
fn split(records []Record) string {
good, bad := records.partition(r => r.valid)
return "${good.len()} accepted, ${bad.len()} rejected"
}
fn main() void {
println(
split(
[
Record { id: 1, valid: true },
Record { id: 2, valid: false },
Record { id: 3, valid: true }
]
)
)
}associate_by builds an index for repeated lookup keyed by the element itself.
associate is the general form: the function returns the (key, value) pair,
so the value need not be the element.
struct Node { id int, label string }
fn labels(nodes &[]Node) Map[int, string] {
return nodes.associate(n => (n.id, n.label.clone()))
}
fn main() void {
nodes := [Node { id: 7, label: "root" }, Node { id: 9, label: "leaf" }]
println(labels(nodes).get(7) ?? "missing")
match nodes.associate_by(n => n.id).get(9) {
Some(n) => println(n.label)
None => println("missing")
}
}group_by is the one-pass form of the same idea, and it is what the two
examples below would otherwise be written around. Filtering per distinct key is
still the clearest thing to write when the keys are few, the list is small, and
the totals are what you want rather than the groups:
struct Sale { region string, amount float }
fn regional_totals(sales []Sale) []string {
mut out: []string = []
for region in sales.map(s => s.region.clone()).distinct().collect().sorted() {
group := sales.filter(s => s.region == region).collect()
total := group.map(s => s.amount).sum()
out.push("${region}: ${total} over ${group.len()} sales")
}
return out
}
fn main() void {
sales := [
Sale { region: "emea", amount: 120.0 },
Sale { region: "amer", amount: 80.0 },
Sale { region: "emea", amount: 45.5 }
]
for line in regional_totals(sales) {
println(line)
}
}For a large list, group_by does it in one pass:
struct Sale { region string, cents int }
fn group_by_region(sales &[]Sale) Map[string, []&Sale] {
return sales.group_by(s => s.region.clone())
}
fn main() void {
sales := [
Sale { region: "emea", cents: 12000 },
Sale { region: "amer", cents: 8000 },
Sale { region: "emea", cents: 4550 }
]
for region, group in group_by_region(sales) {
println("${region}: ${group.sum_of(s => s.cents)} over ${group.len()}")
}
}Combining lists
plus, plus_all, minus, intersect, union, and subtract all return
new lists and leave both operands alone. The set-like three require elements
with equality and hashing.
fn main() void {
a := [1, 2, 3]
b := [3, 4]
println("${a.plus(99).len()}") // 4
println("${a.plus_all(b).len()}") // 5 — duplicates kept
println("${a.minus(1).len()}") // 2
println("${a.intersect(b).len()}") // 1
println("${a.union(b).len()}") // 4 — deduplicated
println("${a.subtract(b).len()}") // 2
println("${[3, 1, 3, 2].to_set().len()}") // 3 — the bridge to Set
}union deduplicates; plus_all does not. minus(item) removes elements equal
to item.
Taking a list apart
drain() takes a list apart in order, handing each element over, and the list
goes with it — nothing is left to name it. What a loop leaves untaken is dropped
with the drain.
fn main() void {
names := ["ada", "brian"]
for n in names.drain() {
println("took ${n}")
}
}for x in xs lends each element — the loop’s name is the element where it
sits, and the list keeps it. drain() is for a loop that keeps what it is
handed. Giving a lent element away takes a copy, and a list of values that
cannot be copied — tasks, open files — has none to give (ATOLL1089), so
for t in tasks.drain() hands each one over instead. One element comes out
with pop() or take_at(i).
xs.extend(other) reads other and clones each element onto xs, so the
element must be Clone. xs.append(other) takes other and moves its elements,
cloning nothing and growing once: use it for a list you are finished with.
Mutating in place
for mut v in list desugars to list.set(i, v) at the end of each
iteration, which avoids building a second list when the transformation is
the point. That is not parameter write-back (ATOLL1063).
fn scale(values &mut []int, factor int) void {
for mut v in values {
v = v * factor
}
}
fn main() void {
mut values := [1, 2, 3]
scale(&mut values, 10)
for v in values {
println("${v}")
}
}update and replace hand an element over rather than reading a second
reference to it. That is what lets a list held in a list grow where it is —
xs[i] followed by xs.set(i, …) makes the element shared, and its push then
copies it first:
fn main() int {
mut buckets: [][]int = [[], [], []]
mut i := 0
for i < 7 {
buckets.update((i % 3).to_usize(), b => {
mut grown := b
grown.push(i)
grown
})
i = i + 1
}
taken := buckets.replace(2, []) ?? []
return (buckets.get(0) ?? []).len() * 100 + (buckets.get(1) ?? []).len() * 10 + taken.len()
}update(i, f) stores f(element) back; replace(i, v) puts v there and
answers what it took out. Past the end, replace answers None and keeps
nothing, update stops the program with a trap, and try_update(i, f) answers
false without calling f.
update hands the element over where nothing but the list’s own name reaches
the list: a local, or a field of one, that no closure captures and no &
takes. Where f could reach it some other way — through a ^ pointer to what
holds it, or as a local a closure shares — update reads the element as
xs[i] does and stores f’s answer as set does, after f has run. f then
sees the list whole, what it does to the list stays, and the answer lands in
the list as f left it, or nowhere if f shortened it past i:
struct Box { xs []int }
struct Holder { b ^Box }
fn main() int {
b := ^Box { xs: [1, 2, 3] }
h := ^Holder { b: b }
mut m := b
m.xs.update(0, v => {
mut w := h.b
mut i := 0
for i < 100 {
w.xs.push(i)
i = i + 1
}
v + 10
})
return b.xs.len().to_int() * 1000 + (b.xs.get(0) ?? 0)
}A list held in a field
A list in a struct field is mutated through the field, at any depth, and the
struct needs no ^ and no wrapper — only a mut binding:
struct Basket { items List[int] }
fn main() int {
mut b: Basket = Basket { items: [] }
b.items.push(9)
b.items.push(8)
e0: int = match b.items.get(0) { Some(v) => v None => -1 }
e1: int = match b.items.get(1) { Some(v) => v None => -1 }
return b.items.len() * 100 + e0 * 10 + e1
}A second value of the struct is a clone: snapshot: Basket = b.clone() holds a
list of its own, and b.items.push(…) leaves it with the elements it had.
The same holds inside a &mut self method, through a &mut parameter, through
a ^T, and through nested fields (b.inner.c.items.push(9)). What is refused
is a receiver with no name at its root — make().items.push(9) — where there
is nothing for the write to reach.
A &mut borrow needs a mutable place at the call site — &mut of a literal
is rejected. There is no index-based remove or insert, so build a
new list with filter when elements have to go:
fn drop_blanks(lines &[]string) []&string {
return lines.filter(l => l.trim().is_not_empty()).collect()
}
fn main() void {
for l in drop_blanks(["a", " ", "b"]) {
println(l)
}
}A worked example
An order-analysis pipeline: parse, validate, aggregate per key, sort, and render, with every intermediate an ordinary list. Money is held as integer cents, per the advice in Numbers.
struct Order { id int, customer string, region string, cents int }
error ReportError { NoOrders }
fn parse(rows &[]string) []Order {
mut orders: []Order = []
for i, row in rows.enumerate() {
fields := row.split(",").map(f => f.trim()).collect()
if fields.len() != 3 { continue }
match (fields.get(2) ?? "").to_int().ok() {
None => continue
Some(cents) => orders.push(
Order {
id: i.to_int()
customer: (fields.get(0) ?? "").clone()
region: (fields.get(1) ?? "").clone()
cents: cents
}
)
}
}
return orders
}
fn top_customers(orders &[]Order, n int) []string {
return orders
.map(o => o.customer.clone())
.distinct()
.map(name => (name, orders.filter(o => o.customer == name).sum_of(o => o.cents))).collect()
.sorted_by_descending(pair => pair.1)
.take(n)
.map(pair => "${pair.0}: ${pair.1} cents").collect()
}
fn regional_share(orders &[]Order) []string ! ReportError {
if orders.is_empty() { error NoOrders }
grand_total := orders.sum_of(o => o.cents)
mut out: []string = []
for region in orders.map(o => o.region.clone()).distinct().collect().sorted() {
region_total := orders.filter(o => o.region == region).sum_of(o => o.cents)
out.push("${region}: ${100 * region_total / grand_total}%")
}
return out
}
fn main() void {
rows := ["ada, emea, 12000", "lin, amer, 8050", "ada, emea, 4525", "malformed row"]
orders := parse(rows)
println(top_customers(orders, 2).join("\n"))
match regional_share(orders) {
Ok(lines) => println(lines.join("\n"))
Err(e) => println("no orders")
}
match regional_share([]) {
Ok(lines) => println(lines.join("\n"))
Err(e) => println("no orders")
}
}Availability
join, join_of, group_by, chunked, windowed, associate, zip,
flatten, distinct_by and shuffled all have bodies in stdlib/list.at
and all compile end to end, measured by calling each one from main and
running the whole pipeline. Use them.
Two of them have signatures worth knowing:
| Signature | What to know |
|---|---|
flatten() |
defined on [][]T only, and lazy like flat_map(x => x): .collect() makes the []T. |
shuffled() |
lowers, but the stdlib has no seedable RNG, so the order is not reproducible between runs. |
Two further shapes type-check but hit backend bugs rather than a missing lowering, so avoid them for now:
sum_of(f)wherefreturns afloat— usemap(f).sum()orfold.average()on a[]float— divide asum()bylen().to_float().
Everything else on list.at — push, set, clear, reserve, get,
first, last, map, filter, flat_map, fold, reduce, scan, any,
all, none, find, find_index, count, enumerate, zip_with_index,
sum, sum_of, average, min, max, min_by, max_by, min_of,
max_of, sorted*, reversed, take*, skip*, slice, partition,
associate_by, distinct, intersect, union, subtract, plus,
plus_all, minus, to_set — compiles.
Related pages
Iteration covers the Iterator and
Iterable traits behind for, and Sequences
covers the []T / [N]T type syntax. A window is []T with cap == 0,
not a [..]T type.
Verified behaviour
Executed by the compiler’s own test suite, heap checked back to zero.
fn main() int {
mut xs: List[int] = [1, 2]
xs.push(3)
return xs.len()
}fn main() int {
mut xs: List[int] = [1, 2]
xs.set(0, 9)
return match xs.get(0) { Some(v) => v None => 0 - 1 }
}fn main() int {
xs: List[int] = [1, 2, 3]
if xs.contains(2) { return 1 }
return 0
}fn main() int {
xs: List[string] = ["ab", "cde"]
return match xs.get(1) { Some(s) => s.len() None => 0 }
}fn main() int {
xs: List[string] = ["a", "bc", "def"]
ys := xs.clone()
return ys.len() * 100 + ys[2].len() * 10 + xs[0].len()
}Known gaps
for … inover a list is not a gap: it lowers, and everyforon this page is compiled by the gate that runs it.- A list of structs, where the struct holds a closure, is refused: a closure’s environment carries no shadow count, so the cycle scan will not walk one. A list of function values is fine.
- There is no
remove.filter,minusandsubtractare what exist.