# Chapter 12: Dependent Types

Dependent types let the **type** of a value depend on another **value**. First supports a practical subset: length-indexed vectors, bounded naturals, dependent pairs, and dependent functions. These let the compiler catch whole categories of bugs — wrong-length arguments, out-of-bounds access, mismatched zip — at compile time rather than at runtime.

---

## Vec\<T, n\> — length-indexed vectors

`Vec<T, n>` is an array of exactly `n` elements of type `T`. The length is part of the type.

```first
import * "Vec";

// vzip requires both arguments to have the same length n — enforced by type checker
let xs: Vec<Int, 3> = [1, 2, 3];
let ys: Vec<Int, 3> = [4, 5, 6];
let pairs = vzip(xs, ys);   // OK: both have length 3
```

If you try to zip vectors of different lengths, the compiler rejects it:

```first
let as: Vec<Int, 2> = [1, 2];
let bs: Vec<Int, 3> = [3, 4, 5];
let bad = vzip(as, bs);   // ERROR: length mismatch: 2 vs 3
```

### Vec operations

```first
import * "Vec";

// head: safe — requires the Vec to be non-empty (length ≥ 1)
export function head<T>(v: Vec<T, n>) -> T

// replicate: fill a Vec of exactly n copies of x
export function replicate<T>(n: Int, x: T) -> Vec<T, n>

// vecConcat: concatenation, lengths add
export function vecConcat<T>(a: Vec<T, m>, b: Vec<T, n>) -> Vec<T, m+n>

// singleton: create a Vec of exactly one element
export function singleton<T>(x: T) -> Vec<T, 1>
```

`head` on a `Vec<T, 0>` is a type error — you get a compile-time guarantee, not a runtime crash.

### Creating Vecs

```first
import * "Vec";

// Vec literals: same syntax as Array
let v3: Vec<String, 3> = ["alice", "bob", "carol"];

// replicate
let zeros: Vec<Int, 5> = replicate(5, 0);

// array literal with explicit type annotation
let v: Vec<Float, 4> = [1.0, 2.0, 3.0, 4.0];
```

---

## Fin\<n\> — bounded naturals

`Fin<n>` is a natural number **strictly less than `n`**. It is the type-safe index for a `Vec<T, n>`. At runtime `Fin<n>` is a plain `Int` — no boxing, no overhead.

```first
import * "Fin";
import * "Vec";

// Int literals are directly assignable to Fin<n>
let i: Fin<5> = 3;    // OK: 3 < 5
let j: Fin<5> = 7;    // type error at compile time

// finId: identity on Fin<n> — the return type Fin<n> is substituted to Fin<5>
function finId(x: Fin<n>) -> Fin<n> {
  return x;
}
let k: Fin<5> = finId(i);   // OK — return type becomes Fin<5>

// finSafe: index a Vec with a Fin — the shared n ensures in-bounds
function finSafe<T>(v: Vec<T, n>, idx: Fin<n>) -> T {
  return v[idx];
}

let v: Vec<Int, 5> = [10, 20, 30, 40, 50];
let elem = finSafe(v, i);   // OK — both have the same n=5
```

The key benefit: `Fin<n>` and `Vec<T, n>` **share the same `n`**. The type checker substitutes `n = 5` throughout when you call `finSafe(v, i)`. An out-of-bounds access is a compile-time error.

---

## Pi types — nat substitution

A Pi type is a function whose **return type depends on the argument value**. First implements Pi types through nat variable substitution. When you write:

```first
function replicate<T>(n: Int, x: T) -> Vec<T, n>
```

the return type `Vec<T, n>` contains a nat variable `n`. At the call site, `n` is substituted with the actual value:

```first
let a = replicate(3, 0);    // return type becomes Vec<Int, 3>
let b = replicate(5, "");   // return type becomes Vec<String, 5>
```

This substitution generalises to **all parameterised types** — not just `Vec`. Any type with a `$nat_var:` argument participates:

```first
// Return type Fin<n> is substituted when n is known
function mkBound(n: Int, x: Int) -> Fin<n> { ... }
let f: Fin<10> = mkBound(10, 7);
```

### Type-level normalization

The type checker normalises arithmetic expressions in nat positions. `Vec<T, n+0>` and `Vec<T, n>` are the same type:

```first
import * "Vec";

// Accept Vec<T, n+0> and return Vec<T, n> — the compiler sees they are equal
function wrapPlusZero<T>(v: Vec<T, n+0>) -> Vec<T, n> {
  return v;
}

function test() -> Int {
  let a: Vec<Int, 3> = [1, 2, 3];
  let b: Vec<Int, 3> = wrapPlusZero(a);   // OK: 3+0 == 3
  let c: Vec<Int, 3+0> = a;               // OK: same type
  return 0;
}
```

The normaliser handles `+`, `-`, `*`, `/`, and unary negation on concrete values and linear expressions over nat variables.

---

## Sigma types — dependent pairs

A Sigma type `(x: A) * B(x)` is a pair where the **type of the second component depends on the value of the first**. Use `mkSigma`, `projFst`, and `projSnd`:

```first
import * "Vec";
import * "Prelude";

// Pack a Vec with its length as a dependent pair
function packVec(v: Vec<Int, n>) -> (n: Int) * Vec<Int, n> {
  return mkSigma(arrayLength(v), v);
}

// Unpack and use the components
function test() -> Int {
  let v: Vec<Int, 3> = [1, 2, 3];
  let p = mkSigma(3, v);    // type: (n: Int) * Vec<Int, n>
  let n = projFst(p);       // Int — the length
  let v2 = projSnd(p);      // Vec<Int, 3> — the vector
  return n;                  // 3
}
```

**When to use Sigma types:** When you need to return a value together with a proof or witness about it, or when you want to existentially quantify over a length. `(n: Int) * Vec<Int, n>` says "there exists some n and a Vec of that length".

### Destructuring with `let`

Instead of `projFst`/`projSnd`, you can destructure a sigma pair with `let`:

```first
let p = mkSigma(3, v);    // type: (n: Int) * Vec<Int, n>
let (n, w) = p;            // n: Int, w: Vec<Int, n>
```

This is syntactic sugar for two separate `projFst`/`projSnd` calls and is the preferred style.

---

## Dependent pattern matching

When you pattern-match a `Vec<T, n>` using the cons pattern `[h|t]`, the tail variable `t` gets type **`Vec<T, n-1>`** — not `Array<T>`. This lets you write recursive functions with Vec return types:

```first
import * "Vec";
import * "Array";

// safeTailVec: drop the first element, return Vec<T, n-1>
function safeTailVec<T>(v: Vec<T, n>) -> Vec<T, n-1> {
  return match v {
    []    => [],       // empty: return empty Vec
    [h|t] => t         // t has type Vec<T, n-1>
  };
}

function test() -> Int {
  let v: Vec<Int, 3> = [10, 20, 30];
  let t: Vec<Int, 2> = safeTailVec(v);   // length decreases from 3 to 2
  return arrayLength(t);                  // 2
}
```

The type `Vec<T, n-1>` threads through recursive calls, giving the compiler a witness that the Vec shrinks by one at each step.

**Pattern summary:**

| Pattern | Binds | Scrutinee type `Vec<T, n>` → tail type |
|---------|-------|----------------------------------------|
| `[]` | nothing | matches when `n = 0` |
| `[h\|t]` | `h: T`, `t: Vec<T, n-1>` | matches when `n > 0` |

---

## Computational rfl for arithmetic

The `rfl` and `refl` tactics now reduce arithmetic expressions before checking equality. This means you can prove `n + 0 = n` by `rfl` without writing a manual induction:

```first
// All four theorems proven by normalisation + rfl
theorem addZeroRight(n: Int) -> Eq(n + 0, n) by { rfl; }

theorem oneAddOne() -> Eq(1 + 1, 2) by { rfl; }

theorem addZeroLeft(n: Int) -> Eq(0 + n, n) by { rfl; }

theorem subtractSelf(n: Int) -> Eq(n - n, 0) by { rfl; }
```

