# Chapter 21: The Math Standard Library

The First standard library ships a set of mathematical modules in `lib/`. Each module provides types, operations, and proved/axiomatic theorems. Import any module with `import "ModuleName"`.

---

## `Nat` — Natural numbers

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

**Type:**
```first
export type Nat = Zero | Succ(Nat);
```

**Arithmetic:**
```first
export function add(m: Nat, n: Nat) -> Nat
export function mul(m: Nat, n: Nat) -> Nat
export function pred(n: Nat) -> Nat        // pred(Zero) = Zero (saturating)
export function sub(m: Nat, n: Nat) -> Nat // saturating: sub(2, 5) = 0
export function leq(m: Nat, n: Nat) -> Bool
export function eq(m: Nat, n: Nat) -> Bool
```

**Key theorems** (all proved, not axiomatic):
```first
export theorem add_comm(m: Nat, n: Nat) -> Eq(add(m, n), add(n, m))
export theorem add_assoc(m: Nat, n: Nat, k: Nat) ->
    Eq(add(add(m, n), k), add(m, add(n, k)))
export theorem add_zero(n: Nat) -> Eq(add(n, Zero), n)
export theorem mul_comm(m: Nat, n: Nat) -> Eq(mul(m, n), mul(n, m))
export theorem mul_zero(n: Nat) -> Eq(mul(n, Zero), Zero)
export theorem mul_one(n: Nat) -> Eq(mul(n, Succ(Zero)), n)
```

---

## `Int` — Integers

```first
import "Int";
```

**Type:** built-in `Int` (64-bit signed integer)

**Operations:** `+`, `-`, `*`, `/`, `%`, unary `-`

**Ring axioms** (proved via `ring`):
```first
export theorem add_comm(a: Int, b: Int) -> Eq(a + b, b + a)
export theorem add_assoc(a: Int, b: Int, c: Int) -> Eq((a + b) + c, a + (b + c))
export theorem mul_comm(a: Int, b: Int) -> Eq(a * b, b * a)
export theorem left_distrib(a: Int, b: Int, c: Int) -> Eq(a * (b + c), a*b + a*c)
export theorem add_zero(a: Int) -> Eq(a + 0, a)
export theorem mul_one(a: Int) -> Eq(a * 1, a)
```

**Additional proved lemmas:**
```first
export theorem sub_self(a: Int) -> Eq(a - a, 0)
export theorem mul_zero(a: Int) -> Eq(a * 0, 0)
export theorem neg_neg(a: Int) -> Eq(-(-a), a)
export theorem mul_two(a: Int) -> Eq(2 * a, a + a)
export theorem dvd_refl(a: Int) -> Eq(a % a, 0)
export theorem add_sub_cancel(a: Int, b: Int) -> Eq((a + b) - b, a)
```

**Order axioms:**
```first
export axiom le_refl(a: Int) -> Eq(a <= a, true)
export axiom le_antisymm(a: Int, b: Int,
    h1: Eq(a <= b, true), h2: Eq(b <= a, true)) -> Eq(a, b)
export axiom le_trans(a: Int, b: Int, c: Int,
    h1: Eq(a <= b, true), h2: Eq(b <= c, true)) -> Eq(a <= c, true)
```

---

## `Real` — Real numbers

```first
import "Real";
```

**Type:**
```first
export type Real = __MkReal(Float);  // opaque; backed by f64 at runtime
```

**Operations:**
```first
export function add(a: Real, b: Real) -> Real
export function sub(a: Real, b: Real) -> Real
export function mul(a: Real, b: Real) -> Real
export function div(a: Real, b: Real) -> Real
export function neg(a: Real) -> Real
export function abs(a: Real) -> Real
export function sqrt(a: Real) -> Real
export function pow(a: Real, n: Int) -> Real
export function zero() -> Real
export function one() -> Real
```

