# Chapter 18: Advanced Tactics

Chapter 17 covered the tactics you will use on most day-to-day proofs. This chapter covers the tactics needed for **structural reasoning** (induction, case analysis), **classical logic** (proof by contradiction, contrapositive, negation pushing), and **tactic combinators** (`try`, `repeat`, `first`). These let you tackle recursive, non-constructive, and multi-branch proofs.

---

## Tier 4: Structural tactics

### `induction`

Proves a goal by **mathematical induction** over a natural number or an inductively-defined type.

```first
import "Nat";

// Sum 0..n = n*(n+1)/2
theorem sum_formula(n: Nat) -> Eq(2 * sumTo(n), n * (n + 1)) by {
    induction n {
        case Zero => { ring; }
        case Succ(k) ih => {
            -- ih: Eq(2 * sumTo(k), k * (k + 1))
            simp [sumTo_succ];
            linarith [ih];
        }
    }
}
```

The `ih` identifier is the induction hypothesis. It has the same form as the goal but with `n` replaced by the predecessor.

For lists:

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

### `cases`

Splits a goal by **case analysis** on a sum type, `Bool`, `Option<T>`, or any ADT — without the induction hypothesis.

```first
theorem option_map_none<A, B>(f: A -> B) -> Eq(map(none(), f), none()) by {
    cases none() {
        case None => { refl; }
        case Some(_) => { refl; }
    }
}

theorem bool_cases(b: Bool) -> Eq(b || (!b), true) by {
    cases b {
        case true => { decide; }
        case false => { decide; }
    }
}
```

Use `cases` when you need to reason about which variant a value has, but don't need an induction hypothesis.

### `obtain`

Destructs a hypothesis of a product, sigma, or existential type into named components.

```first
theorem fst_pair<A, B>(p: { first: A, second: B }) -> A by {
    obtain ⟨a, b⟩ := p;
    exact a;
}
```

### `use`

Provides the witness for an existential goal `∃ x, P(x)`.

```first
theorem exists_even() -> Eq(∃ n: Int, n % 2 == 0, true) by {
    use 4;
    decide;
}
```

---

## Tier 5: Classical-logic tactics

### `calc`

Proves a goal through a **chain of equalities or inequalities**, making each step explicit.

```first
theorem calc_example(a: Int, b: Int) -> Eq(a + b + (a + b), 2 * a + 2 * b) by {
    calc (a + b + (a + b))
        == (a + b) * 2        by { ring; }
     == 2 * (a + b)           by { ring; }
     == 2 * a + 2 * b         by { ring; }
}
```

Each `==` step must be closed by a tactic proof. The final right-hand side must match the goal.

You can also chain inequalities:

```first
theorem chain_ineq(n: Int, h: Eq(n >= 1, true)) -> Eq(n * n >= 1, true) by {
    calc n * n
        >= 1 * n     by { linarith [h]; }
     >= 1 * 1        by { linarith [h]; }
     == 1            by { ring; }
}
```

### `by_contra`

Proves a goal `P` by **assuming ¬P** and deriving a contradiction.

```first
theorem not_zero(n: Nat, h: Eq(n > 0, true)) -> Eq(n != 0, true) by {
    by_contra hc;
    -- hc: Eq(n == 0, true)
    omega;   -- contradicts h: n > 0
}
```

### `push_neg`

Pushes negations inward through quantifiers and connectives, simplifying `¬(∀ x, P x)` to `∃ x, ¬P x`, etc.

```first
theorem not_forall_eq_exists_ne() ->
    Eq(¬(∀ n: Int, n > 0), ∃ n: Int, ¬(n > 0)) by {
    push_neg;
    refl;
}
```

### `contrapose`

Replaces a goal `P → Q` with its contrapositive `¬Q → ¬P`.

```first
theorem contrapose_example(n: Int, h: Eq(n % 2 == 0, false)) ->
    Eq(n != 0, true) by {
    contrapose;
    -- new goal: Eq(n == 0, true) → Eq(n % 2 == 0, true)
    intro hz;
    rw [hz];
    decide;
}
```

### `intro`

Introduces the hypothesis of an implication into the local context.

```first
theorem modus_ponens(P: Prop, Q: Prop, h: P, hpq: P -> Q) -> Q by {
    exact hpq(h);
}

-- Or using intro:
theorem impl_intro(n: Int) -> (Eq(n > 0, true) -> Eq(n >= 1, true)) by {
    intro h;
    omega;
}
```

### `exfalso`

Replace any goal with `False`. Useful when you have a contradictory hypothesis.

```first
theorem from_false(h: Eq(1, 2)) -> Eq(0, 1) by {
    exfalso;
    -- goal is now False
    -- h: Eq(1, 2) is a contradiction — discriminate handles it
    discriminate h;
}
```

### `discriminate`

Proves `False` from a hypothesis equating two distinct constructors.

```first
theorem succ_ne_zero(n: Nat) -> Eq(Succ(n) != Zero, true) by {
    by_contra h;
    discriminate h;
}
```

### `injection`

