# Chapter 19: Proving Your Programs

The payoff of learning theorem proving: you can state and verify **correctness properties of functions you write yourself**. This chapter walks through realistic examples — sorting, arithmetic, data structures — showing how to co-locate a function and its proof in the same file.

---

## The pattern: function + theorem

The standard pattern is to write the function, then state a theorem about it in the same module:

```first
// The function
function double(n: Int) -> Int {
    return n + n;
}

// A theorem about it
theorem double_eq_mul_two(n: Int) -> Eq(double(n), 2 * n) by {
    ring;
}
```

---

## Example 1: factorial

```first
function factorial(n: Nat) -> Nat {
    return if (n == 0) { 1 } else { n * factorial(n - 1) };
}

// factorial is always >= 1
theorem factorial_pos(n: Nat) -> Eq(factorial(n) >= 1, true) by {
    induction n {
        case Zero => { decide; }
        case Succ(k) ih => {
            simp [factorial];
            linarith [ih];
        }
    }
}

// factorial(n) = n * factorial(n-1) when n > 0
theorem factorial_step(n: Nat, h: Eq(n > 0, true)) ->
    Eq(factorial(n), n * factorial(n - 1)) by {
    simp [factorial];
    omega;
}
```

---

## Example 2: sum of a list

```first
import "List";

function sumList(xs: List<Int>) -> Int {
    match xs {
        Nil       => 0,
        Cons(h, t) => h + sumList(t)
    }
}

// sumList of a singleton is just the element
theorem sum_singleton(x: Int) -> Eq(sumList(Cons(x, Nil)), x) by {
    simp [sumList];
    ring;
}

// sumList respects append: sum(xs ++ ys) = sum(xs) + sum(ys)
theorem sum_append(xs: List<Int>, ys: List<Int>) ->
    Eq(sumList(append(xs, ys)), sumList(xs) + sumList(ys)) by {
    induction xs {
        case Nil => { simp [sumList, append]; }
        case Cons(h, t) ih => {
            simp [sumList, append, ih];
            ring;
        }
    }
}
```

---

## Example 3: safe array operations

Theorems can capture the behaviour of functions defined using the standard library:

```first
import "Vec";
import "Nat";

// replicate n x has exactly n elements
theorem replicate_length<T>(n: Nat, x: T) ->
    Eq(arrayLength(replicate(n, x)), n) by {
    induction n {
        case Zero   => { simp [replicate]; }
        case Succ(k) ih => {
            simp [replicate, arrayLength, ih];
            omega;
        }
    }
}
```

---

## Example 4: map preserves length

```first
import "List";

theorem map_length<A, B>(f: A -> B, xs: List<A>) ->
    Eq(length(map(f, xs)), length(xs)) by {
    induction xs {
        case Nil => { simp [map, length]; }
        case Cons(h, t) ih => {
            simp [map, length, ih];
        }
    }
}
```

---

## Example 5: append is associative

```first
import "List";

theorem append_assoc<A>(xs: List<A>, ys: List<A>, zs: List<A>) ->
    Eq(append(append(xs, ys), zs), append(xs, append(ys, zs))) by {
    induction xs {
        case Nil => { simp [append]; }
        case Cons(h, t) ih => {
            simp [append, ih];
        }
    }
}
```

---

## Example 6: gcd correctness

```first
import "Int";

// gcd divides both arguments
theorem gcd_dvd_left(a: Int, b: Int) ->
    Eq(a % gcd(a, b), 0) by {
    sorry;   -- non-trivial; requires the Euclidean algorithm proof
}

// gcd is symmetric
theorem gcd_comm(a: Int, b: Int) ->
    Eq(gcd(a, b), gcd(b, a)) by {
    sorry;
}
```

Using `sorry` to stub theorems is fine during development — it lets the type checker verify the statement is well-formed before you tackle the proof.

---

## Proof strategies by theorem shape

| Goal shape | Try first | If that fails |
|------------|-----------|---------------|
| `Eq(f(a), c)` for concrete `a` | `decide` | `simp [f]` + `norm_num` |
| Algebraic identity | `ring` | `simp` + `ring` |
| Linear inequality | `omega` | `linarith` |
| `∀ n: Nat, ...` | `induction n` | unfold + `simp` + subgoal |
| `∀ xs: List<A>, ...` | `induction xs` | unfold + `simp` + subgoal |
| Statement using library functions | `simp [fn_name]` unfolds definition | add `ih` to `simp` call |
| Contradiction from two hypotheses | `omega` or `linarith` | `exfalso` + `discriminate` |

---

## Co-locating proofs and functions

You can keep theorems right next to the functions they describe:

```first
module Queue;

export type Queue<A> = { front: List<A>, back: List<A> };

export function empty<A>() -> Queue<A> {
    return { front: Nil, back: Nil };
}

export function enqueue<A>(q: Queue<A>, x: A) -> Queue<A> {
    return { front: q.front, back: Cons(x, q.back) };
}

// A queue is logically empty iff both lists are Nil
export theorem empty_correct<A>(q: Queue<A>) ->
    Eq(isEmpty(q), q.front == Nil && q.back == Nil) by {
    cases q.front { cases q.back { decide; } { decide; } }
    cases q.back  { decide; }
    decide;
}
```

This style makes the library's guarantees self-documenting. Users know exactly what properties hold.

---

## Using sorry as a roadmap

A useful workflow when writing a new library: state all theorems you *want* to hold first (using `sorry`), then prove them one by one:

```first
export theorem insert_sorted(xs: SortedList, x: Int) ->
    Eq(isSorted(insert(xs, x)), true) by { sorry; }

export theorem insert_contains(xs: SortedList, x: Int) ->
    Eq(contains(insert(xs, x), x), true) by { sorry; }

export theorem insert_length(xs: SortedList, x: Int) ->
    Eq(length(insert(xs, x)), length(xs) + 1) by { sorry; }
```

The compiler accepts and type-checks the statements even before the proofs exist. Each `sorry` emits a warning, tracking your progress.

---

## Summary

- Write the function first; add theorems immediately after
- `induction` over `Nat` and `List` covers most recursive functions
- `simp [fn_name]` unfolds function definitions for the simplifier
- `ring`, `omega`, `linarith` close arithmetic subgoals after unfolding
- `sorry` lets you state theorems before you prove them — a valuable development workflow
- Keep theorems co-located with the functions they describe

Chapter 20 covers `axiom` declarations and `@[simp]` attributes in depth — the tools you need to build a proof library like first-mathlib.