**Field axioms** (all marked `axiom`):
```first
export axiom add_comm(a: Real, b: Real) -> Eq(add(a, b), add(b, a))
export axiom add_assoc(a: Real, b: Real, c: Real) ->
    Eq(add(add(a, b), c), add(a, add(b, c)))
export axiom add_zero(a: Real) -> Eq(add(a, zero()), a)
export axiom add_neg(a: Real) -> Eq(add(a, neg(a)), zero())
export axiom mul_comm(a: Real, b: Real) -> Eq(mul(a, b), mul(b, a))
export axiom mul_one(a: Real) -> Eq(mul(a, one()), a)
export axiom left_distrib(a: Real, b: Real, c: Real) ->
    Eq(mul(a, add(b, c)), add(mul(a, b), mul(a, c)))
```

**Order axioms:**
```first
export axiom le_refl(a: Real) -> Eq(le(a, a), true)
export axiom le_antisymm(a: Real, b: Real, ...) -> Eq(a, b)
export axiom le_trans(a: Real, b: Real, c: Real, ...) -> Eq(le(a, c), true)
export axiom sqrt_nonneg(a: Real) -> Eq(le(zero(), sqrt(a)), true)
export axiom sqrt_sq(a: Real, h: Eq(le(zero(), a), true)) ->
    Eq(mul(sqrt(a), sqrt(a)), a)
```

---

## `Rat` — Rational numbers

```first
import "Rat";
```

**Type:**
```first
export type Rat = MkRat(Int, Int);  // numerator, denominator
```

**Operations:**
```first
export function ratAdd(p: Rat, q: Rat) -> Rat
export function ratSub(p: Rat, q: Rat) -> Rat
export function ratMul(p: Rat, q: Rat) -> Rat
export function ratDiv(p: Rat, q: Rat) -> Rat
export function ratNeg(p: Rat) -> Rat
export function ratZero() -> Rat
export function ratOne() -> Rat
```

**Field axioms** (all `axiom`):
```first
export axiom ratAdd_comm(p: Rat, q: Rat) -> Eq(ratAdd(p, q), ratAdd(q, p))
export axiom ratAdd_assoc(p: Rat, q: Rat, r: Rat) -> ...
export axiom ratMul_one(p: Rat) -> Eq(ratMul(p, ratOne()), p)
export axiom ratAdd_inv(p: Rat) -> Eq(ratAdd(p, ratNeg(p)), ratZero())
export axiom ratMul_inv(p: Rat, h: ...) -> Eq(ratMul(p, ratDiv(ratOne(), p)), ratOne())
```

---

## `Complex` — Complex numbers

```first
import "Complex";
```

**Type:**
```first
export type Complex = MkComplex(Float, Float);  // real part, imaginary part
```

**Operations:**
```first
export function complexAdd(a: Complex, b: Complex) -> Complex
export function complexMul(a: Complex, b: Complex) -> Complex
export function complexConj(a: Complex) -> Complex
export function complexAbs(a: Complex) -> Float
export function complexRe(a: Complex) -> Float
export function complexIm(a: Complex) -> Float
export function complexI() -> Complex      // the imaginary unit i
export function complexZero() -> Complex
export function complexOne() -> Complex
```

**Key axiom:**
```first
// i^2 = -1 — the defining property of the imaginary unit
export axiom i_sq() ->
    Eq(complexMul(complexI(), complexI()),
       MkComplex(-1.0, 0.0))
```

---

## `Bool` — Boolean algebra

```first
import "Bool";
```

All `Bool` theorems are **proved** (not axiomatic) using `decide`, since `Bool` is a two-element type and all propositions are decidable.

**A selection:**
```first
export theorem and_comm(a: Bool, b: Bool) -> Eq(a && b, b && a)
export theorem and_assoc(a: Bool, b: Bool, c: Bool) -> Eq((a && b) && c, a && (b && c))
export theorem or_comm(a: Bool, b: Bool) -> Eq(a || b, b || a)
export theorem not_not(a: Bool) -> Eq(!(!a), a)
export theorem not_and(a: Bool, b: Bool) -> Eq(!(a && b), !a || !b)   // De Morgan
export theorem not_or(a: Bool, b: Bool)  -> Eq(!(a || b), !a && !b)   // De Morgan
export theorem and_or_distrib(a: Bool, b: Bool, c: Bool) ->
    Eq(a && (b || c), (a && b) || (a && c))
export theorem and_compl(a: Bool) -> Eq(a && !a, false)
export theorem or_compl(a: Bool)  -> Eq(a || !a, true)
```