The normaliser handles:
1. **Concrete evaluation** — both sides reduce to the same integer literal.
2. **Linear normalisation** — both sides reduce to the same linear form `{var → coeff} + constant`.

---

## Type-level functions (experimental)

> **Status:** experimental — the `typefun` keyword and expansion semantics may change in future versions.

A type-level function maps **nat arguments** to a **type**. Use `typefun` to give a name to a parameterised type pattern:

```first
// Buf<n> is a synonym for Vec<Int, n>
typefun Buf<n> = Vec<Int, n>;

// Row<n> is a synonym for Vec<Float, n>
typefun Row<n> = Vec<Float, n>;

// Matrix type: n rows of m columns
typefun Matrix<m, n> = Vec<Vec<Float, n>, m>;
```

### Using a type-level function

```first
typefun Buf<n> = Vec<Int, n>;

export function alloc() -> Int {
    let b: Buf<3> = [1, 2, 3];   // expands to Vec<Int, 3>
    return 0;
}
```

The type checker expands `Buf<3>` to `Vec<Int, 3>` at the use site — it is a purely compile-time substitution, with no runtime overhead.

### Type-fun vs type alias

A regular `type` alias (`type Foo = Vec<Int, 5>`) is a fixed type. A `typefun` takes nat arguments and produces a family of types:

```first
type    Fixed = Vec<Int, 5>;     // always Vec<Int, 5>
typefun Sized<n> = Vec<Int, n>;  // Vec<Int, n> for any n
```

### Limitations (experimental)

- Nat arguments may be **concrete integer literals** (`Buf<3>`) or **nat variables and expressions** (`Buf<n>`, `Buf<n+1>`) from the enclosing function scope.
- Type arguments (non-nat) are not yet supported — only nat parameters.
- Recursive `typefun` definitions are not permitted.

---

## Dependent records

A dependent record is a record type where the **type of a later field depends on the value of an earlier field**. The classic example is a network frame that carries its own length:

```first
type Frame = {
    length: Int,
    payload: Vec<Int, length>   // length here is the *value* of the first field
};
```

The field name `length` on the right-hand side of `Vec<Int, length>` refers to the integer value stored in the `length` field of the same record literal. The type checker substitutes that value when it checks the `payload` field.

### Creating a dependent record

```first
// OK: length field is 3, payload Vec must also have length 3
let f: Frame = { length: 3, payload: [1, 2, 3] };

// ERROR: Vec length is 2 but length field is 3
// let bad: Frame = { length: 3, payload: [1, 2] };
```

Fields are checked **in order**. When the checker sees an `Int` literal for a field (e.g. `length: 3`), it records `length = 3` and uses that substitution for every subsequent field whose type mentions `length`.

### Rules

- The earlier field must be assigned a **concrete `Int` literal** at the call site. Expressions like `2 + 1` do not yet propagate (use `3` directly).
- The dependent field must have a type whose nat dimension matches the field name exactly — `Vec<T, length>` where `length` is a field in the same record.
- Multiple nat fields in the same record are supported: each Int literal updates the substitution map for fields that follow.

---

## Indexed inductive types

An indexed inductive type is a user-defined ADT whose constructors carry a **nat index** in the type. The index can change between the head constructor and the recursive tail:

```first
type Vect<T, n: Int> =
    | Nil
    | Cons(T, Vect<T, n-1>);
```

The `: Int` annotation on `n` tells the compiler that `n` is a *value-level* nat parameter, not an ordinary type parameter. The body uses `n-1` in the recursive position — the type checker understands this arithmetic automatically.

### Writing functions over indexed ADTs

```first
// Drop the first element. Return type is Vect<T, n-1>.
function vtail<T>(v: Vect<T, n>) -> Vect<T, n-1> {
    return match v {
        Nil        => Nil,
        Cons(h, t) => t      // t has type Vect<T, n-1> — derived from scrutinee
    };
}
```

