---
title: "Sequences"
description: "Growable lists, fixed arrays, and borrowed slices — how each is built, read, iterated, and converted."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Sequences

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](#windows). There is no `[..]T` or `Slice[T]` form; neither
spelling parses.

```atoll
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.

```atoll
fn names() []string {
    return ["Ada", "Grace", "Katherine"]
}
```

Both spellings name the same type, so they interchange freely in signatures:

```atoll
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:

```atoll
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.

```atoll
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:

```atoll
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.

```atoll
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:

```atoll fail
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:

```atoll
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.

```atoll
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:

```atoll
fn replace() int {
    mut xs := [1, 2, 3]
    xs = [4, 5]
    return xs.len()
}
```

Reassigning a non-`mut` binding is rejected:

```atoll fail
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.

```atoll
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:

```atoll
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:

```atoll
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`).

```atoll
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`:

```atoll
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:

```atoll
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`.

```atoll
fn loopback() [4]byte {
    return [127, 0, 0, 1]
}
```

The length may be a named integer constant in a local annotation:

```atoll
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:

```atoll
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:

```atoll fail
fn short() void {
    a: [3]int = [1, 2]
}
```

```atoll fail
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](#slicing-an-array).
That is all.

```atoll
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.

```atoll fail
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:

```atoll
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 `..`.

```atoll run=40
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:

```atoll refused=ATOLL2002
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 an `int` and holds nothing,
  `b[1..3].map(f).collect()` is a list of its own, and `keep(b[1..3])` is held
  to the same rule as the slice.

```atoll refused=ATOLL1115
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 mut` and `&xs[i]` on a slice are refused.

```atoll refused=ATOLL1115
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.

```atoll refused=ATOLL1115
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`:

```atoll run=5
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:

```atoll fail
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:

```atoll run=10
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:

```atoll
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.

> **There is no separate slice type**
>
> A window is not a distinct `Slice[T]` type, and neither `Slice[T]` nor
> `[..]T` parses: `xs[range]` answers a `[]T`, and `xs.get(range)` a `[]T?`. `stdlib/list.at`'s own comment
> says why one type is enough — *"a window never has to be refused growth —
> growing one detaches it, which is what a value type should do."*

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:

```atoll
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:

```atoll
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:

```atoll
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.

```atoll
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"
    }
}
```

```atoll fail
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:

```atoll
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:

```atoll
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.

```atoll
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](https://docs.atoll.workreef.dev/language/standard-library/lists/); the ownership rules that make a
slice safe to hold are in [Pointers](https://docs.atoll.workreef.dev/language/types/pointers/) and
[Values](https://docs.atoll.workreef.dev/language/types/values/).

Source: https://docs.atoll.workreef.dev/language/types/sequences/index.mdx