---

## `Set` — Finite boolean sets

```first
import "Set";
```

**Type:**
```first
export type Set<A> = MkSet(A -> Bool);  // characteristic function
```

**Operations:**
```first
export function member<A>(x: A, s: Set<A>) -> Bool
export function union<A>(s: Set<A>, t: Set<A>) -> Set<A>
export function inter<A>(s: Set<A>, t: Set<A>) -> Set<A>
export function compl<A>(s: Set<A>) -> Set<A>
export function empty<A>() -> Set<A>
export function univ<A>() -> Set<A>
export function singleton<A>(x: A) -> Set<A>
```

**Axioms** (classical set theory):
```first
export axiom union_comm<A>(s: Set<A>, t: Set<A>) ->
    Eq(union(s, t), union(t, s))
export axiom inter_comm<A>(s: Set<A>, t: Set<A>) ->
    Eq(inter(s, t), inter(t, s))
export axiom compl_compl<A>(s: Set<A>) ->
    Eq(compl(compl(s)), s)
export axiom de_morgan_union<A>(s: Set<A>, t: Set<A>) ->
    Eq(compl(union(s, t)), inter(compl(s), compl(t)))
export axiom empty_union<A>(s: Set<A>) ->
    Eq(union(empty(), s), s)
export axiom inter_univ<A>(s: Set<A>) ->
    Eq(inter(univ(), s), s)
```

---

## `List` — Polymorphic linked lists

```first
import "List";
```

**Type:**
```first
export type List<A> = Nil | Cons(A, List<A>);
```

**Operations:**
```first
export function length<A>(xs: List<A>) -> Int
export function append<A>(xs: List<A>, ys: List<A>) -> List<A>
export function reverse<A>(xs: List<A>) -> List<A>
export function map<A, B>(xs: List<A>, f: A -> B) -> List<B>
export function filter<A>(xs: List<A>, p: A -> Bool) -> List<A>
export function foldl<A, B>(xs: List<A>, acc: B, f: (B, A) -> B) -> B
export function foldr<A, B>(xs: List<A>, acc: B, f: (A, B) -> B) -> B
export function head<A>(xs: List<A>) -> Option<A>
export function tail<A>(xs: List<A>) -> List<A>
```

**Axioms** (structural properties):
```first
export axiom append_nil<A>(xs: List<A>) ->
    Eq(append(xs, Nil), xs)
export axiom append_assoc<A>(xs: List<A>, ys: List<A>, zs: List<A>) ->
    Eq(append(append(xs, ys), zs), append(xs, append(ys, zs)))
export axiom length_append<A>(xs: List<A>, ys: List<A>) ->
    Eq(length(append(xs, ys)), length(xs) + length(ys))
export axiom map_compose<A, B, C>(xs: List<A>, f: A -> B, g: B -> C) ->
    Eq(map(map(xs, f), g), map(xs, function(x: A) -> C { return g(f(x)); }))
export axiom reverse_involutive<A>(xs: List<A>) ->
    Eq(reverse(reverse(xs)), xs)
```

---

## `Finset` — Finite sets of integers

```first
import "Finset";
```

**Type:**
```first
export type IntSet = ISEmpty | ISCons(Int, IntSet);
```

**Operations:**
```first
export function emptySet() -> IntSet
export function singletonSet(elem: Int) -> IntSet
export function memSet(elem: Int, set: IntSet) -> Bool
export function insertSet(elem: Int, set: IntSet) -> IntSet
export function cardSet(set: IntSet) -> Int
export function unionSet(set: IntSet, other: IntSet) -> IntSet
export function interSet(set: IntSet, other: IntSet) -> IntSet
export function subsetSet(set: IntSet, other: IntSet) -> Bool
```

