lean4-htt/tests/lean/run/issue2021.lean
Joachim Breitner f9dc77673b
feat: dedicated fix operator for well-founded recursion on Nat (#7965)
This PR lets recursive functions defined by well-founded recursion use a
different `fix` function when the termination measure is of type `Nat`.
This fix-point operator use structural recursion on “fuel”, initialized
by the given measure, and is thus reasonable to reduce, e.g. in `by
decide` proofs.

Extra provisions are in place that the fixpoint operator only starts
reducing when the fuel is fully known, to prevent “accidential” defeqs
when the remaining fuel for the recursive calls match the initial fuel
for that recursive argument.

To opt-out, the idiom `termination_by (n,0)` can be used.

We still use `@[irreducible]` as the default for such recursive
definitions, to avoid unexpected `defeq` lemmas. Making these functions
`@[semireducible]` by default showed performance regressions in lean.
When the measure is of type `Nat`, the system will accept an explicit
`@[semireducible]` without the usual warning.

Fixes #5234. Fixes: #11181.
2025-12-01 12:51:55 +00:00

46 lines
1.3 KiB
Text

prelude -- optional
import Init.WF
import Init.WFTactics
import Init.Data.Nat.Basic
namespace Nat'
protected def modCore (y : Nat) : Nat → Nat → Nat
| Nat.zero, x => x
| Nat.succ fuel, x => if 0 < y ∧ y ≤ x then Nat'.modCore y fuel (x - y) else x
protected def mod' (x y : @& Nat) : Nat :=
Nat'.modCore y x x
@[simp] theorem zero_mod' (b : Nat) : Nat'.mod' 0 b = 0 := rfl
end Nat'
namespace Nat
private def gcdF' (x : Nat) : (∀ x₁, x₁ < x → Nat → Nat) → Nat → Nat :=
match x with
| 0 => fun _ y => y
| succ x => fun f y => f (Nat'.mod' y (succ x)) sorry (succ x)
noncomputable def gcd' (a b : Nat) : Nat :=
WellFounded.fix (measure id).wf gcdF' a b
@[simp] theorem gcd'_zero_left (y : Nat) : gcd' 0 y = y :=
rfl
theorem gcd'_succ (x y : Nat) : gcd' (succ x) y = gcd' (Nat'.mod' y (succ x)) (succ x) :=
rfl -- replace with `id rfl` and everything is ok
/--
error: (kernel) application type mismatch
@Eq.ndrec Nat (n✝ + 1) (fun n => gcd' n 0 = n) (of_eq_true (eq_self (n✝ + 1)))
argument has type
n✝ + 1 = n✝ + 1
but function has type
(fun n => gcd' n 0 = n) (n✝ + 1) → ∀ {b : Nat}, n✝ + 1 = b → (fun n => gcd' n 0 = n) b
-/
#guard_msgs in
@[simp] theorem gcd'_zero_right (n : Nat) : gcd' n 0 = n := by
cases n <;> simp [gcd'_succ]
end Nat