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

# Programs

> A program file: fn, let and var, when and match, for each and while, int, float, bool and text, enums with columns, result and try, lists, maps and sets, records with methods, text methods, and print. mz run lowers it to a dependency-free Rust package, builds it and runs it. RFC-0013's slice on the language's main branch since 8 October 2026: numbers, control flow, errors, collections, records and text methods.

> [!NOTE]
>
> Everything on this page is **built and tested**: cross-checked against the language's
> `compiler/src`, `mz harness definition`, and the example programs CI runs through `mz run`
> with their output compared, at language `main` `f9bea2b`, tagged `v0.13.0` (the release of 1 November 2026,
> [mzizi#146](https://github.com/mzizi-dev/mzizi/pull/146); `compiler/`, `examples/` and `primitives/` are unchanged since `v0.12.0`, `9766929`, the release of 29 October,
> [mzizi#140](https://github.com/mzizi-dev/mzizi/pull/140)). On 29 October each
> example, run with `mz run` from `v0.12.0`, printed exactly its `.expected` file. The fourth
> release of 8 October 2026 (tagged `v0.8.0`, [mzizi#109](https://github.com/mzizi-dev/mzizi/pull/109)) carried the
> rest of the text operations from [mzizi#106](https://github.com/mzizi-dev/mzizi/pull/106).
> The third release of that day ([mzizi#104](https://github.com/mzizi-dev/mzizi/pull/104), tagged
> `v0.7.0`) carried collections and records from
> [mzizi#99](https://github.com/mzizi-dev/mzizi/pull/99),
> [mzizi#101](https://github.com/mzizi-dev/mzizi/pull/101) and
> [mzizi#102](https://github.com/mzizi-dev/mzizi/pull/102), and the first text methods from
> [mzizi#98](https://github.com/mzizi-dev/mzizi/pull/98). The first release of that day
> ([mzizi#91](https://github.com/mzizi-dev/mzizi/pull/91)) brought the functions, numbers,
> control flow and errors. It is a slice of
> [RFC-0013](https://github.com/mzizi-dev/mzizi/blob/main/design/RFC-0013-core-language.md),
> not all of it: the rest of the RFC is design, and [what is not built](#what-is-not-built)
> lists it. The tracker rows these features belong to are C1–C10, every one ✅ in the file, so
> M1 is met on `main` ([what still has to be built](https://docs.mzizi.dev/tracker.md)).

A **program** is a Mzizi file that runs. Its first line is `program <name>` and its last is
`end program <name>`. It holds `fn`s and, since control flow landed, `enum`s; every statement
lives inside a `fn`. Exactly one `fn main`, with no parameters, is the entry point, and a
program's output is what it prints. One program per file.

`mz run` checks a program, lowers it to a Rust package with no dependencies, builds it with
Cargo and runs it. `mz build` writes the same package. A program is the second thing in Mzizi
that lowers to Rust, after a `service`; no component lowers.

## The smallest program

`examples/hello.mz`, verbatim:

```mz examples/hello.mz theme={null}
## The smallest program: one line of output (RFC-0013 §1, tracker row C10).
## `mz run examples/hello.mz` prints `hello, world`; CI compares it with hello.expected.
program hello

  fn main
    print("hello, world")
  end fn main

end program hello
```

```text theme={null}
$ mz run examples/hello.mz
hello, world
```

## Functions, bindings and `when`

`examples/fib.mz`, verbatim. It recurses, binds with `let` and `var`, assigns, branches with
`when` and `else`, and interpolates.

```mz examples/fib.mz theme={null}
## Fibonacci numbers by recursion, in RFC-0013's foundation slice (§18.1): functions,
## calls, `let`, `var`, `when`, integer arithmetic and `print`, and no loops yet.
## `mz run examples/fib.mz` prints what fib.expected holds; CI compares the two.
program fib

  fn main
    print("fib(9) is {fib(9)}")
    let n = 20
    let f = fib(n)
    print("fib({n}) is {f}")
    var total = 0
    total = total + fib(10)
    total = total + fib(11)
    print("fib(10) + fib(11) is {total}, and that is fib(12): {total is fib(12)}")
    print(parity(f))
  end fn main

  fn fib(n: int): int
    when n < 2
      return n
    end
    return fib(n - 1) + fib(n - 2)
  end fn fib

  fn parity(n: int): text
    when n % 2 is 0 and n > 0
      return "{n} is even"
    else
      return "{n} is odd, or not positive"
    end
  end fn parity

end program fib
```

```text examples/fib.expected theme={null}
fib(9) is 34
fib(20) is 6765
fib(10) + fib(11) is 144, and that is fib(12): true
6765 is odd, or not positive
```

* **`fn name(a: int, b: text): int`** … **`end fn name`**: typed parameters, a return type
  or none, calls and recursion. Every path of a function with a return type returns
  (`MZ0906`); a wrong call is `MZ0905`, quoting the signature.
* **`let`** binds a value once; **`var`** binds one you assign with `=`. Scope is the block.
  There is no shadowing (`MZ0921`), a name is readable from the line after its binding to
  the end of its block (`MZ0920`), and assigning to a `let` is `MZ0922`. Python's bare first
  assignment, Go's `:=` and Rust's `let mut` each get a fix.
* **`when` / `else when` / `else`**, closed by `end`. A condition is a `bool` and nothing
  else: Mzizi has no truthiness (`MZ0712`).
* **`return`** ends a function early. **`print(value)`** writes one value's text form and a
  newline; to print several, interpolate them into one text.
* **Comments** are lines starting with `##`. `//` and `#` are `MZ0911`, with `##` as the
  `exact` fix.

## Values: `int`, `float`, `bool` and `text`

| Type | What it is |
| - | - |
| `int` | A signed 64-bit integer. Overflow and division or remainder by zero **trap** at run time (exit 101); a constant one is `MZ0915` at check time. Division truncates toward zero; `%` takes the dividend's sign |
| `float` | IEEE 754 binary64, written with a digit on both sides of the point. It never traps: `1.0 / 0.0` is `inf`, `0.0 / 0.0` is `nan`, and `nan is nan` is `false` |
| `bool` | `true` or `false` |
| `text` | UTF-8 text in double quotes on one line, built by interpolation (`"{a} and {b}"`), never by `+`. The escapes are `\n`, `\t`, `\"`, `\\`, `\{` and `\}` |

**`int` and `float` never mix.** `1 + 1.5` is `MZ0912`, with the `exact` fix `1.0` on an
`int` literal and the `guess` `x.to_float()` on anything else. A float prints in the shortest
form that reads back exactly: `1.0`, `0.30000000000000004`, `1.0e21`, `inf`, `nan`.

**The numeric methods** are postfix, so `-2.pow(2)` is `-(2.pow(2))`:

| Method | On | Notes |
| - | - | - |
| `to_float()` | `int` | Exact up to 2^53 |
| `to_int()` | `float` | Truncates toward zero; traps on `nan`, an infinity or a value out of range |
| `round()`, `floor()`, `ceil()` | `float` | `round` takes halves away from zero: `2.5.round()` is `3.0` |
| `sqrt()`, `is_nan()` | `float` | `is_nan` is the only way to ask, since `nan is nan` is `false` |
| `abs()` | `int`, `float` | Traps on `int`'s minimum |
| `min(x)`, `max(x)` | `int`, `float` | Two values of one type; on floats, Rust's `f64::min` and `f64::max` |
| `pow(n)` | `int`, `float` | `n` is an `int`. On `int` it traps on overflow and on a negative `n` |

## Expressions and operators

Highest precedence first, as RFC-0013 §3.5 orders the operators that are built. Lower levels
bind tighter. The level of each operator is the one the checker, the parser and the
[language harness](https://docs.mzizi.dev/language-harness.md) all read:

| Level | Operators |
| - | - |
| 1 | literals, names, `( … )`, calls `f(…)` |
| 2 | postfix `.method(…)`, `.column`, indexing `xs[i]`, and `x with (…)` |
| 3 | prefix `-`, prefix `try` |
| 4 | `*`, `/`, `%` |
| 5 | `+`, `-` |
| 6 | `otherwise`, which is right-associative: `a otherwise b otherwise c` is `a otherwise (b otherwise c)` |
| 7 | `is`, `is not`, `<`, `<=`, `>`, `>=`, `in`, which do not chain (`MZ0913`) |
| 8 | prefix `not` |
| 9 | `and` |
| 10 | `or`, never mixed with `and` without parentheses (`MZ0913`) |

Prefix `not` binds looser than comparison, so `not (a is b)` is the form to write.
`not a is b` without the parentheses is `MZ0910`, whose `exact` fix is `a is not b`. Postfix
binds tighter than prefix `-`, so `-2.pow(2)` is `-4`, and `1 + 2 * 3` is `7`.

Equality is `is` and `is not`. `==`, `!=`, `&&`, `||` and `!` are `MZ0910`, each with an
`exact` fix to the Mzizi word. `+=` and `++` are `MZ0918`; `str(x)` and `x.to_string()` are
`MZ0962`, with the `exact` fix `"{x}"`. `examples/numbers.mz` prints its arithmetic, and
[`numbers.expected`](https://github.com/mzizi-dev/mzizi/blob/main/examples/numbers.expected)
holds what it prints.

## Control flow

From `examples/control.mz` (an excerpt; the file is in the repository, and CI compares its
output with `examples/control.expected`):

```mz examples/control.mz (excerpt) theme={null}
  enum shape
    circle
    square
    triangle
  end

  fn fizzbuzz(n: int): text
    when n % 15 is 0
      return "FizzBuzz"
    else when n % 3 is 0
      return "Fizz"
    else when n % 5 is 0
      return "Buzz"
    end
    return "{n}"
  end fn fizzbuzz

  fn corners(s: shape): int
    match s
      case circle
        return 0
      case square
        return 4
      case triangle
        return 3
    end
  end fn corners

  fn odd_sum(limit: int): int
    var total = 0
    for each i in range(0, to = 100)
      when i >= limit
        break
      end
      when i % 2 is 0
        continue
      end
      total = total + i
    end
    return total
  end fn odd_sum

  fn collatz(start: int): int
    var n = start
    var steps = 0
    while n is not 1
      n = match n % 2
        case 0
          n / 2
        else
          3 * n + 1
      end
      steps = steps + 1
    end
    return steps
  end fn collatz
```

* **`match <value>`** takes `case` lines, each listing one or more values (`case 6 7`), then
  an optional `else`, over an enum, an `int`, a `text` or a `bool`. It is checked for
  exhaustiveness: a missing case is `MZ0930`, naming the missing variants, and a case that can
  never run is `MZ0931`, whose `exact` fix deletes it. A `match` over a `float` is `MZ0711`:
  compare a float with `when`.
* **`for each i in range(a, to = b)`** counts from `a` up to but not including `b`. `for each`
  also runs over a list, and `range(a, to = b)` is a list anywhere; see
  [collections](#collections-c7).
* **`while <condition>`** is the one conditional loop; `while true` with a `break` is the loop
  that ends from inside. **`break`** and **`continue`** act on the innermost loop, and are
  `MZ0935` outside one.
* **`when` and `match` as values.** Either may be the whole value of a `let`, a `var`, an
  assignment or a `return`, each branch one expression line; nowhere else, and there is no
  ternary (`MZ0932`).
* **Other languages' spellings are fixed.** `elif`, `else if`, `switch`, `default:`, `case _`
  and `_ =>` are `MZ0933`; `for x in xs`, `for (const x of xs)`, `loop` and `range(n)` are
  `MZ0934`, each with an `exact` fix. An `else when` chain over one enum's variants is
  `MZ0936`, with a `guess` fix rewriting it as a `match`.

**Enums.** A program declares an `enum`, one variant per line, closed by a bare `end`. A
variant is written bare where the expected type settles its enum, and `<enum>.<variant>`
where two enums share it. Variants compare with `is`, order by declaration and print as their
names. A variant may carry **columns**, a name and a literal each, read with a dot
(`problem.say`), as in `examples/errors.mz` below.

## Errors: `result`, `error` and `try`

`examples/errors.mz`, verbatim:

```mz examples/errors.mz theme={null}
## Checks ages: one function fails with an error, its callers handle it with `match` or
## propagate it with `try`, and `main` itself returns a result (RFC-0013 §12).
program errors

  enum age_problem
    negative say "is below zero"
    too_old  say "is above 150"
  end

  fn main: result(none, age_problem)
    print(describe(42))
    print(describe(-3))
    print(describe(200))
    let total = try total_age(20, 22)
    print("20 and 22 make {total}")
    match total_age(20, 151)
      case ok sum
        print("20 and 151 make {sum}")
      case error problem
        print("20 and 151 were rejected: {problem} {problem.say}")
    end
  end fn main

  fn check_age(n: int): result(int, age_problem)
    when n < 0
      return error(negative)
    end
    when n > 150
      return error(too_old)
    end
    return n
  end fn check_age

  fn describe(n: int): text
    match check_age(n)
      case ok age
        return "age {age} is fine"
      case error problem
        return "{n} is rejected: {problem} {problem.say}"
    end
  end fn describe

  fn total_age(a: int, b: int): result(int, age_problem)
    return try check_age(a) + try check_age(b)
  end fn total_age

end program errors
```

```text examples/errors.expected theme={null}
age 42 is fine
-3 is rejected: negative is below zero
200 is rejected: too_old is above 150
20 and 22 make 42
20 and 151 were rejected: too_old is above 150
```

* A function that can fail returns **`result(T, E)`**, or `result(none, E)`. `return v`
  returns success, **`return error(e)`** returns failure, and `return r` passes a result of
  the function's own type through.
* A caller **matches** the result, with exactly two cases, `case ok <name>` and
  `case error <name>`, or **propagates** its error with a prefix **`try`**, in a function
  that returns a result with the same error type.
* **Any other use of a result is `MZ0950`**: discarding it, printing it, comparing it,
  passing it or holding it in a `var`. A result is never a parameter, nor inside another
  result.
* **`fn main` may return `result(none, E)`.** When it returns an error, the program writes
  `mz: error MZ0992: main returned an error: <the error's text form>` to standard error and
  exits 1.
* **Other languages' idioms are `MZ0952`:** `Ok(v)` (`exact` `v`), `Err(e)` (`exact`
  `error(e)`), Rust's postfix `?` (`exact` prefix `try`), `throw e` and `raise e`
  (`return error(e)`), and `.unwrap()` and `.expect(…)`, which have no fix: an error is never
  turned into a crash.

## `mz run`

```text theme={null}
mz run [--release] <file.mz>     check, lower, build with cargo, run
mz build <file.mz> --out <dir>   write the same Rust package
```

1. **Check.** On any error it prints the diagnostics, exits 3, and does not build.
2. **Lower.** It writes a Cargo package with **no dependencies** into
   `<name>-<path hash>` under `$MZ_CACHE_DIR`, or `mzizi/mz-run/` under `$XDG_CACHE_HOME` or
   `~/.cache`. With none of the three set it exits 2 and names them; it never falls back to
   the system's temporary directory.
3. **Build.** `cargo build --offline --quiet`, with `--release` when asked. No dependencies
   means no network.
4. **Run.** The binary runs with the terminal's standard input, output and error. Standard
   output belongs to the program; everything `mz run` writes of its own goes to standard
   error.

**Every exit status means one thing.** `mz run` departs from the other commands, where 1 means
errors, because 1 belongs to the program it runs:

| Status | Means |
| - | - |
| `0` | The program ran and `main` ended |
| `1` | The program ran and `main` returned an error (`MZ0992`) |
| `2` | A usage, environment or I/O problem: bad arguments, an unreadable file, no `cargo`, no cache directory |
| `3` | The program did not compile: `mz check` errors, or the lowered Rust failed to compile (`MZ0990`). It did not run |
| `101` | The program ran and **trapped**: one line on standard error, `mz: trap MZ0991 at <file>:<line>:<column>: …` |
| `141` | The program ran and its standard output was closed |
| `128+n` | A signal `n` killed the program |

RFC-0013 §13 also designs exit 70 and `MZ0993` for a runtime failure, and `mz run --agent`
for NDJSON on standard error. Neither is built: `mz run --agent` exits 2.

**The lowering.** Every value is owned and no reference or lifetime is emitted: a `text` read
is a `.clone()`. `result(T, E)` is Rust's `Result<T, E>` and `try e` is `e?`; an enum is a
Rust `enum`; a `match` on an enum or a `bool` has no `_` arm unless it has an `else`, so
`rustc` checks exhaustiveness again; `for each i in range(a, to = b)` is `for i in a..b`. The
generated code holds no `unwrap`, `expect`, `panic!` or `unsafe`, which a test checks.

## Nesting is capped

A program's blocks and expressions nest at most 32 deep together, and an expression's tree of
binary operators at most 64. Past the cap is one `MZ0411` per file, not a stack overflow.
`compiler/tests/robustness.rs` holds every case to a 1 MiB stack.

## Text methods (C6)

Text values have methods, written after the value as the numeric ones are. No method changes
the text it is called on: each returns a new value, so `city.trim()` leaves `city` as it was.
Lengths, indices and slices count Unicode scalar values, so an index never lands inside a
character, and there is no `char` type: one character is a `text` of length 1. A method that
may find nothing returns an `option`, read with `otherwise` as the collections are.

| Method | Returns | What it does |
| - | - | - |
| `s.length()` | `int` | Counts Unicode scalar values, not bytes: `"日本語".length()` is `3` |
| `s.contains(t)` | `bool` | Whether `t` occurs in `s` |
| `s.starts_with(t)`, `s.ends_with(t)` | `bool` | Whether `s` begins or ends with `t` |
| `s.trim()` | `text` | Removes Unicode whitespace from both ends |
| `s.to_upper()`, `s.to_lower()` | `text` | Full Unicode case mappings, so `"straße".to_upper()` is `"STRASSE"` |
| `s.replace(old, by = new)` | `text` | Replaces every `old`. The `by` label is required: without it the call is `MZ0927` |
| `s.repeat(n)` | `text` | `n` copies. A negative `n`, or a result too long to hold, traps (`MZ0991`, exit 101) |
| `s[i]` | `option(text)` | The one character at scalar-value index `i`; `none` when `i` is out of range or below 0 |
| `s.slice(a, to = b)` | `option(text)` | The scalar values from `a` up to, not including, `b`; `none` when an end is outside the text or `a` is past `b` |
| `s.find(t)` | `option(int)` | The scalar-value index of the first `t`, or `none`; `0` for `""` |
| `s.split(sep)` | `list(text)` | The pieces between each `sep`. `sep` must not be empty: `s.split("")` is `MZ0915`, and an empty one at run time traps (`MZ0991`) |
| `s.chars()` | `list(text)` | One text per scalar value |
| `s.parse_int()` | `option(int)` | An optional `-`, then ASCII digits that fit an `int`. `"0x10"`, `"1e2"`, `" 7 "` and `"1.5"` are `none` |
| `s.parse_float()` | `option(float)` | An optional `-`, then digits, then a `.` only when a digit follows it. `"1."` and `".5"` are `none`; no exponent, `inf` or `nan` |

`parse_int` uses RFC-0011 §4.2's rule on purpose, so a query parameter and a parsed string agree.

`examples/text.mz`, verbatim, with the output it prints:

```mz examples/text.mz theme={null}
## Text, RFC-0013 §10: lengths count Unicode scalar values, not bytes, and every method is
## safe on non-ASCII text. Emptiness is `s is ""`, and text is built by interpolation.
## `mz run examples/text.mz` prints what text.expected holds; CI compares the two.
program text

  fn main
    let city = "  Zürich  "
    let name = city.trim()
    print("[{name}] has {name.length()} characters; with its spaces, {city.length()}")
    print("upper {name.to_upper()}, lower {name.to_lower()}")
    let greeting = "habari, dunia"
    let polite = greeting.starts_with("habari")
    print("{greeting} starts with habari: {polite}")
    print(greeting.ends_with("dunia"))
    print(greeting.contains("ri, d"))
    print(greeting.replace("dunia", by = "Mzizi"))
    let kanji = "日本語"
    print("{kanji} is {kanji.length()} characters long")
    let street = "straße"
    print("{street} in upper case is {street.to_upper()}")
    print(banner("ok", 3))
    print(describe(""))
    print(describe(name))
    print("-".repeat(12))
    let sentence = "héllo, 日本語"
    print(sentence[1] otherwise "?")
    print(sentence[9] otherwise "?")
    print(sentence.slice(0, to = 5) otherwise "?")
    print(sentence.find("日") otherwise -1)
    print(first_word(sentence))
    print(first_word("one two"))
    for each c in sentence.chars()
      print("[{c}]")
    end
    print(split_count("a,,b", ","))
    print(split_count("", ","))
    print("42".parse_int() otherwise 0)
    print("-0x10".parse_int() otherwise 0)
    print("1.5".parse_float() otherwise 0.0)
    print("1.".parse_float() otherwise 0.0)
  end fn main

  fn first_word(s: text): text
    let stop = s.find(" ") otherwise s.length()
    return s.slice(0, to = stop) otherwise s
  end fn first_word

  fn split_count(s: text, sep: text): int
    return s.split(sep).length()
  end fn split_count

  fn banner(word: text, width: int): text
    let edge = "=".repeat(width)
    return "{edge} {word} {edge}"
  end fn banner

  fn describe(s: text): text
    when s is ""
      return "empty"
    end
    let shout = s.to_upper()
    return "{s.length()} characters, {shout} when shouted"
  end fn describe

end program text
```

```text examples/text.expected theme={null}
[Zürich] has 6 characters; with its spaces, 10
upper ZÜRICH, lower zürich
habari, dunia starts with habari: true
true
true
habari, Mzizi
日本語 is 3 characters long
straße in upper case is STRASSE
=== ok ===
empty
6 characters, ZÜRICH when shouted
------------
é
語
héllo
7
héllo,
one
[h]
[é]
[l]
[l]
[o]
[,]
[ ]
[日]
[本]
[語]
3
1
42
0
1.5
0.0
```

* **Other languages' spellings are `MZ0962`, with fixes.** `len(s)` gets the `exact` fix
  `s.length()`, since Python also counts scalar values. `s.len()`, `s.size()`, `s.count()` and
  `s.length` get `s.length()` as a `guess`, because Rust's `len` counts bytes and JavaScript's
  `length` counts UTF-16 units. `strip()` gets `trim()` as a `guess`, because Python's `strip`
  also removes U+001C to U+001F. `upper()`, `toUpperCase()`, `startswith` and `replaceAll(a, b)`
  get their Mzizi names as `exact` fixes. `int(s)`, `float(s)`, `parseInt(s)` and `parseFloat(s)`
  on text get `s.parse_int()` and `s.parse_float()` as `guess`es, `indexOf` gets `find` and
  `substring` gets `slice`, and `toCharArray()` gets `chars`.
* **`t in s` is `MZ0962`, with an `exact` fix.** On text, `in` asks about a collection, so the
  fix is `s.contains(t)`, as RFC-0013 §3.3 says.
* **Emptiness is `s is ""`.** `s.is_empty()`, `s.length() is 0` and their relatives are one
  `MZ0962`, whose `exact` fix is `s is ""` or `s is not ""`.
* **Not built.** Regular expressions, padding and number formatting. They are the standard
  library's (P2), which is not started, and formatting is interpolation until then. The owner
  decided on 8 October 2026 (RFC-0013 §20 Q20) that built-in methods with tests meet C6's "Done
  when"; P2's `text` module documents the same operations once modules (P1) exist.

## Collections (C7)

A program has three collection types: `list(T)`, `map(K, V)` and `set(K)`. A bracket literal
takes its type from the place it stands, so `[3, 1, 3]` is a list where a list is expected and
a `set(int)` where a set is. A literal that cannot be typed, such as `[1, "two"]`, is `MZ0961`.

`examples/collections.mz`, verbatim, builds a list, a map and a set and transforms them in
functions. Its output is below it.

```mz examples/collections.mz theme={null}
## Collections, RFC-0013 §9 (C7): a list, a map and a set built with bracket literals and
## transformed in functions, indexing that gives an option read with `otherwise`, `in`, the
## methods of §9.2 and the named folds of §9.4.
## `mz run examples/collections.mz` prints what collections.expected holds; CI compares the two.
program collections

  enum suit
    hearts
    spades
  end

  fn main
    let primes = [2, 3, 5, 7, 11]
    print(primes)
    print("{primes.length()} primes: the first is {primes[0] otherwise 0}, the tenth {primes[9] otherwise -1}")
    print(sum_of_even_squares(range(1, to = 11)))
    print(primes.map(square))
    print(primes.filter(is_odd).sum())
    print(primes.fold(0, step = add))
    print("{primes.count(is_odd)} odd, any even: {primes.any(is_even)}, all odd: {primes.all(is_odd)}")
    print(primes.first(is_even) otherwise 0)
    print(primes.slice(1, to = 3) otherwise [])
    print(primes.slice(4, to = 9) otherwise [])
    print([5, 3, 9, 1].sort_by(negate))
    print(primes.group_by(is_odd))
    var ages: map(text, int) = ["ada": 36, "alan": 41]
    ages["grace"] = 85
    ages["ada"] = 37
    ages.remove("alan")
    print(ages)
    let grace = ages["grace"] otherwise 0
    let linus = ages["linus"] otherwise 0
    print("grace {grace}, linus {linus}, {ages.length()} people, {ages.values().sum()} years")
    print(ages.keys())
    var seen: set(int) = [3, 1, 3, 2]
    seen.insert(10)
    seen.remove(1)
    print("{seen} holds 3: {3 in seen}, {seen.to_list().length()} values")
    var hands: list(suit) = []
    print(hands is none)
    for each p in primes
      when p % 2 is 0
        hands.push(hearts)
      else
        hands.push(spades)
      end
    end
    hands[1] = hearts
    print(hands)
    print(hands is not none and spades in hands)
    let tags = ["a \"b\"", "c"]
    print(tags)
    print(tags.join(" + "))
  end fn main

  fn sum_of_even_squares(xs: list(int)): int
    return xs.filter(is_even).map(square).fold(0, step = add)
  end fn sum_of_even_squares

  fn square(n: int): int
    return n * n
  end fn square

  fn is_even(n: int): bool
    return n % 2 is 0
  end fn is_even

  fn is_odd(n: int): bool
    return n % 2 is 1
  end fn is_odd

  fn add(a: int, b: int): int
    return a + b
  end fn add

  fn negate(n: int): int
    return -n
  end fn negate

end program collections
```

```text examples/collections.expected theme={null}
[2, 3, 5, 7, 11]
5 primes: the first is 2, the tenth -1
220
[4, 9, 25, 49, 121]
26
28
4 odd, any even: true, all odd: false
2
[3, 5]
[]
[9, 5, 3, 1]
[false: [2], true: [3, 5, 7, 11]]
["ada": 37, "grace": 85]
grace 85, linus 0, 2 people, 122 years
["ada", "grace"]
[2, 3, 10] holds 3: true, 3 values
true
[hearts, hearts, spades, spades, spades]
true
["a \"b\"", "c"]
a "b" + c
```

* **Indexing returns an option.** `xs[i]` and `m[k]` are `none` when `i` is outside the list or
  `k` is not a key. `x otherwise d` gives `x`, or `d` when `x` is `none`. It binds below
  arithmetic and above comparison (RFC-0013 §3.5, level 6), and is right-associative. Using an
  option as its value without `otherwise` is `MZ0710`.
* **Changing a collection needs a `var`.** `xs[i] = v` and `m[k] = v` set an element or a key,
  and `m[k] = v` adds the key when it is missing. `xs[i] = v` traps when `i` is outside the list
  (`MZ0991`, exit 101). `push`, `insert`, `remove` and indexed assignment on a `let` are
  `MZ0960`, whose `exact` fix is `var`.
* **Membership.** `x in xs` asks about an element, `k in m` about a key, and `x in s` about an
  element of a set. `in` on text is `MZ0962`, with `s.contains(t)` as the fix.
* **Keys have an order.** A map key or set element that is a `float`, a collection or an option
  is `MZ0964`. Maps and sets iterate and print in key order. Mzizi has no tuples: `(a, b)` is
  `MZ0963`.
* **`for each` over a list** iterates the list as it was when the loop began. A map or a set
  is `MZ0711`, with `keys()` or `to_list()` in its fix.
* **Functions passed to a method** are named `fn`s of the program. A lambda, `x => …`, is
  `MZ0909`, with no fix.
* **A collection is a value.** `let b = a` copies it, and a function does not change the list
  its caller holds.

| Type | Methods |
| - | - |
| `list(T)` | `length()`, `slice(a, to = b)` (an option), `map(f)`, `filter(f)`, `join(sep)` on `list(text)`, `push(v)` on a `var` |
| `list(T)`, the folds | `count(f)`, `sum()` on `list(int)` or `list(float)`, `any(f)`, `all(f)`, `first(f)` (an option), `fold(init, step = f)`, `sort_by(f)` (a key of `int`, `text`, `bool` or an enum), `group_by(f)` |
| `map(K, V)` | `length()`, `keys()`, `values()`, `remove(k)` on a `var` |
| `set(K)` | `length()`, `to_list()`, `insert(v)` on a `var`, `remove(v)` on a `var` |

`map` and `filter` take a function of one element, `fold` takes its start value and a `step`
function of two, and `group_by` returns a `map(K, list(T))`.

**Not built:**

* `option(T)` written as a type, `none` as a value, and narrowing an option with
  `when x is not none`: the "C4 options" follow-up (RFC-0013 §18.2).
* Tuples, which RFC-0013 §2 decided against.
* Labels on these calls other than `range`'s `to`, `slice`'s `to` and `fold`'s `step`.

The codes these constructs report, with their `say` text and fix kinds, are in
[the compiler's table of the MZ09xx codes](https://docs.mzizi.dev/compiler.md#program-codes-mz09xx).

## Records and methods (C8)

A `record` groups named fields, and its `fn`s are methods that read the value through `self`.
A record may carry a `contract` of `always` clauses that every value must keep.

`examples/records.mz`, verbatim, with the output it prints:

```mz examples/records.mz theme={null}
## Records, RFC-0013 §11 (C8): a record built by field name, copied with `with`, read by
## field, given methods that read `self`, a field of a `var` assigned, and an `always`
## clause that every value holds.
## `mz run examples/records.mz` prints what records.expected holds; CI compares the two.
program records

  record point
    field x: float
    field y: float

    fn norm: float
      return (self.x * self.x + self.y * self.y).sqrt()
    end fn norm

    fn scaled(k: float): point
      return point(x = self.x * k, y = self.y * k)
    end fn scaled
  end

  record span
    field low: int
    field high: int

    contract
      always low <= high
    end
  end

  fn width(s: span): int
    return s.high - s.low
  end fn width

  fn main
    let p = point(x = 3.0, y = 4.0)
    print(p)
    print(p.norm())
    print(p.scaled(2.0))
    print(p with (y = 0.0))
    print(p is point(x = 3.0, y = 4.0))
    var q = point(x = 1.0, y = 1.0)
    q.x = 5.0
    print(q)
    let s = span(low = 2, high = 9)
    print(width(s))
    print("{s} is {width(s)} wide")
  end fn main

end program records
```

```text examples/records.expected theme={null}
point(x = 3.0, y = 4.0)
5.0
point(x = 6.0, y = 8.0)
point(x = 3.0, y = 0.0)
true
point(x = 5.0, y = 1.0)
7
span(low = 2, high = 9) is 7 wide
```

* **Built by field name.** `point(x = 3.0, y = 4.0)` is a value; built from positional values
  it is `MZ0808`, with no fix. A field the record lacks, or one given twice, is `MZ0808` too.
* **Copied with `with`.** `p with (y = 0.0)` is a new value with one field changed, and `p` is
  unchanged. A `with` that names a field the record does not have is `MZ0974`.
* **Fields and `var`s.** A field is read with a dot. `q.x = 5.0` changes a field of a `var`;
  changing a field of a `let`, or of a value no name holds, is `MZ0960`, whose `exact` fix is
  `var`.
* **Equality and text.** `is` compares two records, and a record prints as its name and its
  fields, as in `point(x = 3.0, y = 4.0)`.
* **Methods.** A method's receiver is `self`, which is read and never assigned. `self` outside a
  method is `MZ0970`, and assigning to `self` or one of its fields inside one is `MZ0971`. A
  method that needs a changed record returns `self with (…)`.
* **`always` clauses.** Each clause is checked when a value is built, when a `with` copies it,
  and after a field is assigned. A broken clause traps at run time (`MZ0991`, exit 101). A record
  literal that breaks one is `MZ0975` at check time.

**Not built:** `fn … changes self` and a record that holds itself (both `MZ0919`); payload enums
(RFC-0013 §11.5); a fix for a positional construction; and `to_json`. Generics and interfaces are a
separate row, P12, deferred past M1.

## What is not built

These are designed in RFC-0013 and are not in the compiler on `main`. Most are `MZ0919`, which
says the form is designed and not built; some, such as `via`, fall to generic codes (`MZ0917`):

* Generics and interfaces, a separate row, P12, deferred past M1.
* `option(T)` written as a type, `none` as a value, and narrowing an option with
  `when x is not none` (the "C4 options" follow-up, RFC-0013 §18.2).
* A method that changes its record, `fn … changes self`, and a record that holds itself
  (`MZ0919`), and payload enums (RFC-0013 §11.5).
* A decimal type.
* Named arguments beyond `range`'s `to`, `slice`'s `to` and `fold`'s `step`, `try … via f`
  (`MZ0955`), and a `match` stub as the fix for `MZ0950`.
* A program's `contract` block, `mz test`, `mz run --agent`, and `mz outline`, `mz ir` and
  `mz hash` on a program, which exit 2.
* Modules: one program per file, and nothing is imported.

The benchmark's prompts do not describe programs yet, so no benchmark arm knows about them, and
nothing has been measured. Whether an agent writes these forms well is for the benchmark to
find out. See [Status](https://docs.mzizi.dev/status.md) and [the compiler](https://docs.mzizi.dev/compiler.md#program-codes-mz09xx) for every
`MZ09xx` code.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.