**Axioms:**
```first
export axiom mem_empty(elem: Int) -> Eq(memSet(elem, emptySet()), false)
export axiom mem_singleton(elem: Int, y: Int) -> Eq(memSet(elem, singletonSet(y)), elem == y)
export axiom mem_insert(elem: Int, y: Int, set: IntSet) ->
    Eq(memSet(elem, insertSet(y, set)), (elem == y) || memSet(elem, set))
export axiom mem_union(elem: Int, set: IntSet, other: IntSet) ->
    Eq(memSet(elem, unionSet(set, other)), memSet(elem, set) || memSet(elem, other))
export axiom mem_inter(elem: Int, set: IntSet, other: IntSet) ->
    Eq(memSet(elem, interSet(set, other)), memSet(elem, set) && memSet(elem, other))
export axiom card_empty() -> Eq(cardSet(emptySet()), 0)
export axiom subset_refl(set: IntSet) -> Eq(subsetSet(set, set), true)
```

**Proved theorems:**
```first
export theorem empty_not_mem(elem: Int) -> Eq(memSet(elem, emptySet()), false)
export theorem singleton_mem_self(elem: Int) -> Eq(memSet(elem, singletonSet(elem)), elem == elem)
export theorem insert_mem_self(elem: Int, set: IntSet) ->
    Eq(memSet(elem, insertSet(elem, set)), true)
```

---

## `Algebra` — Algebraic class hierarchy

```first
import "Algebra";
```

Provides type classes for algebraic structures and instances for `Int` and `Float`. Classes are **flat** (no inheritance — each class declares all its methods independently).

**Classes:**
```first
export class AddMonoid<T> { function zero() -> T; function add(T, T) -> T; }
export class AddGroup<T>  { function zero() -> T; function add(T, T) -> T; function neg(T) -> T; }
export class Ring<T>      { function zero() -> T; function one() -> T;
                            function add(T, T) -> T; function neg(T) -> T; function mul(T, T) -> T; }
export class Field<T>     { function zero() -> T; function one() -> T;
                            function add(T, T) -> T; function neg(T) -> T;
                            function mul(T, T) -> T; function inv(T) -> T; }
export class Ord<T>       { function leq(T, T) -> Bool; }
export class OrderedRing<T> { ... }  // Ring + Ord methods combined
```

**Instances provided:**

| Instance | Type |
|----------|------|
| `AddMonoid<Int>`, `AddGroup<Int>`, `Ring<Int>`, `Ord<Int>`, `OrderedRing<Int>` | `Int` |
| `AddMonoid<Float>`, `Ring<Float>`, `Field<Float>`, `Ord<Float>` | `Float` |

**Key axioms:**
```first
export axiom ring_add_comm(a: Int, b: Int) -> Eq(add(a, b), add(b, a))
export axiom ring_mul_comm(a: Int, b: Int) -> Eq(mul(a, b), mul(b, a))
export axiom ring_add_assoc(a: Int, b: Int, c: Int) ->
    Eq(add(add(a, b), c), add(a, add(b, c)))
export axiom ring_mul_one(a: Int) -> Eq(mul(a, one()), a)
export axiom ring_add_neg(a: Int) -> Eq(add(a, neg(a)), zero())
export axiom ring_left_distrib(a: Int, b: Int, c: Int) ->
    Eq(mul(a, add(b, c)), add(mul(a, b), mul(a, c)))
export axiom field_mul_inv_float(a: Float) -> Eq(mul(a, inv(a)), one())
export axiom ord_refl_int(a: Int) -> Eq(leq(a, a), true)
```

**Proved theorems:**
```first
export theorem int_add_comm(a: Int, b: Int) -> Eq(add(a, b), add(b, a))
export theorem int_mul_comm(a: Int, b: Int) -> Eq(mul(a, b), mul(b, a))
export theorem int_add_zero(a: Int) -> Eq(add(a, zero()), a)
export theorem int_ord_refl(a: Int) -> Eq(leq(a, a), true)
```

**Example usage:**
```first
import "Algebra";

function ringSum<T>[Ring<T>](a: T, b: T) -> T {
    return add(a, b);
}

theorem ring_add_comm_theorem(a: Int, b: Int) -> Eq(add(a, b), add(b, a)) by {
    exact int_add_comm(a, b);
}
```