When the type checker pattern-matches a `Vect<T, 5>` against `Cons(h, t)`, it:
1. Looks up `Vect`'s nat parameter list (`[n]`) in the internal registry.
2. Extracts `n = 5` from the scrutinee's type argument.
3. Applies `n ↦ 5` to the constructor's second argument type `Vect<T, n-1>`, yielding `Vect<T, 4>`.

This means `t` gets type `Vect<T, 4>` automatically — no annotation needed.

### Declaring a nat parameter

```
type Name<TypeParam, natParam: Int> = ...
```

- Any type parameter followed by `: Int` is a nat parameter.
- Nat parameters and type parameters may be interleaved: `type Matrix<T, m: Int, n: Int>`.
- The parameter name is available in the body as a nat expression: `Vect<T, n-1>`, `Matrix<T, m, n-1>`, etc.

### Comparison with Lean 4

```lean
-- Lean 4 equivalent
inductive Vect (α : Type) : Nat → Type where
  | nil  : Vect α 0
  | cons : α → Vect α n → Vect α (n + 1)
```

First's syntax keeps the nat index inside the same `<...>` parameter list as ordinary type parameters, which is more familiar to programmers coming from generic-typed languages.

---

## When to use dependent types

| Use case | Type to reach for |
|----------|------------------|
| Fixed-size buffer | `Vec<T, n>` |
| Safe array index | `Fin<n>` |
| Shared length constraint | `function f(v: Vec<T, n>, i: Fin<n>)` |
| Return value with size proof | `(n: Int) * Vec<T, n>` |
| Matrix operations (m×n) | `Vec<Vec<T, n>, m>` |
| Prove arithmetic identity | `theorem ... -> Eq(a, b) by { rfl; }` |
| Record with matching-length field | `type Frame = { length: Int, payload: Vec<T, length> }` |
| User-defined length-indexed list | `type Vect<T, n: Int> = \| Nil \| Cons(T, Vect<T, n-1>)` |

---

## Common pitfalls

**Don't mix `Array<T>` and `Vec<T, n>` carelessly.** An `Array<T>` has no compile-time length. `Vec<T, n>` and `Array<T>` with the same element type unify at runtime (Vec is Array at runtime), but only where the type checker allows it.

**Length expressions must be linear.** The type checker handles `m+n`, `n-1`, `2*n` but not arbitrary functions over lengths. For non-linear dependencies, use a Sigma type or a refinement type.

**`Fin<n>` is an `Int` at runtime.** No bounds check is inserted by the compiler — the type system guarantees it. If you get a `Fin<n>` from outside the type system (e.g., from user input), use `mkFin` from `lib/Fin.first` which returns `Option<Fin<n>>`.

---

## Summary

- `Vec<T, n>` — array with compile-time length guarantee
- `Fin<n>` — bounded index (plain `Int` at runtime); assignable from Int literals
- Pi substitution — nat variables in return types are substituted at call sites, generalised to all parameterised types
- Sigma types — `(x: A) * B(x)` via `mkSigma` / `projFst` / `projSnd`
- Type-level normalisation — `Vec<T, n+0> = Vec<T, n>` and similar arithmetic equalities
- Dependent pattern matching — `[h|t]` on `Vec<T, n>` gives `t: Vec<T, n-1>`
- Computational `rfl` — proves arithmetic equalities like `n+0 = n` by normalisation
- Dependent records — `type Frame = { length: Int, payload: Vec<T, length> }` — later field types reference earlier field values
- Indexed inductive types — `type Vect<T, n: Int>` — ADTs with nat parameters that flow through pattern matching
- Type-level functions (experimental) — `typefun Buf<n> = Vec<Int, n>` — name a family of types parameterised by a nat

Chapter 13 covers **refinement types**, which let you constrain values with arbitrary boolean predicates rather than just length invariants.