Extracts the argument equality from an equality between constructors:  
`Eq(Succ(m), Succ(n)) → Eq(m, n)`.

```first
theorem succ_inj(m: Nat, n: Nat, h: Eq(Succ(m), Succ(n))) -> Eq(m, n) by {
    injection h;
    assumption;
}
```

### `specialize`

Instantiate a universally quantified hypothesis with specific values.

```first
theorem specialize_example(h: ∀ n: Int, Eq(n + 0, n)) -> Eq(5 + 0, 5) by {
    specialize h 5;
    exact h;
}
```

### `symm`

Swap the two sides of an `Eq` goal: turn `Eq(a, b)` into `Eq(b, a)`.

```first
theorem symm_example(a: Int, b: Int, h: Eq(a, b)) -> Eq(b, a) by {
    symm;
    exact h;
}
```

### `congr`

Prove `Eq(f(a), f(b))` by reducing to `Eq(a, b)` — congruence of a function application.

```first
theorem congr_example(n: Int, h: Eq(n, 5)) -> Eq(n + 1, 5 + 1) by {
    congr;
    exact h;
}
```

---

## Tactic combinators

Tactic combinators let you build composite tactics from simpler ones without writing new C++ or new `tactic` declarations.

### `try { tac; }`

Runs `tac` and **always succeeds** — if `tac` fails, the goal is left unchanged (no error).

```first
theorem try_example(a: Int, b: Int) -> Eq(a + b, b + a) by {
    try { refl; }   -- fails silently: a+b and b+a are not definitionally equal
    ring;           -- ring closes it
}
```

`try` is useful before a tactic that might not apply (e.g., `try { simp; }` to simplify if possible, then continue).

### `repeat { tac; }`

Runs `tac` **repeatedly** until it fails or the goal is closed.

```first
theorem repeat_simp(a: Int) -> Eq(((a + 0) + 0) + 0, a) by {
    repeat { simp [add_zero]; }   -- applies add_zero as many times as needed
}
```

`repeat` is most useful with `simp` variants or rewriting rules that make incremental progress. Avoid it with tactics that do not make the goal strictly smaller — it will loop.

### `first { t1; } | { t2; } | { t3; }`

Tries each branch in order and uses the **first one that succeeds**. If all branches fail, the whole tactic fails.

```first
theorem first_example(a: Int, b: Int) -> Eq(a + b, b + a) by {
    first { refl; } | { ring; }   -- refl fails, ring succeeds
}

-- Auto-arithmetic: try ring, then omega, then linarith
theorem auto_arith(a: Int, b: Int) -> Eq(a * b, b * a) by {
    first { ring; } | { omega; } | { linarith; }
}
```

The `first` combinator is the core building block for user-defined automation tactics (see Chapter 20).

### Combining combinators

```first
// Try simp; if it doesn't close the goal, fall back to ring or omega
theorem combined(n: Int) -> Eq(n + 0, n) by {
    first { simp; } | { ring; } | { omega; }
}

// Apply simp_lemma wherever it matches, then close with ring
theorem repeat_and_ring(a: Int, b: Int) -> Eq((a + 0) * (b + 0), a * b) by {
    repeat { try { simp [add_zero]; } }
    ring;
}
```

---

## Putting it together: a complete induction proof

```first
import "List";

// reverse (reverse l) = l
theorem reverse_involutive<A>(l: List<A>) -> Eq(reverse(reverse(l)), l) by {
    induction l {
        case Nil => {
            simp [reverse];
        }
        case Cons(h, t) ih => {
            simp [reverse, reverse_append];
            rw [ih];
            simp [reverse];
        }
    }
}
```

---

## Choosing the right tactic

| Situation | Tactic |
|-----------|--------|
| `Eq(a, a)` after computation | `refl` |
| Polynomial/ring identity | `ring` |
| Linear arithmetic | `omega` / `linarith` |
| Decide a finite case | `decide` |
| Known lemma | `exact lemma_name(args)` |
| Rewrite using a hypothesis | `rw [h]` |
| Step-by-step chain | `calc` |
| Inductive type | `induction` |
| ADT/sum-type split | `cases` |
| Proof by contradiction | `by_contra` |
| Negation normal form | `push_neg` |
| Contrapositive | `contrapose` |
| Constructor mismatch | `discriminate` |
| Constructor injectivity | `injection` |

---

## Summary

- `induction` — prove over `Nat`, `List`, any ADT; `ih` is the induction hypothesis
- `cases` — split on ADT variant without induction hypothesis
- `obtain` — destructs product/sigma hypotheses
- `use` — provide existential witness
- `calc` — explicit equational/inequality chains
- `by_contra` — assume negation, derive contradiction
- `push_neg` — push negations inward
- `contrapose` — switch to contrapositive
- `symm`, `congr`, `injection`, `discriminate`, `specialize`, `exfalso` — utility tactics
- `try { t; }` — run t, never fail
- `repeat { t; }` — run t until it fails
- `first { t1; } | { t2; }` — try branches in order, use first success

Chapter 19 applies all of these to **proving properties of programs** — theorems about functions you write yourself.
