Atoll has three sequence forms. They are not spellings of one another — each makes a different promise about growth and ownership.
| Form | Nominal type | Length | Owns storage | Has methods |
|---|---|---|---|---|
[]T |
List[T] |
runtime, growable | yes | the full list API |
[N]T |
fixed array | compile-time N |
inline value | none — indexing and slicing |
Both are homogeneous: every element has type T.
A window — xs[range] — is a []T too, sharing another list’s
block instead of owning one. It is a value of the same type, not a third form;
see Windows. There is no [..]T or Slice[T] form; neither
spelling parses.
fn shapes() int {
growable: []int = [1, 2, 3]
fixed: [3]int = [1, 2, 3]
view := growable.get(0..2)
return growable.len() + (view?.len() ?? 0) + (fixed.get(0) ?? 0)
}Lists
List[T] is the nominal type and []T is the sugar you should write. A
square-bracket literal builds one whenever the expected type is growable.
fn names() []string {
return ["Ada", "Grace", "Katherine"]
}Both spellings name the same type, so they interchange freely in signatures:
fn a(xs []int) int => xs.len()
fn b(xs List[int]) int => a(xs)
fn f() int {
return b([1, 2, 3])
}An empty literal has nothing to infer T from, so it needs either an
annotation or a later use that pins the element type:
fn annotated() int {
empty: []int = []
return empty.len()
}
fn inferred_from_use() int {
mut values := []
values.push(42)
return values.len()
}Constructors
[]T() builds an empty list, and an integer argument is a capacity hint. It
desugars to List.new[T](capacity), which you can also call directly.
fn constructors() int {
empty := []int()
buffer := []byte(4096)
same := List.new[int]()
reserved := List.new[byte](4096)
return empty.len() + buffer.len() + same.len() + reserved.len()
}Capacity reserves storage; it does not change the logical length. All four
lists above have len() == 0. Reserve up front when you know the final size,
and use reserve to extend the hint later:
fn build(count int) []int {
mut out := []int(count)
out.reserve(count)
mut i := 0
for i < count {
out.push(i * i)
i += 1
}
return out
}len() and size() are aliases; capacity() reports the reserved slot
count, which is always at least len().
Reading elements
Indexing is checked, as in Rust. xs[0] has type T and stops the
program with a trap when the index is out of range; xs.get(0) has type T?
and answers None there. Use xs[i] where the index is known to be in range
(a loop below len()), and get where it may not be.
fn reads() int {
xs := [10, 20, 30]
first := xs[0] // 10; xs[5] would trap
a := xs.get(0) ?? -1 // Option fallback operator
b := xs.get(5).unwrap_or(-1) // method form
c := match xs.get(1) {
Some(v) => v
None => 0
}
return first + a + b + c
}Forgetting that get answers an optional is a type error, not a silent coercion:
fn oops() int {
xs := [1, 2, 3]
return xs.get(0) + 1
}first() and last() are the endpoint shortcuts, and they are optional for
the same reason:
fn endpoints(xs []int) string {
lo := xs.first() ?? 0
hi := xs.last() ?? 0
return "${lo}..${hi}"
}get_unchecked(i) returns T directly and skips the bounds test. It exists
for code that has already proved the index is in range — reach for it only
behind such a proof, never as a convenience to dodge the Option.
Growing and updating
push appends, set (or xs[i] = v) overwrites an existing position. A
write past the end stops the program with a trap, as in Rust, rather than
growing the list or being ignored. try_set is the checked form: it answers
false and leaves the list unchanged when the index is out of range.
fn mutate() string {
mut xs := [1, 2]
xs.push(3)
xs.set(0, 10)
wrote := xs.try_set(99, 0) // out of range: false
return "${xs.len()} ${xs.get(0) ?? 0} ${wrote}"
}Declare the binding mut when you intend to change the list. It documents
intent at the definition site and keeps whole-value reassignment available:
fn replace() int {
mut xs := [1, 2, 3]
xs = [4, 5]
return xs.len()
}Reassigning a non-mut binding is rejected:
fn frozen() int {
xs := [1, 2, 3]
xs = [4, 5]
return xs.len()
}Transforming
The list API is built from non-mutating combinators — map, filter,
sorted_by, take, distinct, and friends return a new list and leave
the receiver alone.
fn squares_of_odds(xs []int) int {
return xs.filter(v => v % 2 == 1).map(v => v * v).sum()
}
fn top_two(xs []int) []int {
return xs.distinct().collect().sorted().take(2).collect()
}Closures take either form — v => ... as an argument, or a trailing brace
block:
fn predicates(xs []int) bool {
return xs.any(v => v > 2) && xs.all { v => v > 0 }
}partition returns a tuple of two lists, accessed positionally:
fn split(xs []int) string {
parts := xs.partition(v => v % 2 == 0)
return "${parts.0.len()} even, ${parts.1.len()} odd"
}Iterating
for walks a list element by element. for mut desugars to xs.set(i, v)
at the end of each iteration, so assigning to the loop variable updates the
list. That is not parameter write-back (ATOLL1063).
fn sum(xs []int) int {
mut total := 0
for v in xs {
total += v
}
return total
}
fn double_in_place() int? {
mut xs := [1, 2, 3]
for mut v in xs {
v = v * 2
}
return xs.get(0)
}enumerate() pairs each element with its index; the pair is a tuple, so use
.0 and .1:
fn numbered(xs []string) []string {
mut out := []string()
for pair in xs.enumerate() {
out.push("${pair.0}: ${pair.1}")
}
return out
}Nested lists iterate the same way — [][]T is just a list whose element type
is a list:
fn grid_total() int {
grid: [][]int = [[1, 2], [3, 4]]
mut total := 0
for row in grid {
for v in row {
total += v
}
}
return total
}Adding to or removing from a list while a traversal of it is live can
invalidate the traversal’s logical assumptions even though memory stays safe.
Build a new list with map/filter and collect(), or finish iterating
before you mutate.
Fixed arrays
[N]T has its length in the type. The literal must contain exactly N
elements, and each is checked against T.
fn loopback() [4]byte {
return [127, 0, 0, 1]
}The length may be a named integer constant in a local annotation:
const WIDTH = 4
fn blank_row() int {
row: [WIDTH]byte = [0, 0, 0, 0]
return row.get(0)?.to_int() ?? 0
}It names the length in a parameter or return type the same way:
const WIDTH = 4
fn blank_row() [WIDTH]byte {
return [0, 0, 0, 0]
}Both conditions are compile-time. A wrong count and a mixed element type are each rejected outright:
fn short() void {
a: [3]int = [1, 2]
}fn mixed() void {
xs := [1, "two"]
}Arrays carry no methods
This is the sharpest practical difference from a list. A fixed array supports indexing — still optional-valued — indexed assignment, and slicing. That is all.
fn array_ops() int {
mut a: [4]int = [1, 2, 3, 4]
a[1] = 20
mut total := 0
mut i := 0
for i < 4 {
total += a.get(i) ?? 0
i += 1
}
return total
}Note the loop: it counts to the literal N rather than calling len(), since
there is no len() — N is already visible in the type.
fn no_len() int {
a: [4]byte = [127, 0, 0, 1]
return a.len()
}The same is true of size, first, map, and the rest of the list API. When you want them, copy the array into a list:
fn to_list(a [4]byte) []byte {
mut out := []byte()
mut i := 0
for i < 4 {
out.push(a.get(i) ?? 0u8)
i += 1
}
return out
}for value in array type-checks, but the loop it lowers to does not currently
terminate. Until that is fixed, walk an array with the counted for condition form shown above, or convert it to a []T and iterate that.
Slicing an array
b[range] on a fixed array is a []T over the array’s own bytes: nothing is
copied, allocated or counted. The window is a compare and a few additions,
and every range form works as it does on a list — a..b, a..=b, a..,
..b, ..=b and ...
fn sum(v &[]int) int {
mut total := 0
for x in v {
total += x
}
return total
}
fn main() int {
b: [6]int = [1, 2, 3, 4, 5, 6]
return sum(b[1..3]) + sum(b[..=1]) + sum(b[4..]) + sum(b[..])
}The array’s length is part of its type, so a range written with numbers that cannot lie inside it is a compile error, naming the range and the length. A range the compiler cannot see the ends of stops the program when it is outside, as a list’s does:
fn main() int {
b: [4]int = [1, 2, 3, 4]
return b[2..7].len().to_int()
}Because the slice is the array’s memory rather than a counted block, the
compiler holds it to a rule about where it may go, the way a borrowed &T
parameter is held (ATOLL1115). It may be read, indexed, iterated, sliced
again, handed to any call and have any method called on it. It may not:
- Outlive the array. Returned, stored in a field, a block or a variable
declared outside the array’s scope, captured by a task, or handed to a
function that keeps it. A call’s result holds the slice only where the
callee’s body says it may:
sum(b[1..3])answers anintand holds nothing,b[1..3].map(f).collect()is a list of its own, andkeep(b[1..3])is held to the same rule as the slice.
fn middle() []int {
b: [4]int = [1, 2, 3, 4]
return b[1..3]
}- Be written. A write to a list that does not own its block copies the
block first, which for a slice would be an allocation nothing in the program
says.
set,push,for mutand&xs[i]on a slice are refused.
fn main() int {
b: [4]int = [1, 2, 3, 4]
mut w := b[1..3]
w[0] = 9
return w[0]
}- Show a changed array. The slice is the array as it was made. Using it after the array is written is refused; make the slice again.
fn main() int {
mut b: [4]int = [1, 2, 3, 4]
w := b[1..3]
b[1] = 7
return w[0]
}The one copy is the one the program writes. List.copy(b[1..3]) is a list of
its own that may be returned, stored, written or kept past a change to b:
fn middle() []int {
b: [4]int = [1, 2, 3, 4]
return List.copy(b[1..3])
}
fn main() int {
xs := middle()
return xs[0] + xs[1]
}An array of values that own storage ([3]string) is not sliced: a window over
owning elements must retain each of them, which is a copy. The array must be
held in a local, a parameter or a field of one — not a call’s result, a
constant (bind it first: t := TABLE), or behind a ^T.
Array types are exact
Arrays of the same element type but different lengths are different types, and an array never implicitly becomes a list:
fn coerce() void {
a: [3]int = [1, 2, 3]
xs: []int = a
}Use [N]T for protocol fields, fixed vectors, and layouts where the count is
part of the contract. Use []T whenever the length is decided at runtime.
Assigning an array to a second binding does not currently give you an
independent copy — writing through the new binding is observable through the
original. Treat an array as data you build once and read, and go through a
[]T when two bindings must diverge.
Arrays in struct fields
An array can be declared and constructed as a struct field, and indexed through the field path:
struct Ipv4 { octets [4]byte }
fn main() int {
ip := Ipv4 { octets: [10, 0, 0, 1] }
return match ip.octets.get(0) { Some(b) => b.to_int() None => -1 }
}Reading the field back through ip.octets[0] works: the program answers 10.
Declaring the field as []byte is what you want when the length is not a
protocol invariant:
struct Ipv4 { octets []byte }
fn first_octet() byte? {
ip := Ipv4 { octets: [10, 0, 0, 1] }
return ip.octets.get(0)
}Fixed arrays are at their best as locals and as parameters, where the checker enforces the count and the code reads them by index.
Windows
A window is a []T that shares another list’s block instead of owning
one. No separate buffer is allocated, and the window keeps the backing storage
valid for as long as it lives. A window that is only read (indexed, walked,
passed to a call that borrows it) counts nothing; one that is kept takes its
reference where it is kept. A window over elements that own something, a
[]string, is a copy.
Take one with xs.get(range). The range is half-open — 1..3 selects indices
1 and 2 — and an out-of-range request returns None; xs[range] is the window
itself and stops the program out of range:
fn middle_len(xs []int) int {
return xs.get(1..3)?.len() ?? 0
}A match is the usual shape when the body is more than one expression:
fn window_sum(xs []int) int {
match xs.get(1..3) {
Some(view) => {
mut total := 0
for v in view {
total += v
}
return total
}
None => return 0
}
}Windows in signatures
Take []T. A window is one, so a function that reads a contiguous run needs
no second spelling — and one that must not retain the elements says so by not
retaining them:
fn checksum(data []byte) int {
mut acc := 0
for b in data {
acc = (acc + b.to_int()) % 255
}
return acc
}
fn head(xs &[]int) (&[]int)? {
return xs.get(0..1)
}The parentheses are load-bearing. []int? parses as a list of
int?, so an optional list is written ([]int)? or Option[[]int].
The window API
A window is a []T, so it has the whole list surface. What it does not have
is an owner’s block: push and reserve on one detach it onto a block of
its own rather than writing into somebody else’s elements.
fn view_api(xs []int) string {
match xs.get(0..3) {
Some(v) => {
sub := v.get(1..2)
return "${v.len()} ${v.first() ?? 0} ${sub?.len() ?? 0} ${v.clone().len()}"
}
None => return "none"
}
}fn cannot_grow(xs []int) void {
match xs.get(0..1) {
Some(v) => v.push(9)
None => {}
}
}Re-slicing produces another window over the same backing storage; clone() is
what copies the viewed elements onto a block of their own.
A view reads what it borrows and changes none of it. To write a run of
elements, write the list, or clone() the view and write that:
fn write_through() int? {
mut xs := [1, 2, 3]
mut own := (xs.get(0..2) ?? []).clone()
own.set(0, 99)
return own.get(0)
}Growth versus views
Appending to a list may move its backing storage, so a change to the list ends
the views of it. A use of a view past the change is refused (ATOLL1097). Read
the view first, or keep a .clone() of it:
fn growth() string {
mut xs := [1, 2, 3]
seen := xs.get(0..3)?.len() ?? 0
xs.push(4)
return "view=${seen} list=${xs.len()}"
}Choosing a form
| Requirement | Type |
|---|---|
| Append, remove, or reserve | []T |
| The exact count is part of the contract | [N]T |
| Read a contiguous range without owning a buffer | xs[range], or xs.get(range) for a []T? |
| Independently owned copy of viewed elements | xs[range] then .clone() |
| Growable binary buffer | []byte |
| Borrowed binary input | []byte — a window is one |
Do not accept a list when the count is a protocol invariant — take a [N]T so
the checker enforces it.
A composed example
Everything above in one unit: a fixed-size protocol header, a growable buffer of samples, and a borrowed window handed to a pure function.
struct Reading {
sensor string
value float
}
const WINDOW = 3
fn moving_average(samples &[]float) float {
if samples.is_empty() {
return 0.0
}
mut total := 0.0
for v in samples {
total = total + v
}
return total / samples.len().to_float()
}
fn latest_window(samples &[]float) (&[]float)? {
if samples.len() < WINDOW {
return samples.get(0..samples.len().to_usize())
}
return samples.get((samples.len() - WINDOW).to_usize()..samples.len().to_usize())
}
fn format(readings []Reading) []string {
mut lines := []string()
for r in readings {
lines.push("${r.sensor}=${r.value}")
}
return lines
}
fn main() void {
mut samples := []float(8)
samples.push(1.0)
samples.push(2.0)
samples.push(6.0)
samples.push(3.0)
avg := match latest_window(samples) {
Some(w) => moving_average(w)
None => 0.0
}
for line in format([Reading { sensor: "t0", value: avg }]) {
println(line)
}
tag: [4]byte = [65, 84, 79, 76]
mut header := []byte(4)
mut i := 0
for i < 4 {
header.push(tag.get(i) ?? 0u8)
i += 1
}
println("header bytes: ${header.len()}")
}The library chapter documents the full method surface in Lists; the ownership rules that make a slice safe to hold are in Pointers and Values.