# Chapter 24: Termination and Total Functions

By default, First functions may be recursive without proof of termination. When you want the **compiler to verify** that a function always terminates, use the `total` modifier together with a `decreasing` annotation.

---

## The `total` modifier

Prefix a function with `total` to tell the compiler it must terminate on every input:

```first
total function fib(n: Int) -> Int {
  decreasing(n);
  return if (n <= 0) { 0 }
         else if (n == 1) { 1 }
         else { fib(n - 1) + fib(n - 2) };
}
```

The compiler checks that every recursive call strictly decreases the measure given to `decreasing`. Here `n` is the measure: the recursive calls pass `n - 1` and `n - 2`, both strictly less than `n`.

If the compiler cannot verify that the measure decreases, it rejects the program:

```first
// ERROR: fib(n) calls fib(n) — measure does not decrease
total function bad(n: Int) -> Int {
  decreasing(n);
  return bad(n);  // compile-time error: recursive call does not decrease n
}
```

---

## The `decreasing` annotation

`decreasing(expr)` declares the **termination measure** — a value that must strictly decrease at every recursive call. The expression:

- Must be of type `Int` or `Nat`.
- Must evaluate to a non-negative integer at the recursive call site.
- Must be strictly smaller at every recursive call than it was at the entry point.

Place `decreasing` as the first statement in the function body:

```first
total function countdown(n: Int) -> Int {
  decreasing(n);
  return if (n <= 0) { 0 } else { countdown(n - 1) };
}
```

---

## Structural termination with Vec

When the input is a length-indexed vector, use `arrayLength(v)` as the measure. The `[h|t]` pattern binding gives `t: Vec<T, n-1>`, which is automatically a smaller `Vec`:

```first
import * "Vec"

total function vsum(v: Vec<Int, n>) -> Int {
  decreasing(arrayLength(v));
  return match v {
    []    => 0,
    [h|t] => h + vsum(t)
  };
}
```

---

## Mutual recursion

Mutually recursive `total` functions are not yet supported — each function in the group needs its own independent decreasing measure. For now, flatten mutual recursion into a single function with a discriminating argument, or use a helper counter:

```first
// Workaround: even/odd via a single function and a tag
total function evenOdd(n: Int, isEven: Bool) -> Bool {
  decreasing(n);
  return if (n == 0) { isEven }
         else { evenOdd(n - 1, !isEven) };
}

function isEven(n: Int) -> Bool { return evenOdd(n, true); }
function isOdd(n: Int) -> Bool { return evenOdd(n, false); }
```

---

## Well-founded recursion on structured types

For list or ADT recursion, use the structural size as the measure. First's `decreasing` accepts any expression whose value is a non-negative integer:

```first
import * "List"

total function listSum(xs: List<Int>) -> Int {
  decreasing(listLength(xs));
  return match xs {
    Nil        => 0,
    Cons(h, t) => h + listSum(t)
  };
}
```

If the recursive structure is not on a numeric type, compute an integer measure explicitly (e.g., `listLength`, `arrayLength`, tree depth).

---

## Relationship to Lean 4 and Idris 2

| Feature | First | Lean 4 | Idris 2 |
|---------|-------|--------|---------|
| Termination annotation | `decreasing(expr)` | `termination_by expr` | `assert_total` / structural |
| Structural termination | via `arrayLength` | automatic on `Nat`/`List` | automatic on inductive |
| Well-founded (`WellFounded`) | numeric descent | any `WellFoundedRelation` | `Accessible` |
| Mutual termination | not yet | `mutual` block | supported |

First's `decreasing` is equivalent to Lean 4's `termination_by` for numeric measures. Structural termination (automatically checked for `Nat`/`List`) is currently handled by threading the structural size through `decreasing`.

---

## Common pitfalls

**Don't forget `total`.** A function with `decreasing` but without `total` will compile but the termination measure won't be verified — the annotation is silently ignored.

**The measure must decrease at every branch.** Both `fib(n - 1)` and `fib(n - 2)` are smaller than `n` for `n > 1`. If any branch is non-decreasing, the compiler rejects it.

**Base cases don't need to be non-recursive.** A branch that returns a constant or non-recursive value is always fine — only recursive calls are checked.

---

## Summary

- `total function f(x: T) -> R { decreasing(measure); ... }` — declare a terminating function
- `decreasing(expr)` — the measure: an `Int`/`Nat` expression that strictly shrinks at every recursive call
- Use `arrayLength(v)` for Vec/Array structural recursion
- Mutual termination via `mutual` is not yet supported — use a combined function with a tag

Chapter 25 covers **metaprogramming** with the `macro` system and `quote`/splice.