---

## `NumberTheory` — Elementary number theory

```first
import "NumberTheory";
```

Provides GCD, LCM, divisibility, and primality over `Int`.

**Functions:**
```first
export function gcd(a: Int, b: Int) -> Int   // Euclidean algorithm
export function lcm(a: Int, b: Int) -> Int
export function divides(d: Int, n: Int) -> Bool
export function isPrime(n: Int) -> Bool       // trial division
```

**GCD axioms:**
```first
export axiom gcd_comm(a: Int, b: Int) -> Eq(gcd(a, b), gcd(b, a))
export axiom gcd_zero(a: Int) -> Eq(gcd(a, 0), a)
export axiom gcd_self(a: Int) -> Eq(gcd(a, a), a)
export axiom gcd_divides_left(a: Int, b: Int) -> Eq(divides(gcd(a, b), a), true)
export axiom gcd_divides_right(a: Int, b: Int) -> Eq(divides(gcd(a, b), b), true)
export axiom gcd_greatest(a: Int, b: Int, d: Int) ->
    Eq(divides(d, a) && divides(d, b), true) -> Eq(divides(d, gcd(a, b)), true)
```

**Divisibility axioms:**
```first
export axiom divides_refl(a: Int) -> Eq(divides(a, a), true)
export axiom divides_trans(a: Int, b: Int, c: Int) ->
    Eq(divides(a, b) && divides(b, c), true) -> Eq(divides(a, c), true)
```

**Primality axioms:**
```first
export axiom prime_two() -> Eq(isPrime(2), true)
export axiom prime_three() -> Eq(isPrime(3), true)
export axiom prime_gt_one(p: Int) -> Eq(isPrime(p), true) -> Eq(p > 1, true)
export axiom prime_not_composite(p: Int, a: Int, b: Int) ->
    Eq(isPrime(p), true) -> Eq(p, a * b) -> Eq(a == 1 || b == 1, true)
export axiom gcd_prime_coprime(p: Int, n: Int) ->
    Eq(isPrime(p), true) -> Eq(divides(p, n), false) -> Eq(gcd(p, n), 1)
```

**Proved theorems:**
```first
export theorem gcd_zero_right(a: Int) -> Eq(gcd(a, 0), a)
export theorem gcd_self_eq(a: Int) -> Eq(gcd(a, a), a)
export theorem two_is_prime() -> Eq(isPrime(2), true)
export theorem three_is_prime() -> Eq(isPrime(3), true)
export theorem gcd_divides(a: Int, b: Int) -> Eq(divides(gcd(a, b), a), true)
export theorem divides_self(a: Int) -> Eq(divides(a, a), true)
```

---

## Module summary

| Module | Type | Proof style |
|--------|------|-------------|
| `Nat` | `Zero \| Succ(Nat)` | Proved theorems |
| `Int` | built-in `Int` | Mixed: `ring`/`omega` proofs + order axioms |
| `Real` | opaque `__MkReal(Float)` | All axioms |
| `Rat` | `MkRat(Int, Int)` | All axioms |
| `Complex` | `MkComplex(Float, Float)` | All axioms |
| `Bool` | built-in `Bool` | All proved via `decide` |
| `Set<A>` | `MkSet(A -> Bool)` | All axioms |
| `List<A>` | `Nil \| Cons(A, List<A>)` | All axioms |
| `Finset` | `ISEmpty \| ISCons(Int, IntSet)` | 7 axioms + 3 proved theorems |
| `Algebra` | type classes (Ring/Field/Ord/…) | 11 axioms + 4 proved theorems |
| `NumberTheory` | GCD/LCM/primality over Int | 15 axioms + 6 proved theorems |

---

## Summary

Import a module with `import "ModuleName"`. Use its exported functions in your code, and use its exported theorems in your proofs via `exact`, `simp`, `apply`, and `rw`.

Chapter 22 covers **type classes in proofs** — writing generic theorems that work over any type satisfying a class constraint (like `Ring` or `Ord`).
