source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/mathlib/Archive/Imo/Imo2019Q4.lean | import Mathlib.Data.Nat.Factorial.BigOperators
import Mathlib.Data.Nat.Multiplicity
import Mathlib.Data.Nat.Prime.Int
import Mathlib.Tactic.IntervalCases
import Mathlib.Tactic.GCongr
/-!
# IMO 2019 Q4
Find all pairs `(k, n)` of positive integers such that
```
k! = (2 ^ n - 1)(2 ^ n - 2)(2 ^ n - 4)···(2 ^ n - 2 ^ (n - 1))
```
We show in this file that this property holds iff `(k, n) = (1, 1) ∨ (k, n) = (3, 2)`.
Proof sketch:
The idea of the proof is to count the factors of 2 on both sides. The LHS has less than `k` factors
of 2, and the RHS has exactly `n * (n - 1) / 2` factors of 2. So we know that `n * (n - 1) / 2 < k`.
Now for `n ≥ 6` we have `RHS < 2 ^ (n ^ 2) < (n(n-1)/2)! < k!`. We then treat the cases `n < 6`
individually.
-/
open scoped Nat
open Nat hiding zero_le Prime
open Finset
namespace Imo2019Q4
theorem upper_bound {k n : ℕ} (hk : k > 0)
(h : (k ! : ℤ) = ∏ i ∈ range n, ((2 : ℤ) ^ n - (2 : ℤ) ^ i)) : n < 6 := by
have h2 : ∑ i ∈ range n, i < k := by
suffices emultiplicity 2 (k ! : ℤ) = ↑(∑ i ∈ range n, i : ℕ) by
rw [← Nat.cast_lt (α := ℕ∞), ← this]; change emultiplicity ((2 : ℕ) : ℤ) _ < _
simp_rw [Int.natCast_emultiplicity, emultiplicity_two_factorial_lt hk.lt.ne.symm]
rw [h, Finset.emultiplicity_prod Int.prime_two, Nat.cast_sum]
apply sum_congr rfl; intro i hi
rw [emultiplicity_sub_of_gt, emultiplicity_pow_self_of_prime Int.prime_two]
rwa [emultiplicity_pow_self_of_prime Int.prime_two,
emultiplicity_pow_self_of_prime Int.prime_two, Nat.cast_lt, ← mem_range]
rw [← not_le]; intro hn
apply _root_.ne_of_gt _ h
calc ∏ i ∈ range n, ((2:ℤ) ^ n - (2:ℤ) ^ i) ≤ ∏ __ ∈ range n, (2:ℤ) ^ n := ?_
_ < ↑ k ! := ?_
· gcongr
· intro i hi
simp only [mem_range] at hi
have : (2:ℤ) ^ i ≤ (2:ℤ) ^ n := by gcongr; norm_num
linarith
· apply sub_le_self
positivity
norm_cast
calc ∏ __ ∈ range n, 2 ^ n = 2 ^ (n * n) := by rw [prod_const, card_range, ← pow_mul]
_ < (∑ i ∈ range n, i)! := ?_
_ ≤ k ! := by gcongr
clear h h2
induction n, hn using Nat.le_induction with
| base => decide
| succ n' hn' IH =>
let A := ∑ i ∈ range n', i
have le_sum : ∑ i ∈ range 6, i ≤ A := by
apply sum_le_sum_of_subset
simpa using hn'
calc 2 ^ ((n' + 1) * (n' + 1))
≤ 2 ^ (n' * n' + 4 * n') := by gcongr <;> linarith
_ = 2 ^ (n' * n') * (2 ^ 4) ^ n' := by rw [← pow_mul, ← pow_add]
_ < A ! * (2 ^ 4) ^ n' := by gcongr
_ = A ! * (15 + 1) ^ n' := rfl
_ ≤ A ! * (A + 1) ^ n' := by gcongr; exact le_sum
_ ≤ (A + n')! := factorial_mul_pow_le_factorial
_ = (∑ i ∈ range (n' + 1), i)! := by rw [sum_range_succ]
end Imo2019Q4
theorem imo2019_q4 {k n : ℕ} (hk : k > 0) (hn : n > 0) :
(k ! : ℤ) = ∏ i ∈ range n, ((2:ℤ) ^ n - (2:ℤ) ^ i) ↔ (k, n) = (1, 1) ∨ (k, n) = (3, 2) := by
-- The implication `←` holds.
constructor
swap
· rintro (h | h) <;> simp [Prod.ext_iff] at h <;> rcases h with ⟨rfl, rfl⟩ <;> decide
intro h
-- We know that n < 6.
have := Imo2019Q4.upper_bound hk h
interval_cases n
-- n = 1
· norm_num at h; simp [le_antisymm h (succ_le_of_lt hk)]
-- n = 2
· right; congr; norm_num [prod_range_succ] at h; norm_cast at h; rwa [← factorial_inj']
norm_num
all_goals exfalso; norm_num [prod_range_succ] at h; norm_cast at h
-- n = 3
· refine monotone_factorial.ne_of_lt_of_lt_nat 5 ?_ ?_ _ h <;> decide
-- n = 4
· refine monotone_factorial.ne_of_lt_of_lt_nat 7 ?_ ?_ _ h <;> decide
-- n = 5
· refine monotone_factorial.ne_of_lt_of_lt_nat 10 ?_ ?_ _ h <;> decide |
.lake/packages/mathlib/Archive/Imo/Imo1959Q1.lean | import Mathlib.Tactic.Ring
import Mathlib.Data.Nat.Prime.Basic
/-!
# IMO 1959 Q1
Prove that the fraction `(21n+4)/(14n+3)` is irreducible for every natural number `n`.
Since Lean doesn't have a concept of "irreducible fractions" per se, we just formalize this
as saying the numerator and denominator are relatively prime.
-/
open Nat
namespace Imo1959Q1
theorem calculation (n k : ℕ) (h1 : k ∣ 21 * n + 4) (h2 : k ∣ 14 * n + 3) : k ∣ 1 :=
have h3 : k ∣ 2 * (21 * n + 4) := h1.mul_left 2
have h4 : k ∣ 3 * (14 * n + 3) := h2.mul_left 3
have h5 : 3 * (14 * n + 3) = 2 * (21 * n + 4) + 1 := by ring
(Nat.dvd_add_right h3).mp (h5 ▸ h4)
end Imo1959Q1
open Imo1959Q1
theorem imo1959_q1 : ∀ n : ℕ, Coprime (21 * n + 4) (14 * n + 3) := fun n =>
coprime_of_dvd' fun k _ h1 h2 => calculation n k h1 h2 |
.lake/packages/mathlib/Archive/Imo/Imo2011Q3.lean | import Mathlib.Data.Real.Basic
import Mathlib.Tactic.Linarith
/-!
# IMO 2011 Q3
Let f : ℝ → ℝ be a function that satisfies
f(x + y) ≤ y * f(x) + f(f(x))
for all x and y. Prove that f(x) = 0 for all x ≤ 0.
## Solution
Direct translation of the solution found in https://www.imo-official.org/problems/IMO2011SL.pdf
-/
theorem imo2011_q3 (f : ℝ → ℝ) (hf : ∀ x y, f (x + y) ≤ y * f x + f (f x)) : ∀ x ≤ 0, f x = 0 := by
-- reparameterize
have hxt : ∀ x t, f t ≤ t * f x - x * f x + f (f x) := fun x t =>
calc
f t = f (x + (t - x)) := by rw [add_eq_of_eq_sub' rfl]
_ ≤ (t - x) * f x + f (f x) := hf x (t - x)
_ = t * f x - x * f x + f (f x) := by rw [sub_mul]
have h_ab_combined : ∀ a b, a * f a + b * f b ≤ 2 * f a * f b := fun a b => by
linarith [hxt b (f a), hxt a (f b)]
have h_f_nonneg_of_pos : ∀ a < 0, 0 ≤ f a := fun a han =>
suffices a * f a ≤ 0 from nonneg_of_mul_nonpos_right this han
add_le_iff_nonpos_left.mp (h_ab_combined a (2 * f a))
have h_f_nonpos : ∀ x, f x ≤ 0 := fun x => by
by_contra h_suppose_not
-- If we choose a small enough argument for f, then we get a contradiction.
let s := (x * f x - f (f x)) / f x
have hm : min 0 s - 1 < s := (sub_one_lt _).trans_le (min_le_right 0 s)
have hml : min 0 s - 1 < 0 := (sub_one_lt _).trans_le (min_le_left 0 s)
suffices f (min 0 s - 1) < 0 from not_le.mpr this (h_f_nonneg_of_pos (min 0 s - 1) hml)
have hp : 0 < f x := not_le.mp h_suppose_not
calc
f (min 0 s - 1) ≤ (min 0 s - 1) * f x - x * f x + f (f x) := hxt x (min 0 s - 1)
_ < s * f x - x * f x + f (f x) := by linarith [mul_lt_mul_of_pos_right hm hp]
_ = 0 := by rw [(eq_div_iff hp.ne.symm).mp rfl]; linarith
have h_fx_zero_of_neg : ∀ x < 0, f x = 0 := fun x hxz =>
(h_f_nonpos x).antisymm (h_f_nonneg_of_pos x hxz)
intro x hx
obtain (h_x_neg : x < 0) | (rfl : x = 0) := hx.lt_or_eq
· exact h_fx_zero_of_neg _ h_x_neg
· suffices 0 ≤ f 0 from le_antisymm (h_f_nonpos 0) this
have hno : f (-1) = 0 := h_fx_zero_of_neg (-1) neg_one_lt_zero
have hp := hxt (-1) (-1)
rw [hno] at hp
linarith |
.lake/packages/mathlib/Archive/Imo/Imo2024Q6.lean | import Mathlib.Data.Rat.Floor
import Mathlib.SetTheory.Cardinal.Basic
/-!
# IMO 2024 Q6
A function `f: ℚ → ℚ` is called *aquaesulian* if the following
property holds: for every `x, y ∈ ℚ`,
`f(x + f(y)) = f(x) + y` or `f(f(x) + y) = x + f(y)`.
Show that there exists an integer `c` such that for any aquaesulian function `f` there are at
most `c` different rational numbers of the form `f(r)+f(-r)` for some rational number `r`,
and find the smallest possible value of `c`.
We follow Solution 1 from the
[official solutions](https://www.imo2024.uk/s/IMO-2024-Paper-1-Solutions.pdf). A key observation
is that `f(-f(-x)) = x`. We then consider a pair of distinct nonzero values of `f(x)+f(-x)`,
and a series of manipulations together with the previous observation result in a contradiction,
so there are at most two values of `f(x)+f(-x)`. All this works over any `AddCommGroup`; over
`ℚ`, we then show that `⌊x⌋ - Int.fract x` achieves two different values of `f(x)+f(-x)`.
-/
namespace Imo2024Q6
open scoped Cardinal
namespace General
variable {G : Type*} [AddCommGroup G]
/-- The condition on functions in the problem (for a general `AddCommGroup` and in
symmetric form). -/
def Aquaesulian (f : G → G) : Prop := ∀ x y, f (f y + x) = f x + y ∨ f (f x + y) = f y + x
variable {f : G → G} (h : Aquaesulian f)
include h
lemma Aquaesulian.apply_apply_add (x : G) : f (f x + x) = f x + x := by
rcases h x x with hx | hx <;> exact hx
lemma Aquaesulian.eq_of_apply_eq_inl {x₁ x₂ : G} (he : f x₁ = f x₂)
(hc : f (f x₁ + x₂) = f x₂ + x₁) : x₁ = x₂ := by
rw [he, h.apply_apply_add, add_right_inj] at hc
exact hc.symm
lemma Aquaesulian.injective : Function.Injective f := by
intro x₁ x₂ he
rcases h x₁ x₂ with hc | hc
· exact (h.eq_of_apply_eq_inl he.symm hc).symm
· exact h.eq_of_apply_eq_inl he hc
@[simp]
lemma Aquaesulian.apply_zero : f 0 = 0 := by
refine h.injective ?_
convert h.apply_apply_add 0 using 1 <;> simp
@[simp]
lemma Aquaesulian.apply_neg_apply_add (x : G) : f (-(f x)) + x = 0 := by
rcases h x (-(f x)) with hc | hc
· rw [add_neg_cancel, ← h.apply_zero] at hc
exact h.injective hc
· rw [add_neg_cancel, h.apply_zero] at hc
exact hc.symm
@[simp]
lemma Aquaesulian.apply_neg_apply (x : G) : f (-(f x)) = -x := by
rw [← add_eq_zero_iff_eq_neg]
exact h.apply_neg_apply_add x
lemma Aquaesulian.apply_neg_apply_neg (x : G) : f (-(f (-x))) = x := by
simp [h]
lemma Aquaesulian.apply_neg_of_apply_eq {x₁ x₂ : G} (hx : f x₁ = x₂) : f (-x₂) = -x₁ := by
rw [← hx]
exact h.apply_neg_apply _
lemma Aquaesulian.apply_neg_eq_neg_iff {x₁ x₂ : G} : f (-x₂) = -x₁ ↔ f x₁ = x₂ := by
refine ⟨fun hn ↦ ?_, h.apply_neg_of_apply_eq⟩
convert h.apply_neg_of_apply_eq hn <;> rw [neg_neg]
lemma Aquaesulian.pair_lemma {x u v : G} (huv : u ≠ v) (hx : f x = u ∨ f u = x)
(hy : f x = v ∨ f v = x) : f x = v ∨ f x = u := by
rcases hx with hx | hx <;> rcases hy with hy | hy
· exact (huv (hx.symm.trans hy)).elim
· exact .inr hx
· exact .inl hy
· exact ((h.injective.ne huv) (hx.trans hy.symm)).elim
lemma Aquaesulian.g_two {x y u v : G} (huv : u ≠ v) (hx : f x + f (-x) = u)
(hy : f y + f (-y) = v) :
f (x + y) = -(f (-x)) + -(f (-y)) + v ∨ f (x + y) = -(f (-x)) + -(f (-y)) + u := by
refine h.pair_lemma ?_ ?_ ?_
· simp [huv]
· convert h x (-(f (-y))) using 2
· rw [h.apply_neg_apply_neg, add_comm]
· rw [← hx]
abel
· rw [← hx]
abel_nf
· rw [h.apply_neg_apply_neg, add_comm]
· convert h y (-(f (-x))) using 2
· rw [h.apply_neg_apply_neg]
· rw [← hy]
abel
· rw [← hy]
abel_nf
· rw [h.apply_neg_apply_neg]
lemma Aquaesulian.u_eq_zero {x y u v : G} (huv : u ≠ v) (hx : f x + f (-x) = u)
(hy : f y + f (-y) = v) (hxyv : f (x + y) = -(f (-x)) + -(f (-y)) + v) : u = 0 := by
rw [← eq_sub_iff_add_eq, ← h.apply_neg_eq_neg_iff, neg_sub] at hx
rw [add_comm, ← eq_sub_iff_add_eq] at hy
have hc := h (x + y) (f (-x) - u)
rw [hx, hxyv, neg_add_cancel_left, hy] at hc
rcases hc with hc | hc
· abel_nf at hc
simpa using hc
· nth_rw 2 [← h.apply_neg_apply_neg y] at hc
rw [h.injective.eq_iff, hy] at hc
abel_nf at hc
simp [add_comm, huv] at hc
lemma Aquaesulian.u_eq_zero_or_v_eq_zero {x y u v : G} (huv : u ≠ v) (hx : f x + f (-x) = u)
(hy : f y + f (-y) = v) : u = 0 ∨ v = 0 := by
rcases h.g_two huv hx hy with hxy' | hxy'
· exact .inl (h.u_eq_zero huv hx hy hxy')
· rw [add_comm x y, add_comm (-(f (-x))) (-(f (-y)))] at hxy'
exact .inr (h.u_eq_zero huv.symm hy hx hxy')
lemma Aquaesulian.card_le_two : #(Set.range (fun x ↦ f x + f (-x))) ≤ 2 := by
classical
by_cases! hf : ∀ x, f x + f (-x) = 0
· simp [hf]
· rcases hf with ⟨x, hx⟩
suffices #(Set.range (fun x ↦ f x + f (-x))) ≤ (2 : ℕ) from mod_cast this
rw [Cardinal.mk_le_iff_forall_finset_subset_card_le]
intro s hs
simp_rw [Set.subset_def, Set.mem_range] at hs
refine (Finset.card_le_card_of_surjOn (fun x ↦ f x + f (-x)) ?_).trans
(Finset.card_le_two (a := 0) (b := x))
intro y hy
rcases hs y hy with ⟨t, ht⟩
simp only [Finset.coe_insert, Finset.coe_singleton, Set.mem_image, Set.mem_insert_iff,
Set.mem_singleton_iff, exists_eq_or_imp, neg_zero, exists_eq_left, h.apply_zero,
add_zero]
by_cases h0 : y = 0
· simp [h0]
· refine .inr ?_
by_contra hxy
have huv := h.u_eq_zero_or_v_eq_zero hxy rfl ht
simp [hx, h0] at huv
end General
/-- The condition on functions in the problem (for `ℚ` and in the original form). -/
def Aquaesulian (f : ℚ → ℚ) : Prop := ∀ x y, f (x + f y) = f x + y ∨ f (f x + y) = x + f y
lemma aquaesulian_iff_general {f : ℚ → ℚ} : Aquaesulian f ↔ General.Aquaesulian f := by
rw [Aquaesulian, General.Aquaesulian]
refine forall_congr' (fun x ↦ forall_congr' (fun y ↦ ?_))
rw [add_comm x]
lemma Aquaesulian.card_le_two {f : ℚ → ℚ} (h : Aquaesulian f) :
#(Set.range (fun x ↦ f x + f (-x))) ≤ 2 := by
rw [aquaesulian_iff_general] at h
exact h.card_le_two
/-- An example of a function achieving the maximum number of values of `f(r)+f(-r)`. -/
def fExample (x : ℚ) : ℚ := ⌊x⌋ - Int.fract x
lemma fExample_add (x y : ℚ) : fExample x + y = ⌊x⌋ + ⌊y⌋ + (Int.fract y - Int.fract x) := by
rw [fExample]
nth_rw 1 [← Int.floor_add_fract y]
abel
lemma add_fExample (x y : ℚ) : x + fExample y = ⌊x⌋ + ⌊y⌋ + (Int.fract x - Int.fract y) := by
rw [add_comm, fExample_add]
abel
lemma fExample_intCast_add (x : ℤ) (y : ℚ) : fExample (x + y) = x + fExample y := by
simp_rw [fExample, Int.floor_intCast_add, Int.fract_intCast_add, ← add_sub_assoc]
exact_mod_cast rfl
lemma fExample_of_mem_Ico {x : ℚ} (h : x ∈ Set.Ico 0 1) : fExample x = -x := by
rw [fExample, Int.fract_eq_self.2 h, Int.floor_eq_zero_iff.2 h]
simp
lemma apply_fExample_add_apply_of_fract_le {x y : ℚ} (h : Int.fract y ≤ Int.fract x) :
fExample (x + fExample y) = fExample x + y := by
rw [← sub_nonneg] at h
have h₁ : Int.fract x - Int.fract y < 1 :=
(sub_le_self (Int.fract x) (Int.fract_nonneg y)).trans_lt (Int.fract_lt_one x)
rw [fExample_add, add_fExample, add_assoc, fExample_intCast_add, fExample_intCast_add,
fExample_of_mem_Ico ⟨h, h₁⟩]
abel
lemma aquaesulian_fExample : Aquaesulian fExample := by
intro x y
rcases lt_or_ge (Int.fract x) (Int.fract y) with h | h
· rw [add_comm (fExample x), add_comm x]
exact .inr (apply_fExample_add_apply_of_fract_le h.le)
· exact .inl (apply_fExample_add_apply_of_fract_le h)
lemma fract_fExample (x : ℚ) :
Int.fract (fExample x) = if Int.fract x = 0 then 0 else 1 - Int.fract x := by
by_cases h : Int.fract x = 0
· simp [fExample, h]
· simp [fExample, h, sub_eq_add_neg, Int.fract_neg]
lemma floor_fExample (x : ℚ) :
⌊fExample x⌋ = if Int.fract x = 0 then x else ⌊x⌋ - 1 := by
by_cases h : Int.fract x = 0
· simp only [h, if_true, fExample, sub_zero, Int.floor_intCast]
rw [Int.fract, sub_eq_zero] at h
exact h.symm
· simp only [h, if_false, fExample, sub_eq_add_neg, Int.floor_intCast_add, Int.cast_add,
add_right_inj]
suffices ⌊-Int.fract x⌋ = -1 from mod_cast this
rw [Int.floor_eq_iff]
simp [(Int.fract_nonneg x).lt_of_ne' h, (Int.fract_lt_one x).le]
lemma card_range_fExample : #(Set.range (fun x ↦ fExample x + fExample (-x))) = 2 := by
have h : Set.range (fun x ↦ fExample x + fExample (-x)) = {0, -2} := by
ext x
simp only [Set.mem_range, Set.mem_insert_iff, Set.mem_singleton_iff]
refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩
· rcases h with ⟨y, rfl⟩
rw [← Int.floor_add_fract (fExample y), ← Int.floor_add_fract (fExample (-y))]
by_cases h : Int.fract y = 0
· simp [fract_fExample, floor_fExample, h]
· refine .inr ?_
simp only [fract_fExample, floor_fExample, h, if_false, sub_add_sub_cancel,
Int.fract_neg_eq_zero]
rw [Int.fract_neg h, Int.floor_neg, Int.cast_neg, Int.ceil_eq_add_one_sub_fract h,
← Int.self_sub_fract]
abel_nf
simp
· rcases h with rfl | rfl
· refine ⟨0, by simp [fExample]⟩
· refine ⟨1 / 2, ?_⟩
rw [(by norm_num : (-(1 / 2) : ℚ) = (-1 : ℤ) + (1 / 2 : ℚ)), fExample_intCast_add,
fExample_of_mem_Ico ⟨by simp, by norm_num⟩]
norm_num
rw [h]
simp
/-- The answer 2 is to be determined by the solver of the original problem. -/
theorem _root_.imo2024q6 : (∀ f, Aquaesulian f → #(Set.range (fun x ↦ f x + f (-x))) ≤ (2 : ℕ)) ∧
∀ c : ℕ, (∀ f, Aquaesulian f → #(Set.range (fun x ↦ f x + f (-x))) ≤ c) → 2 ≤ c := by
refine ⟨fun _ ↦ Aquaesulian.card_le_two, fun c h ↦ ?_⟩
replace h := h fExample aquaesulian_fExample
rw [card_range_fExample] at h
exact_mod_cast h
end Imo2024Q6 |
.lake/packages/mathlib/Archive/Imo/Imo2001Q2.lean | import Mathlib.Analysis.SpecialFunctions.Pow.Real
/-!
# IMO 2001 Q2
Let $a$, $b$, $c$ be positive reals. Prove that
$$
\frac{a}{\sqrt{a^2 + 8bc}} +
\frac{b}{\sqrt{b^2 + 8ca}} +
\frac{c}{\sqrt{c^2 + 8ab}} ≥ 1.
$$
## Solution
This proof is based on the bound
$$
\frac{a}{\sqrt{a^2 + 8bc}} ≥
\frac{a^{\frac43}}{a^{\frac43} + b^{\frac43} + c^{\frac43}}.
$$
-/
open Real
variable {a b c : ℝ}
namespace Imo2001Q2
theorem bound (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) :
a ^ 4 / (a ^ 4 + b ^ 4 + c ^ 4) ≤ a ^ 3 / sqrt ((a ^ 3) ^ 2 + ↑8 * b ^ 3 * c ^ 3) := by
rw [div_le_div_iff₀ (by positivity) (by positivity)]
calc a ^ 4 * sqrt ((a ^ 3) ^ 2 + (8:ℝ) * b ^ 3 * c ^ 3)
= a ^ 3 * (a * sqrt ((a ^ 3) ^ 2 + (8:ℝ) * b ^ 3 * c ^ 3)) := by ring
_ ≤ a ^ 3 * (a ^ 4 + b ^ 4 + c ^ 4) := ?_
gcongr
apply le_of_pow_le_pow_left₀ two_ne_zero (by positivity)
rw [mul_pow, sq_sqrt (by positivity), ← sub_nonneg]
calc
(a ^ 4 + b ^ 4 + c ^ 4) ^ 2 - a ^ 2 * ((a ^ 3) ^ 2 + 8 * b ^ 3 * c ^ 3)
= 2 * (a ^ 2 * (b ^ 2 - c ^ 2)) ^ 2 + (b ^ 4 - c ^ 4) ^ 2 +
(2 * (a ^ 2 * b * c - b ^ 2 * c ^ 2)) ^ 2 := by ring
_ ≥ 0 := by positivity
theorem imo2001_q2' (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) :
↑1 ≤ a ^ 3 / sqrt ((a ^ 3) ^ 2 + ↑8 * b ^ 3 * c ^ 3) +
b ^ 3 / sqrt ((b ^ 3) ^ 2 + ↑8 * c ^ 3 * a ^ 3) +
c ^ 3 / sqrt ((c ^ 3) ^ 2 + ↑8 * a ^ 3 * b ^ 3) :=
have H : a ^ 4 + b ^ 4 + c ^ 4 ≠ 0 := by positivity
calc
_ ≥ _ := add_le_add (add_le_add (bound ha hb hc) (bound hb hc ha)) (bound hc ha hb)
_ = 1 := by ring_nf at H ⊢; field
end Imo2001Q2
open Imo2001Q2
theorem imo2001_q2 (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : ↑1 ≤
a / sqrt (a ^ 2 + ↑8 * b * c) + b / sqrt (b ^ 2 + ↑8 * c * a) + c / sqrt (c ^ 2 + ↑8 * a * b) :=
have h3 : ∀ {x : ℝ}, 0 < x → (x ^ (3 : ℝ)⁻¹) ^ 3 = x := fun hx =>
show ↑3 = (3 : ℝ) by simp ▸ rpow_inv_natCast_pow hx.le three_ne_zero
calc
1 ≤ _ := imo2001_q2' (rpow_pos_of_pos ha _) (rpow_pos_of_pos hb _) (rpow_pos_of_pos hc _)
_ = _ := by rw [h3 ha, h3 hb, h3 hc] |
.lake/packages/mathlib/Archive/Imo/Imo1997Q3.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.Group.Submonoid.Membership
import Mathlib.Data.Real.Basic
import Mathlib.Data.Sign.Defs
import Mathlib.GroupTheory.Perm.Sign
import Mathlib.Tactic.Linarith
/-!
# IMO 1997 Q3
Let $x_1, x_2, \dots, x_n$ be real numbers satisfying the conditions
$|x_1 + x_2 + \cdots + x_n| = 1$ and $|x_i| ≤ \frac{n+1}2$ for $i = 1, 2, \dots, n$.
Show that there exists a permutation $y_1, y_2, \dots, y_n$ of $x_1, x_2, \dots, x_n$ such that
$|y_1 + 2y_2 + \cdots + ny_n| ≤ \frac{n+1}2$.
## Solution
For a permutation $π$ let $S(π) = \sum_{i=1}^n i x_{π(i)}$. We wish to show that there exists $π$
with $|S(π)| ≤ \frac{n+1}2$.
Suppose the contrary, that all permutations satisfy $\frac{n+1}2 < |S(π)|$. Then we note that for
two permutations $π, π'$ differing by a swap of adjacent elements, say $x_k$ and $x_{k+1}$,
$|S(π) - S(π')| = |x_k - x_{k+1}| ≤ n + 1$. This being the size of the interval
$[-\frac{n+1}/2, \frac{n+1}/2]$ forbidden to the $|S(π)|$, $S(π)$ and $S(π')$ must be on the
same side of said interval, i.e. they have the same sign.
By induction all the $S(\pi)$ have the same sign.
But now consider the identity permutation $1$ and the reverse permutation $R$. We have
$|S(1) + S(R)| = |(1 + n)x_1 + \cdots + (n + 1)x_n| = (n + 1)|x_1 + \cdots + x_n| = n + 1$.
Since $S(1)$ and $S(R)$ have the same sign yet are strictly larger than $\frac{n+1}2$ in
absolute value, $|S(1) + S(R)| > n + 1$, which yields a contradiction. Therefore the initial
assumption that all permutations satisfy $\frac{n+1}2 < |S(π)|$ must be false; the result follows.
-/
namespace Imo1997Q3
open Equiv Fin Finset SignType
variable {n : ℕ}
/-- The sum $x_1 + 2x_2 + \cdots + nx_n$ mentioned in the problem. -/
def S (x : Fin n → ℝ) (p : Perm (Fin n)) : ℝ :=
∑ i, (i + 1) * x (p i)
lemma sign_eq_of_abs_sub_le {a b c : ℝ} (ha : c / 2 < |a|) (hb : c / 2 < |b|) (hc : 0 < c)
(hs : |a - b| ≤ c) : sign a = sign b := by
rcases lt_trichotomy 0 a with ha' | rfl | ha' <;>
rcases lt_trichotomy 0 b with hb' | rfl | hb' <;>
simp_all [abs_of_pos, abs_of_neg, abs_le] <;> linarith
lemma lt_abs_add_of_sign_eq {a b c : ℝ} (ha : c / 2 < |a|) (hb : c / 2 < |b|) (hc : 0 < c)
(hs : sign a = sign b) : c < |a + b| := by
rcases lt_trichotomy 0 a with ha' | rfl | ha' <;>
rcases lt_trichotomy 0 b with hb' | rfl | hb' <;>
simp_all [abs_of_pos, abs_of_neg, lt_abs]
· left; linarith
· linarith
· right; linarith
/-- For fixed nonempty `x`, assuming the opposite of what is to be proven,
the signs of `S x p` are all the same. -/
lemma sign_eq_of_contra
{x : Fin (n + 1) → ℝ} (hx₂ : ∀ i, |x i| ≤ ((n + 1 : ℕ) + 1) / 2)
(h : ∀ (p : Perm (Fin (n + 1))), ((n + 1 : ℕ) + 1) / 2 < |S x p|) :
∀ p, sign (S x 1) = sign (S x p) := fun p ↦ by
induction p using Submonoid.induction_of_closure_eq_top_right
(Perm.mclosure_swap_castSucc_succ n) with
| one => rfl
| mul_right p s sform ih =>
suffices |S x p - S x (p * s)| ≤ (n + 1 : ℕ) + 1 by
rw [ih]; exact sign_eq_of_abs_sub_le (h _) (h _) (by norm_cast; omega) this
rw [Set.mem_range] at sform; obtain ⟨i, hi⟩ := sform
iterate 2 rw [S, ← sum_add_sum_compl {i.castSucc, i.succ}]
have cg : ∑ j ∈ {i.castSucc, i.succ}ᶜ, (j + 1) * x ((p * s) j) =
∑ j ∈ {i.castSucc, i.succ}ᶜ, (j + 1) * x (p j) := by
congr! 3 with j mj; rw [Perm.mul_apply, ← hi]; congr
rw [mem_compl, mem_insert, mem_singleton, not_or] at mj
exact swap_apply_of_ne_of_ne mj.1 mj.2
rw [cg, add_sub_add_right_eq_sub,
sum_pair (castSucc_lt_succ _).ne, sum_pair (castSucc_lt_succ _).ne,
Perm.mul_apply, Perm.mul_apply, ← hi, swap_apply_left, swap_apply_right,
add_comm, add_sub_add_comm, ← sub_mul, ← sub_mul,
val_succ, coe_castSucc, Nat.cast_add, Nat.cast_one, add_sub_cancel_left, sub_add_cancel_left,
one_mul, neg_one_mul]
calc
_ ≤ |x (p i.succ)| + |-x (p i.castSucc)| := abs_add_le ..
_ ≤ ((n + 1 : ℕ) + 1) / 2 + ((n + 1 : ℕ) + 1) / 2 := by
rw [abs_neg]; exact add_le_add (hx₂ _) (hx₂ _)
_ = _ := add_halves _
lemma S_one_add_S_revPerm
{x : Fin n → ℝ} (hx₁ : |∑ i, x i| = 1) : |S x 1 + S x revPerm| = n + 1 := by
nth_rw 2 [S]; rw [← revPerm.sum_comp _ _ (by simp)]
simp_rw [revPerm_apply, val_rev, rev_rev, S, Perm.one_apply, ← sum_add_distrib, ← add_mul]
have cg : ∑ i : Fin n, (i + 1 + ((n - (i + 1) : ℕ) + 1)) * x i = ∑ i, (n + 1) * x i := by
congr! 2 with i; norm_cast; omega
rw [cg, ← mul_sum, abs_mul, hx₁, mul_one]; exact abs_of_nonneg (by norm_cast; omega)
theorem result {x : Fin n → ℝ} (hx₁ : |∑ i, x i| = 1) (hx₂ : ∀ i, |x i| ≤ (n + 1) / 2) :
∃ p, |S x p| ≤ (n + 1) / 2 := by
match n with
| 0 => simp [S]
| n + 1 =>
by_contra! h
exact (lt_abs_add_of_sign_eq (h _) (h _) (by norm_cast; omega)
(sign_eq_of_contra hx₂ h _)).ne' (S_one_add_S_revPerm hx₁)
end Imo1997Q3 |
.lake/packages/mathlib/Archive/Imo/Imo1982Q1.lean | import Mathlib.Tactic.NormNum
import Mathlib.Tactic.Linarith
import Mathlib.Data.PNat.Basic
/-!
# IMO 1982 Q1
The function `f` is defined for all positive integers `n` and takes on
non-negative integer values. Also, for all `m`, `n`
`f (m + n) - f(m) - f(n) = 0` or `1`
`f 2 = 0`, `f 3 > 0`, and `f 9999 = 3333`.
Determine `f 1982`.
The solution is based on the one at the
[Art of Problem Solving](https://artofproblemsolving.com/wiki/index.php/1982_IMO_Problems/Problem_1)
website.
We prove the helper lemmas:
1. `f m + f n ≤ f(m + n)` `superadditive`.
2. `n * f(m) ≤ f(m * n)` `superhomogeneous`.
3. `a * f a + c * f d ≤ f (a * b + c * d)` `superlinear`, (derived from 1. and 2.).
So we can establish on the one hand that `f 1980 ≤ 660`,
by observing that `660 * 1 = 660 * f3 ≤ f 1980 = f (660 * 3)`.
On the other hand, we establish that `f 1980 ≥ 660`
from `5 * f 1980 + 33 * f 3 ≤ f (5 * 1980 + 33 * 1) = f 9999 = 3333`.
We then conclude `f 1980 = 660` and then eventually determine that either
`f 1982 = 660` or `f 1982 = 661`.
In the latter case we derive a contradiction, because if `f 1982 = 661` then
`3334 = 5 * f 1982 + 29 * f(3) + f(2) ≤ f (5 * 1982 + 29 * 3 + 2) = f 9999 = 3333`.
-/
namespace Imo1982Q1
structure IsGood (f : ℕ+ → ℕ) : Prop where
/-- The function satisfies the functional relation. -/
rel: ∀ m n : ℕ+, f (m + n) = f m + f n ∨ f (m + n) = f m + f n + 1
f₂ : f 2 = 0
hf₃ : 0 < f 3
f_9999 : f 9999 = 3333
namespace IsGood
variable {f : ℕ+ → ℕ} (hf : IsGood f)
include hf
lemma f₁ : f 1 = 0 := by
have h : f 2 = 2 * f 1 ∨ f 2 = 2 * f 1 + 1 := by rw [two_mul]; exact hf.rel 1 1
obtain h₁ | h₂ := hf.f₂ ▸ h
· rw [eq_comm, mul_eq_zero] at h₁
apply h₁.resolve_left
norm_num
· cases Nat.succ_ne_zero _ h₂.symm
lemma f₃ : f 3 = 1 := by
have h : f 3 = f 2 + f 1 ∨ f 3 = f 2 + f 1 + 1 := hf.rel 2 1
rw [hf.f₁, hf.f₂, add_zero, zero_add] at h
exact h.resolve_left hf.hf₃.ne'
lemma superadditive {m n : ℕ+} : f m + f n ≤ f (m + n) := by have h := hf.rel m n; grind
lemma superhomogeneous {m n : ℕ+} : ↑n * f m ≤ f (n * m) := by
induction n with
| one => simp
| succ n' ih =>
calc
↑(n' + 1) * f m = ↑n' * f m + f m := by rw [PNat.add_coe, add_mul, PNat.val_ofNat, one_mul]
_ ≤ f (n' * m) + f m := by gcongr
_ ≤ f (n' * m + m) := hf.superadditive
_ = f ((n' + 1) * m) := by congr; rw [add_mul, one_mul]
lemma superlinear {a b c d : ℕ+} : a * f b + c * f d ≤ f (a * b + c * d) :=
(add_le_add hf.superhomogeneous hf.superhomogeneous).trans hf.superadditive
lemma le_mul_three_apply (n : ℕ+) : n ≤ f (3 * n) := by
rw [← mul_one (n : ℕ), ← hf.f₃, mul_comm 3]
exact hf.superhomogeneous
lemma part_1 : 660 ≤ f (1980) := by
exact hf.le_mul_three_apply 660
lemma part_2 : f 1980 ≤ 660 := by
have h : 5 * f 1980 + 33 * f 3 ≤ 5 * 660 + 33 := by
calc (5 : ℕ+) * f 1980 + (33 : ℕ+) * f 3 ≤ f (5 * 1980 + 33 * 3) := by apply hf.superlinear
_ = f 9999 := by rfl
_ = 5 * 660 + 33 := by rw [hf.f_9999]
rw [hf.f₃, mul_one] at h
-- from 5 * f 1980 + 33 ≤ 5 * 660 + 33 we show f 1980 ≤ 660
linarith
end IsGood
end Imo1982Q1
open Imo1982Q1
lemma imo1982_q1 {f : ℕ+ → ℕ} (hf : IsGood f) : f 1982 = 660 := by
have f_1980 := hf.part_2.antisymm hf.part_1
have h : f 1982 = f 1980 + f 2 ∨ f 1982 = f 1980 + f 2 + 1 := hf.rel 1980 2
rw [f_1980, hf.f₂, add_zero] at h
apply h.resolve_right
intro hr
suffices h : 3334 ≤ 3333 by simp at h
calc
3334 = 5 * f 1982 + 29 * f 3 + f 2 := by rw [hf.f₃, hf.f₂, hr, add_zero, mul_one]
(5 : ℕ+) * f 1982 + (29 : ℕ+) * f 3 + f 2 ≤ f (5 * 1982 + 29 * 3) + f 2 := by
grw [hf.superlinear]
_ ≤ f (5 * 1982 + 29 * 3 + 2) := hf.superadditive
_ = 3333 := hf.f_9999 |
.lake/packages/mathlib/Archive/Imo/Imo2013Q5.lean | import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Algebra.Ring.GeomSum
import Mathlib.Algebra.Ring.Regular
import Mathlib.Data.Real.Archimedean
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.LinearCombination
/-!
# IMO 2013 Q5
Let `ℚ>₀` be the positive rational numbers. Let `f : ℚ>₀ → ℝ` be a function satisfying
the conditions
1. `f(x) * f(y) ≥ f(x * y)`
2. `f(x + y) ≥ f(x) + f(y)`
for all `x, y ∈ ℚ>₀`. Given that `f(a) = a` for some rational `a > 1`, prove that `f(x) = x` for
all `x ∈ ℚ>₀`.
## Solution
We provide a direct translation of the solution found in
https://www.imo-official.org/problems/IMO2013SL.pdf
-/
namespace Imo2013Q5
theorem le_of_all_pow_lt_succ {x y : ℝ} (hx : 1 < x) (hy : 1 < y)
(h : ∀ n : ℕ, 0 < n → x ^ n - 1 < y ^ n) : x ≤ y := by
by_contra! hxy
have hxmy : 0 < x - y := sub_pos.mpr hxy
have hn : ∀ n : ℕ, 0 < n → (x - y) * (n : ℝ) ≤ x ^ n - y ^ n := by
intro n _
have hterm : ∀ i : ℕ, i ∈ Finset.range n → 1 ≤ x ^ i * y ^ (n - 1 - i) := by
intro i _
calc
1 ≤ x ^ i := one_le_pow₀ hx.le
_ = x ^ i * 1 := by ring
_ ≤ x ^ i * y ^ (n - 1 - i) := by gcongr; apply one_le_pow₀ hy.le
calc
(x - y) * (n : ℝ) = (n : ℝ) * (x - y) := by ring
_ = (∑ _i ∈ Finset.range n, (1 : ℝ)) * (x - y) := by
simp only [mul_one, Finset.sum_const, nsmul_eq_mul, Finset.card_range]
_ ≤ (∑ i ∈ Finset.range n, x ^ i * y ^ (n - 1 - i)) * (x - y) := by
gcongr with i hi; apply hterm i hi
_ = x ^ n - y ^ n := geom_sum₂_mul x y n
-- Choose n larger than 1 / (x - y).
obtain ⟨N, hN⟩ := exists_nat_gt (1 / (x - y))
have hNp : 0 < N := mod_cast (one_div_pos.mpr hxmy).trans hN
have :=
calc
1 = (x - y) * (1 / (x - y)) := by field
_ < (x - y) * N := by gcongr
_ ≤ x ^ N - y ^ N := hn N hNp
linarith [h N hNp]
/-- Like `le_of_all_pow_lt_succ`, but with a weaker assumption for `y`.
-/
theorem le_of_all_pow_lt_succ' {x y : ℝ} (hx : 1 < x) (hy : 0 < y)
(h : ∀ n : ℕ, 0 < n → x ^ n - 1 < y ^ n) : x ≤ y := by
refine le_of_all_pow_lt_succ hx ?_ h
by_contra! hy'' : y ≤ 1
-- Then there exists y' such that 0 < y ≤ 1 < y' < x.
have h_y'_lt_x : (x + 1) / 2 < x := by linarith
have h1_lt_y' : 1 < (x + 1) / 2 := by linarith
set y' := (x + 1) / 2
have h_y_lt_y' : y < y' := by linarith
have hh : ∀ n, 0 < n → x ^ n - 1 < y' ^ n := by
intro n hn
calc
x ^ n - 1 < y ^ n := h n hn
_ ≤ y' ^ n := by gcongr
exact h_y'_lt_x.not_ge (le_of_all_pow_lt_succ hx h1_lt_y' hh)
theorem f_pos_of_pos {f : ℚ → ℝ} {q : ℚ} (hq : 0 < q)
(H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) :
0 < f q := by
have num_pos : 0 < q.num := Rat.num_pos.mpr hq
have hmul_pos :=
calc
(0 : ℝ) < q.num := Int.cast_pos.mpr num_pos
_ = ((q.num.natAbs : ℤ) : ℝ) := congr_arg Int.cast (Int.natAbs_of_nonneg num_pos.le).symm
_ ≤ f q.num.natAbs := (H4 q.num.natAbs ((@Int.natAbs_pos q.num).mpr num_pos.ne.symm))
_ = f q.num := by rw [Nat.cast_natAbs, abs_of_nonneg num_pos.le]
_ = f (q * q.den) := by rw [← Rat.mul_den_eq_num]
_ ≤ f q * f q.den := H1 q q.den hq (Nat.cast_pos.mpr q.pos)
have h_f_denom_pos :=
calc
(0 : ℝ) < q.den := Nat.cast_pos.mpr q.pos
_ ≤ f q.den := H4 q.den q.pos
exact pos_of_mul_pos_left hmul_pos h_f_denom_pos.le
theorem fx_gt_xm1 {f : ℚ → ℝ} {x : ℚ} (hx : 1 ≤ x)
(H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y)
(H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) :
(x - 1 : ℝ) < f x := by
have hx0 :=
calc
(x - 1 : ℝ) < ⌊x⌋₊ := mod_cast Nat.sub_one_lt_floor x
_ ≤ f ⌊x⌋₊ := H4 _ (Nat.floor_pos.2 hx)
obtain h_eq | h_lt := (Nat.floor_le <| zero_le_one.trans hx).eq_or_lt
· rwa [h_eq] at hx0
calc
(x - 1 : ℝ) < f ⌊x⌋₊ := hx0
_ < f (x - ⌊x⌋₊) + f ⌊x⌋₊ := (lt_add_of_pos_left _ (f_pos_of_pos (sub_pos.mpr h_lt) H1 H4))
_ ≤ f (x - ⌊x⌋₊ + ⌊x⌋₊) := (H2 _ _ (sub_pos.mpr h_lt) (Nat.cast_pos.2 (Nat.floor_pos.2 hx)))
_ = f x := by ring_nf
theorem pow_f_le_f_pow {f : ℚ → ℝ} {n : ℕ} (hn : 0 < n) {x : ℚ} (hx : 1 < x)
(H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n) :
f (x ^ n) ≤ f x ^ n := by
induction n with
| zero => exfalso; exact Nat.lt_asymm hn hn
| succ pn hpn =>
rcases pn with - | pn
· norm_num
have hpn' := hpn pn.succ_pos
rw [pow_succ x (pn + 1), pow_succ (f x) (pn + 1)]
have hxp : 0 < x := by positivity
calc
_ ≤ f (x ^ (pn + 1)) * f x := H1 (x ^ (pn + 1)) x (pow_pos hxp (pn + 1)) hxp
_ ≤ f x ^ (pn + 1) * f x := by gcongr; exact (f_pos_of_pos hxp H1 H4).le
theorem fixed_point_of_pos_nat_pow {f : ℚ → ℝ} {n : ℕ} (hn : 0 < n)
(H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n)
(H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x) {a : ℚ} (ha1 : 1 < a) (hae : f a = a) :
f (a ^ n) = a ^ n := by
have hh0 : (a : ℝ) ^ n ≤ f (a ^ n) := mod_cast H5 (a ^ n) (one_lt_pow₀ ha1 hn.ne')
have hh1 :=
calc
f (a ^ n) ≤ f a ^ n := pow_f_le_f_pow hn ha1 H1 H4
_ = (a : ℝ) ^ n := by rw [← hae]
exact mod_cast hh1.antisymm hh0
theorem fixed_point_of_gt_1 {f : ℚ → ℝ} {x : ℚ} (hx : 1 < x)
(H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y)
(H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n)
(H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x) {a : ℚ} (ha1 : 1 < a) (hae : f a = a) : f x = x := by
-- Choose n such that 1 + x < a^n.
obtain ⟨N, hN⟩ := pow_unbounded_of_one_lt (1 + x) ha1
have h_big_enough : (1 : ℚ) < a ^ N - x := lt_sub_iff_add_lt.mpr hN
have h1 :=
calc
(x : ℝ) + (a ^ N - x : ℚ) ≤ f x + (a ^ N - x : ℚ) := by gcongr; exact H5 x hx
_ ≤ f x + f (a ^ N - x) := by gcongr; exact H5 _ h_big_enough
have hxp : 0 < x := by positivity
have hNp : 0 < N := by by_contra! H; rw [Nat.le_zero.mp H] at hN; linarith
have h2 :=
calc
f x + f (a ^ N - x) ≤ f (x + (a ^ N - x)) := H2 x (a ^ N - x) hxp (by positivity)
_ = f (a ^ N) := by ring_nf
_ = a ^ N := fixed_point_of_pos_nat_pow hNp H1 H4 H5 ha1 hae
_ = x + (a ^ N - x) := by ring
have heq := h1.antisymm (mod_cast h2)
linarith [H5 x hx, H5 _ h_big_enough]
end Imo2013Q5
open Imo2013Q5
theorem imo2013_q5 (f : ℚ → ℝ) (H1 : ∀ x y, 0 < x → 0 < y → f (x * y) ≤ f x * f y)
(H2 : ∀ x y, 0 < x → 0 < y → f x + f y ≤ f (x + y)) (H_fixed_point : ∃ a, 1 < a ∧ f a = a) :
∀ x, 0 < x → f x = x := by
obtain ⟨a, ha1, hae⟩ := H_fixed_point
have H3 : ∀ x : ℚ, 0 < x → ∀ n : ℕ, 0 < n → ↑n * f x ≤ f (n * x) := by
intro x hx n hn
rcases n with - | n
· exact (lt_irrefl 0 hn).elim
induction n with
| zero => norm_num
| succ pn hpn =>
calc
↑(pn + 2) * f x = (↑pn + 1 + 1) * f x := by norm_cast
_ = (↑pn + 1) * f x + f x := by ring
_ ≤ f (↑pn.succ * x) + f x := by norm_cast; grw [hpn pn.succ_pos]
_ ≤ f ((↑pn + 1) * x + x) := by exact_mod_cast H2 _ _ (mul_pos pn.cast_add_one_pos hx) hx
_ = f ((↑pn + 1 + 1) * x) := by ring_nf
_ = f (↑(pn + 2) * x) := by norm_cast
have H4 : ∀ n : ℕ, 0 < n → (n : ℝ) ≤ f n := by
intro n hn
have hf1 : 1 ≤ f 1 := by
have a_pos : (0 : ℝ) < a := Rat.cast_pos.mpr (zero_lt_one.trans ha1)
suffices ↑a * 1 ≤ ↑a * f 1 by rwa [← mul_le_mul_iff_right₀ a_pos]
calc
↑a * 1 = ↑a := mul_one (a : ℝ)
_ = f a := hae.symm
_ = f (a * 1) := by rw [mul_one]
_ ≤ f a * f 1 := (H1 a 1) (zero_lt_one.trans ha1) zero_lt_one
_ = ↑a * f 1 := by rw [hae]
calc
(n : ℝ) = (n : ℝ) * 1 := (mul_one _).symm
_ ≤ (n : ℝ) * f 1 := by gcongr
_ ≤ f (n * 1) := H3 1 zero_lt_one n hn
_ = f n := by rw [mul_one]
have H5 : ∀ x : ℚ, 1 < x → (x : ℝ) ≤ f x := by
intro x hx
have hxnm1 : ∀ n : ℕ, 0 < n → (x : ℝ) ^ n - 1 < f x ^ n := by
intro n hn
calc
(x : ℝ) ^ n - 1 < f (x ^ n) :=
mod_cast fx_gt_xm1 (one_le_pow₀ hx.le) H1 H2 H4
_ ≤ f x ^ n := pow_f_le_f_pow hn hx H1 H4
have hx' : 1 < (x : ℝ) := mod_cast hx
have hxp : 0 < x := by positivity
exact le_of_all_pow_lt_succ' hx' (f_pos_of_pos hxp H1 H4) hxnm1
have h_f_commutes_with_pos_nat_mul : ∀ n : ℕ, 0 < n → ∀ x : ℚ, 0 < x → f (n * x) = n * f x := by
intro n hn x hx
have h2 : f (n * x) ≤ n * f x := by
rcases n with - | n
· exfalso; exact Nat.lt_asymm hn hn
rcases n with - | n
· norm_num
have hfneq : f n.succ.succ = n.succ.succ := by
have :=
fixed_point_of_gt_1 (Nat.one_lt_cast.mpr (Nat.succ_lt_succ n.succ_pos)) H1 H2 H4 H5 ha1
hae
rwa [Rat.cast_natCast n.succ.succ] at this
rw [← hfneq]
exact H1 (n.succ.succ : ℚ) x (Nat.cast_pos.mpr hn) hx
exact h2.antisymm (H3 x hx n hn)
-- For the final calculation, we expand x as (2 * x.num) / (2 * x.den), because
-- we need the top of the fraction to be strictly greater than 1 in order
-- to apply `fixed_point_of_gt_1`.
intro x hx
have H₀ : x * x.den = x.num := x.mul_den_eq_num
have H : x * (↑(2 * x.den) : ℚ) = (↑(2 * x.num) : ℚ) := by push_cast; linear_combination 2 * H₀
set x2denom := 2 * x.den
set x2num := 2 * x.num
have hx2pos : 0 < 2 * x.den := by positivity
have hx2cnezr : (x2denom : ℝ) ≠ (0 : ℝ) := by positivity
have : 0 < x.num := by rwa [Rat.num_pos]
have hx2num_gt_one : (1 : ℚ) < (2 * x.num : ℤ) := by norm_cast; linarith
apply mul_left_cancel₀ hx2cnezr
calc
x2denom * f x
= f (x2denom * x) := (h_f_commutes_with_pos_nat_mul x2denom hx2pos x hx).symm
_ = f x2num := by congr; linear_combination H
_ = x2num := fixed_point_of_gt_1 hx2num_gt_one H1 H2 H4 H5 ha1 hae
_ = ((x2num : ℚ) : ℝ) := by norm_cast
_ = (↑(x2denom * x) : ℝ) := by congr; linear_combination -H
_ = x2denom * x := by push_cast; rfl |
.lake/packages/mathlib/Archive/Imo/Imo1975Q1.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.Order.Rearrangement
import Mathlib.Data.Real.Basic
import Mathlib.Order.Interval.Finset.Nat
/-!
# IMO 1975 Q1
Let `x₁, x₂, ... , xₙ` and `y₁, y₂, ... , yₙ` be two sequences of real numbers, such that
`x₁ ≥ x₂ ≥ ... ≥ xₙ` and `y₁ ≥ y₂ ≥ ... ≥ yₙ`. Prove that if `z₁, z₂, ... , zₙ` is any permutation
of `y₁, y₂, ... , yₙ`, then `∑ (xᵢ - yᵢ)^2 ≤ ∑ (xᵢ - zᵢ)^2`
## Solution
Firstly, we expand the squares within both sums and distribute into separate finite sums. Then,
noting that `∑ yᵢ ^ 2 = ∑ zᵢ ^ 2`, it remains to prove that `∑ xᵢ * zᵢ ≤ ∑ xᵢ * yᵢ`, which is true
by the Rearrangement Inequality
-/
/- Let `n` be a natural number, `x` and `y` be as in the problem statement and `σ` be the
permutation of natural numbers such that `z = y ∘ σ` -/
variable (n : ℕ) (σ : Equiv.Perm ℕ) (x y : ℕ → ℝ)
theorem imo1975_q1 (hσ : {x | σ x ≠ x} ⊆ Finset.Icc 1 n)
(hx : AntitoneOn x (Finset.Icc 1 n)) (hy : AntitoneOn y (Finset.Icc 1 n)) :
∑ i ∈ Finset.Icc 1 n, (x i - y i) ^ 2 ≤ ∑ i ∈ Finset.Icc 1 n, (x i - y (σ i)) ^ 2 := by
simp only [sub_sq, Finset.sum_add_distrib, Finset.sum_sub_distrib]
-- a finite sum is invariant if we permute the order of summation
have hσy : ∑ i ∈ Finset.Icc 1 n, y i ^ 2 = ∑ i ∈ Finset.Icc 1 n, y (σ i) ^ 2 := by
rw [← Equiv.Perm.sum_comp σ (Finset.Icc 1 n) _ hσ]
-- let's cancel terms appearing on both sides
rw [hσy, add_le_add_iff_right, sub_le_sub_iff_left]
simp only [mul_assoc, ← Finset.mul_sum, zero_lt_two, mul_le_mul_iff_right₀]
-- what's left to prove is a version of the rearrangement inequality
apply MonovaryOn.sum_mul_comp_perm_le_sum_mul _ hσ
-- finally we need to show that `x` and `y` 'vary' together on `[1, n]` and this is due to both of
-- them being `decreasing`
exact AntitoneOn.monovaryOn hx hy |
.lake/packages/mathlib/Archive/Imo/Imo2001Q5.lean | import Mathlib.Geometry.Euclidean.Triangle
/-!
# IMO 2001 Q5
Let `ABC` be a triangle. Let `AP` bisect `∠BAC` and let `BQ` bisect `∠ABC`, with `P` on `BC` and
`Q` on `AC`. If `AB + BP = AQ + QB` and `∠BAC = 60°`, what are the angles of the triangle?
## Solution
We follow the solution from https://web.evanchen.cc/exams/IMO-2001-notes.pdf.
Let `x = ∠ABQ = ∠QBC`; it must be in `(0°, 60°)`. By angle chasing and the law of sines we derive
```
1 + sin 30° / sin (150° - 2x) = (sin x + sin 60°) / sin (120° - x)
```
Solving this equation gives `x = 40°`, yielding `∠ABC = 80°` and `∠ACB = 40°`.
-/
open Affine EuclideanGeometry
open scoped Real
variable {V X : Type*}
variable [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace X] [NormedAddTorsor V X]
noncomputable section
namespace Imo2001Q5
variable (X) in
/-- The problem's configuration. -/
structure Setup where
(A B C P Q : X)
P_on_BC : Wbtw ℝ B P C
AP_bisect_BAC : ∠ B A P = ∠ P A C
Q_on_AC : Wbtw ℝ A Q C
BQ_bisect_ABC : ∠ A B Q = ∠ Q B C
dist_sum : dist A B + dist B P = dist A Q + dist Q B
BAC_eq : ∠ B A C = π / 3
namespace Setup
variable (s : Setup X)
/-! ### Nondegeneracy properties and values of angles -/
lemma A_ne_B : s.A ≠ s.B := by
by_contra h; have := s.BAC_eq
rw [h, angle_self_left] at this; linarith [Real.pi_pos]
lemma A_ne_C : s.A ≠ s.C := by
by_contra h; have := s.BAC_eq
rw [h, angle_self_right] at this; linarith [Real.pi_pos]
lemma B_ne_C : s.B ≠ s.C := by
by_contra h; have := s.BAC_eq
rw [h, angle_self_of_ne s.A_ne_C.symm] at this; linarith [Real.pi_pos]
lemma not_collinear_BAC : ¬Collinear ℝ {s.B, s.A, s.C} := by
simp_rw [collinear_iff_eq_or_eq_or_sin_eq_zero, not_or, s.A_ne_B.symm, s.A_ne_C.symm, s.BAC_eq,
Real.sin_pi_div_three]
simp
lemma BAP_eq : ∠ s.B s.A s.P = π / 6 := by
have := angle_add_of_ne_of_ne s.A_ne_B s.A_ne_C s.P_on_BC
rw [← s.AP_bisect_BAC, ← two_mul, s.BAC_eq] at this; grind
lemma PAC_eq : ∠ s.P s.A s.C = π / 6 := by
have := angle_add_of_ne_of_ne s.A_ne_B s.A_ne_C s.P_on_BC
rw [s.AP_bisect_BAC, ← two_mul, s.BAC_eq] at this; grind
lemma P_ne_B : s.P ≠ s.B := by
by_contra h; have := s.BAP_eq
rw [h, angle_self_of_ne s.A_ne_B.symm] at this; linarith [Real.pi_pos]
lemma P_ne_C : s.P ≠ s.C := by
by_contra h; have := s.PAC_eq
rw [h, angle_self_of_ne s.A_ne_C.symm] at this; linarith [Real.pi_pos]
lemma sbtw_BPC : Sbtw ℝ s.B s.P s.C := ⟨s.P_on_BC, s.P_ne_B, s.P_ne_C⟩
lemma BPC_eq : ∠ s.B s.P s.C = π := by rw [angle_eq_pi_iff_sbtw]; exact s.sbtw_BPC
/-- `x = ∠ABQ = ∠QBC`. This is the main angle in the solution and it suffices to show
this is `2 * π / 9`. -/
def x : ℝ := ∠ s.A s.B s.Q
lemma ABQ_eq : ∠ s.A s.B s.Q = s.x := rfl
lemma QBC_eq : ∠ s.Q s.B s.C = s.x := by rw [← s.BQ_bisect_ABC, s.ABQ_eq]
lemma ABC_eq : ∠ s.A s.B s.C = 2 * s.x := by
have := angle_add_of_ne_of_ne s.A_ne_B.symm s.B_ne_C s.Q_on_AC
rw [s.ABQ_eq, s.QBC_eq] at this; grind
lemma x_pos : 0 < s.x := by
by_contra! h
replace h : s.x = 0 := le_antisymm h (angle_nonneg ..)
have col := s.ABC_eq; rw [h, mul_zero] at col
replace col : Collinear ℝ {s.A, s.B, s.C} := by
apply collinear_of_sin_eq_zero; rw [col, Real.sin_zero]
apply s.not_collinear_BAC; convert col using 1; grind
lemma Q_ne_A : s.Q ≠ s.A := by
by_contra h; have := s.ABQ_eq
rw [h, angle_self_of_ne s.A_ne_B] at this; linarith [s.x_pos]
lemma Q_ne_C : s.Q ≠ s.C := by
by_contra h; have := s.QBC_eq
rw [h, angle_self_of_ne s.B_ne_C.symm] at this; linarith [s.x_pos]
lemma sbtw_AQC : Sbtw ℝ s.A s.Q s.C := ⟨s.Q_on_AC, s.Q_ne_A, s.Q_ne_C⟩
lemma AQC_eq : ∠ s.A s.Q s.C = π := by rw [angle_eq_pi_iff_sbtw]; exact s.sbtw_AQC
lemma ACB_eq : ∠ s.A s.C s.B = 2 * π / 3 - 2 * s.x := by
have := angle_add_angle_add_angle_eq_pi s.A s.B_ne_C
rw [angle_comm, s.ABC_eq, s.BAC_eq] at this; grind
lemma x_lt_pi_div_three : s.x < π / 3 := by
by_contra! h
have col : ∠ s.A s.C s.B = 0 := by linarith [s.ACB_eq, angle_nonneg s.A s.C s.B]
replace col : Collinear ℝ {s.A, s.C, s.B} := by
apply collinear_of_sin_eq_zero; rw [col, Real.sin_zero]
apply s.not_collinear_BAC; convert col using 1; grind
lemma APB_eq : ∠ s.A s.P s.B = 5 * π / 6 - 2 * s.x := by
have := angle_add_angle_add_angle_eq_pi s.P s.A_ne_B
rw [s.BAP_eq, angle_comm s.P, angle_eq_angle_of_angle_eq_pi _ s.BPC_eq, s.ABC_eq] at this
grind
lemma AQB_eq : ∠ s.A s.Q s.B = 2 * π / 3 - s.x := by
have := angle_add_angle_add_angle_eq_pi s.Q s.A_ne_B
rw [angle_eq_angle_of_angle_eq_pi _ s.AQC_eq, s.BAC_eq, angle_comm s.Q, s.ABQ_eq] at this
grind
/-- A macro for applying the bounds on `x`, `x_pos` and `x_lt_pi_div_three`. -/
macro (name := bx) "bx" : tactic => `(tactic| linarith [s.x_pos, s.x_lt_pi_div_three])
/-! ### Trigonometric reduction using the law of sines -/
/-- `dist B P` in terms of `dist A B`. -/
lemma BP_by_AB :
dist s.B s.P = Real.sin (π / 6) / Real.sin (5 * π / 6 - 2 * s.x) * dist s.A s.B := by
rw [div_mul_eq_mul_div₀]; apply eq_div_of_mul_eq
· refine (Real.sin_pos_of_pos_of_lt_pi ?_ ?_).ne' <;> bx
rw [← s.APB_eq, mul_comm, dist_comm, sin_angle_mul_dist_eq_sin_angle_mul_dist, ← s.BAP_eq,
dist_comm]
/-- `dist A Q` in terms of `dist A B`. -/
lemma AQ_by_AB :
dist s.A s.Q = Real.sin s.x / Real.sin (2 * π / 3 - s.x) * dist s.A s.B := by
rw [div_mul_eq_mul_div₀]; apply eq_div_of_mul_eq
· refine (Real.sin_pos_of_pos_of_lt_pi ?_ ?_).ne' <;> bx
rw [← s.AQB_eq, mul_comm, ← sin_angle_mul_dist_eq_sin_angle_mul_dist, angle_comm, s.ABQ_eq,
dist_comm]
/-- `dist Q B` in terms of `dist A B`. -/
lemma QB_by_AB :
dist s.Q s.B = Real.sin (π / 3) / Real.sin (2 * π / 3 - s.x) * dist s.A s.B := by
rw [div_mul_eq_mul_div₀]; apply eq_div_of_mul_eq
· refine (Real.sin_pos_of_pos_of_lt_pi ?_ ?_).ne' <;> bx
rw [← s.AQB_eq, mul_comm, sin_angle_mul_dist_eq_sin_angle_mul_dist,
angle_eq_angle_of_angle_eq_pi _ s.AQC_eq, s.BAC_eq, dist_comm]
/-- The key trigonometric equation for `x`. -/
lemma key_x_equation :
1 + Real.sin (π / 6) / Real.sin (5 * π / 6 - 2 * s.x) =
(Real.sin s.x + Real.sin (π / 3)) / Real.sin (2 * π / 3 - s.x) := by
have := s.dist_sum
rw [s.BP_by_AB, ← one_add_mul, s.AQ_by_AB, s.QB_by_AB, ← add_mul, ← add_div] at this
exact mul_right_cancel₀ (dist_ne_zero.mpr s.A_ne_B) this
/-! ### Solving the trigonometric equation -/
lemma x_eq : s.x = 2 * π / 9 := by
have work := s.key_x_equation
rw [Real.sin_add_sin, show 2 * π / 3 - s.x = π - 2 * ((s.x + π / 3) / 2) by ring, Real.sin_pi_sub,
Real.sin_two_mul, mul_div_mul_left] at work; swap
· refine mul_ne_zero two_ne_zero (Real.sin_pos_of_pos_of_lt_pi ?_ ?_).ne' <;> bx
rw [← eq_sub_iff_add_eq', div_sub_one] at work; swap
· refine (Real.cos_pos_of_mem_Ioo ⟨?_, ?_⟩).ne' <;> bx
rw [add_div, sub_div s.x, ← Real.two_mul_sin_mul_sin, show π / 3 / 2 = π / 6 by ring,
Real.sin_pi_div_six, show 2 * Real.sin (s.x / 2) * (1 / 2) = Real.sin (s.x / 2) by ring] at work
apply mul_eq_mul_of_div_eq_div at work; rotate_left
· refine (Real.sin_pos_of_pos_of_lt_pi ?_ ?_).ne' <;> bx
· refine (Real.cos_pos_of_mem_Ioo ⟨?_, ?_⟩).ne' <;> bx
rw [one_div_mul_eq_div, div_eq_iff_mul_eq two_ne_zero, ← mul_rotate, Real.two_mul_sin_mul_sin,
show s.x / 2 - (5 * π / 6 - 2 * s.x) = 5 * (s.x / 2) + π / 6 - π by ring, Real.cos_sub_pi,
show s.x / 2 + (5 * π / 6 - 2 * s.x) = π - (3 * (s.x / 2) + π / 6) by ring, Real.cos_pi_sub,
neg_sub_neg] at work
rw [mul_div_assoc, mul_comm, ← div_eq_iff two_ne_zero]
set y := s.x / 2
have iden := Real.cos_add_cos (y + π / 6) (5 * y + π / 6)
rw [← work, sub_add_cancel, show (y + π / 6 + (5 * y + π / 6)) / 2 = 3 * y + π / 6 by ring,
show (y + π / 6 - (5 * y + π / 6)) / 2 = -(2 * y) by ring, Real.cos_neg, ← mul_rotate, eq_comm,
mul_left_eq_self₀] at iden
have notleft : Real.cos (2 * y) * 2 ≠ 1 := by
unfold y; rw [mul_div_cancel₀ _ two_ne_zero]; by_contra h
rw [← eq_div_iff_mul_eq two_ne_zero, ← Real.cos_pi_div_three] at h
apply Real.injOn_cos ⟨s.x_pos.le, by bx⟩ ⟨by positivity, by bound⟩ at h
exact s.x_lt_pi_div_three.ne h
replace iden := iden.resolve_left notleft
rw [← Real.cos_pi_div_two] at iden
apply Real.injOn_cos ⟨by unfold y; bx, by unfold y; bx⟩ ⟨by positivity, by bound⟩ at iden
grind
end Setup
theorem result (s : Setup X) : ∠ s.A s.B s.C = 4 * π / 9 ∧ ∠ s.A s.C s.B = 2 * π / 9 := by
rw [s.ABC_eq, s.ACB_eq, s.x_eq]; constructor <;> ring
end Imo2001Q5 |
.lake/packages/mathlib/Archive/Imo/Imo2024Q1.lean | import Mathlib.Algebra.BigOperators.Intervals
import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.Order.BigOperators.Group.LocallyFinite
import Mathlib.Algebra.Order.ToIntervalMod
import Mathlib.Data.Real.Archimedean
import Mathlib.Tactic.Peel
import Mathlib.Tactic.Recall
/-!
# IMO 2024 Q1
Determine all real numbers $\alpha$ such that, for every positive integer $n$, the integer
\[
\lfloor \alpha \rfloor + \lfloor 2\alpha \rfloor + \cdots + \lfloor n\alpha \rfloor
\]
is a multiple of~$n$.
We follow Solution 3 from the
[official solutions](https://www.imo2024.uk/s/IMO-2024-Paper-1-Solutions.pdf).
First reducing modulo 2, any answer that is not a multiple of 2 is inductively shown to be
contained in a decreasing sequence of intervals, with empty intersection.
-/
open Finset
namespace Imo2024Q1
/-- The condition of the problem. -/
def Condition (α : ℝ) : Prop := (∀ n : ℕ, 0 < n → (n : ℤ) ∣ ∑ i ∈ Finset.Icc 1 n, ⌊i * α⌋)
/-- This is to be determined by the solver of the original problem. -/
def solutionSet : Set ℝ := {α : ℝ | ∃ m : ℤ, α = 2 * m}
lemma condition_two_mul_int (m : ℤ) : Condition (2 * m) := by
rintro n -
suffices (n : ℤ) ∣ ∑ i ∈ Finset.Icc 0 n, ⌊((i * (2 * m) : ℤ) : ℝ)⌋ by
rw [← insert_Icc_add_one_left_eq_Icc n.zero_le, sum_insert_zero (by simp)] at this
exact_mod_cast this
simp_rw [Int.floor_intCast, ← sum_mul, ← Ico_succ_right_eq_Icc, ← range_eq_Ico, ← mul_assoc]
apply dvd_mul_of_dvd_left
rw [← Nat.cast_sum, ← Nat.cast_ofNat (n := 2), ← Nat.cast_mul, Finset.sum_range_id_mul_two]
simp
lemma condition_sub_two_mul_int_iff {α : ℝ} (m : ℤ) : Condition (α - 2 * m) ↔ Condition α := by
peel with n hn
apply dvd_iff_dvd_of_dvd_sub
simp_rw [← Finset.sum_sub_distrib, mul_sub]
norm_cast
simp_rw [Int.floor_sub_intCast, sub_sub_cancel_left]
convert condition_two_mul_int (-m) n hn
norm_cast
rw [Int.floor_intCast]
simp
lemma condition_toIcoMod_iff {α : ℝ} :
Condition (toIcoMod (by simp : (0 : ℝ) < 2) 0 α) ↔ Condition α := by
rw [toIcoMod, zsmul_eq_mul, mul_comm, condition_sub_two_mul_int_iff]
namespace Condition
variable {α : ℝ} (hc : Condition α)
include hc
lemma mem_Ico_one_of_mem_Ioo (h : α ∈ Set.Ioo 0 2) : α ∈ Set.Ico 1 2 := by
rcases h with ⟨h0, h2⟩
refine ⟨?_, h2⟩
by_contra! hn
have hr : 1 < ⌈α⁻¹⌉₊ := by
rw [Nat.lt_ceil]
exact_mod_cast (one_lt_inv₀ h0).2 hn
apply hr.ne'
suffices ⌈α⁻¹⌉₊ = (1 : ℤ) from mod_cast this
apply Int.eq_one_of_dvd_one (Int.zero_le_ofNat _)
convert hc ⌈α⁻¹⌉₊ (zero_lt_one.trans hr)
rw [← Finset.add_sum_Ico_eq_sum_Icc hr.le]
convert (add_zero _).symm
· rw [Int.floor_eq_iff]
constructor
· rw [Int.cast_one]
calc 1 ≤ α⁻¹ * α := by simp [h0.ne']
_ ≤ ⌈α⁻¹⌉₊ * α := by gcongr; exact Nat.le_ceil α⁻¹
· calc ⌈α⁻¹⌉₊ * α
_ < (α⁻¹ + 1) * α := by gcongr; exact Nat.ceil_lt_add_one (inv_nonneg.2 h0.le)
_ = 1 + α := by field
_ ≤ (1 : ℕ) + 1 := by gcongr; norm_cast
· apply Finset.sum_eq_zero
intro x hx
rw [Int.floor_eq_zero_iff]
refine ⟨by positivity, ?_⟩
rw [Finset.mem_Ico, Nat.lt_ceil] at hx
calc x * α < α⁻¹ * α := by gcongr; exact hx.2
_ = 1 := by simp [h0.ne']
lemma mem_Ico_n_of_mem_Ioo (h : α ∈ Set.Ioo 0 2) {n : ℕ} (hn : 0 < n) :
α ∈ Set.Ico ((2 * n - 1) / n : ℝ) 2 := by
suffices ∑ i ∈ Finset.Icc 1 n, ⌊i * α⌋ = n ^ 2 ∧ α ∈ Set.Ico ((2 * n - 1) / n : ℝ) 2 from this.2
induction n, hn using Nat.le_induction with
| base =>
obtain ⟨h1, h2⟩ := hc.mem_Ico_one_of_mem_Ioo h
simp only [Finset.Icc_self, Finset.sum_singleton, Nat.cast_one, one_mul, one_pow,
Int.floor_eq_iff, Int.cast_one, mul_one, div_one, Set.mem_Ico, tsub_le_iff_right]
exact ⟨⟨h1, by linarith⟩, by linarith, h2⟩
| succ k kpos hk =>
rcases hk with ⟨hks, hkl, hk2⟩
have hs : (∑ i ∈ Finset.Icc 1 (k + 1), ⌊i * α⌋) =
⌊(k + 1 : ℕ) * α⌋ + ((k : ℕ) : ℤ) ^ 2 := by
have hn11 : k + 1 ∉ Finset.Icc 1 k := by
rw [Finset.mem_Icc]
omega
rw [← insert_Icc_right_eq_Icc_add_one (Nat.le_add_left 1 k), sum_insert hn11, hks]
specialize hc (k + 1) k.succ_pos
rw [hs] at hc ⊢
have hkl' : 2 * k ≤ ⌊(k + 1 : ℕ) * α⌋ := by
rw [Int.le_floor]
calc ((2 * k : ℤ) : ℝ) = ((2 * k : ℤ) : ℝ) + 0 := (add_zero _).symm
_ ≤ ((2 * k : ℤ) : ℝ) + (k - 1) / k := by gcongr; norm_cast; positivity
_ = (k + 1 : ℕ) * ((2 * (k : ℕ) - 1) / ((k : ℕ) : ℝ)) := by simp [field]; ring
_ ≤ (k + 1 : ℕ) * α := by gcongr
have hk2' : ⌊(k + 1 : ℕ) * α⌋ < (k + 1 : ℕ) * 2 := by
rw [Int.floor_lt]
push_cast
gcongr
have hk' : ⌊(k + 1 : ℕ) * α⌋ = 2 * k + 1 := by
by_contra
rw [show ⌊(k + 1 : ℕ) * α⌋ = 2 * k by omega] at hc
have hc' : ((k + 1 : ℕ) : ℤ) ∣ ((k + 1 : ℕ) : ℤ) * ((k + 1 : ℕ) : ℤ) - 1 := by
convert hc using 1
push_cast
ring
rw [dvd_sub_right (dvd_mul_right _ _), ← isUnit_iff_dvd_one, Int.isUnit_iff] at hc'
omega
rw [hk']
refine ⟨?_, ?_, h.2⟩
· push_cast
ring
· rw [Int.floor_eq_iff] at hk'
rw [div_le_iff₀ (by norm_cast; omega), mul_comm α]
convert hk'.1
push_cast
ring
end Condition
lemma not_condition_of_mem_Ioo {α : ℝ} (h : α ∈ Set.Ioo 0 2) : ¬Condition α := by
intro hc
let n : ℕ := ⌊(2 - α)⁻¹⌋₊ + 1
have hn : 0 < n := by omega
have hna := (hc.mem_Ico_n_of_mem_Ioo h hn).1
rcases h with ⟨-, h2⟩
have hna' : 2 - (n : ℝ)⁻¹ ≤ α := by
convert hna using 1
field
rw [sub_eq_add_neg, ← le_sub_iff_add_le', neg_le, neg_sub] at hna'
rw [le_inv_comm₀ (by linarith) (mod_cast hn), ← not_lt] at hna'
apply hna'
exact_mod_cast Nat.lt_floor_add_one (_ : ℝ)
lemma condition_iff_of_mem_Ico {α : ℝ} (h : α ∈ Set.Ico 0 2) : Condition α ↔ α = 0 := by
constructor
· intro hc
cases Set.eq_left_or_mem_Ioo_of_mem_Ico h with
| inl h => exact h
| inr ho => exact False.elim (not_condition_of_mem_Ioo ho hc)
· rintro rfl
convert condition_two_mul_int 0
norm_num
recall Imo2024Q1.Condition (α : ℝ) := (∀ n : ℕ, 0 < n → (n : ℤ) ∣ ∑ i ∈ Finset.Icc 1 n, ⌊i * α⌋)
recall Imo2024Q1.solutionSet := {α : ℝ | ∃ m : ℤ, α = 2 * m}
theorem result (α : ℝ) : Condition α ↔ α ∈ solutionSet := by
refine ⟨fun h ↦ ?_, ?_⟩
· rw [← condition_toIcoMod_iff, condition_iff_of_mem_Ico (toIcoMod_mem_Ico' _ _),
← AddCommGroup.modEq_iff_toIcoMod_eq_left, AddCommGroup.ModEq] at h
simp_rw [sub_zero] at h
rcases h with ⟨m, rfl⟩
rw [zsmul_eq_mul, mul_comm]
simp [solutionSet]
· rintro ⟨m, rfl⟩
exact condition_two_mul_int m
end Imo2024Q1 |
.lake/packages/mathlib/Archive/Imo/Imo1994Q1.lean | import Mathlib.Algebra.Group.Fin.Basic
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Data.Finset.Sort
import Mathlib.Order.Interval.Finset.Fin
import Mathlib.Tactic.Linarith
/-!
# IMO 1994 Q1
Let `m` and `n` be two positive integers.
Let `a₁, a₂, ..., aₘ` be `m` different numbers from the set `{1, 2, ..., n}`
such that for any two indices `i` and `j` with `1 ≤ i ≤ j ≤ m` and `aᵢ + aⱼ ≤ n`,
there exists an index `k` such that `aᵢ + aⱼ = aₖ`.
Show that `(a₁+a₂+...+aₘ)/m ≥ (n+1)/2`
## Sketch of solution
We can order the numbers so that `a₁ ≤ a₂ ≤ ... ≤ aₘ`.
The key idea is to pair the numbers in the sum and show that `aᵢ + aₘ₊₁₋ᵢ ≥ n+1`.
Indeed, if we had `aᵢ + aₘ₊₁₋ᵢ ≤ n`, then `a₁ + aₘ₊₁₋ᵢ, a₂ + aₘ₊₁₋ᵢ, ..., aᵢ + aₘ₊₁₋ᵢ`
would be `m` elements of the set of `aᵢ`'s all larger than `aₘ₊₁₋ᵢ`, which is impossible.
-/
open Finset
namespace Imo1994Q1
theorem tedious (m : ℕ) (k : Fin (m + 1)) : m - ((m + 1 - ↑k) + m) % (m + 1) = ↑k := by
obtain ⟨k, hk⟩ := k
rw [Nat.lt_succ_iff, le_iff_exists_add] at hk
rcases hk with ⟨c, rfl⟩
have : (k + c + 1 - k) + (k + c) = c + (k + c + 1) := by cutsat
rw [Fin.val_mk, this, Nat.add_mod_right, Nat.mod_eq_of_lt, Nat.add_sub_cancel]
omega
end Imo1994Q1
open Imo1994Q1
theorem imo1994_q1 (n : ℕ) (m : ℕ) (A : Finset ℕ) (hm : #A = m + 1)
(hrange : ∀ a ∈ A, 0 < a ∧ a ≤ n)
(hadd : ∀ a ∈ A, ∀ b ∈ A, a + b ≤ n → a + b ∈ A) :
(m + 1) * (n + 1) ≤ 2 * ∑ x ∈ A, x := by
set a := orderEmbOfFin A hm
-- We sort the elements of `A`
have ha : ∀ i, a i ∈ A := fun i => orderEmbOfFin_mem A hm i
set rev := Equiv.subLeft (Fin.last m)
-- `i ↦ m-i`
-- We reindex the sum by fin (m+1)
have : ∑ x ∈ A, x = ∑ i : Fin (m + 1), a i := by
convert sum_image fun x _ y _ => a.eq_iff_eq.1
rw [← coe_inj]; simp [a]
rw [this]; clear this
-- The main proof is a simple calculation by rearranging one of the two sums
suffices hpair : ∀ k ∈ univ, a k + a (rev k) ≥ n + 1 by calc
2 * ∑ i : Fin (m + 1), a i = ∑ i : Fin (m + 1), a i + ∑ i : Fin (m + 1), a i := two_mul _
_ = ∑ i : Fin (m + 1), a i + ∑ i : Fin (m + 1), a (rev i) := by rw [Equiv.sum_comp rev]
_ = ∑ i : Fin (m + 1), (a i + a (rev i)) := sum_add_distrib.symm
_ ≥ ∑ i : Fin (m + 1), (n + 1) := sum_le_sum hpair
_ = (m + 1) * (n + 1) := by rw [sum_const, card_fin, Nat.nsmul_eq_mul]
-- It remains to prove the key inequality, by contradiction
rintro k -
by_contra! h : a k + a (rev k) < n + 1
-- We exhibit `k+1` elements of `A` greater than `a (rev k)`
set f : Fin (m + 1) ↪ ℕ :=
⟨fun i => a i + a (rev k), by
apply injective_of_le_imp_le
intro i j hij
rwa [add_le_add_iff_right, a.map_rel_iff] at hij ⟩
-- Proof that the `f i` are greater than `a (rev k)` for `i ≤ k`
have hf : map f (Icc 0 k) ⊆ map a.toEmbedding (Ioc (rev k) (Fin.last m)) := by
intro x hx
simp only [Equiv.subLeft_apply, a, rev] at h
simp only [mem_map, mem_Icc, mem_Ioc, Fin.zero_le, true_and, Equiv.subLeft_apply,
Function.Embedding.coeFn_mk, RelEmbedding.coe_toEmbedding, f, rev] at hx ⊢
rcases hx with ⟨i, ⟨hi, rfl⟩⟩
have h1 : a i + a (Fin.last m - k) ≤ n := by unfold a; linarith only [h, a.monotone hi]
have h2 : a i + a (Fin.last m - k) ∈ A := hadd _ (ha _) _ (ha _) h1
rw [← mem_coe, ← range_orderEmbOfFin A hm, Set.mem_range] at h2
obtain ⟨j, hj⟩ := h2
refine ⟨j, ⟨?_, Fin.le_last j⟩, hj⟩
rw [← a.strictMono.lt_iff_lt, hj]
simpa using (hrange (a i) (ha i)).1
-- A set of size `k+1` embed in one of size `k`, which yields a contradiction
simpa [Fin.coe_sub, tedious, rev] using card_le_card hf |
.lake/packages/mathlib/Archive/Imo/Imo1981Q3.lean | import Mathlib.Data.Int.Lemmas
import Mathlib.Data.Nat.Fib.Basic
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.LinearCombination
/-!
# IMO 1981 Q3
Determine the maximum value of `m ^ 2 + n ^ 2`, where `m` and `n` are integers in
`{1, 2, ..., 1981}` and `(n ^ 2 - m * n - m ^ 2) ^ 2 = 1`.
The trick to this problem is that `m` and `n` have to be consecutive Fibonacci numbers,
because you can reduce any solution to a smaller one using the Fibonacci recurrence.
-/
/-
First, define the problem in terms of finding the maximum of a set.
We first generalize the problem to `{1, 2, ..., N}` and specialize to `N = 1981` at the very end.
-/
open Int Nat Set
namespace Imo1981Q3
variable (N : ℕ)
-- N = 1981
@[mk_iff]
structure ProblemPredicate (m n : ℤ) : Prop where
m_range : m ∈ Ioc 0 (N : ℤ)
n_range : n ∈ Ioc 0 (N : ℤ)
eq_one : (n ^ 2 - m * n - m ^ 2) ^ 2 = 1
def specifiedSet : Set ℤ :=
{k : ℤ | ∃ m : ℤ, ∃ n : ℤ, k = m ^ 2 + n ^ 2 ∧ ProblemPredicate N m n}
/-
We want to reduce every solution to a smaller solution. Specifically,
we show that when `(m, n)` is a solution, `(n - m, m)` is also a solution,
except for the base case of `(1, 1)`.
-/
namespace ProblemPredicate
variable {N}
theorem m_le_n {m n : ℤ} (h1 : ProblemPredicate N m n) : m ≤ n := by
by_contra h2
have h3 : 1 = (n * (n - m) - m ^ 2) ^ 2 := by linear_combination - h1.eq_one
have h4 : n * (n - m) - m ^ 2 < -1 := by nlinarith [h1.n_range.left]
have h5 : 1 < (n * (n - m) - m ^ 2) ^ 2 := by nlinarith
exact h5.ne h3
theorem eq_imp_1 {n : ℤ} (h1 : ProblemPredicate N n n) : n = 1 :=
have : n * (n * (n * n)) = 1 := by linear_combination h1.eq_one
eq_one_of_mul_eq_one_right h1.m_range.left.le this
theorem reduction {m n : ℤ} (h1 : ProblemPredicate N m n) (h2 : 1 < n) :
ProblemPredicate N (n - m) m := by
obtain (rfl : m = n) | (h3 : m < n) := h1.m_le_n.eq_or_lt
· have h4 : m = 1 := h1.eq_imp_1
exact absurd h4.symm h2.ne
exact
{ n_range := h1.m_range
m_range := by
have h5 : 0 < n - m := sub_pos.mpr h3
have h6 : n - m < N := by
calc
_ < n := sub_lt_self n h1.m_range.left
_ ≤ N := h1.n_range.right
exact ⟨h5, h6.le⟩
eq_one := by linear_combination h1.eq_one }
end ProblemPredicate
/-
It will be convenient to have the lemmas above in their natural number form.
Most of these can be proved with the `norm_cast` family of tactics.
-/
def NatPredicate (m n : ℕ) : Prop :=
ProblemPredicate N ↑m ↑n
namespace NatPredicate
variable {N}
nonrec theorem m_le_n {m n : ℕ} (h1 : NatPredicate N m n) : m ≤ n := mod_cast h1.m_le_n
nonrec theorem eq_imp_1 {n : ℕ} (h1 : NatPredicate N n n) : n = 1 := mod_cast h1.eq_imp_1
nonrec theorem reduction {m n : ℕ} (h1 : NatPredicate N m n) (h2 : 1 < n) :
NatPredicate N (n - m) m := by
have : m ≤ n := h1.m_le_n
exact mod_cast h1.reduction (mod_cast h2)
theorem n_pos {m n : ℕ} (h1 : NatPredicate N m n) : 0 < n := mod_cast h1.n_range.left
theorem m_pos {m n : ℕ} (h1 : NatPredicate N m n) : 0 < m := mod_cast h1.m_range.left
theorem n_le_N {m n : ℕ} (h1 : NatPredicate N m n) : n ≤ N := mod_cast h1.n_range.right
/-
Now we can use induction to show that solutions must be Fibonacci numbers.
-/
theorem imp_fib {n : ℕ} (m : ℕ) (h : NatPredicate N m n) :
∃ k : ℕ, m = fib k ∧ n = fib (k + 1) := by
induction n using Nat.strong_induction_on generalizing m with | h n ih => ?_
have h3 : m ≤ n := h.m_le_n
obtain (rfl : 1 = n) | (h4 : 1 < n) := (succ_le_iff.mpr h.n_pos).eq_or_lt
· use 1
have h5 : 1 ≤ m := succ_le_iff.mpr h.m_pos
simpa using h3.antisymm h5
· obtain (rfl : m = n) | (h6 : m < n) := h3.eq_or_lt
· exact absurd h.eq_imp_1 (Nat.ne_of_gt h4)
· have h7 : NatPredicate N (n - m) m := h.reduction h4
obtain ⟨k : ℕ, hnm : n - m = fib k, rfl : m = fib (k + 1)⟩ := ih m h6 (n - m) h7
use k + 1, rfl
rw [fib_add_two, ← hnm, tsub_add_cancel_of_le h3]
end NatPredicate
/-
Next, we prove that if `N < fib K + fib (K+1)`, then the largest `m` and `n`
satisfying `NatPredicate m n N` are `fib K` and `fib (K+1)`, respectively.
-/
variable {K : ℕ} (HK : N < fib K + fib (K + 1)) {N}
include HK in
theorem m_n_bounds {m n : ℕ} (h1 : NatPredicate N m n) : m ≤ fib K ∧ n ≤ fib (K + 1) := by
obtain ⟨k : ℕ, hm : m = fib k, hn : n = fib (k + 1)⟩ := h1.imp_fib m
by_cases h2 : k < K + 1
· have h3 : k ≤ K := Nat.lt_succ_iff.mp h2
constructor
· calc
m = fib k := hm
_ ≤ fib K := fib_mono h3
· have h6 : k + 1 ≤ K + 1 := succ_le_succ h3
calc
n = fib (k + 1) := hn
_ ≤ fib (K + 1) := fib_mono h6
· have h7 : N < n := by
have h8 : K + 2 ≤ k + 1 := succ_le_succ (not_lt.mp h2)
rw [← fib_add_two] at HK
calc
N < fib (K + 2) := HK
_ ≤ fib (k + 1) := fib_mono h8
_ = n := hn.symm
have h9 : n ≤ N := h1.n_le_N
exact absurd h7 h9.not_gt
/-
We spell out the consequences of this result for `specifiedSet N` here.
-/
variable {M : ℕ} (HM : M = fib K ^ 2 + fib (K + 1) ^ 2)
include HK HM
theorem k_bound {m n : ℤ} (h1 : ProblemPredicate N m n) : m ^ 2 + n ^ 2 ≤ M := by
have h2 : 0 ≤ m := h1.m_range.left.le
have h3 : 0 ≤ n := h1.n_range.left.le
rw [← natAbs_of_nonneg h2, ← natAbs_of_nonneg h3] at h1; clear h2 h3
obtain ⟨h4 : m.natAbs ≤ fib K, h5 : n.natAbs ≤ fib (K + 1)⟩ := m_n_bounds HK h1
have h6 : m ^ 2 ≤ (fib K : ℤ) ^ 2 := Int.natAbs_le_iff_sq_le.mp h4
have h7 : n ^ 2 ≤ (fib (K + 1) : ℤ) ^ 2 := Int.natAbs_le_iff_sq_le.mp h5
linarith
theorem solution_bound : ∀ {k : ℤ}, k ∈ specifiedSet N → k ≤ M
| _, ⟨_, _, rfl, h⟩ => k_bound HK HM h
theorem solution_greatest (H : ProblemPredicate N (fib K) (fib (K + 1))) :
IsGreatest (specifiedSet N) M :=
⟨⟨fib K, fib (K + 1), by simp [HM], H⟩, fun k h => solution_bound HK HM h⟩
end Imo1981Q3
open Imo1981Q3
/-
Now we just have to demonstrate that 987 and 1597 are in fact the largest Fibonacci
numbers in this range, and thus provide the maximum of `specifiedSet`.
-/
theorem imo1981_q3 : IsGreatest (specifiedSet 1981) 3524578 := by
simpa +decide [problemPredicate_iff] using (@solution_greatest 1981 16 · 3524578) |
.lake/packages/mathlib/Archive/Imo/Imo2019Q2.lean | import Mathlib.Geometry.Euclidean.Angle.Sphere
import Mathlib.Geometry.Euclidean.Sphere.SecondInter
/-!
# IMO 2019 Q2
In triangle `ABC`, point `A₁` lies on side `BC` and point `B₁` lies on side `AC`. Let `P` and
`Q` be points on segments `AA₁` and `BB₁`, respectively, such that `PQ` is parallel to `AB`.
Let `P₁` be a point on line `PB₁`, such that `B₁` lies strictly between `P` and `P₁`, and
`∠PP₁C = ∠BAC`. Similarly, let `Q₁` be a point on line `QA₁`, such that `A₁` lies strictly
between `Q` and `Q₁`, and `∠CQ₁Q = ∠CBA`.
Prove that points `P`, `Q`, `P₁`, and `Q₁` are concyclic.
We follow Solution 1 from the
[official solutions](https://www.imo2019.uk/wp-content/uploads/2018/07/solutions-r856.pdf).
Letting the rays `AA₁` and `BB₁` intersect the circumcircle of `ABC` at `A₂` and `B₂`
respectively, we show with an angle chase that `P`, `Q`, `A₂`, `B₂` are concyclic and let `ω` be
the circle through those points. We then show that `C`, `Q₁`, `A₂`, `A₁` are concyclic, and
then that `Q₁` lies on `ω`, and similarly that `P₁` lies on `ω`, so the required four points are
concyclic.
Note that most of the formal proof is actually proving nondegeneracy conditions needed for that
angle chase / concyclicity argument, where an informal solution doesn't discuss those conditions
at all. Also note that (as described in `Geometry.Euclidean.Angle.Oriented.Basic`) the oriented
angles used are modulo `2 * π`, so parts of the angle chase that are only valid for angles modulo
`π` (as used in the informal solution) are represented as equalities of twice angles, which we write
as `(2 : ℤ) • ∡ _ _ _ = (2 : ℤ) • ∡ _ _ _`.
-/
library_note2 «IMO geometry formalization conventions» /--
We apply the following conventions for formalizing IMO geometry problems. A problem is assumed
to take place in the plane unless that is clearly not intended, so it is not required to prove
that the points are coplanar (whether or not that in fact follows from the other conditions).
Angles in problem statements are taken to be unoriented. A reference to an angle `∠XYZ` is taken
to imply that `X` and `Z` are not equal to `Y`, since choices of junk values play no role in
informal mathematics, and those implications are included as hypotheses for the problem whether
or not they follow from the other hypotheses. Similar, a reference to `XY` as a line is taken to
imply that `X` does not equal `Y` and that is included as a hypothesis, and a reference to `XY`
being parallel to something is considered a reference to it as a line. However, such an implicit
hypothesis about two points being different is included only once for any given two points (even
if it follows from more than one reference to a line or an angle), if `X ≠ Y` is included then
`Y ≠ X` is not included separately, and such hypotheses are not included in the case where there
is also a reference in the problem to a triangle including those two points, or to strict
betweenness of three points including those two. If betweenness is stated, it is taken to be
strict betweenness. However, segments and sides are taken to include their endpoints (unless
this makes a problem false), although those degenerate cases might not necessarily have been
considered when the problem was formulated and contestants might not have been expected to deal
with them. A reference to a point being on a side or a segment is expressed directly with `Wbtw`
rather than more literally with `affineSegment`.
-/
open Affine Affine.Simplex EuclideanGeometry Module
open scoped Affine EuclideanGeometry Real
attribute [local instance] FiniteDimensional.of_fact_finrank_eq_two
variable (V : Type*) (Pt : Type*)
variable [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace Pt]
variable [NormedAddTorsor V Pt]
namespace Imo2019Q2
noncomputable section
/-- A configuration satisfying the conditions of the problem. We define this structure to avoid
passing many hypotheses around as we build up information about the configuration; the final
result for a statement of the problem not using this structure is then deduced from one in terms
of this structure. -/
structure Imo2019q2Cfg where
(A B C A₁ B₁ P Q P₁ Q₁ : Pt)
affineIndependent_ABC : AffineIndependent ℝ ![A, B, C]
wbtw_B_A₁_C : Wbtw ℝ B A₁ C
wbtw_A_B₁_C : Wbtw ℝ A B₁ C
wbtw_A_P_A₁ : Wbtw ℝ A P A₁
wbtw_B_Q_B₁ : Wbtw ℝ B Q B₁
PQ_parallel_AB : line[ℝ, P, Q] ∥ line[ℝ, A, B]
-- A hypothesis implicit in the named line.
P_ne_Q : P ≠ Q
sbtw_P_B₁_P₁ : Sbtw ℝ P B₁ P₁
angle_PP₁C_eq_angle_BAC : ∠ P P₁ C = ∠ B A C
-- A hypothesis implicit in the first named angle.
C_ne_P₁ : C ≠ P₁
sbtw_Q_A₁_Q₁ : Sbtw ℝ Q A₁ Q₁
angle_CQ₁Q_eq_angle_CBA : ∠ C Q₁ Q = ∠ C B A
-- A hypothesis implicit in the first named angle.
C_ne_Q₁ : C ≠ Q₁
/-- A default choice of orientation, for lemmas that need to pick one. -/
def someOrientation [hd2 : Fact (finrank ℝ V = 2)] : Module.Oriented ℝ V (Fin 2) :=
⟨Basis.orientation (finBasisOfFinrankEq _ _ hd2.out)⟩
variable {V Pt}
namespace Imo2019q2Cfg
variable (cfg : Imo2019q2Cfg V Pt)
/-- The configuration has symmetry, allowing results proved for one point to be applied for
another (where the informal solution says "similarly"). -/
def symm : Imo2019q2Cfg V Pt where
A := cfg.B
B := cfg.A
C := cfg.C
A₁ := cfg.B₁
B₁ := cfg.A₁
P := cfg.Q
Q := cfg.P
P₁ := cfg.Q₁
Q₁ := cfg.P₁
affineIndependent_ABC := by
rw [← affineIndependent_equiv (Equiv.swap (0 : Fin 3) 1)]
convert cfg.affineIndependent_ABC using 1
ext x
fin_cases x <;> rfl
wbtw_B_A₁_C := cfg.wbtw_A_B₁_C
wbtw_A_B₁_C := cfg.wbtw_B_A₁_C
wbtw_A_P_A₁ := cfg.wbtw_B_Q_B₁
wbtw_B_Q_B₁ := cfg.wbtw_A_P_A₁
PQ_parallel_AB := Set.pair_comm cfg.P cfg.Q ▸ Set.pair_comm cfg.A cfg.B ▸ cfg.PQ_parallel_AB
P_ne_Q := cfg.P_ne_Q.symm
sbtw_P_B₁_P₁ := cfg.sbtw_Q_A₁_Q₁
angle_PP₁C_eq_angle_BAC :=
angle_comm cfg.C cfg.Q₁ cfg.Q ▸ angle_comm cfg.C cfg.B cfg.A ▸ cfg.angle_CQ₁Q_eq_angle_CBA
C_ne_P₁ := cfg.C_ne_Q₁
sbtw_Q_A₁_Q₁ := cfg.sbtw_P_B₁_P₁
angle_CQ₁Q_eq_angle_CBA :=
angle_comm cfg.P cfg.P₁ cfg.C ▸ angle_comm cfg.B cfg.A cfg.C ▸ cfg.angle_PP₁C_eq_angle_BAC
C_ne_Q₁ := cfg.C_ne_P₁
/-! ### Configuration properties that are obvious from the diagram, and construction of the
points `A₂` and `B₂` -/
theorem A_ne_B : cfg.A ≠ cfg.B :=
cfg.affineIndependent_ABC.injective.ne (by decide : (0 : Fin 3) ≠ 1)
theorem A_ne_C : cfg.A ≠ cfg.C :=
cfg.affineIndependent_ABC.injective.ne (by decide : (0 : Fin 3) ≠ 2)
theorem B_ne_C : cfg.B ≠ cfg.C :=
cfg.affineIndependent_ABC.injective.ne (by decide : (1 : Fin 3) ≠ 2)
theorem not_collinear_ABC : ¬Collinear ℝ ({cfg.A, cfg.B, cfg.C} : Set Pt) :=
affineIndependent_iff_not_collinear_set.1 cfg.affineIndependent_ABC
/-- `ABC` as a `Triangle`. -/
def triangleABC : Triangle ℝ Pt :=
⟨_, cfg.affineIndependent_ABC⟩
theorem A_mem_circumsphere : cfg.A ∈ cfg.triangleABC.circumsphere :=
cfg.triangleABC.mem_circumsphere 0
theorem B_mem_circumsphere : cfg.B ∈ cfg.triangleABC.circumsphere :=
cfg.triangleABC.mem_circumsphere 1
theorem C_mem_circumsphere : cfg.C ∈ cfg.triangleABC.circumsphere :=
cfg.triangleABC.mem_circumsphere 2
theorem symm_triangleABC : cfg.symm.triangleABC = cfg.triangleABC.reindex (Equiv.swap 0 1) := by
ext i; fin_cases i <;> rfl
theorem symm_triangleABC_circumsphere :
cfg.symm.triangleABC.circumsphere = cfg.triangleABC.circumsphere := by
rw [symm_triangleABC, Affine.Simplex.circumsphere_reindex]
/-- `A₂` is the second point of intersection of the ray `AA₁` with the circumcircle of `ABC`. -/
def A₂ : Pt :=
cfg.triangleABC.circumsphere.secondInter cfg.A (cfg.A₁ -ᵥ cfg.A)
/-- `B₂` is the second point of intersection of the ray `BB₁` with the circumcircle of `ABC`. -/
def B₂ : Pt :=
cfg.triangleABC.circumsphere.secondInter cfg.B (cfg.B₁ -ᵥ cfg.B)
theorem A₂_mem_circumsphere : cfg.A₂ ∈ cfg.triangleABC.circumsphere :=
(Sphere.secondInter_mem _).2 cfg.A_mem_circumsphere
theorem B₂_mem_circumsphere : cfg.B₂ ∈ cfg.triangleABC.circumsphere :=
(Sphere.secondInter_mem _).2 cfg.B_mem_circumsphere
theorem symm_A₂ : cfg.symm.A₂ = cfg.B₂ := by simp_rw [A₂, B₂, symm_triangleABC_circumsphere]; rfl
theorem QP_parallel_BA : line[ℝ, cfg.Q, cfg.P] ∥ line[ℝ, cfg.B, cfg.A] := by
rw [Set.pair_comm cfg.Q, Set.pair_comm cfg.B]; exact cfg.PQ_parallel_AB
theorem A_ne_A₁ : cfg.A ≠ cfg.A₁ := by
intro h
have h' := cfg.not_collinear_ABC
rw [h, Set.insert_comm] at h'
exact h' cfg.wbtw_B_A₁_C.collinear
theorem collinear_PAA₁A₂ : Collinear ℝ ({cfg.P, cfg.A, cfg.A₁, cfg.A₂} : Set Pt) := by
rw [A₂,
(cfg.triangleABC.circumsphere.secondInter_collinear cfg.A cfg.A₁).collinear_insert_iff_of_ne
(Set.mem_insert _ _) (Set.mem_insert_of_mem _ (Set.mem_insert _ _)) cfg.A_ne_A₁,
Set.insert_comm]
exact cfg.wbtw_A_P_A₁.collinear
theorem A₁_ne_C : cfg.A₁ ≠ cfg.C := by
intro h
have hsbtw := cfg.sbtw_Q_A₁_Q₁
rw [h] at hsbtw
have ha := hsbtw.angle₂₃₁_eq_zero
rw [angle_CQ₁Q_eq_angle_CBA, angle_comm] at ha
exact (angle_ne_zero_of_not_collinear cfg.not_collinear_ABC) ha
theorem B₁_ne_C : cfg.B₁ ≠ cfg.C :=
cfg.symm.A₁_ne_C
theorem Q_notMem_CB : cfg.Q ∉ line[ℝ, cfg.C, cfg.B] := by
intro hQ
have hQA₁ : line[ℝ, cfg.Q, cfg.A₁] ≤ line[ℝ, cfg.C, cfg.B] :=
affineSpan_pair_le_of_mem_of_mem hQ cfg.wbtw_B_A₁_C.symm.mem_affineSpan
have hQ₁ : cfg.Q₁ ∈ line[ℝ, cfg.C, cfg.B] := by
rw [AffineSubspace.le_def'] at hQA₁
exact hQA₁ _ cfg.sbtw_Q_A₁_Q₁.right_mem_affineSpan
have hc : Collinear ℝ ({cfg.C, cfg.Q₁, cfg.Q} : Set Pt) :=
haveI hc' : Collinear ℝ ({cfg.B, cfg.C, cfg.Q₁, cfg.Q} : Set Pt) := by
rw [Set.insert_comm cfg.B, Set.insert_comm cfg.B, Set.pair_comm, Set.insert_comm cfg.C,
Set.insert_comm cfg.C]
exact collinear_insert_insert_of_mem_affineSpan_pair hQ₁ hQ
hc'.subset (Set.subset_insert _ _)
rw [collinear_iff_eq_or_eq_or_angle_eq_zero_or_angle_eq_pi, cfg.angle_CQ₁Q_eq_angle_CBA,
or_iff_right cfg.C_ne_Q₁, or_iff_right cfg.sbtw_Q_A₁_Q₁.left_ne_right, angle_comm] at hc
exact cfg.not_collinear_ABC (hc.elim collinear_of_angle_eq_zero collinear_of_angle_eq_pi)
@[deprecated (since := "2025-05-23")] alias Q_not_mem_CB := Q_notMem_CB
theorem Q_ne_B : cfg.Q ≠ cfg.B := by
intro h
have h' := cfg.Q_notMem_CB
rw [h] at h'
exact h' (right_mem_affineSpan_pair _ _ _)
theorem sOppSide_CB_Q_Q₁ : line[ℝ, cfg.C, cfg.B].SOppSide cfg.Q cfg.Q₁ :=
cfg.sbtw_Q_A₁_Q₁.sOppSide_of_notMem_of_mem cfg.Q_notMem_CB cfg.wbtw_B_A₁_C.symm.mem_affineSpan
/-! ### Relate the orientations of different angles in the configuration -/
section Oriented
variable [Module.Oriented ℝ V (Fin 2)]
theorem oangle_CQ₁Q_sign_eq_oangle_CBA_sign [Fact (finrank ℝ V = 2)] :
(∡ cfg.C cfg.Q₁ cfg.Q).sign = (∡ cfg.C cfg.B cfg.A).sign := by
rw [← cfg.sbtw_Q_A₁_Q₁.symm.oangle_eq_right,
cfg.sOppSide_CB_Q_Q₁.oangle_sign_eq_neg (left_mem_affineSpan_pair ℝ cfg.C cfg.B)
cfg.wbtw_B_A₁_C.symm.mem_affineSpan,
← Real.Angle.sign_neg, ← oangle_rev,
cfg.wbtw_B_A₁_C.oangle_sign_eq_of_ne_right cfg.Q cfg.A₁_ne_C, oangle_rotate_sign,
cfg.wbtw_B_Q_B₁.oangle_eq_right cfg.Q_ne_B,
cfg.wbtw_A_B₁_C.symm.oangle_sign_eq_of_ne_left cfg.B cfg.B₁_ne_C.symm]
theorem oangle_CQ₁Q_eq_oangle_CBA [Fact (finrank ℝ V = 2)] :
∡ cfg.C cfg.Q₁ cfg.Q = ∡ cfg.C cfg.B cfg.A :=
oangle_eq_of_angle_eq_of_sign_eq cfg.angle_CQ₁Q_eq_angle_CBA
cfg.oangle_CQ₁Q_sign_eq_oangle_CBA_sign
end Oriented
/-! ### More obvious configuration properties -/
section
variable [hd2 : Fact (finrank ℝ V = 2)]
theorem A₁_ne_B : cfg.A₁ ≠ cfg.B := by
intro h
have hwbtw := cfg.wbtw_A_P_A₁
rw [h] at hwbtw
have hPQ : line[ℝ, cfg.P, cfg.Q] = line[ℝ, cfg.A, cfg.B] := by
rw [AffineSubspace.eq_iff_direction_eq_of_mem (left_mem_affineSpan_pair _ _ _)
hwbtw.mem_affineSpan]
exact cfg.PQ_parallel_AB.direction_eq
haveI := someOrientation V
have haQ : (2 : ℤ) • ∡ cfg.C cfg.B cfg.Q = (2 : ℤ) • ∡ cfg.C cfg.B cfg.A := by
rw [Collinear.two_zsmul_oangle_eq_right _ cfg.A_ne_B cfg.Q_ne_B]
rw [Set.pair_comm, Set.insert_comm]
refine collinear_insert_of_mem_affineSpan_pair ?_
rw [← hPQ]
exact right_mem_affineSpan_pair _ _ _
have ha : (2 : ℤ) • ∡ cfg.C cfg.B cfg.Q = (2 : ℤ) • ∡ cfg.C cfg.Q₁ cfg.Q := by
rw [oangle_CQ₁Q_eq_oangle_CBA, haQ]
have hn : ¬Collinear ℝ ({cfg.C, cfg.B, cfg.Q} : Set Pt) := by
rw [collinear_iff_of_two_zsmul_oangle_eq haQ, Set.pair_comm, Set.insert_comm, Set.pair_comm]
exact cfg.not_collinear_ABC
have hc := cospherical_of_two_zsmul_oangle_eq_of_not_collinear ha hn
have hBQ₁ : cfg.B ≠ cfg.Q₁ := by rw [← h]; exact cfg.sbtw_Q_A₁_Q₁.ne_right
have hQQ₁ : cfg.Q ≠ cfg.Q₁ := cfg.sbtw_Q_A₁_Q₁.left_ne_right
have hBQ₁Q : AffineIndependent ℝ ![cfg.B, cfg.Q₁, cfg.Q] :=
hc.affineIndependent_of_mem_of_ne (Set.mem_insert_of_mem _ (Set.mem_insert _ _))
(Set.mem_insert_of_mem _ (Set.mem_insert_of_mem _ (Set.mem_insert _ _)))
(Set.mem_insert_of_mem _
(Set.mem_insert_of_mem _ (Set.mem_insert_of_mem _ (Set.mem_singleton _))))
hBQ₁ cfg.Q_ne_B.symm hQQ₁.symm
rw [affineIndependent_iff_not_collinear_set] at hBQ₁Q
refine hBQ₁Q ?_
rw [← h, Set.pair_comm, Set.insert_comm]
exact cfg.sbtw_Q_A₁_Q₁.wbtw.collinear
theorem sbtw_B_A₁_C : Sbtw ℝ cfg.B cfg.A₁ cfg.C :=
⟨cfg.wbtw_B_A₁_C, cfg.A₁_ne_B, cfg.A₁_ne_C⟩
theorem sbtw_A_B₁_C : Sbtw ℝ cfg.A cfg.B₁ cfg.C :=
cfg.symm.sbtw_B_A₁_C
theorem sbtw_A_A₁_A₂ : Sbtw ℝ cfg.A cfg.A₁ cfg.A₂ := by
refine Sphere.sbtw_secondInter cfg.A_mem_circumsphere ?_
convert cfg.sbtw_B_A₁_C.dist_lt_max_dist _
change _ = max (dist (cfg.triangleABC.points 1) _) (dist (cfg.triangleABC.points 2) _)
simp_rw [circumsphere_center, circumsphere_radius, dist_circumcenter_eq_circumradius, max_self]
theorem sbtw_B_B₁_B₂ : Sbtw ℝ cfg.B cfg.B₁ cfg.B₂ := by
rw [← cfg.symm_A₂]; exact cfg.symm.sbtw_A_A₁_A₂
theorem A₂_ne_A : cfg.A₂ ≠ cfg.A :=
cfg.sbtw_A_A₁_A₂.left_ne_right.symm
theorem A₂_ne_P : cfg.A₂ ≠ cfg.P :=
(cfg.sbtw_A_A₁_A₂.trans_wbtw_left_ne cfg.wbtw_A_P_A₁).symm
theorem A₂_ne_B : cfg.A₂ ≠ cfg.B := by
intro h
have h₁ := cfg.sbtw_A_A₁_A₂
rw [h] at h₁
refine cfg.not_collinear_ABC ?_
have hc : Collinear ℝ ({cfg.A, cfg.C, cfg.B, cfg.A₁} : Set Pt) :=
collinear_insert_insert_of_mem_affineSpan_pair h₁.left_mem_affineSpan
cfg.sbtw_B_A₁_C.right_mem_affineSpan
refine hc.subset ?_
rw [Set.pair_comm _ cfg.A₁, Set.insert_comm _ cfg.A₁, Set.insert_comm _ cfg.A₁, Set.pair_comm]
exact Set.subset_insert _ _
theorem A₂_ne_C : cfg.A₂ ≠ cfg.C := by
intro h
have h₁ := cfg.sbtw_A_A₁_A₂
rw [h] at h₁
refine cfg.not_collinear_ABC ?_
have hc : Collinear ℝ ({cfg.A, cfg.B, cfg.C, cfg.A₁} : Set Pt) :=
collinear_insert_insert_of_mem_affineSpan_pair h₁.left_mem_affineSpan
cfg.sbtw_B_A₁_C.left_mem_affineSpan
refine hc.subset ?_
gcongr
rw [Set.singleton_subset_iff]
exact Set.mem_insert _ _
theorem B₂_ne_B : cfg.B₂ ≠ cfg.B := by rw [← symm_A₂]; exact cfg.symm.A₂_ne_A
theorem B₂_ne_Q : cfg.B₂ ≠ cfg.Q := by rw [← symm_A₂]; exact cfg.symm.A₂_ne_P
theorem B₂_ne_A₂ : cfg.B₂ ≠ cfg.A₂ := by
intro h
have hA : Sbtw ℝ (cfg.triangleABC.points 1) cfg.A₁ (cfg.triangleABC.points 2) := cfg.sbtw_B_A₁_C
have hB : Sbtw ℝ (cfg.triangleABC.points 0) cfg.B₁ (cfg.triangleABC.points 2) := cfg.sbtw_A_B₁_C
have hA' : cfg.A₂ ∈ line[ℝ, cfg.triangleABC.points 0, cfg.A₁] :=
Sphere.secondInter_vsub_mem_affineSpan _ _ _
have hB' : cfg.A₂ ∈ line[ℝ, cfg.triangleABC.points 1, cfg.B₁] := by
rw [← h]; exact Sphere.secondInter_vsub_mem_affineSpan _ _ _
exact (sbtw_of_sbtw_of_sbtw_of_mem_affineSpan_pair (by decide) hA hB hA' hB').symm.not_rotate
cfg.sbtw_A_A₁_A₂.wbtw
theorem wbtw_B_Q_B₂ : Wbtw ℝ cfg.B cfg.Q cfg.B₂ :=
cfg.sbtw_B_B₁_B₂.wbtw.trans_left cfg.wbtw_B_Q_B₁
/-! ### The first equality in the first angle chase in the solution -/
section Oriented
variable [Module.Oriented ℝ V (Fin 2)]
theorem two_zsmul_oangle_QPA₂_eq_two_zsmul_oangle_BAA₂ :
(2 : ℤ) • ∡ cfg.Q cfg.P cfg.A₂ = (2 : ℤ) • ∡ cfg.B cfg.A cfg.A₂ := by
refine two_zsmul_oangle_of_parallel cfg.QP_parallel_BA ?_
convert AffineSubspace.Parallel.refl (k := ℝ) (P := Pt) _ using 1
rw [cfg.collinear_PAA₁A₂.affineSpan_eq_of_ne (Set.mem_insert_of_mem _
(Set.mem_insert_of_mem _ (Set.mem_insert_of_mem _ (Set.mem_singleton _))))
(Set.mem_insert_of_mem _ (Set.mem_insert _ _)) cfg.A₂_ne_A,
cfg.collinear_PAA₁A₂.affineSpan_eq_of_ne (Set.mem_insert_of_mem _
(Set.mem_insert_of_mem _ (Set.mem_insert_of_mem _ (Set.mem_singleton _))))
(Set.mem_insert _ _) cfg.A₂_ne_P]
end Oriented
/-! ### More obvious configuration properties -/
theorem not_collinear_QPA₂ : ¬Collinear ℝ ({cfg.Q, cfg.P, cfg.A₂} : Set Pt) := by
haveI := someOrientation V
rw [collinear_iff_of_two_zsmul_oangle_eq cfg.two_zsmul_oangle_QPA₂_eq_two_zsmul_oangle_BAA₂, ←
affineIndependent_iff_not_collinear_set]
have h : Cospherical ({cfg.B, cfg.A, cfg.A₂} : Set Pt) := by
refine cfg.triangleABC.circumsphere.cospherical.subset ?_
simp only [Set.insert_subset_iff, cfg.A_mem_circumsphere, cfg.B_mem_circumsphere,
cfg.A₂_mem_circumsphere, Sphere.mem_coe, Set.singleton_subset_iff, and_true]
exact h.affineIndependent_of_ne cfg.A_ne_B.symm cfg.A₂_ne_B.symm cfg.A₂_ne_A.symm
theorem Q₁_ne_A₂ : cfg.Q₁ ≠ cfg.A₂ := by
intro h
have h₁ := cfg.sbtw_Q_A₁_Q₁
rw [h] at h₁
refine cfg.not_collinear_QPA₂ ?_
have hA₂ := cfg.sbtw_A_A₁_A₂.right_mem_affineSpan
have hA₂A₁ : line[ℝ, cfg.A₂, cfg.A₁] ≤ line[ℝ, cfg.A, cfg.A₁] :=
affineSpan_pair_le_of_left_mem hA₂
have hQ : cfg.Q ∈ line[ℝ, cfg.A, cfg.A₁] := by
rw [AffineSubspace.le_def'] at hA₂A₁
exact hA₂A₁ _ h₁.left_mem_affineSpan
exact collinear_triple_of_mem_affineSpan_pair hQ cfg.wbtw_A_P_A₁.mem_affineSpan hA₂
theorem affineIndependent_QPA₂ : AffineIndependent ℝ ![cfg.Q, cfg.P, cfg.A₂] :=
affineIndependent_iff_not_collinear_set.2 cfg.not_collinear_QPA₂
theorem affineIndependent_PQB₂ : AffineIndependent ℝ ![cfg.P, cfg.Q, cfg.B₂] := by
rw [← symm_A₂]; exact cfg.symm.affineIndependent_QPA₂
/-- `QPA₂` as a `Triangle`. -/
def triangleQPA₂ : Triangle ℝ Pt :=
⟨_, cfg.affineIndependent_QPA₂⟩
/-- `PQB₂` as a `Triangle`. -/
def trianglePQB₂ : Triangle ℝ Pt :=
⟨_, cfg.affineIndependent_PQB₂⟩
theorem symm_triangleQPA₂ : cfg.symm.triangleQPA₂ = cfg.trianglePQB₂ := by
simp_rw [trianglePQB₂, ← symm_A₂]; ext i; fin_cases i <;> rfl
/-- `ω` is the circle containing `Q`, `P` and `A₂`, which will be shown also to contain `B₂`,
`P₁` and `Q₁`. -/
def ω : Sphere Pt :=
cfg.triangleQPA₂.circumsphere
theorem P_mem_ω : cfg.P ∈ cfg.ω :=
cfg.triangleQPA₂.mem_circumsphere 1
theorem Q_mem_ω : cfg.Q ∈ cfg.ω :=
cfg.triangleQPA₂.mem_circumsphere 0
/-! ### The rest of the first angle chase in the solution -/
section Oriented
variable [Module.Oriented ℝ V (Fin 2)]
theorem two_zsmul_oangle_QPA₂_eq_two_zsmul_oangle_QB₂A₂ :
(2 : ℤ) • ∡ cfg.Q cfg.P cfg.A₂ = (2 : ℤ) • ∡ cfg.Q cfg.B₂ cfg.A₂ :=
calc
(2 : ℤ) • ∡ cfg.Q cfg.P cfg.A₂ = (2 : ℤ) • ∡ cfg.B cfg.A cfg.A₂ :=
cfg.two_zsmul_oangle_QPA₂_eq_two_zsmul_oangle_BAA₂
_ = (2 : ℤ) • ∡ cfg.B cfg.B₂ cfg.A₂ :=
(Sphere.two_zsmul_oangle_eq cfg.B_mem_circumsphere cfg.A_mem_circumsphere
cfg.B₂_mem_circumsphere cfg.A₂_mem_circumsphere cfg.A_ne_B cfg.A₂_ne_A.symm cfg.B₂_ne_B
cfg.B₂_ne_A₂)
_ = (2 : ℤ) • ∡ cfg.Q cfg.B₂ cfg.A₂ := by
rw [cfg.wbtw_B_Q_B₂.symm.oangle_eq_left cfg.B₂_ne_Q.symm]
end Oriented
/-! ### Conclusions from that first angle chase -/
theorem cospherical_QPB₂A₂ : Cospherical ({cfg.Q, cfg.P, cfg.B₂, cfg.A₂} : Set Pt) :=
haveI := someOrientation V
cospherical_of_two_zsmul_oangle_eq_of_not_collinear
cfg.two_zsmul_oangle_QPA₂_eq_two_zsmul_oangle_QB₂A₂ cfg.not_collinear_QPA₂
theorem symm_ω_eq_trianglePQB₂_circumsphere : cfg.symm.ω = cfg.trianglePQB₂.circumsphere := by
rw [ω, symm_triangleQPA₂]
theorem symm_ω : cfg.symm.ω = cfg.ω := by
rw [symm_ω_eq_trianglePQB₂_circumsphere, ω]
refine circumsphere_eq_of_cospherical hd2.out cfg.cospherical_QPB₂A₂ ?_ ?_
· simp only [trianglePQB₂, Matrix.range_cons, Matrix.range_empty, Set.singleton_union,
insert_empty_eq]
rw [Set.insert_comm]
gcongr
simp
· simp only [triangleQPA₂, Matrix.range_cons, Matrix.range_empty, Set.singleton_union,
insert_empty_eq]
gcongr
simp
/-! ### The second angle chase in the solution -/
section Oriented
variable [Module.Oriented ℝ V (Fin 2)]
theorem two_zsmul_oangle_CA₂A₁_eq_two_zsmul_oangle_CBA :
(2 : ℤ) • ∡ cfg.C cfg.A₂ cfg.A₁ = (2 : ℤ) • ∡ cfg.C cfg.B cfg.A :=
calc
(2 : ℤ) • ∡ cfg.C cfg.A₂ cfg.A₁ = (2 : ℤ) • ∡ cfg.C cfg.A₂ cfg.A := by
rw [cfg.sbtw_A_A₁_A₂.symm.oangle_eq_right]
_ = (2 : ℤ) • ∡ cfg.C cfg.B cfg.A :=
Sphere.two_zsmul_oangle_eq cfg.C_mem_circumsphere cfg.A₂_mem_circumsphere
cfg.B_mem_circumsphere cfg.A_mem_circumsphere cfg.A₂_ne_C cfg.A₂_ne_A cfg.B_ne_C
cfg.A_ne_B.symm
theorem two_zsmul_oangle_CA₂A₁_eq_two_zsmul_oangle_CQ₁A₁ :
(2 : ℤ) • ∡ cfg.C cfg.A₂ cfg.A₁ = (2 : ℤ) • ∡ cfg.C cfg.Q₁ cfg.A₁ :=
calc
(2 : ℤ) • ∡ cfg.C cfg.A₂ cfg.A₁ = (2 : ℤ) • ∡ cfg.C cfg.B cfg.A :=
cfg.two_zsmul_oangle_CA₂A₁_eq_two_zsmul_oangle_CBA
_ = (2 : ℤ) • ∡ cfg.C cfg.Q₁ cfg.Q := by rw [oangle_CQ₁Q_eq_oangle_CBA]
_ = (2 : ℤ) • ∡ cfg.C cfg.Q₁ cfg.A₁ := by rw [cfg.sbtw_Q_A₁_Q₁.symm.oangle_eq_right]
end Oriented
/-! ### Conclusions from that second angle chase -/
theorem not_collinear_CA₂A₁ : ¬Collinear ℝ ({cfg.C, cfg.A₂, cfg.A₁} : Set Pt) := by
haveI := someOrientation V
rw [collinear_iff_of_two_zsmul_oangle_eq cfg.two_zsmul_oangle_CA₂A₁_eq_two_zsmul_oangle_CBA,
Set.pair_comm, Set.insert_comm, Set.pair_comm]
exact cfg.not_collinear_ABC
theorem cospherical_A₁Q₁CA₂ : Cospherical ({cfg.A₁, cfg.Q₁, cfg.C, cfg.A₂} : Set Pt) := by
haveI := someOrientation V
rw [Set.insert_comm cfg.Q₁, Set.insert_comm cfg.A₁, Set.pair_comm, Set.insert_comm cfg.A₁,
Set.pair_comm]
exact cospherical_of_two_zsmul_oangle_eq_of_not_collinear
cfg.two_zsmul_oangle_CA₂A₁_eq_two_zsmul_oangle_CQ₁A₁ cfg.not_collinear_CA₂A₁
/-! ### The third angle chase in the solution -/
section Oriented
variable [Module.Oriented ℝ V (Fin 2)]
theorem two_zsmul_oangle_QQ₁A₂_eq_two_zsmul_oangle_QPA₂ :
(2 : ℤ) • ∡ cfg.Q cfg.Q₁ cfg.A₂ = (2 : ℤ) • ∡ cfg.Q cfg.P cfg.A₂ :=
calc
(2 : ℤ) • ∡ cfg.Q cfg.Q₁ cfg.A₂ = (2 : ℤ) • ∡ cfg.A₁ cfg.Q₁ cfg.A₂ := by
rw [cfg.sbtw_Q_A₁_Q₁.symm.oangle_eq_left]
_ = (2 : ℤ) • ∡ cfg.A₁ cfg.C cfg.A₂ :=
(cfg.cospherical_A₁Q₁CA₂.two_zsmul_oangle_eq cfg.sbtw_Q_A₁_Q₁.right_ne cfg.Q₁_ne_A₂
cfg.A₁_ne_C.symm cfg.A₂_ne_C.symm)
_ = (2 : ℤ) • ∡ cfg.B cfg.C cfg.A₂ := by rw [cfg.sbtw_B_A₁_C.symm.oangle_eq_left]
_ = (2 : ℤ) • ∡ cfg.B cfg.A cfg.A₂ :=
(Sphere.two_zsmul_oangle_eq cfg.B_mem_circumsphere cfg.C_mem_circumsphere
cfg.A_mem_circumsphere cfg.A₂_mem_circumsphere cfg.B_ne_C.symm cfg.A₂_ne_C.symm cfg.A_ne_B
cfg.A₂_ne_A.symm)
_ = (2 : ℤ) • ∡ cfg.Q cfg.P cfg.A₂ := cfg.two_zsmul_oangle_QPA₂_eq_two_zsmul_oangle_BAA₂.symm
end Oriented
/-! ### Conclusions from that third angle chase -/
theorem Q₁_mem_ω : cfg.Q₁ ∈ cfg.ω :=
haveI := someOrientation V
Affine.Triangle.mem_circumsphere_of_two_zsmul_oangle_eq (by decide : (0 : Fin 3) ≠ 1)
(by decide : (0 : Fin 3) ≠ 2) (by decide) cfg.two_zsmul_oangle_QQ₁A₂_eq_two_zsmul_oangle_QPA₂
theorem P₁_mem_ω : cfg.P₁ ∈ cfg.ω := by rw [← symm_ω]; exact cfg.symm.Q₁_mem_ω
theorem result : Concyclic ({cfg.P, cfg.Q, cfg.P₁, cfg.Q₁} : Set Pt) := by
refine ⟨?_, coplanar_of_fact_finrank_eq_two _⟩
rw [cospherical_iff_exists_sphere]
refine ⟨cfg.ω, ?_⟩
simp only [Set.insert_subset_iff, Set.singleton_subset_iff]
exact ⟨cfg.P_mem_ω, cfg.Q_mem_ω, cfg.P₁_mem_ω, cfg.Q₁_mem_ω⟩
end
end Imo2019q2Cfg
end
end Imo2019Q2
open Imo2019Q2
theorem imo2019_q2 [Fact (finrank ℝ V = 2)] (A B C A₁ B₁ P Q P₁ Q₁ : Pt)
(affine_independent_ABC : AffineIndependent ℝ ![A, B, C]) (wbtw_B_A₁_C : Wbtw ℝ B A₁ C)
(wbtw_A_B₁_C : Wbtw ℝ A B₁ C) (wbtw_A_P_A₁ : Wbtw ℝ A P A₁) (wbtw_B_Q_B₁ : Wbtw ℝ B Q B₁)
(PQ_parallel_AB : line[ℝ, P, Q] ∥ line[ℝ, A, B]) (P_ne_Q : P ≠ Q)
(sbtw_P_B₁_P₁ : Sbtw ℝ P B₁ P₁) (angle_PP₁C_eq_angle_BAC : ∠ P P₁ C = ∠ B A C)
(C_ne_P₁ : C ≠ P₁) (sbtw_Q_A₁_Q₁ : Sbtw ℝ Q A₁ Q₁)
(angle_CQ₁Q_eq_angle_CBA : ∠ C Q₁ Q = ∠ C B A) (C_ne_Q₁ : C ≠ Q₁) :
Concyclic ({P, Q, P₁, Q₁} : Set Pt) :=
(⟨A, B, C, A₁, B₁, P, Q, P₁, Q₁, affine_independent_ABC, wbtw_B_A₁_C, wbtw_A_B₁_C, wbtw_A_P_A₁,
wbtw_B_Q_B₁, PQ_parallel_AB, P_ne_Q, sbtw_P_B₁_P₁, angle_PP₁C_eq_angle_BAC, C_ne_P₁,
sbtw_Q_A₁_Q₁, angle_CQ₁Q_eq_angle_CBA, C_ne_Q₁⟩ :
Imo2019q2Cfg V Pt).result |
.lake/packages/mathlib/Archive/Imo/Imo2011Q5.lean | import Mathlib.Algebra.Order.Group.Int
import Mathlib.Algebra.Order.Group.Unbundled.Basic
import Mathlib.Algebra.Ring.Divisibility.Basic
import Mathlib.Algebra.Ring.Int.Defs
/-!
# IMO 2011 Q5
Let `f` be a function from the set of integers to the set
of positive integers. Suppose that, for any two integers
`m` and `n`, the difference `f m - f n` is divisible by
`f (m - n)`. Prove that, for all integers `m` and `n` with
`f m ≤ f n`, the number `f n` is divisible by `f m`.
-/
open Int
theorem imo2011_q5 (f : ℤ → ℤ) (hpos : ∀ n : ℤ, 0 < f n) (hdvd : ∀ m n : ℤ, f (m - n) ∣ f m - f n) :
∀ m n : ℤ, f m ≤ f n → f m ∣ f n := by
intro m n h_fm_le_fn
rcases lt_or_eq_of_le h_fm_le_fn with h_fm_lt_fn | h_fm_eq_fn
· -- m < n
let d := f m - f (m - n)
have h_fn_dvd_d : f n ∣ d := by
rw [← sub_sub_self m n]
exact hdvd m (m - n)
have h_d_lt_fn : d < f n := calc
d < f m := sub_lt_self _ (hpos (m - n))
_ < f n := h_fm_lt_fn
have h_neg_d_lt_fn : -d < f n := by
calc
-d = f (m - n) - f m := neg_sub _ _
_ < f (m - n) := sub_lt_self _ (hpos m)
_ ≤ f n - f m := le_of_dvd (sub_pos.mpr h_fm_lt_fn) ?_
_ < f n := sub_lt_self _ (hpos m)
-- ⊢ f (m - n) ∣ f n - f m
rw [← Int.dvd_neg, neg_sub]
exact hdvd m n
have h_d_eq_zero : d = 0 := by
obtain hd | hd | hd : d > 0 ∨ d = 0 ∨ d < 0 := trichotomous d 0
· -- d > 0
have h₁ : f n ≤ d := le_of_dvd hd h_fn_dvd_d
have h₂ : ¬f n ≤ d := not_le.mpr h_d_lt_fn
contradiction
· -- d = 0
exact hd
· -- d < 0
have h₁ : f n ≤ -d := le_of_dvd (neg_pos.mpr hd) h_fn_dvd_d.neg_right
have h₂ : ¬f n ≤ -d := not_le.mpr h_neg_d_lt_fn
contradiction
have h₁ : f m = f (m - n) := sub_eq_zero.mp h_d_eq_zero
have h₂ : f (m - n) ∣ f m - f n := hdvd m n
rw [← h₁] at h₂
exact (dvd_iff_dvd_of_dvd_sub h₂).mp dvd_rfl
· -- m = n
rw [h_fm_eq_fn] |
.lake/packages/mathlib/Archive/Imo/Imo1960Q2.lean | import Mathlib.Data.Real.Sqrt
/-!
# IMO 1960 Q2
For what values of the variable $x$ does the following inequality hold:
\[\dfrac{4x^2}{(1 - \sqrt {2x + 1})^2} < 2x + 9 \ ?\]
We follow solution at
[Art of Problem Solving](https://artofproblemsolving.com/wiki/index.php/1960_IMO_Problems/Problem_2)
with minor modifications.
-/
open Real Set
namespace Imo1960Q2
/-- The predicate says that `x` satisfies the inequality
\[\dfrac{4x^2}{(1 - \sqrt {2x + 1})^2} < 2x + 9\]
and belongs to the domain of the function on the left-hand side.
-/
@[mk_iff isGood_iff']
structure IsGood (x : ℝ) : Prop where
/-- The number satisfies the inequality. -/
ineq : 4 * x ^ 2 / (1 - sqrt (2 * x + 1)) ^ 2 < 2 * x + 9
/-- The number belongs to the domain of \(\sqrt {2x + 1}\). -/
sqrt_dom : 0 ≤ 2 * x + 1
/-- The number belongs to the domain of the denominator. -/
denom_dom : (1 - sqrt (2 * x + 1)) ^ 2 ≠ 0
/-- Solution of IMO 1960 Q2: solutions of the inequality
are the numbers of the half-closed interval \([-1/2, 45/8)\) except for the number zero. -/
theorem isGood_iff {x} : IsGood x ↔ x ∈ Ico (-1/2) (45/8) \ {0} := by
-- First, note that the denominator is equal to zero at `x = 0`, hence it's not a solution.
rcases eq_or_ne x 0 with rfl | hx
· simp [isGood_iff']
cases lt_or_ge x (-1/2) with
| inl hx2 =>
-- Next, if `x < -1/2`, then the square root is undefined.
have : 2 * x + 1 < 0 := by linarith
simp [hx2.not_ge, isGood_iff', this.not_ge]
| inr hx2 =>
-- Now, if `x ≥ -1/2`, `x ≠ 0`, then the expression is well-defined.
have hx2' : 0 ≤ 2 * x + 1 := by linarith
have H : 1 - sqrt (2 * x + 1) ≠ 0 := by
rw [sub_ne_zero, ne_comm, ne_eq, sqrt_eq_iff_eq_sq hx2' zero_le_one]
simpa
calc
-- Note that the fraction in the LHS is equal to `(1 + sqrt (2 * x + 1)) ^ 2`
IsGood x ↔ (1 + sqrt (2 * x + 1)) ^ 2 < 2 * x + 9 := by
have : 4 * x ^ 2 = (1 + sqrt (2 * x + 1)) ^ 2 * (1 - sqrt (2 * x + 1)) ^ 2 := by
rw [← mul_pow, ← sq_sub_sq, sq_sqrt hx2']
ring
simp [isGood_iff', *]
-- Simplify the inequality
_ ↔ sqrt (2 * x + 1) < 7 / 2 := by
rw [add_sq, sq_sqrt hx2']; constructor <;> intro <;> linarith
_ ↔ 2 * x + 1 < (7 / 2) ^ 2 := sqrt_lt' <| by positivity
_ ↔ x < 45 / 8 := by constructor <;> intro <;> linarith
_ ↔ x ∈ Ico (-1/2) (45/8) \ {0} := by simp [*]
end Imo1960Q2 |
.lake/packages/mathlib/Archive/Imo/Imo1969Q1.lean | import Mathlib.Algebra.Ring.Identities
import Mathlib.Data.Int.NatPrime
import Mathlib.Data.Set.Finite.Lemmas
import Mathlib.Tactic.Linarith
/-!
# IMO 1969 Q1
Prove that there are infinitely many natural numbers $a$ with the following property:
the number $z = n^4 + a$ is not prime for any natural number $n$.
-/
open Int Nat
namespace Imo1969Q1
/-- `goodNats` is the set of natural numbers satisfying the condition in the problem
statement, namely the `a : ℕ` such that `n^4 + a` is not prime for any `n : ℕ`. -/
def goodNats : Set ℕ :=
{a : ℕ | ∀ n : ℕ, ¬Nat.Prime (n ^ 4 + a)}
/-!
The key to the solution is that you can factor $z$ into the product of two polynomials,
if $a = 4*m^4$. This is Sophie Germain's identity, called `pow_four_add_four_mul_pow_four`
in mathlib.
-/
theorem factorization {m n : ℤ} :
((n - m) ^ 2 + m ^ 2) * ((n + m) ^ 2 + m ^ 2) = n ^ 4 + 4 * m ^ 4 :=
pow_four_add_four_mul_pow_four.symm
/-!
To show that the product is not prime, we need to show each of the factors is at least 2,
which `nlinarith` can solve since they are each expressed as a sum of squares.
-/
theorem left_factor_large {m : ℤ} (n : ℤ) (h : 1 < m) : 1 < (n - m) ^ 2 + m ^ 2 := by nlinarith
theorem right_factor_large {m : ℤ} (n : ℤ) (h : 1 < m) : 1 < (n + m) ^ 2 + m ^ 2 := by nlinarith
/-!
The factorization is over the integers, but we need the nonprimality over the natural numbers.
-/
theorem int_large {m : ℤ} (h : 1 < m) : 1 < m.natAbs := by
exact_mod_cast lt_of_lt_of_le h le_natAbs
theorem not_prime_of_int_mul' {m n : ℤ} {c : ℕ} (hm : 1 < m) (hn : 1 < n) (hc : m * n = (c : ℤ)) :
¬Nat.Prime c :=
not_prime_of_int_mul (int_large hm).ne' (int_large hn).ne' hc
/-- Every natural number of the form `n^4 + 4*m^4` is not prime. -/
theorem polynomial_not_prime {m : ℕ} (h1 : 1 < m) (n : ℕ) : ¬Nat.Prime (n ^ 4 + 4 * m ^ 4) := by
have h2 : 1 < (m : ℤ) := Int.ofNat_lt.mpr h1
refine not_prime_of_int_mul' (left_factor_large (n : ℤ) h2) (right_factor_large (n : ℤ) h2) ?_
apply factorization
/-- We define $a_{choice}(b) := 4*(2+b)^4$, so that we can take $m = 2+b$ in `polynomial_not_prime`.
-/
def aChoice (b : ℕ) : ℕ :=
4 * (2 + b) ^ 4
theorem aChoice_good (b : ℕ) : aChoice b ∈ goodNats :=
polynomial_not_prime (show 1 < 2 + b by linarith)
/-- `aChoice` is a strictly monotone function; this is easily proven by chaining together lemmas
in the `strictMono` namespace. -/
theorem aChoice_strictMono : StrictMono aChoice :=
((strictMono_id.const_add 2).nat_pow (by decide)).const_mul (by decide)
end Imo1969Q1
open Imo1969Q1
/-- We conclude by using the fact that `aChoice` is an injective function from the natural numbers
to the set `goodNats`. -/
theorem imo1969_q1 : Set.Infinite {a : ℕ | ∀ n : ℕ, ¬Nat.Prime (n ^ 4 + a)} :=
Set.infinite_of_injective_forall_mem aChoice_strictMono.injective aChoice_good |
.lake/packages/mathlib/Archive/Imo/Imo2001Q4.lean | import Mathlib.Algebra.BigOperators.Intervals
import Mathlib.Data.Int.Interval
import Mathlib.GroupTheory.Perm.Fin
/-!
# IMO 2001 Q4
Let $n > 1$ be an odd integer and let $c_1, c_2, \dots, c_n$ be integers. For each permutation
$a = (a_1, a_2, \dots, a_n)$ of $\{1, 2, \dots, n\}$, define $S(a) = \sum_{i=1}^n c_i a_i$.
Prove that there exist two permutations $a ≠ b$ of $\{1, 2, \dots, n\}$ such that
$n!$ is a divisor of $S(a) - S(b)$.
## Solution
Suppose for contradiction that all the $S(a)$ have distinct residues modulo $n!$, then
$$\sum_{i=0}^{n!-1} i ≡ \sum_a S(a) = \sum_i c_i \sum_a a_i = (n-1)! \frac{n(n+1)}2 \sum_i c_i$$
$$= n! \frac{n+1}2 \sum_i c_i ≡ 0 \bmod n$$
where the last equality relies on $n$ being odd. But $\sum_{i=0}^{n!-1} i = \frac{n!(n!-1)}2$
is not divisible by $n!$, since the quotient is $\frac{n!-1}2$ and $n!$ is even when $n > 1$.
-/
namespace Imo2001Q4
open Equiv Finset
open scoped Nat
variable {n : ℕ} {c : Fin n → ℤ}
/-- The function `S` in the problem. As implemented here it accepts a permutation of `Fin n`
rather than `Icc 1 n`, and as such contains `+ 1` to compensate. -/
def S (c : Fin n → ℤ) (a : Perm (Fin n)) : ℤ := ∑ i, c i * (a i + 1)
/-- Assuming the opposite of what is to be proved, the sum of `S` over all permutations is
congruent to the sum of all residues modulo `n!`, i.e. `n! * (n! - 1) / 2`. -/
lemma sum_range_modEq_sum_of_contra (hS : ¬∃ a b, a ≠ b ∧ (n ! : ℤ) ∣ S c a - S c b) :
n ! * ((n ! : ℤ) - 1) / 2 ≡ ∑ a, S c a [ZMOD n !] := by
have mir : ∀ a, S c a % n ! ∈ Ico (0 : ℤ) n ! := fun a ↦ by
rw [mem_Ico]; constructor
· exact Int.emod_nonneg _ (by positivity)
· exact Int.emod_lt_of_pos _ (by positivity)
let f : Perm (Fin n) → Ico (0 : ℤ) n ! := fun a ↦ ⟨_, mir a⟩
have bijf : Function.Bijective f := by
rw [Fintype.bijective_iff_injective_and_card, Fintype.card_coe, Int.card_Ico, sub_zero,
Int.toNat_natCast, Fintype.card_perm, Fintype.card_fin, Function.Injective]
refine ⟨?_, rfl⟩
contrapose! hS
obtain ⟨a, b, he, hn⟩ := hS
use a, b, hn
simp only [f, Subtype.mk.injEq] at he
exact Int.ModEq.dvd he.symm
let e : Perm (Fin n) ≃ Ico (0 : ℤ) n ! := ofBijective _ bijf
change _ % _ = _ % _; rw [sum_int_mod]; congr 1
change _ = ∑ i, (e i).1; rw [Equiv.sum_comp]
change _ = ∑ i : { x // x ∈ _ }, id i.1; simp_rw [sum_coe_sort, id_eq]
have Ico_eq : Ico (0 : ℤ) n ! = (range n !).map ⟨_, Nat.cast_injective⟩ := by
ext i
simp_rw [mem_Ico, mem_map, mem_range, Function.Embedding.coeFn_mk]
constructor <;> intro h
· lift i to ℕ using h.1; rw [Nat.cast_lt] at h; simp [h.2]
· obtain ⟨z, lz, rfl⟩ := h; simp [lz]
rw [Ico_eq, sum_map, Function.Embedding.coeFn_mk, ← Nat.cast_sum, sum_range_id]
change _ = ((_ : ℕ) : ℤ) / (2 : ℕ)
rw [Nat.cast_mul, Nat.cast_ofNat, Nat.cast_pred (Nat.factorial_pos n)]
/-- The sum over all permutations of `Icc 1 n` of the entry at any fixed position is
`(n - 1)! * (n * (n + 1) / 2)`. -/
lemma sum_perm_add_one {i : Fin n} (hn : 1 ≤ n) :
∑ a : Perm (Fin n), ((a i).1 + 1) = (n - 1)! * (n * (n + 1) / 2) := by
rw [le_iff_exists_add'] at hn; obtain ⟨n, rfl⟩ := hn
rw [← sum_comp (Equiv.mulRight (swap i 0))]
simp_rw [coe_mulRight, Perm.coe_mul, Function.comp_apply, swap_apply_left, univ_perm_fin_succ,
sum_map, coe_toEmbedding, Fintype.sum_prod_type, Perm.decomposeFin_symm_apply_zero, sum_const,
smul_eq_mul, ← mul_sum, Finset.card_univ, Fintype.card_perm, Fintype.card_fin]
congr
have es := sum_range_add id 1 (n + 1)
simp_rw [id_eq, sum_range_one, zero_add, add_comm 1] at es
rw [Fin.sum_univ_eq_sum_range (· + 1), ← es, sum_range_id, add_tsub_cancel_right, mul_comm]
/-- For odd `n`, the sum of `S` over all permutations is divisible by `n!`. -/
lemma sum_modEq_zero_of_odd (hn : Odd n) : ∑ a, S c a ≡ 0 [ZMOD n !] := by
unfold S; rw [sum_comm]
conv_lhs => enter [2, i, 2, a]; rw [← Nat.cast_one, ← Nat.cast_add]
simp_rw [← mul_sum, ← Nat.cast_sum]
have eqv : ∀ i, c i * ↑(∑ a : Perm (Fin n), ((a i).1 + 1)) =
c i * ((n - 1)! * (n * (n + 1) / 2) : ℕ) := fun i ↦ by rw [sum_perm_add_one hn.pos]
rw [sum_congr rfl fun i _ ↦ eqv i, ← sum_mul,
Nat.mul_div_assoc _ (hn.add_odd odd_one).two_dvd, ← mul_assoc, mul_comm _ n,
Nat.mul_factorial_pred hn.pos.ne', Nat.cast_mul, ← mul_assoc, ← mul_rotate]
exact (Int.dvd_mul_left ..).modEq_zero_int
theorem result (hn : Odd n ∧ 1 < n) : ∃ a b, a ≠ b ∧ (n ! : ℤ) ∣ S c a - S c b := by
by_contra h
have key := (sum_range_modEq_sum_of_contra h).trans (sum_modEq_zero_of_odd hn.1)
rw [Int.modEq_zero_iff_dvd, dvd_def] at key; obtain ⟨c, hc⟩ := key
have feven : 2 ∣ (n ! : ℤ) := mod_cast Nat.dvd_factorial zero_lt_two hn.2
nth_rw 3 [← Int.ediv_mul_cancel feven] at hc
rw [mul_comm, Int.mul_ediv_assoc _ feven, mul_rotate] at hc
have halfpos : 0 < (n ! : ℤ) / 2 :=
Int.ediv_pos_of_pos_of_dvd (by positivity) zero_le_two feven
rw [mul_left_inj' halfpos.ne', sub_eq_iff_eq_add] at hc
rw [← even_iff_two_dvd, ← Int.not_odd_iff_even] at feven
exact feven ⟨_, hc⟩
end Imo2001Q4 |
.lake/packages/mathlib/Archive/Imo/Imo2005Q3.lean | import Mathlib.Data.Real.Basic
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.Field
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Ring
/-!
# IMO 2005 Q3
Let `x`, `y` and `z` be positive real numbers such that `xyz ≥ 1`. Prove that:
`(x^5 - x^2)/(x^5 + y^2 + z^2) + (y^5 - y^2)/(y^5 + z^2 + x^2) + (z^5 - z^2)/(z^5 + x^2 + y^2) ≥ 0`
## Solution
The solution by Iurie Boreico from Moldova is presented, which won a special prize during the exam.
The key insight is that `(x^5-x^2)/(x^5+y^2+z^2) ≥ (x^2-y*z)/(x^2+y^2+z^2)`, which is proven by
factoring `(x^5-x^2)/(x^5+y^2+z^2) - (x^5-x^2)/(x^3*(x^2+y^2+z^2))` into a non-negative expression
and then making use of `xyz ≥ 1` to show `(x^5-x^2)/(x^3*(x^2+y^2+z^2)) ≥ (x^2-y*z)/(x^2+y^2+z^2)`.
-/
namespace Imo2005Q3
theorem key_insight (x y z : ℝ) (hx : x > 0) (hy : y > 0) (hz : z > 0) (h : x * y * z ≥ 1) :
(x ^ 5 - x ^ 2) / (x ^ 5 + y ^ 2 + z ^ 2) ≥ (x ^ 2 - y * z) / (x ^ 2 + y ^ 2 + z ^ 2) := by
have key :
(x ^ 5 - x ^ 2) / (x ^ 5 + y ^ 2 + z ^ 2) -
(x ^ 5 - x ^ 2 * 1) / (x ^ 3 * (x ^ 2 + y ^ 2 + z ^ 2)) =
(x ^ 3 - 1) ^ 2 * x ^ 2 * (y ^ 2 + z ^ 2) /
((x ^ 5 + y ^ 2 + z ^ 2) * (x ^ 3 * (x ^ 2 + y ^ 2 + z ^ 2))) := by field
have h₅ :
(x ^ 3 - 1) ^ 2 * x ^ 2 * (y ^ 2 + z ^ 2) /
((x ^ 5 + y ^ 2 + z ^ 2) * (x ^ 3 * (x ^ 2 + y ^ 2 + z ^ 2))) ≥ 0 := by positivity
calc
(x ^ 5 - x ^ 2) / (x ^ 5 + y ^ 2 + z ^ 2)
≥ (x ^ 5 - x ^ 2 * 1) / (x ^ 3 * (x ^ 2 + y ^ 2 + z ^ 2)) := by linarith only [key, h₅]
_ ≥ (x ^ 5 - x ^ 2 * (x * y * z)) / (x ^ 3 * (x ^ 2 + y ^ 2 + z ^ 2)) := by gcongr
_ = (x ^ 2 - y * z) / (x ^ 2 + y ^ 2 + z ^ 2) := by field
end Imo2005Q3
open Imo2005Q3
theorem imo2005_q3 (x y z : ℝ) (hx : x > 0) (hy : y > 0) (hz : z > 0) (h : x * y * z ≥ 1) :
(x ^ 5 - x ^ 2) / (x ^ 5 + y ^ 2 + z ^ 2) + (y ^ 5 - y ^ 2) / (y ^ 5 + z ^ 2 + x ^ 2) +
(z ^ 5 - z ^ 2) / (z ^ 5 + x ^ 2 + y ^ 2) ≥
0 := by
calc
(x ^ 5 - x ^ 2) / (x ^ 5 + y ^ 2 + z ^ 2) + (y ^ 5 - y ^ 2) / (y ^ 5 + z ^ 2 + x ^ 2) +
(z ^ 5 - z ^ 2) / (z ^ 5 + x ^ 2 + y ^ 2) ≥
(x ^ 2 - y * z) / (x ^ 2 + y ^ 2 + z ^ 2) + (y ^ 2 - z * x) / (y ^ 2 + z ^ 2 + x ^ 2) +
(z ^ 2 - x * y) / (z ^ 2 + x ^ 2 + y ^ 2) := by
gcongr ?_ + ?_ + ?_ <;> apply key_insight <;> linarith
_ = 1 / 2 * ((x - y) ^ 2 + (y - z) ^ 2 + (z - x) ^ 2) / (x ^ 2 + y ^ 2 + z ^ 2) := by ring
_ ≥ 0 := by positivity |
.lake/packages/mathlib/Archive/Examples/PropEncodable.lean | import Mathlib.Data.W.Basic
import Mathlib.Data.Fin.VecNotation
/-!
# W types
The file `Mathlib/Data/W/Basic.lean` shows that if `α` is an encodable fintype and for every
`a : α`, `β a` is encodable, then `W β` is encodable.
As an example of how this can be used, we show that the type of propositional formulas with
variables labeled from an encodable type is encodable.
The strategy is to define a type of labels corresponding to the constructors.
From the definition (using `sum`, `unit`, and an encodable type), Lean can infer
that it is encodable. We then define a map from propositional formulas to the
corresponding `Wfin` type, and show that map has a left inverse.
We mark the auxiliary constructions `private`, since their only purpose is to
show encodability.
-/
namespace PropEncodable
/-- Propositional formulas with labels from `α`. -/
inductive PropForm (α : Type*)
| var : α → PropForm α
| not : PropForm α → PropForm α
| and : PropForm α → PropForm α → PropForm α
| or : PropForm α → PropForm α → PropForm α
namespace PropForm
private def Constructors (α : Type*) :=
α ⊕ (Unit ⊕ (Unit ⊕ Unit))
local notation "cvar " a => Sum.inl a
local notation "cnot" => Sum.inr (Sum.inl Unit.unit)
local notation "cand" => Sum.inr (Sum.inr (Sum.inr Unit.unit))
local notation "cor" => Sum.inr (Sum.inr (Sum.inl Unit.unit))
@[simp]
private def arity (α : Type*) : Constructors α → Nat
| cvar _ => 0
| cnot => 1
| cand => 2
| cor => 2
variable {α : Type*}
instance : ∀ c : Unit ⊕ (Unit ⊕ Unit), NeZero (arity α (.inr c))
| .inl () => ⟨one_ne_zero⟩
| .inr (.inl ()) => ⟨two_ne_zero⟩
| .inr (.inr ()) => ⟨two_ne_zero⟩
private def f : PropForm α → WType fun i => Fin (arity α i)
| var a => ⟨cvar a, ![]⟩
| not p => ⟨cnot, ![f p]⟩
| and p q => ⟨cand, ![f p, f q]⟩
| or p q => ⟨cor, ![f p, f q]⟩
private def finv : (WType fun i => Fin (arity α i)) → PropForm α
| ⟨cvar a, _⟩ => var a
| ⟨cnot, fn⟩ => not (finv (fn 0))
| ⟨cand, fn⟩ => and (finv (fn 0)) (finv (fn 1))
| ⟨cor, fn⟩ => or (finv (fn 0)) (finv (fn 1))
instance [Encodable α] : Encodable (PropForm α) :=
haveI : Encodable (Constructors α) := by unfold Constructors; infer_instance
Encodable.ofLeftInverse f finv (by intro p; induction p <;> simp [f, finv, *])
end PropForm
end PropEncodable |
.lake/packages/mathlib/Archive/Examples/Kuratowski.lean | import Mathlib.Topology.Instances.Irrational
import Mathlib.Topology.Instances.Real.Lemmas
import Archive.Kuratowski
/-!
# Kuratowski's closure-complement theorem is sharp
Kuratowski's closure-complement theorem says that if one repeatedly applies the closure and
complement operators to a set in a topological space, at most 14 distinct sets can be obtained.
This file gives an example of a so-called "14-set" in ℝ, from which exactly 14 distinct sets
can be obtained.
Our strategy is to show there is no duplication within the fourteen sets obtained from this set
`s`: the fourteen sets can be decomposed into six closed sets, six open sets that are the
complements of the closed sets, and `s` and `sᶜ` which are neither closed nor open.
This reduces `14*13/2 = 91` inequalities to check down to `6*5/2 = 15` inequalities.
We'll further show that the 15 inequalities follow from a subset of 6 by algebra.
There are charaterizations and criteria for a set to be a 14-set in the paper
"Characterization of Kuratowski 14-Sets" by Eric Langford which we do not formalize.
## Main definitions
* `Topology.ClosureCompl.fourteenSet`: an explicit example of a 14-set in ℝ.
* `Topology.ClosureCompl.theClosedSix`: the six open sets obtainable from a given set.
* `Topology.ClosureCompl.theOpenSix`: the six open sets obtainable from a given set.
* `Topology.ClosureCompl.TheSixIneq`: six inequalities that suffice to deduce
that the six closed sets obtained from a given set contain no duplicates.
## Main results
* `Topology.ClosureCompl.nodup_theFourteen_fourteenSet`:
the application of all 14 operations on the defined `fourteenSet` in ℝ gives no duplicates.
* `Topology.ClosureCompl.ncard_isObtainable_fourteenSet`:
for the defined `fourteenSet` in ℝ, there are exactly 14 distinct sets that can be obtained from
`fourteenSet` using the closure and complement operations.
-/
namespace Topology.ClosureCompl
variable {X : Type*} [TopologicalSpace X] {s t : Set X}
/-- The six closed sets obtained from a given set `s` are given by applying
`k, kc, kck, kckc, kckck, kckckc` to `s`. -/
def theClosedSix (s : Set X) : Multiset (Set X) :=
{k s, k sᶜ, k (k s)ᶜ, k (k sᶜ)ᶜ, k (k (k s)ᶜ)ᶜ, k (k (k sᶜ)ᶜ)ᶜ}
/-- The complements of the six closed sets. -/
def theOpenSix (s : Set X) : Multiset (Set X) :=
(theClosedSix s).map compl
/- By applying the identity and complement operations to the six closed sets, we obtain
precisely the six closed sets plus the six open sets. -/
theorem sum_map_theClosedSix_add_compl (s : Set X) :
((theClosedSix s).map fun t ↦ {t} + {tᶜ}).sum = theClosedSix s + theOpenSix s :=
Multiset.sum_map_add
/-- `theFourteen s` can be splitted into 3 subsets. -/
theorem theFourteen_eq_pair_add_theClosedSix_add_theOpenSix (s : Set X) :
theFourteen s = {s, sᶜ} + theClosedSix s + theOpenSix s := by
rw [add_assoc, ← sum_map_theClosedSix_add_compl]; rfl
/-- Every set in `theClosedSix s` is closed (because the last operation is closure). -/
theorem isClosed_of_mem_theClosedSix (h : t ∈ theClosedSix s) : IsClosed t := by
repeat obtain _ | ⟨_, h⟩ := h; rotate_left
all_goals exact isClosed_closure
/-- Every set in `theOpenSix s` is open. -/
theorem isOpen_of_mem_theOpenSix (h : t ∈ theOpenSix s) : IsOpen t := by
obtain ⟨t, ht, rfl⟩ := Multiset.mem_map.mp h
exact (isClosed_of_mem_theClosedSix ht).isOpen_compl
theorem mem_theOpenSix_iff : t ∈ theOpenSix s ↔ tᶜ ∈ theClosedSix s := by
conv_lhs => rw [theOpenSix, ← compl_compl t, Multiset.mem_map_of_injective compl_injective]
/-- Six inequalities that suffice to deduce the six closed sets obtained from a given set
contain no duplicates. -/
def TheSixIneq (s : Set X) : Prop :=
k (k (k sᶜ)ᶜ)ᶜ ≠ k (k (k s)ᶜ)ᶜ
∧ k (k (k sᶜ)ᶜ)ᶜ ≠ k (k sᶜ)ᶜ
∧ k (k (k sᶜ)ᶜ)ᶜ ≠ k (k s)ᶜ
∧ k (k (k sᶜ)ᶜ)ᶜ ≠ k sᶜ
∧ k (k (k s)ᶜ)ᶜ ≠ k (k s)ᶜ
∧ k (k (k s)ᶜ)ᶜ ≠ k s
open Multiset in
/-- `theClosedSix` applied to an arbitrary set `s` results in no duplicates iff `TheSixIneq`
is true for `s`. -/
theorem nodup_theClosedSix_theFourteen_iff : (theClosedSix s).Nodup ↔ TheSixIneq s := by
rw [TheSixIneq, theClosedSix]
simp only [insert_eq_cons, nodup_cons, mem_cons, mem_singleton,
not_or, nodup_singleton, and_true, ← ne_eq, and_assoc]
-- The goal becomes 6 inequalities ↔ 15 inequalities.
constructor -- Show both implications.
· -- One implication is almost trivial as the six inequalities are among the fifteen.
tauto
· intro h -- Introduce `TheSixIneq` as an assumption.
repeat obtain ⟨_, h⟩ := h -- Split the hypothesis into six different inequalities.
repeat refine .symm (.intro ?_ ?_) -- Split the goal into 15 inequalities.
any_goals
rw [ne_comm]
try assumption
-- Solve trivial goals (the six inequalities contained in `TheSixIneq`).
any_goals
/- Now eight other goals can be solved by simplifying
and then using one of the six given inequalities. -/
apply mt (congr_arg (k ·ᶜ))
first
| try repeat rw [kckckck_eq_kck, eq_comm]
assumption
| apply mt (congr_arg (k ·ᶜ))
try repeat rw [kckckck_eq_kck, eq_comm]
assumption
-- One last goal (`k (k (k sᶜ)ᶜ)ᶜ ≠ k s`) needs some other simplifying steps:
· apply mt (congr_arg fun s ↦ k (k sᶜ)ᶜ)
rw [kckckck_eq_kck]
assumption
open Multiset in
/-- `theFourteen s` contains no duplicates if and only if `theClosedSix s` has none,
and `theClosedSix s` is disjoint from `theOpenSix s`. -/
theorem nodup_theFourteen_of_nodup_theClosedSix_of_disjoint
(nodup : (theClosedSix s).Nodup) (disj : Disjoint (theClosedSix s) (theOpenSix s)) :
(theFourteen s).Nodup := by
rw [theFourteen_eq_pair_add_theClosedSix_add_theOpenSix, add_assoc, nodup_add, nodup_add]
refine ⟨?_, ⟨nodup, nodup.map compl_injective, disj⟩, ?_⟩
-- The two goals now are {s, sᶜ}.Nodup and Disjoint {s, sᶜ} (theClosedSix s + theOpenSix s).
· -- The first follows from nontriviality of the topological space.
have : Nontrivial (Set X) := ⟨_, _, (List.pairwise_cons.mp nodup).1 _ (.head _)⟩
simp
have hs : ¬ IsClosed s := fun h ↦ by simp [theClosedSix] at nodup
have hsc : ¬ IsClosed sᶜ := fun h ↦ by simp [theClosedSix] at nodup
-- Show `s ∉ theClosedSix s ∧ sᶜ ∉ theClosedSix s` and `s ∉ theOpenSix s ∧ sᶜ ∉ theOpenSix s`.
simp only [insert_eq_cons, disjoint_add_right, disjoint_cons_left, singleton_disjoint,
mem_theOpenSix_iff, compl_compl, and_comm, and_self]
exact ⟨(hs <| isClosed_of_mem_theClosedSix ·), (hsc <| isClosed_of_mem_theClosedSix ·)⟩
open Set
/-- A set in `ℝ` from which the maximum of 14 distinct sets can be obtained. -/
def fourteenSet : Set ℝ := Ioo 0 1 ∪ Ioo 1 2 ∪ {3} ∪ (Icc 4 5 ∩ range Rat.cast)
/-!
Let the fourteenSet be s: `(0,1) ∪ (1,2) ∪ {3} ∪ ([4,5] ∩ ℚ)`
Then the following sets can be obtained via the closure and complement operations:
* `cs = (-∞,0] ∪ {1} ∪ [2,3) ∪ (3,4) ∪ ([4,5] \ ℚ) ∪ (5,∞)`
* `kcs = (-∞,0] ∪ {1} ∪ [2,∞)`
* `ckcs = (0,1) ∪ (1,2)`
* `kckcs = [0,2]`
* `ckckcs = (-∞,0) ∪ (2,∞)`
* `kckckcs = (-∞,0] ∪ [2,∞)`
* `ckckckcs = (0,2)`
* `ks = [0,2] ∪ {3} ∪ [4,5]`
* `cks = (-∞,0) ∪ (2,3) ∪ (3,4) ∪ (5,∞)`
* `kcks = (-∞,0] ∪ [2,4] ∪ [5,∞)`
* `ckcks = (0,2) ∪ (4,5)`
* `kckcks = [0,2] ∪ [4,5]`
* `ckckcks = (-∞,0) ∪ (2,4) ∪ (5,∞)`
We can see that the sets are pairwise distinct, so we have 14 distinct sets.
-/
theorem k_Icc_4_5_inter_rat : k (Icc (4 : ℝ) 5 ∩ range Rat.cast) = Icc 4 5 :=
(closure_ordConnected_inter_rat ordConnected_Icc ⟨4, by norm_num, 5, by norm_num⟩).trans
isClosed_Icc.closure_eq
theorem i_fourteenSet : i fourteenSet = Ioo 0 1 ∪ Ioo 1 2 := by
have := interior_eq_empty_iff_dense_compl.mpr dense_irrational
rw [fourteenSet, interior_union_of_disjoint_closure, interior_union_of_disjoint_closure]
· simp [(isOpen_Ioo.union isOpen_Ioo).interior_eq, this]
all_goals norm_num [-union_singleton, k_Icc_4_5_inter_rat,
disjoint_iff_inter_eq_empty, union_inter_distrib_right, Icc_inter_Icc]
theorem k_fourteenSet : k fourteenSet = Icc 0 2 ∪ {3} ∪ Icc 4 5 := by
simp_rw [fourteenSet, closure_union]
rw [closure_Ioo, closure_Ioo, k_Icc_4_5_inter_rat, Icc_union_Icc']
all_goals norm_num
theorem kc_fourteenSet : k fourteenSetᶜ = (Ioo 0 1 ∪ Ioo 1 2)ᶜ := by
rw [closure_compl, compl_inj_iff, i_fourteenSet]
theorem kck_fourteenSet : k (k fourteenSet)ᶜ = (Ioo 0 2 ∪ Ioo 4 5)ᶜ := by
rw [closure_compl, k_fourteenSet,
interior_union_of_disjoint_closure, interior_union_of_disjoint_closure]
all_goals norm_num
[-union_singleton, disjoint_iff_inter_eq_empty, union_inter_distrib_right, Icc_inter_Icc]
theorem kckc_fourteenSet : k (k fourteenSetᶜ)ᶜ = Icc 0 2 := by
rw [kc_fourteenSet, compl_compl, closure_union, closure_Ioo, closure_Ioo]
all_goals norm_num
theorem kckck_fourteenSet : k (k (k fourteenSet)ᶜ)ᶜ = Icc 0 2 ∪ Icc 4 5 := by
rw [kck_fourteenSet, compl_compl, closure_union, closure_Ioo, closure_Ioo]
all_goals norm_num
theorem kckckc_fourteenSet : k (k (k fourteenSetᶜ)ᶜ)ᶜ = (Ioo 0 2)ᶜ := by
rw [kckc_fourteenSet, closure_compl, interior_Icc]
/-- `theClosedSix` applied to the specific `fourteenSet` generates no duplicates. -/
theorem nodup_theClosedSix_fourteenSet : (theClosedSix fourteenSet).Nodup := by
rw [nodup_theClosedSix_theFourteen_iff, TheSixIneq, kckckc_fourteenSet, kckck_fourteenSet,
kckc_fourteenSet, kck_fourteenSet, kc_fourteenSet, k_fourteenSet]
refine ⟨(ne_of_mem_of_not_mem' (a := 1) ?_ ?_).symm,
(ne_of_mem_of_not_mem' (a := 1) ?_ ?_).symm,
ne_of_mem_of_not_mem' (a := 4.5) ?_ ?_,
(ne_of_mem_of_not_mem' (a := 1) ?_ ?_).symm,
ne_of_mem_of_not_mem' (a := 1) ?_ ?_,
(ne_of_mem_of_not_mem' (a := 3) ?_ ?_).symm⟩
all_goals norm_num
/-- No set from `theClosedSix fourteenSet` is empty. -/
theorem nonempty_of_mem_theClosedSix_fourteenSet {s}
(h : s ∈ theClosedSix fourteenSet) : s.Nonempty := by
rw [theClosedSix, kckckc_fourteenSet, kckck_fourteenSet,
kckc_fourteenSet, kck_fourteenSet, kc_fourteenSet, k_fourteenSet] at h
repeat obtain _ | ⟨_, h⟩ := h; rotate_left
all_goals use 2; norm_num
/-- No set from `theClosedSix fourteenSet` is the universal set. -/
theorem not_eq_univ_of_mem_theClosedSix_fourteenSet {s}
(h : s ∈ theClosedSix fourteenSet) : s ≠ univ := by
rw [theClosedSix, kckckc_fourteenSet, kckck_fourteenSet,
kckc_fourteenSet, kck_fourteenSet, kc_fourteenSet, k_fourteenSet] at h
rw [Ne, eq_univ_iff_forall]
push_neg
repeat obtain _ | ⟨_, h⟩ := h; rotate_left
· use 1/2; norm_num
· use 1/2; norm_num
· use 6; norm_num
· use 6; norm_num
· use 1/2; norm_num
· use 6; norm_num
/-- The fourteen different operations applied to the `fourteenSet` generate no duplicates. -/
theorem nodup_theFourteen_fourteenSet : (theFourteen fourteenSet).Nodup :=
nodup_theFourteen_of_nodup_theClosedSix_of_disjoint nodup_theClosedSix_fourteenSet <|
Multiset.disjoint_iff_ne.mpr <| by
rintro s hc _ ho rfl
exact not_eq_univ_of_mem_theClosedSix_fourteenSet hc <| IsClopen.eq_univ
⟨isClosed_of_mem_theClosedSix hc, isOpen_of_mem_theOpenSix ho⟩
(nonempty_of_mem_theClosedSix_fourteenSet hc)
/-- The number of distinct sets obtainable from `fourteenSet` is exactly 14. -/
theorem ncard_isObtainable_fourteenSet : {t | IsObtainable fourteenSet t}.ncard = 14 := by
classical rw [← card_theFourteen fourteenSet, ← Multiset.toFinset_card_of_nodup
nodup_theFourteen_fourteenSet, ← Set.ncard_coe_finset]
congr; ext; simp [mem_theFourteen_iff_isObtainable]
end Topology.ClosureCompl |
.lake/packages/mathlib/Archive/Examples/MersennePrimes.lean | import Mathlib.NumberTheory.LucasLehmer
/-!
# Explicit Mersenne primes
We run some Lucas-Lehmer tests to prove the first Mersenne primes are prime.
See the discussion at the end of [Mathlib/NumberTheory/LucasLehmer.lean]
for ideas about extending this to larger Mersenne primes.
-/
-- The Lucas-Lehmer test does not apply to `mersenne 2`
example : ¬ LucasLehmerTest 2 := by norm_num
example : (mersenne 2).Prime := by decide
example : (mersenne 3).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 5).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 7).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : ¬ (mersenne 11).Prime := by
intro h
have := lucas_lehmer_necessity 11 (by norm_num) h
norm_num at this
example : (mersenne 13).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 17).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 19).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : ¬ (mersenne 23).Prime := by
intro h
have := lucas_lehmer_necessity 23 (by norm_num) h
norm_num at this
/-- 2147483647.Prime, Euler (1772) -/
example : (mersenne 31).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
/-- Pervushin (1883), Seelhoff (1886) -/
example : (mersenne 61).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 89).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 107).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
/-- Édouard Lucas (1876) -/
example : (mersenne 127).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
/-- Lehmer and Robinson using SWAC computer, (1952) -/
example : (mersenne 521).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 607).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 1279).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 2203).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 2281).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 3217).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 4253).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
example : (mersenne 4423).Prime :=
lucas_lehmer_sufficiency _ (by simp) (by norm_num)
/-
`mersenne 9689` seems to be system dependent:
locally it works fine, but in CI it fails with `(kernel) deep recursion detected`
-/
-- example : (mersenne 9689).Prime :=
-- lucas_lehmer_sufficiency _ (by norm_num) (by norm_num)
/-
`mersenne 9941` seems to be system dependent:
locally it works fine, but in CI it fails with `(kernel) deep recursion detected`
-/
-- example : (mersenne 9941).Prime :=
-- lucas_lehmer_sufficiency _ (by norm_num) (by norm_num)
/-
`mersenne 11213` fails with `(kernel) deep recursion detected` locally as well.
-/
-- example : (mersenne 11213).Prime :=
-- lucas_lehmer_sufficiency _ (by norm_num) (by norm_num) |
.lake/packages/mathlib/Archive/Examples/Eisenstein.lean | import Mathlib.Algebra.CharP.Quotient
import Mathlib.Algebra.Field.ZMod
import Mathlib.Algebra.Polynomial.SpecificDegree
import Mathlib.RingTheory.Ideal.Quotient.Operations
import Mathlib.RingTheory.Polynomial.Eisenstein.Basic
import Mathlib.Tactic.ComputeDegree
/-! # Example of an application of the generalized Eisenstein criterion
We show here how `Polynomial.generalizedEisenstein` can be applied
to establish the irreducibility of the explicit polynomial of degree 4
`X ^ 4 - 10 * X ^ 2 + 1 : ℤ[X]`.
(to which the standard criterion) wouldn't apply.
One argues modulo `3`, with `q := X ^ 2 + 1`.
-/
namespace Polynomial
open Ideal.Quotient Ideal RingHom
example : Irreducible (X ^ 4 - 10 * X ^ 2 + 1 : ℤ[X]) := by
-- We will apply the generalized Eisenstein criterion with `q = X ^ 2 + 1` and `K = ZMod 3`.
set f : ℤ[X] := X ^ 4 - 10 * X ^ 2 + 1 with hf_eq
have hdeg_f : f.natDegree = 4 := by unfold f; compute_degree!
have hf_lC : f.leadingCoeff = 1 := by
simp only [f, leadingCoeff, hdeg_f]; compute_degree!
set q : ℤ [X] := X ^ 2 + 1 with hq_eq
have hq_deg : q.natDegree = 2 := by unfold q; compute_degree!
have hq_monic : q.Monic := by unfold q; monicity!
have hfq : f = q ^ 2 - 12 * q + 12 := by ring
-- On the other hand, `f %ₘ q = 12`, which is not a multiple of `9`.
apply generalizedEisenstein (K := ZMod 3) (q := q) (p := 2)
· set q₃ : (ZMod 3)[X] := X ^ 2 + 1
have hdeg_q₃ : q₃.natDegree = 2 := by unfold q₃; compute_degree!
suffices Irreducible q₃ by simpa [q] using this
apply irreducible_of_degree_le_three_of_not_isRoot
(by simp_all) (by simp_all [q₃]; decide)
· unfold q; monicity!
· exact Monic.isPrimitive hf_lC
· simp_all
· suffices f.leadingCoeff = 1 by
simp [this, map_one, one_ne_zero]
simp only [leadingCoeff, hdeg_f]
unfold f; compute_degree!
· nth_rewrite 1 [hfq]
rw [hf_lC, ← map_C, C_1, Polynomial.map_one, one_mul, ← sub_eq_zero]
have : (12 : (ZMod 3)[X]) = 0 := by apply CharP.ofNat_eq_zero' _ 3 12; norm_num
simp [this]
· suffices f %ₘ q = 12 by
rw [this, ← map_ofNat C, Polynomial.map_C, ne_eq, C_eq_zero, eq_zero_iff_mem,
CharP.ker_intAlgebraMap_eq_span 3, span_singleton_pow, mem_span_singleton]
norm_num
rw [hfq, ← modByMonicHom_apply, LinearMap.map_add]
convert zero_add _
· rw [← LinearMap.mem_ker, mem_ker_modByMonic hq_monic]
rw [pow_two, ← sub_mul]
apply dvd_mul_left
· symm
simp only [modByMonicHom_apply, Polynomial.modByMonic_eq_self_iff hq_monic]
rw [show q.degree = 2 by unfold q; compute_degree!]
rw [show degree _ = 0 by compute_degree!]
norm_num
end Polynomial |
.lake/packages/mathlib/Archive/Examples/IfNormalization/Statement.lean | /-!
# If normalization
Rustan Leino, Stephan Merz, and Natarajan Shankar have recently been discussing challenge problems
to compare proof assistants.
(See https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Rustan's.20challenge)
Their first suggestion was "if-normalization".
This file contains a Lean formulation of the problem. See `Result.lean` for a Lean solution.
-/
/-- An if-expression is either Boolean literal, a numbered variable,
or an if-then-else expression where each subexpression is an if-expression. -/
inductive IfExpr
| lit : Bool → IfExpr
| var : Nat → IfExpr
| ite : IfExpr → IfExpr → IfExpr → IfExpr
deriving DecidableEq, Repr
namespace IfExpr
/--
An if-expression has a "nested if" if it contains
an if-then-else where the "if" is itself an if-then-else.
-/
def hasNestedIf : IfExpr → Bool
| lit _ => false
| var _ => false
| ite (ite _ _ _) _ _ => true
| ite _ t e => t.hasNestedIf || e.hasNestedIf
/--
An if-expression has a "constant if" if it contains
an if-then-else where the "if" is itself a literal.
-/
def hasConstantIf : IfExpr → Bool
| lit _ => false
| var _ => false
| ite (lit _) _ _ => true
| ite i t e => i.hasConstantIf || t.hasConstantIf || e.hasConstantIf
/--
An if-expression has a "redundant if" if it contains
an if-then-else where the then and else clauses are identical.
-/
def hasRedundantIf : IfExpr → Bool
| lit _ => false
| var _ => false
| ite i t e => t == e || i.hasRedundantIf || t.hasRedundantIf || e.hasRedundantIf
/--
All the variables appearing in an if-expressions, read left to right, without removing duplicates.
-/
def vars : IfExpr → List Nat
| lit _ => []
| var i => [i]
| ite i t e => i.vars ++ t.vars ++ e.vars
/--
A helper function to specify that two lists are disjoint.
-/
def _root_.List.disjoint {α} [DecidableEq α] : List α → List α → Bool
| [], _ => true
| x::xs, ys => x ∉ ys && xs.disjoint ys
/--
An if expression evaluates each variable at most once if for each if-then-else
the variables in the if clause are disjoint from the variables in the then clause, and
the variables in the if clause are disjoint from the variables in the else clause.
-/
def disjoint : IfExpr → Bool
| lit _ => true
| var _ => true
| ite i t e =>
i.vars.disjoint t.vars && i.vars.disjoint e.vars && i.disjoint && t.disjoint && e.disjoint
/--
An if expression is "normalized" if it has not nested, constant, or redundant ifs,
and it evaluates each variable at most once.
-/
def normalized (e : IfExpr) : Bool :=
!e.hasNestedIf && !e.hasConstantIf && !e.hasRedundantIf && e.disjoint
/--
The evaluation of an if expression at some assignment of variables.
-/
def eval (f : Nat → Bool) : IfExpr → Bool
| lit b => b
| var i => f i
| ite i t e => bif i.eval f then t.eval f else e.eval f
end IfExpr
/--
This is the statement of the if normalization problem.
We require a function from that transforms if expressions to normalized if expressions,
preserving all evaluations.
-/
def IfNormalization : Type := { Z : IfExpr → IfExpr // ∀ e, (Z e).normalized ∧ (Z e).eval = e.eval } |
.lake/packages/mathlib/Archive/Examples/IfNormalization/Result.lean | import Archive.Examples.IfNormalization.Statement
import Mathlib.Data.List.AList
import Mathlib.Tactic.Recall
/-!
# A solution to the if normalization challenge in Lean.
See `Statement.lean` for background.
-/
macro "◾" : tactic => `(tactic| aesop)
macro "◾" : term => `(term| by aesop)
namespace IfExpr
/-!
We add some local simp lemmas so we can unfold the definitions of the normalization condition.
-/
attribute [local simp] normalized hasNestedIf hasConstantIf hasRedundantIf disjoint vars
List.disjoint
attribute [local simp] apply_ite ite_eq_iff'
variable {b : Bool} {f : ℕ → Bool} {i : ℕ} {t e : IfExpr}
/-!
Simp lemmas for `eval`.
We don't want a `simp` lemma for `(ite i t e).eval` in general, only once we know the shape of `i`.
-/
@[simp] theorem eval_lit : (lit b).eval f = b := rfl
@[simp] theorem eval_var : (var i).eval f = f i := rfl
@[simp] theorem eval_ite_lit :
(ite (.lit b) t e).eval f = bif b then t.eval f else e.eval f := rfl
@[simp] theorem eval_ite_var :
(ite (.var i) t e).eval f = bif f i then t.eval f else e.eval f := rfl
@[simp] theorem eval_ite_ite {a b c d e : IfExpr} :
(ite (ite a b c) d e).eval f = (ite a (ite b d e) (ite c d e)).eval f := by
cases h : eval f a <;> simp_all [eval]
/-- Custom size function for if-expressions, used for proving termination. -/
@[simp] def normSize : IfExpr → Nat
| lit _ => 0
| var _ => 1
| .ite i t e => 2 * normSize i + max (normSize t) (normSize e) + 1
/-- Normalizes the expression at the same time as assigning all variables in
`e` to the literal Booleans given by `l` -/
def normalize (l : AList (fun _ : ℕ => Bool)) :
(e : IfExpr) → { e' : IfExpr //
(∀ f, e'.eval f = e.eval (fun w => (l.lookup w).elim (f w) id))
∧ e'.normalized
∧ ∀ (v : ℕ), v ∈ vars e' → l.lookup v = none }
| lit b => ⟨lit b, ◾⟩
| var v =>
match h : l.lookup v with
| none => ⟨var v, ◾⟩
| some b => ⟨lit b, ◾⟩
| .ite (lit true) t e => have t' := normalize l t; ⟨t'.1, ◾⟩
| .ite (lit false) t e => have e' := normalize l e; ⟨e'.1, ◾⟩
| .ite (.ite a b c) t e => have i' := normalize l (.ite a (.ite b t e) (.ite c t e)); ⟨i'.1, ◾⟩
| .ite (var v) t e =>
match h : l.lookup v with
| none =>
have ⟨t', ht₁, ht₂, ht₃⟩ := normalize (l.insert v true) t
have ⟨e', he₁, he₂, he₃⟩ := normalize (l.insert v false) e
⟨if t' = e' then t' else .ite (var v) t' e', by
refine ⟨fun f => ?_, ?_, fun w b => ?_⟩
· -- eval = eval
simp? says simp only [apply_ite, eval_ite_var, ite_eq_iff']
cases hfv : f v
· simp_all
congr
ext w
by_cases w = v <;> ◾
· simp [h, ht₁]
congr
ext w
by_cases w = v <;> ◾
· -- normalized
have := ht₃ v
have := he₃ v
split <;> ◾
· -- lookup = none
have := ht₃ w
have := he₃ w
by_cases w = v <;> ◾⟩
| some b =>
have i' := normalize l (.ite (lit b) t e); ⟨i'.1, ◾⟩
termination_by e => e.normSize
/-
We recall the statement of the if-normalization problem.
We want a function from if-expressions to if-expressions,
that outputs normalized if-expressions and preserves meaning.
-/
recall IfNormalization :=
{ Z : IfExpr → IfExpr // ∀ e, (Z e).normalized ∧ (Z e).eval = e.eval }
example : IfNormalization :=
⟨_, fun e => ⟨(IfExpr.normalize ∅ e).2.2.1, by simp [(IfExpr.normalize ∅ e).2.1]⟩⟩
end IfExpr |
.lake/packages/mathlib/Archive/Examples/IfNormalization/WithoutAesop.lean | import Archive.Examples.IfNormalization.Statement
import Mathlib.Data.List.AList
/-!
# A variant of Chris Hughes' solution for the if normalization challenge.
In this variant we eschew the use of `aesop`, and instead write out the proofs.
(In order to avoid duplicated names with `Result.lean`,
we put primes on the declarations in the file.)
-/
namespace IfExpr
attribute [local simp] eval normalized hasNestedIf hasConstantIf hasRedundantIf disjoint vars
List.disjoint
theorem eval_ite_ite' {a b c d e : IfExpr} {f : ℕ → Bool} :
(ite (ite a b c) d e).eval f = (ite a (ite b d e) (ite c d e)).eval f := by
cases h : eval f a <;> simp_all
/-- Custom size function for if-expressions, used for proving termination. -/
@[simp] def normSize' : IfExpr → ℕ
| lit _ => 0
| var _ => 1
| .ite i t e => 2 * normSize' i + max (normSize' t) (normSize' e) + 1
/-- Normalizes the expression at the same time as assigning all variables in
`e` to the literal Booleans given by `l` -/
def normalize' (l : AList (fun _ : ℕ => Bool)) :
(e : IfExpr) → { e' : IfExpr //
(∀ f, e'.eval f = e.eval (fun w => (l.lookup w).elim (f w) id))
∧ e'.normalized
∧ ∀ (v : ℕ), v ∈ vars e' → l.lookup v = none }
| lit b => ⟨lit b, by simp⟩
| var v =>
match h : l.lookup v with
| none => ⟨var v, by simp_all⟩
| some b => ⟨lit b, by simp_all⟩
| .ite (lit true) t e =>
have ⟨t', ht'⟩ := normalize' l t
⟨t', by simp_all⟩
| .ite (lit false) t e =>
have ⟨e', he'⟩ := normalize' l e
⟨e', by simp_all⟩
| .ite (.ite a b c) d e =>
have ⟨t', ht₁, ht₂⟩ := normalize' l (.ite a (.ite b d e) (.ite c d e))
⟨t', fun f => by rw [ht₁, eval_ite_ite'], ht₂⟩
| .ite (var v) t e =>
match h : l.lookup v with
| none =>
have ⟨t', ht₁, ht₂, ht₃⟩ := normalize' (l.insert v true) t
have ⟨e', he₁, he₂, he₃⟩ := normalize' (l.insert v false) e
⟨if t' = e' then t' else .ite (var v) t' e', by
refine ⟨fun f => ?_, ?_, fun w b => ?_⟩
· simp only [eval, apply_ite, ite_eq_iff']
cases hfv : f v
· simp +contextual only [cond_false, h, he₁]
refine ⟨fun _ => ?_, fun _ => ?_⟩
· congr
ext w
by_cases h : w = v
· substs h
simp_all
· simp_all
· congr
ext w
by_cases h : w = v
· substs h
simp_all
· simp_all
· simp only [cond_true, h, ht₁]
refine ⟨fun _ => ?_, fun _ => ?_⟩
· congr
ext w
by_cases h : w = v
· substs h
simp_all
· simp_all
· congr
ext w
by_cases h : w = v
· substs h
simp_all
· simp_all
· have := ht₃ v
have := he₃ v
simp_all? says
simp_all only [normalized, Bool.and_eq_true, Bool.not_eq_eq_eq_not, Bool.not_true,
AList.lookup_insert_eq_none, ne_eq, AList.lookup_insert, reduceCtorEq, imp_false]
obtain ⟨⟨⟨tn, tc⟩, tr⟩, td⟩ := ht₂
split <;> rename_i h'
· subst h'
simp_all
· simp_all
· have := ht₃ w
have := he₃ w
by_cases h : w = v
· subst h; simp_all
· simp_all? says
simp_all only [normalized, Bool.and_eq_true, Bool.not_eq_eq_eq_not, Bool.not_true,
AList.lookup_insert_eq_none, ne_eq, not_false_eq_true, AList.lookup_insert_ne,
implies_true]
obtain ⟨⟨⟨en, ec⟩, er⟩, ed⟩ := he₂
split at b <;> rename_i h'
· subst h'; simp_all
· simp_all only [vars, List.cons_append, List.mem_cons, List.mem_append, false_or]
cases b <;> simp_all⟩
| some b =>
have ⟨e', he'⟩ := normalize' l (.ite (lit b) t e)
⟨e', by simp_all⟩
termination_by e' => e'.normSize'
example : IfNormalization :=
⟨fun e => (normalize' ∅ e).1,
fun e => ⟨(normalize' ∅ e).2.2.1, by simp [(normalize' ∅ e).2.1]⟩⟩
end IfExpr |
.lake/packages/mathlib/Archive/OxfordInvariants/Summer2021/Week3P1.lean | import Mathlib.Algebra.BigOperators.Ring.Finset
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Data.Nat.Cast.Field
import Mathlib.Data.Nat.Cast.Order.Field
/-!
# The Oxford Invariants Puzzle Challenges - Summer 2021, Week 3, Problem 1
## Original statement
Let `n ≥ 3`, `a₁, ..., aₙ` be strictly positive integers such that `aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` for
`i = 2, ..., n - 1`. Show that $\sum_{i=1}^{n-1}\dfrac{a_0a_n}{a_ia_{i+1}} ∈ \mathbb N$.
## Comments
Mathlib is based on type theory, so saying that a rational is a natural doesn't make sense. Instead,
we ask that there exists `b : ℕ` whose cast to `α` is the sum we want.
In mathlib, `ℕ` starts at `0`. To make the indexing cleaner, we use `a₀, ..., aₙ₋₁` instead of
`a₁, ..., aₙ`. Similarly, it's nicer to not use subtraction of naturals, so we replace
`aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` by `aᵢ₊₁ ∣ aᵢ + aᵢ₊₂`.
We don't actually have to work in `ℚ` or `ℝ`. We can be even more general by stating the result for
any linearly ordered field.
Instead of having `n` naturals, we use a function `a : ℕ → ℕ`.
In the proof itself, we replace `n : ℕ, 1 ≤ n` by `n + 1`.
The statement is actually true for `n = 0, 1` (`n = 1, 2` before the reindexing) as the sum is
simply `0` and `1` respectively. So the version we prove is slightly more general.
Overall, the indexing is a bit of a mess to understand. But, trust Lean, it works.
## Formalised statement
Let `n : ℕ`, `a : ℕ → ℕ`, `∀ i ≤ n, 0 < a i`, `∀ i, i + 2 ≤ n → aᵢ₊₁ ∣ aᵢ + aᵢ₊₂` (read `→` as
"implies"). Then there exists `b : ℕ` such that `b` as an element of any linearly ordered field
equals $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$.
## Proof outline
The case `n = 0` is trivial.
For `n + 1`, we prove the result by induction but by adding `aₙ₊₁ ∣ aₙ * b - a₀` to the induction
hypothesis, where `b` is the previous sum, $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$, as a
natural.
* Base case:
* $\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1})$ is a natural:
$\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1}) = (a_0 a_1) / (a_0 a_1) = 1$.
* Divisibility condition:
`a₀ * 1 - a₀ = 0` is clearly divisible by `a₁`.
* Induction step:
* $\sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1})$ is a natural:
$$\sum_{i=0}^{n+1} (a_0 a_{n+2}) / (a_i a_{i+1})
= \sum_{i=0}^n\ (a_0 a_{n+2}) / (a_i a_{i+1}) + (a_0 a_{n+2}) / (a_{n+1} a_{n+2})
= a_{n+2} / a_{n+1} × \sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1}) + a_0 / a_{n+1}
= a_{n+2} / a_{n+1} × b + a_0 / a_{n+1}
= (a_n + a_{n+2}) / a_{n+1} × b - (a_n b - a_0)(a_{n+1})$$
which is a natural because `(aₙ + aₙ₊₂)/aₙ₊₁`, `b` and `(aₙ * b - a₀)/aₙ₊₁` are (plus an
annoying inequality, or the fact that the original sum is positive because its terms are).
* Divisibility condition:
`aₙ₊₁ * ((aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁) - a₀ = aₙ₊₁aₙ₊₂b` is divisible by `aₙ₊₂`.
-/
variable {α : Type*} [Field α] [LinearOrder α] [IsStrictOrderedRing α]
theorem OxfordInvariants.Week3P1 (n : ℕ) (a : ℕ → ℕ) (a_pos : ∀ i ≤ n, 0 < a i)
(ha : ∀ i, i + 2 ≤ n → a (i + 1) ∣ a i + a (i + 2)) :
∃ b : ℕ, (b : α) = ∑ i ∈ Finset.range n, (a 0 : α) * a n / (a i * a (i + 1)) := by
-- Treat separately `n = 0` and `n ≥ 1`
rcases n with - | n
/- Case `n = 0`
The sum is trivially equal to `0` -/
· exact ⟨0, by rw [Nat.cast_zero, Finset.sum_range_zero]⟩
-- `⟨Claim it, Prove it⟩`
/- Case `n ≥ 1`. We replace `n` by `n + 1` everywhere to make this inequality explicit
Set up the stronger induction hypothesis -/
rsuffices ⟨b, hb, -⟩ :
∃ b : ℕ,
(b : α) = ∑ i ∈ Finset.range (n + 1), (a 0 : α) * a (n + 1) / (a i * a (i + 1)) ∧
a (n + 1) ∣ a n * b - a 0
· exact ⟨b, hb⟩
simp_rw [← @Nat.cast_pos α] at a_pos
/- Declare the induction
`ih` will be the induction hypothesis -/
induction n with
| zero =>
/- Base case
Claim that the sum equals `1` -/
refine ⟨1, ?_, ?_⟩
-- Check that this indeed equals the sum
· rw [Nat.cast_one, Finset.sum_range_one]
norm_num
rw [div_self]
exact (mul_pos (a_pos 0 (Nat.zero_le _)) (a_pos 1 (Nat.zero_lt_succ _))).ne'
-- Check the divisibility condition
· rw [mul_one, tsub_self]
exact dvd_zero _
| succ n ih =>
/- Induction step
`b` is the value of the previous sum as a natural, `hb` is the proof that it is indeed the
value, and `han` is the divisibility condition -/
obtain ⟨b, hb, han⟩ :=
ih (fun i hi => ha i <| Nat.le_succ_of_le hi) fun i hi => a_pos i <| Nat.le_succ_of_le hi
specialize ha n le_rfl
have ha₀ : a 0 ≤ a n * b := by
-- Needing this is an artifact of `ℕ`-subtraction.
rw [← @Nat.cast_le α, Nat.cast_mul, hb, ←
div_le_iff₀' (a_pos _ <| n.le_succ.trans <| Nat.le_succ _), ←
mul_div_mul_right _ _ (a_pos _ <| Nat.le_succ _).ne']
suffices h : ∀ i, i ∈ Finset.range (n + 1) → 0 ≤ (a 0 : α) * a (n + 1) / (a i * a (i + 1)) from
Finset.single_le_sum h (Finset.self_mem_range_succ n)
refine fun i _ ↦ div_nonneg ?_ ?_ <;> refine mul_nonneg ?_ ?_ <;> exact Nat.cast_nonneg _
-- Claim that the sum equals `(aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁`
refine ⟨(a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1), ?_, ?_⟩
-- Check that this indeed equals the sum
· calc
(((a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : ℕ) : α) =
((a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) ) := by
have :((a (n + 1)) : α) ≠ 0 := ne_of_gt <| a_pos (n + 1) <| Nat.le_succ (n + 1)
simp only [← Nat.cast_add, ← Nat.cast_div ha this, ← Nat.cast_mul, ← Nat.cast_sub ha₀,
← Nat.cast_div han this]
rw [Nat.cast_sub (Nat.div_le_of_le_mul _)]
rw [← mul_assoc, Nat.mul_div_cancel' ha, add_mul]
exact tsub_le_self.trans (Nat.le_add_right _ _)
_ = a (n + 2) / a (n + 1) * b + a 0 * a (n + 2) / (a (n + 1) * a (n + 2)) := by
rw [add_div, add_mul, sub_div, mul_div_right_comm, add_sub_sub_cancel,
mul_div_mul_right _ _ (a_pos _ le_rfl).ne']
_ = ∑ i ∈ Finset.range (n + 2), (a 0 : α) * a (n + 2) / (a i * a (i + 1)) := by
rw [Finset.sum_range_succ, hb, Finset.mul_sum]
congr; ext i
rw [← mul_div_assoc, ← mul_div_right_comm, mul_div_assoc,
mul_div_cancel_right₀ _ (a_pos _ <| Nat.le_succ _).ne', mul_comm]
-- Check the divisibility condition
· rw [Nat.mul_sub, ← mul_assoc, Nat.mul_div_cancel' ha, add_mul, Nat.mul_div_cancel' han,
add_tsub_tsub_cancel ha₀, add_tsub_cancel_right]
exact dvd_mul_right _ _ |
.lake/packages/mathlib/MathlibTest/TacticAnalysis.lean | import Mathlib.Tactic.TacticAnalysis.Declarations
import Mathlib.Tactic.AdaptationNote
import Lean.PremiseSelection
section terminalReplacement
section omega
set_option linter.tacticAnalysis.omegaToCutsat true
/-- warning: `cutsat` can replace `omega` -/
#guard_msgs in
example : 1 + 1 = 2 := by
omega
end omega
@[tacticAnalysis linter.tacticAnalysis.dummy]
def foo : Mathlib.TacticAnalysis.Config :=
Mathlib.TacticAnalysis.terminalReplacement "simp" "simp only" ``Lean.Parser.Tactic.simp
(fun _ _ _ => `(tactic| simp only))
(reportSuccess := true) (reportFailure := true)
/--
warning: `simp only` left unsolved goals where `simp` succeeded.
Original tactic:
simp
Replacement tactic:
simp only
Unsolved goals:
[⊢ (List.map (fun x => x + 1) [1, 2, 3]).sum = 9 ]
-/
#guard_msgs in
set_option linter.tacticAnalysis.dummy true in
example : List.sum ([1,2,3].map fun x ↦ x + 1) = 9 := by
simp
end terminalReplacement
section rwMerge
set_option linter.tacticAnalysis.rwMerge true
def x := 1
def y := 1
def z := 1
theorem xy : x = y := rfl
theorem yz : y = z := rfl
example : x = y := by
rw [xy]
/--
warning: Try this: rw [xy, yz]
-/
#guard_msgs in
example : x = z := by
rw [xy]
rw [yz]
-- Definitions using `where` clauses did not get picked up by the framework,
-- since apparently their syntax bounds do not match the original.
structure Fact (p : Prop) : Prop where
out : p
/--
warning: Try this: rw [xy, yz]
-/
#guard_msgs in
example : Fact (x = z) where
out := by
rw [xy]
rw [yz]
universe u
def a : PUnit.{u} := ⟨⟩
def b : PUnit.{u} := ⟨⟩
def c : PUnit.{u} := ⟨⟩
theorem ab : a = b := rfl
theorem bc : b = c := rfl
/--
warning: Try this: rw [ab.{u}, bc.{u}]
-/
#guard_msgs in
example : a.{u} = c := by
rw [ab.{u}]
rw [bc.{u}]
theorem xyz (h : x = z → y = z) : x = y := by rw [h yz]; rfl
-- The next example tripped up `rwMerge` because `rw [xyz fun h => ?_, ← h, xy]` gives
-- an unknown identifier `h`.
example : x = y := by
rw [xyz fun h => ?_]
rw [← h, xy]
end rwMerge
section mergeWithGrind
set_option linter.tacticAnalysis.mergeWithGrind true
example : 1 + 1 = 2 := by
grind
/--
warning: 'have : 1 + 1 < 3 := by omega; grind' can be replaced with 'grind'
-/
#guard_msgs in
example : 1 + 1 = 2 := by
have : 1 + 1 < 3 := by omega
grind
-- `#adaptation_note` is ignored
example : 1 + 1 = 2 := by
#adaptation_note /-- -/
grind
set_option linter.unusedTactic false
/-- warning: 'skip; grind' can be replaced with 'grind' -/
#guard_msgs in
example : 0 = 0 := by
intros
intros
intros
intros
skip
grind
set_option linter.unusedTactic true
end mergeWithGrind
section replaceWithGrind
set_option linter.tacticAnalysis.terminalToGrind true
example : 1 + 1 = 2 := by
grind
/--
warning: replace the proof with 'grind': have : 1 + 1 < 3 := by omega;
have : 1 + 1 < 4 := by omega;
rfl
-/
#guard_msgs in
example : 1 + 1 = 2 := by
have : 1 + 1 < 3 := by omega
have : 1 + 1 < 4 := by omega
rfl
universe u v
-- This next example used to fail with `unknown universe level 'v'`.
/--
warning: replace the proof with 'grind': let T : Type max u v := Sigma f;
have : 1 + 1 = 2 := rfl;
rfl
-/
#guard_msgs in
example {α : Type u} (f : α → Type max u v) : 1 = 1 := by
let T : Type max u v := Sigma f
have : 1 + 1 = 2 := rfl -- Extra line to ensure the linter picks it up.
rfl
-- Ensure the effects of `classical` are picked up. Otherwise we get an error like:
-- failed to synthesize
-- Decidable b
theorem forall_imp_iff_exists_imp {α : Type} {p : α → Prop} {b : Prop} [ha : Nonempty α] :
(∀ x, p x) → b ↔ ∃ x, p x → b := by
classical
let ⟨a⟩ := ha
refine ⟨fun h ↦ Decidable.not_forall_not.1 fun h' ↦ ?_, fun ⟨x, hx⟩ h ↦ hx (h x)⟩
exact if hb : b then h' a fun _ ↦ hb else hb <| h fun x ↦ (Decidable.not_imp_iff_and_not.1 (h' x)).1
end replaceWithGrind
section introMerge
set_option linter.tacticAnalysis.introMerge true
/-- warning: Try this: intro a b -/
#guard_msgs in
example : ∀ a b : Unit, a = b := by
intro a
intro b
rfl
/-- warning: Try this: intro _ b -/
#guard_msgs in
example : ∀ a b : Unit, a = b := by
intro
intro b
rfl
/-- warning: Try this: intro a _ -/
#guard_msgs in
example : ∀ a b : Unit, a = b := by
intro a
intro _
rfl
#guard_msgs in
example : ∀ a b : Unit, a = b := by
intro a b
rfl
end introMerge
section tryAtEachStep
section
set_option linter.tacticAnalysis.tryAtEachStepGrind true
/-- info: `rfl` can be replaced with `grind` -/
#guard_msgs in
example : 1 + 1 = 2 := by
rfl
/--
info: `skip` can be replaced with `grind`
---
info: `rfl` can be replaced with `grind`
---
warning: 'skip' tactic does nothing
Note: This linter can be disabled with `set_option linter.unusedTactic false`
-/
#guard_msgs in
example : 1 + 1 = 2 := by
skip
rfl
end
section
def P (_ : Nat) := True
theorem p : P 37 := trivial
set_premise_selector fun _ _ => pure #[{ name := `p, score := 1.0 }]
-- FIXME: remove this one `grind +premises` lands.
macro_rules | `(tactic| grind +premises) => `(tactic| grind [p])
example : P 37 := by
grind +premises
set_option linter.tacticAnalysis.tryAtEachStepGrindPremises true
/-- info: `trivial` can be replaced with `grind +premises✝` -/
#guard_msgs in
example : P 37 := by
trivial
end
end tryAtEachStep
section grindReplacement
set_option linter.tacticAnalysis.regressions.omegaToCutsat true
-- We should not complain about `omega` (and others) failing in a `try` context.
example : x = y := by
try omega
rfl
-- Example with more than one tactic step:
example : x = y := by
try
symm
symm
omega
rfl
set_option linter.unusedVariables false in
theorem create_a_few_goals (h1 : 1 + 1 = 2) (h2 : y = z) : x = y := rfl
-- We should not complain about `omega` (and others) failing in an `any_goals` context.
example : x = y := by
apply create_a_few_goals
any_goals omega
rfl
-- Example with more than one tactic step:
example : x = y := by
apply create_a_few_goals
any_goals
symm
symm
omega
rfl
end grindReplacement |
.lake/packages/mathlib/MathlibTest/toAdditiveIrredDef.lean | import Mathlib.Tactic.IrreducibleDef
import Mathlib.Algebra.Group.Defs
set_option autoImplicit true
@[to_additive]
irreducible_def mul_conj [Group G] (a b : G) := a⁻¹ * b * a
example [AddGroup A] (a b : A) : add_conj a b = (-a) + b + a :=
add_conj_def a b |
.lake/packages/mathlib/MathlibTest/toAdditive.lean | import Mathlib.Algebra.Group.Defs
import Mathlib.Lean.Exception
import Mathlib.Tactic.ReduceModChar.Ext
import Qq.MetaM
open Qq Lean Meta Elab Command Mathlib Tactic Translate ToAdditive
set_option autoImplicit true
-- work in a namespace so that it doesn't matter if names clash
namespace Test
-- [note] use the below options for diagnostics:
-- set_option trace.to_additive true
-- set_option trace.to_additive_detail true
-- set_option pp.universes true
-- set_option pp.explicit true
-- set_option pp.notation false
@[to_additive bar0]
def foo0 {α} [Mul α] [One α] (x y : α) : α := x * y * 1
theorem bar0_works : bar0 3 4 = 7 := by decide
class my_has_pow (α : Type u) (β : Type v) where
(pow : α → β → α)
instance : my_has_pow Nat Nat := ⟨fun a b => a ^ b⟩
class my_has_scalar (M : Type u) (α : Type v) where
(smul : M → α → α)
instance : my_has_scalar Nat Nat := ⟨fun a b => a * b⟩
attribute [to_additive (reorder := 1 2) my_has_scalar] my_has_pow
/--
error: Cannot apply attribute @[to_additive] to 'Test.my_has_pow.pow': it is already translated to 'Test.my_has_scalar.smul'. ⏎
If you need to set the `reorder` or `relevant_arg` option, this is still possible with the ⏎
`@[to_additive (reorder := ...)]` or `@[to_additive (relevant_arg := ...)]` syntax.
-/
#guard_msgs in
attribute [to_additive] my_has_pow.pow
/--
error: `to_additive` validation failed: expected
{β : Type u} → {α : Type v} → [self : my_has_scalar β α] → α → β → α
but 'Test.my_has_scalar.smul' has type
{M : Type u} → {α : Type v} → [self : my_has_scalar M α] → M → α → α
-/
#guard_msgs in
attribute [to_additive (reorder := 1 2)] my_has_pow.pow
attribute [to_additive (reorder := 1 2, 4 5)] my_has_pow.pow
@[to_additive bar1]
def foo1 {α : Type u} [my_has_pow α ℕ] (x : α) (n : ℕ) : α := @my_has_pow.pow α ℕ _ x n
theorem foo1_works : foo1 3 4 = Nat.pow 3 4 := by decide
theorem bar1_works : bar1 3 4 = 3 * 4 := by decide
infix:80 " ^ " => my_has_pow.pow
instance dummy_pow : my_has_pow ℕ <| PLift ℤ := ⟨fun _ _ => 5⟩
@[to_additive bar2]
def foo2 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) (m : PLift ℤ) : α := x ^ (n ^ m)
theorem foo2_works : foo2 2 3 (PLift.up 2) = Nat.pow 2 5 := by decide
theorem bar2_works : bar2 2 3 (PLift.up 2) = 2 * 5 := by decide
@[to_additive bar3]
def foo3 {α} [my_has_pow α ℕ] (x : α) : ℕ → α := @my_has_pow.pow α ℕ _ x
theorem foo3_works : foo3 2 3 = Nat.pow 2 3 := by decide
theorem bar3_works : bar3 2 3 = 2 * 3 := by decide
@[to_additive bar4]
def foo4 {α : Type u} : Type v → Type (max u v) := @my_has_pow α
@[to_additive bar4_test]
lemma foo4_test {α β : Type u} : @foo4 α β = @my_has_pow α β := rfl
@[to_additive bar5]
def foo5 {α} [my_has_pow α ℕ] [my_has_pow ℕ ℤ] : True := True.intro
@[to_additive bar6]
def foo6 {α} [my_has_pow α ℕ] : α → ℕ → α := @my_has_pow.pow α ℕ _
-- fails because of workaround in `transform`. Not sure if this will show up in practice
-- @[to_additive bar7]
-- def foo7 := @my_has_pow.pow
-- theorem foo7_works : foo7 2 3 = Nat.pow 2 3 := by decide
-- theorem bar7_works : bar7 2 3 = 2 * 3 := by decide
/-- Check that we don't additivize `Nat` expressions. -/
@[to_additive bar8]
def foo8 (a b : ℕ) := a * b
theorem bar8_works : bar8 2 3 = 6 := by decide
/-- Check that we don't additivize `Nat` numerals. -/
@[to_additive bar9]
def foo9 := 1
theorem bar9_works : bar9 = 1 := by decide
@[to_additive bar10]
def foo10 (n m : ℕ) := HPow.hPow n m + n * m * 2 + 1 * 0 + 37 * 1 + 2
theorem bar10_works : bar10 = foo10 := rfl
@[to_additive bar11]
def foo11 (n : ℕ) (m : ℤ) := n * m * 2 + 1 * 0 + 37 * 1 + 2
theorem bar11_works : bar11 = foo11 := rfl
@[to_additive bar12]
def foo12 (_ : Nat) (_ : Int) : Fin 37 := ⟨2, by decide⟩
@[to_additive (reorder := 1 2, 4 5) bar13]
lemma foo13 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : x ^ y = x ^ y := rfl
@[to_additive (reorder := 1 2, 4 5) bar14]
def foo14 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : α := (x ^ y) ^ y
@[to_additive (reorder := 1 2, 4 5) bar15]
lemma foo15 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : foo14 x y = (x ^ y) ^ y := rfl
@[to_additive (reorder := 1 2, 4 5) bar16]
lemma foo16 {α β : Type u} [my_has_pow α β] (x : α) (y : β) : foo14 x y = (x ^ y) ^ y := foo15 x y
@[to_additive bar17]
def foo17 [Group α] (x : α) : α := x * 1
@[to_additive (attr := simp) bar18]
lemma foo18 [Group α] (x : α) : foo17 x = x ∧ foo17 x = 1 * x :=
⟨mul_one x, mul_one x |>.trans <| one_mul x |>.symm⟩
example [Group α] (x : α) : foo17 x = 1 * x := by simp
example [Group α] (x : α) : foo17 x = x := by simp
example [AddGroup α] (x : α) : bar17 x = 0 + x := by simp
example [AddGroup α] (x : α) : bar17 x = x := by simp
/- Testing nested to_additive calls -/
@[to_additive (attr := simp, to_additive baz19) bar19]
def foo19 := 1
example {x} (h : 1 = x) : foo19 = x := by simp; guard_target = 1 = x; exact h
example {x} (h : 1 = x) : bar19 = x := by simp; guard_target = 1 = x; exact h
example {x} (h : 1 = x) : baz19 = x := by simp; guard_target = 1 = x; exact h
/- Testing that the order of the attributes doesn't matter -/
@[to_additive (attr := to_additive baz20, simp) bar20]
def foo20 := 1
example {x} (h : 1 = x) : foo20 = x := by simp; guard_target = 1 = x; exact h
example {x} (h : 1 = x) : bar20 = x := by simp; guard_target = 1 = x; exact h
example {x} (h : 1 = x) : baz20 = x := by simp; guard_target = 1 = x; exact h
@[to_additive bar21]
def foo21 {N} {A} [Pow A N] (a : A) (n : N) : A := a ^ n
run_cmd liftCoreM <| MetaM.run' <| guard <| relevantArgAttr.find? (← getEnv) `Test.foo21 == some 1
@[to_additive bar22]
abbrev foo22 {α} [Monoid α] (a : α) : ℕ → α
| 0 => 1
| _ => a
run_cmd liftCoreM <| MetaM.run' <| do
-- make `abbrev` definition `reducible` automatically
guard <| (← getReducibilityStatus `Test.bar22) == .reducible
-- make `abbrev` definition `inline` automatically
guard <| (Compiler.getInlineAttribute? (← getEnv) `Test.bar22) == some .inline
-- some auxiliary definitions are also `abbrev` but not `reducible`
guard <| (← getReducibilityStatus `Test.bar22.match_1) != .reducible
guard <| (Compiler.getInlineAttribute? (← getEnv) `Test.bar22.match_1) == some .inline
/- test the eta-expansion applied on `foo6`. -/
run_cmd do
let c ← getConstInfo `Test.foo6
let e : Expr ← liftCoreM <| MetaM.run' <| expand ToAdditive.data c.value!
let t ← liftCoreM <| MetaM.run' <| expand ToAdditive.data c.type
let decl := c |>.updateName `Test.barr6 |>.updateType t |>.updateValue e |>.toDeclaration!
liftCoreM <| addAndCompile decl
-- test that we cannot transport a declaration to itself
successIfFail <| liftCoreM <| addTranslationAttr ToAdditive.data `bar11_works { ref := ← getRef }
/- Test on inductive types -/
inductive AddInd : ℕ → Prop where
| basic : AddInd 2
| zero : AddInd 0
@[to_additive]
inductive MulInd : ℕ → Prop where
| basic : MulInd 2
| one : MulInd 1
run_cmd do
unless findTranslation? (← getEnv) ToAdditive.data `Test.MulInd.one == some `Test.AddInd.zero do throwError "1"
unless findTranslation? (← getEnv) ToAdditive.data `Test.MulInd.basic == some `Test.AddInd.basic do throwError "2"
unless findTranslation? (← getEnv) ToAdditive.data `Test.MulInd == some `Test.AddInd do throwError "3"
@[to_additive addFixedNumeralTest]
def fixedNumeralTest {α} [One α] :=
@OfNat.ofNat ((fun _ => ℕ) (1 : α)) 1 _
@[to_additive addFixedNumeralTest2]
def fixedNumeralTest2 {α} [One α] :=
@OfNat.ofNat ((fun _ => ℕ) (1 : α)) 1 (@One.toOfNat1 ((fun _ => ℕ) (1 : α)) _)
/-! Test the namespace bug (https://github.com/leanprover-community/mathlib4/pull/8733).
This code should *not* generate a lemma
`add_some_def.in_namespace`. -/
def some_def.in_namespace : Bool := false
def some_def {α : Type u} [Mul α] (x : α) : α :=
if some_def.in_namespace then x * x else x
def myFin (_ : ℕ) := ℕ
instance : One (myFin n) := ⟨(1 : ℕ)⟩
@[to_additive bar]
def myFin.foo : myFin (n + 1) := 1
/-- We can pattern-match with `1`, which creates a term with a pure nat literal.
See https://github.com/leanprover-community/mathlib4/pull/2046 -/
@[to_additive]
def mul_foo {α} [Monoid α] (a : α) : ℕ → α
| 0 => 1
| 1 => 1
| (_ + 2) => a
-- cannot apply `@[to_additive]` to `some_def` if `some_def.in_namespace` doesn't have the attribute
run_cmd liftCoreM <| successIfFail <|
transformDecl ToAdditive.data { ref := ← getRef} `Test.some_def `Test.add_some_def
attribute [to_additive some_other_name] some_def.in_namespace
attribute [to_additive add_some_def] some_def
run_cmd do liftCoreM <| successIfFail (getConstInfo `Test.add_some_def.in_namespace)
section
set_option linter.unusedVariables false in
def foo_mul {I J K : Type} (n : ℕ) {f : I → Type} (L : Type) [∀ i, One (f i)]
[Add I] [Mul L] : true := by trivial
@[to_additive]
instance pi.has_one {I : Type} {f : I → Type} [(i : I) → One <| f i] : One ((i : I) → f i) :=
⟨fun _ => 1⟩
run_cmd do
let n ← liftCoreM <| MetaM.run' <| findRelevantArg ToAdditive.data `Test.pi.has_one
if n != 1 then throwError "{n} != 1"
let n ← liftCoreM <| MetaM.run' <| findRelevantArg ToAdditive.data `Test.foo_mul
if n != 4 then throwError "{n} != 4"
end
@[to_additive]
def nat_pi_has_one {α : Type} [One α] : One ((x : Nat) → α) := by infer_instance
@[to_additive]
def pi_nat_has_one {I : Type} : One ((x : I) → Nat) := pi.has_one
example : @pi_nat_has_one = @pi_nat_has_zero := rfl
section instances
class FooClass (α) : Prop where
refle : ∀ a : α, a = a
@[to_additive]
instance FooClass_one [One α] : FooClass α := ⟨fun _ ↦ rfl⟩
lemma one_fooClass [One α] : FooClass α := by infer_instance
lemma zero_fooClass [Zero α] : FooClass α := by infer_instance
end instances
/- Test that we can rewrite with definitions with the `@[to_additive]` attribute. -/
@[to_additive]
lemma npowRec_zero [One M] [Mul M] (x : M) : npowRec 0 x = 1 := by
rw [npowRec]
/- Test that we can rewrite with definitions without the `@[to_additive]` attribute. -/
@[to_additive addoptiontest]
lemma optiontest (x : Option α) : x.elim none some = x := by
cases x <;> rw [Option.elim]
/- Check that `to_additive` works if a `_match` aux declaration is created. -/
@[to_additive]
def IsUnit [Mul M] (a : M) : Prop := a ≠ a
@[to_additive]
theorem isUnit_iff_exists_inv [Mul M] {a : M} : IsUnit a ↔ ∃ _ : α, a ≠ a :=
⟨fun h => absurd rfl h, fun ⟨_, hab⟩ => hab⟩
/-! Test that `@[to_additive]` correctly translates auxiliary declarations that do not have the
original declaration name as prefix. -/
@[to_additive]
def IsUnit' [Monoid M] (a : M) : Prop := ∃ b : M, a * b = 1
@[to_additive]
theorem isUnit'_iff_exists_inv [CommMonoid M] {a : M} : IsUnit' a ↔ ∃ b, a * b = 1 := Iff.rfl
@[to_additive]
theorem isUnit'_iff_exists_inv' [CommMonoid M] {a : M} : IsUnit' a ↔ ∃ b, b * a = 1 := by
simp [isUnit'_iff_exists_inv, mul_comm]
/-! Test a permutation with a cycle of length > 2. -/
@[to_additive (reorder := 3 4 5)]
def reorderMulThree {α : Type _} [Mul α] (x y z : α) : α := x * y * z
/-! Test a permutation that is too big for the list of arguments. -/
/--
error: the permutation
[[2, 3, 50]]
provided by the `(reorder := ...)` option is out of bounds, the type
{α : Type u_1} → [Add α] → α → α → α → α
has only 5 arguments
-/
#guard_msgs in
@[to_additive (reorder := 3 4 51)]
def reorderMulThree' {α : Type _} [Mul α] (x y z : α) : α := x * y * z
/-! Test `(reorder := ...)` when the proof needs to be eta-expanded. -/
@[to_additive (reorder := 3 4 5)]
alias reorderMulThree_alias := reorderMulThree
@[to_additive (reorder := 3 4 2)]
alias reorderMulThree_alias' := reorderMulThree
@[to_additive (reorder := 3 4 5)]
def reorderMulThree_alias'' {α : Type _} [Mul α] (x y : α) : α → α := reorderMulThree x y
/--
error: invalid cycle `04`, a cycle must have at least 2 elements.
`(reorder := ...)` uses cycle notation to specify a permutation.
For example `(reorder := 1 2, 5 6)` swaps the first two arguments with each other and the fifth and the sixth argument and `(reorder := 3 4 5)` will move the fifth argument before the third argument.
-/
#guard_msgs in
@[to_additive (reorder := 04)]
example : True := trivial
/-- error: invalid position `00`, positions are counted starting from 1. -/
#guard_msgs in
@[to_additive (reorder := 100 200, 2 00)]
example : True := trivial
example {α : Type _} [Add α] (x y z : α) : reorderAddThree z x y = x + y + z := rfl
def Ones : ℕ → Q(Nat)
| 0 => q(1)
| (n + 1) => q($(Ones n) + $(Ones n))
-- This test just exists to see if this finishes in finite time. It should take <100ms.
-- #time
run_cmd do
let e : Expr := Ones 300
let _ ← liftCoreM <| MetaM.run' <| applyReplacementFun ToAdditive.data e
-- testing `isConstantApplication`
run_cmd do
unless !(q((fun _ y => y) 3 4) : Q(Nat)).isConstantApplication do throwError "1"
unless (q((fun x _ => x) 3 4) : Q(Nat)).isConstantApplication do throwError "2"
unless !(q((fun x => x) 3) : Q(Nat)).isConstantApplication do throwError "3"
unless (q((fun _ => 5) 3) : Q(Nat)).isConstantApplication do throwError "4"
@[to_additive, to_additive_dont_translate]
def MonoidEnd : Type := Unit
run_cmd do
let stx ← `(Semigroup MonoidEnd)
liftTermElabM do
let e ← Term.elabTerm stx none
guard <| shouldTranslate (← getEnv) ToAdditive.data e == some (.inl `Test.MonoidEnd)
@[to_additive instSemiGroupAddMonoidEnd]
instance : Semigroup MonoidEnd where
mul _ _ := ()
mul_assoc _ _ _ := rfl
@[to_additive]
lemma monoidEnd_lemma (x y z : MonoidEnd) : x * (y * z) = (x * y) * z := mul_assoc .. |>.symm
/-- info: Test.addMonoidEnd_lemma (x y z : AddMonoidEnd) : x * (y * z) = x * y * z -/
#guard_msgs in
#check addMonoidEnd_lemma
/-!
Some arbitrary tests to check whether additive names are guessed correctly.
-/
section guessName
def checkGuessName (s t : String) : Elab.Command.CommandElabM Unit :=
unless (GuessName.guessName { nameDict, abbreviationDict } s) == t do
throwError "failed: {GuessName.guessName { nameDict, abbreviationDict } s} != {t}"
run_cmd
checkGuessName "HMul_Eq_LEOne_Conj₂MulLT'" "HAdd_Eq_Nonpos_Conj₂AddLT'"
checkGuessName "OneMulSMulInvDivPow" "ZeroAddVAddNegSubNSMul"
checkGuessName "ProdFinprodNPowZPow" "SumFinsumNSMulZSMul"
-- The current design swaps all instances of `Comm`+`Add` in order to have
-- `AddCommMonoid` instead of `CommAddMonoid`.
checkGuessName "comm_mul_CommMul_commMul" "comm_add_AddComm_addComm"
checkGuessName "mul_comm_MulComm_mulComm" "add_comm_AddComm_addComm"
checkGuessName "mul_single_eq_same" "single_eq_same"
checkGuessName "mul_support" "support"
checkGuessName "mul_tsupport" "tsupport"
checkGuessName "mul_indicator" "indicator"
checkGuessName "CommMonoid" "AddCommMonoid"
checkGuessName "commMonoid" "addCommMonoid"
checkGuessName "CancelCommMonoid" "AddCancelCommMonoid"
checkGuessName "cancelCommMonoid" "addCancelCommMonoid"
checkGuessName "CancelMonoid" "AddCancelMonoid"
checkGuessName "cancelMonoid" "addCancelMonoid"
checkGuessName "RightCancelMonoid" "AddRightCancelMonoid"
checkGuessName "rightCancelMonoid" "addRightCancelMonoid"
checkGuessName "LeftCancelMonoid" "AddLeftCancelMonoid"
checkGuessName "leftCancelMonoid" "addLeftCancelMonoid"
checkGuessName "IsLeftRegular" "IsAddLeftRegular"
checkGuessName "isRightRegular" "isAddRightRegular"
checkGuessName "IsRegular" "IsAddRegular"
checkGuessName "LTOne_LEOne_OneLE_OneLT" "Neg_Nonpos_Nonneg_Pos"
checkGuessName "LTHMulHPowLEHDiv" "LTHAddHSMulLEHSub"
checkGuessName "OneLEHMul" "NonnegHAdd"
checkGuessName "OneLTHPow" "PosHSMul"
checkGuessName "OneLTPow" "PosNSMul"
checkGuessName "instCoeTCOneHom" "instCoeTCZeroHom"
checkGuessName "instCoeTOneHom" "instCoeTZeroHom"
checkGuessName "instCoeOneHom" "instCoeZeroHom"
checkGuessName "invFun_eq_symm" "invFun_eq_symm"
checkGuessName "MulEquiv.symmInvFun" "AddEquiv.symmInvFun"
checkGuessName "IsScalarTower" "VAddAssocClass"
checkGuessName "isScalarTower" "vaddAssocClass"
checkGuessName "eventuallyLE_one_mul_atBot" "eventuallyLE_zero_add_atBot"
end guessName
end Test
insert_to_additive_translation localize add_localize
@[to_additive] def localize.r := Nat
@[to_additive add_localize] def localize := Nat
@[to_additive] def localize.s := Nat
run_cmd do
unless findTranslation? (← getEnv) ToAdditive.data `localize.r == some `add_localize.r do throwError "1"
unless findTranslation? (← getEnv) ToAdditive.data `localize == some `add_localize do throwError "2"
unless findTranslation? (← getEnv) ToAdditive.data `localize.s == some `add_localize.s do throwError "3"
/--
warning: The source declaration one_eq_one was given the simp-attribute(s) simp, reduce_mod_char before calling @[to_additive].
The preferred method is to use something like `@[to_additive (attr := simp, reduce_mod_char)]`
to apply the attribute to both one_eq_one and the target declaration zero_eq_zero.
Note: This linter can be disabled with `set_option linter.existingAttributeWarning false`
-/
#guard_msgs in
@[simp, reduce_mod_char, to_additive]
lemma one_eq_one {α : Type*} [One α] : (1 : α) = 1 := rfl
@[to_additive (attr := reduce_mod_char, simp)]
lemma one_eq_one' {α : Type*} [One α] : (1 : α) = 1 := rfl
section
-- Test the error message for a name that cannot be additivised.
/--
error: to_additive: the generated translated name equals the original name 'foo'.
If this is intentional, use the `@[to_additive self]` syntax.
Otherwise, check that your declaration name is correct (if your declaration is an instance, try naming it)
or provide a translated name using the `@[to_additive my_add_name]` syntax.
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
@[to_additive]
local instance foo {α : Type*} [Semigroup α] : Monoid α := sorry
end
-- Test the error message for a wrong `to_additive existing`.
/--
error: `to_additive` validation failed:
expected 1 universe levels, but 'Nat.le_trans' has 0 universe levels
-/
#guard_msgs in
@[to_additive existing Nat.le_trans]
lemma one_eq_one'' {α : Type*} [One α] : (1 : α) = 1 := rfl
/--
error: `to_additive` validation failed: expected
∀ {α : Type u} [inst : Zero α], 0 = 0
but 'Eq.trans' has type
∀ {α : Sort u} {a b c : α}, a = b → b = c → a = c
-/
#guard_msgs in
@[to_additive existing Eq.trans]
lemma one_eq_one''' {α : Type*} [One α] : (1 : α) = 1 := rfl
/-!
Test that @[to_additive] can reorder arguments of raw kernel projections.
-/
open Lean in
elab "unfold%" e:term : term => do
let e ← Elab.Term.elabTerm e none
Meta.unfoldDefinition e
@[to_additive]
def myPow {α β : Type} [i : Pow α β] (a : α) := unfold% i.1 a
/--
info: def myPow : {α β : Type} → [i : Pow α β] → α → β → α :=
fun {α β} [i : Pow α β] a => i.1 a
-/
#guard_msgs in
#print myPow
/--
info: def myNSMul : {α β : Type} → [i : SMul β α] → α → β → α :=
fun {α β} [SMul β α] a a_1 => SMul.smul a_1 a
-/
#guard_msgs in
#print myNSMul
@[to_additive]
def myMul {α : Type} [i : Mul α] (a : α) := unfold% i.1 a
/--
info: def myMul : {α : Type} → [i : Mul α] → α → α → α :=
fun {α} [i : Mul α] a => i.1 a
-/
#guard_msgs in
#print myMul
/--
info: def myAdd : {α : Type} → [i : Add α] → α → α → α :=
fun {α} [Add α] a => Add.add a
-/
#guard_msgs in
#print myAdd
/-! Test that the `existingAttributeWarning` linter doesn't fire for `to_additive self`. -/
@[simp, to_additive self]
theorem test1 : 5 = 5 := rfl
/-! Test that we can't write `to_additive self (attr := ..)`. -/
/--
error: invalid `(attr := ...)` after `self`, as there is only one declaration for the attributes.
Instead, you can write the attributes in the usual way.
-/
#guard_msgs in
@[to_additive self (attr := simp)]
theorem test2 : 5 = 5 := rfl
/-! Previously, An application that isn't a constant, such as `(no_index Add) α`, would be seen as
multiplicative, hence `α` would be set as the `to_additive_relevant_arg`. -/
@[to_additive]
def fooMul {α β : Type} (_ : (no_index Add) α) [Mul β] (x y : β) : β := x * y
@[to_additive] -- this would not translate `fooMul`
def barMul {β : Type} [Mul β] (x y : β) : β := fooMul instAddNat x y
/-! Test that additive docstrings work -/
@[to_additive /-- (via `docComment` syntax) I am an additive docstring! -/]
theorem mulTrivial : True := trivial
/-- info: (via `docComment` syntax) I am an additive docstring! -/
#guard_msgs in
run_cmd
let some doc ← findDocString? (← getEnv) ``addTrivial
| throwError "no `docComment` docstring found"
logInfo doc
/--
warning: String syntax for `to_additive` docstrings is deprecated: Use docstring syntax instead (e.g. `@[to_additive /-- example -/]`)
Update deprecated syntax to:
[apply] /-- (via `str` syntax) I am an additive docstring! -/
-/
#guard_msgs in
@[to_additive "(via `str` syntax) I am an additive docstring!"]
theorem mulTrivial' : True := trivial
/-- info: (via `str` syntax) I am an additive docstring! -/
#guard_msgs in
run_cmd
let some doc ← findDocString? (← getEnv) ``addTrivial'
| throwError "no `str` docstring found"
logInfo doc
/-! Test handling of noncomputability -/
elab "#computability " decl:ident : command => do
let name ← liftCoreM (realizeGlobalConstNoOverloadWithInfo decl)
let markedNonComp := isNoncomputable (← getEnv) name
let hasNoExec := (IR.findEnvDecl (← getEnv) name).isNone
let desc :=
if markedNonComp then "is marked noncomputable"
else if hasNoExec then "has no executable code"
else "is computable"
logInfo m!"`{name}` {desc}"
/- Both should be computable -/
@[to_additive]
def mulComputableTest : Nat := 0
/-- info: `mulComputableTest` is computable -/
#guard_msgs in #computability mulComputableTest
/-- info: `addComputableTest` is computable -/
#guard_msgs in #computability addComputableTest
/- Both should be marked noncomputable -/
@[to_additive]
noncomputable def mulMarkedNoncomputable : Nat := 0
/-- info: `mulMarkedNoncomputable` is marked noncomputable -/
#guard_msgs in #computability mulMarkedNoncomputable
/-- info: `addMarkedNoncomputable` is marked noncomputable -/
#guard_msgs in #computability addMarkedNoncomputable
noncomputable section
/- Compilation should succeed despite `noncomputable` -/
@[to_additive]
def mulComputableTest' : Nat := 0
/-- info: `mulComputableTest'` is computable -/
#guard_msgs in #computability mulComputableTest'
/-- info: `addComputableTest'` is computable -/
#guard_msgs in #computability addComputableTest'
/- Both should be marked noncomputable -/
@[to_additive]
noncomputable def mulMarkedNoncomputable' : Nat := 0
/-- info: `mulMarkedNoncomputable'` is marked noncomputable -/
#guard_msgs in #computability mulMarkedNoncomputable'
/-- info: `addMarkedNoncomputable'` is marked noncomputable -/
#guard_msgs in #computability addMarkedNoncomputable'
/-
Compilation should fail silently.
If `mulNoExec` ever becomes marked noncomputable (meaning Lean's handling of
`noncomputable section` has changed), then the check for executable code in
`Mathlib.Tactic.ToAdditive.Frontend` should be replaced with a simple `isNoncomputable` check and
mark `addNoExec` `noncomputable` as well (plus a check for whether the original declaration is an
axiom, if `to_additive` ever handles axioms).
-/
@[to_additive]
def mulNoExec {G} (n : Nonempty G) : G := Classical.choice n
/-- info: `mulNoExec` has no executable code -/
#guard_msgs in #computability mulNoExec
/-- info: `addNoExec` has no executable code -/
#guard_msgs in #computability addNoExec
end
/-! Test structures with a private constructor and private fields -/
structure MyPrivateAdd where
private mk ::
private add : Nat
@[to_additive]
structure MyPrivateMul where
private mk ::
private mul : Nat
@[to_additive]
def MyPrivateMul.mk' (a : Nat) := MyPrivateMul.mk a
@[to_additive]
def MyPrivateMul.mul' (x : MyPrivateMul) := x.mul
/-! Test the `(dont_translate := ...)` framework -/
class MyRing (α : Type*) extends Group α
@[to_additive (dont_translate := β γ) add_neg_iff_mul_inv]
lemma mul_inv_iff_mul_inv {α β γ : Type} [Group α] [MyRing β] [MyRing γ] (a : α) (b : β) (c : γ) :
a * a⁻¹ = 1 ↔ b * b⁻¹ = 1 ∨ c * c⁻¹ = 1 := by
simp
/--
info: add_neg_iff_mul_inv {α β γ : Type} [AddGroup α] [MyRing β] [MyRing γ] (a : α) (b : β) (c : γ) :
a + -a = 0 ↔ b * b⁻¹ = 1 ∨ c * c⁻¹ = 1
-/
#guard_msgs in
#check add_neg_iff_mul_inv
@[to_additive (dont_translate := β) add_neg_iff_mul_inv]
def Subtype.mul_inv_iff_mul_inv {α β : Type} [Group α] [MyRing β] (a : α) (b : β) :
{a : α // a * a⁻¹ = 1 ↔ b * b⁻¹ = 1} := by
exists a
simp
/--
info: Subtype.mul_inv_iff_mul_inv._proof_1 {α β : Type} [Group α] [MyRing β] (a : α) (b : β) : a * a⁻¹ = 1 ↔ b * b⁻¹ = 1
-/
#guard_msgs in
#check Subtype.mul_inv_iff_mul_inv._proof_1
/--
info: Subtype.add_neg_iff_mul_inv._proof_1 {α β : Type} [AddGroup α] [MyRing β] (a : α) (b : β) : a + -a = 0 ↔ b * b⁻¹ = 1
-/
#guard_msgs in
#check Subtype.add_neg_iff_mul_inv._proof_1
/-!
Test that `relevant_arg` and `reorder` are passed to `simps` and `.eq_1`, and to
structure fields/constructors.
-/
structure SimpleNSMul (β : Type 1) (α : Type) where
x : Nat
@[to_additive (reorder := 1 2) (relevant_arg := 2)]
structure SimplePow (α : Type) (β : Type 1) where
x : Nat
@[to_additive (reorder := 1 2) (attr := simps)]
def simplePowZero (α β) : SimplePow α β where
x := 0
@[to_additive]
lemma simplePowZero_x' {β} : (simplePowZero Nat β).x = 0 := by
rw [simplePowZero_x]
@[to_additive]
lemma simplePowZero_x'' {β} : (simplePowZero Nat β).x = 0 := by
rw [simplePowZero.eq_1]
/-- info: simpleNSMulZero_x' {β : Type 1} : (simpleNSMulZero β ℕ).x = 0 -/
#guard_msgs in
#check simpleNSMulZero_x'
/-- info: simpleNSMulZero_x'' {β : Type 1} : (simpleNSMulZero β ℕ).x = 0 -/
#guard_msgs in
#check simpleNSMulZero_x''
structure AddMonoidAlgebra' (k G : Type) where
x : G → k
@[to_additive (relevant_arg := 2)]
structure MonoidAlgebra' (k G : Type) where
x : G → k
variable {G : Type} [Monoid G]
@[to_additive]
instance : Mul (MonoidAlgebra' Nat G) where
mul a b := ⟨fun i => a.1 i * b.1 1⟩
-- Unfortunately, `relevant_arg` information isn't passed to `*.casesOn`:
/--
error: @[to_additive] failed. The translated value is not type correct. For help, see the docstring of `to_additive`, section `Troubleshooting`. Failed to add declaration
instAddAddMonoidAlgebra'Nat_1.match_1:
Application type mismatch: The argument
fun x => motive x x✝
has type
AddMonoidAlgebra' ℕ G → Sort u_1
but is expected to have type
MonoidAlgebra' ℕ G → Sort u_1
in the application
@MonoidAlgebra'.casesOn ℕ G fun x => motive x x✝
-/
#guard_msgs in
@[to_additive]
instance : Mul (MonoidAlgebra' Nat G) where
mul | ⟨a⟩, ⟨b⟩ => ⟨fun i => a i * b 1⟩ |
.lake/packages/mathlib/MathlibTest/algebraize.lean | import Mathlib.Tactic.Algebraize
set_option linter.unusedVariables false
section example_definitions
/-- Test property for when `RingHom` and `Algebra` properties are definitionally the same,
see e.g. `RingHom.FiniteType` for a concrete example of this. -/
class Algebra.TestProperty1 (A B : Type*) [CommRing A] [CommRing B] [Algebra A B] : Prop where
out : ∀ x : A, algebraMap A B x = 0
/-- Test property for when `RingHom` and `Algebra` properties are definitionally the same,
see e.g. `RingHom.FiniteType` for a concrete example of this. -/
@[algebraize]
def RingHom.TestProperty1 {A B : Type*} [CommRing A] [CommRing B] (f : A →+* B) : Prop :=
@Algebra.TestProperty1 A B _ _ f.toAlgebra
/-- Test property for when the `RingHom` property corresponds to a `Module` property (that is
definitionally the same). See e.g. `Module.Finite` for a concrete example of this. -/
class Module.TestProperty2 (A M : Type*) [Semiring A] [AddCommMonoid M] [Module A M] : Prop where
out : ∀ x : A, ∀ M : M, x • M = 0
/-- Test property for when the `RingHom` property corresponds to a `Module` property (that is
definitionally the same). See e.g. `Module.Finite` for a concrete example of this. -/
@[algebraize Module.TestProperty2]
def RingHom.TestProperty2 {A B : Type*} [CommRing A] [CommRing B] (f : A →+* B) : Prop :=
letI : Algebra A B := f.toAlgebra
Module.TestProperty2 A B
/-- Test property for when the `RingHom` property corresponds to a `Algebra` property that is not
definitionally the same, and needs to be created through a lemma. See e.g. `Algebra.IsIntegral` for
an example. -/
class Algebra.TestProperty3 (A B : Type*) [CommRing A] [CommRing B] [Algebra A B] : Prop where
out : Algebra.TestProperty1 A B
/- Test property for when the `RingHom` property corresponds to a `Algebra` property that is not
definitionally the same, and needs to be created through a lemma. See e.g. `Algebra.IsIntegral` for
an example. -/
@[algebraize Algebra.TestProperty3.mk]
def RingHom.TestProperty3 {A B : Type*} [CommRing A] [CommRing B] (f : A →+* B) : Prop :=
f.TestProperty1
/- Test property for when the `RingHom` (and `Algebra`) property have an extra explicit argument,
and hence needs to be created through a lemma. See e.g.
`Algebra.IsStandardSmoothOfRelativeDimension` for an example. -/
class Algebra.TestProperty4 (n : ℕ) (A B : Type*) [CommRing A] [CommRing B] [Algebra A B] : Prop where
out : ∀ m, n = m
/- Test property for when the `RingHom` (and `Algebra`) property have an extra explicit argument,
and hence needs to be created through a lemma. See e.g.
`Algebra.IsStandardSmoothOfRelativeDimension` for an example. -/
@[algebraize RingHom.TestProperty4.toAlgebra]
def RingHom.TestProperty4 (n : ℕ) {A B : Type*} [CommRing A] [CommRing B] (_ : A →+* B) : Prop :=
∀ m, n = m
/--
warning: Hypothesis hf has type
RingHom.TestProperty4 n f.
Its head symbol RingHom.TestProperty4 is (effectively) tagged with `@[algebraize RingHom.TestProperty4.toAlgebra]`, but no constant
RingHom.TestProperty4.toAlgebra
has been found.
Check for missing imports, missing namespaces or typos.
-/
#guard_msgs (warning) in
example (n : ℕ) {A B : Type*} [CommRing A] [CommRing B] (f : A →+* B) (hf : f.TestProperty4 n) :
True := by
algebraize [f]
trivial
lemma RingHom.TestProperty4.toAlgebra (n : ℕ) {A B : Type*} [CommRing A] [CommRing B] (f : A →+* B)
(hf : f.TestProperty4 n) :
letI : Algebra A B := f.toAlgebra
Algebra.TestProperty4 n A B :=
letI : Algebra A B := f.toAlgebra
{ out := hf }
/-- Test property for when the `RingHom` property corresponds to a `Module` property
using `RingHom.toModule`. (Compare to property 2, which uses `RingHom.toAlgebra.toModule`.) -/
class Module.TestProperty5 (A M : Type*) [Semiring A] [AddCommMonoid M] [Module A M] : Prop where
out : ∀ x : A, ∀ M : M, x • M = 0
/-- Test property for when the `RingHom` property corresponds to a `Module` property
using `RingHom.toModule`. (Compare to property 2, which uses `RingHom.toAlgebra.toModule`.) -/
@[algebraize Module.TestProperty5]
def RingHom.TestProperty5 {A B : Type*} [CommRing A] [CommRing B] (f : A →+* B) : Prop :=
@Module.TestProperty5 A B _ _ f.toModule
end example_definitions
set_option tactic.hygienic false
/-- Synthesize algebra instance from ring hom. -/
example (A B : Type*) [CommRing A] [CommRing B] (f : A →+* B) : True := by
fail_if_success -- Check that this instance is not available by default
have h : Algebra A B := inferInstance
algebraize [f]
guard_hyp algInst := f.toAlgebra
trivial
/-- Synthesize algebra instance from ring hom defined using a `let` statement. -/
example (A B : Type*) [CommRing A] [CommRing B] (f : A →+* B) : True := by
let f' : A →+* B := f
fail_if_success -- Check that this instance is not available by default
have h : Algebra A B := inferInstance
algebraize [f']
guard_hyp algInst :=ₛ f'.toAlgebra
trivial
/-- Synthesize algebra instance from a composition -/
example (A B C : Type*) [CommRing A] [CommRing B] [CommRing C] (f : A →+* B) (g : B →+* C) :
True := by
fail_if_success -- Check that this instance is not available by default
have h : Algebra A C := inferInstance
algebraize [g.comp f]
guard_hyp algInst := (g.comp f).toAlgebra
trivial
/-- Synthesize algebra instance and scalar tower instance from a composition -/
example (A B C : Type*) [CommRing A] [CommRing B] [CommRing C] (f : A →+* B) (g : B →+* C) :
True := by
fail_if_success -- Check that this instance is not available by default
have h : IsScalarTower A B C := inferInstance
algebraize [f, g, g.comp f]
guard_hyp scalarTowerInst := IsScalarTower.of_algebraMap_eq' rfl
trivial
example (A B : Type*) [CommRing A] [CommRing B] (f g : A →+* B) (hf : f.TestProperty1)
(hg : g.TestProperty1) : True := by
algebraize [f]
guard_hyp algebraizeInst : @Algebra.TestProperty1 A B _ _ f.toAlgebra
fail_if_success
guard_hyp algebraizeInst_1
trivial
example (A B : Type*) [CommRing A] [CommRing B] (f g : A →+* B) (hf : f.TestProperty2)
(hg : g.TestProperty2) : True := by
algebraize [f]
guard_hyp algebraizeInst : @Module.TestProperty2 A B _ _ f.toAlgebra.toModule
fail_if_success
guard_hyp algebraizeInst_1
trivial
example (A B : Type*) [CommRing A] [CommRing B] (f g : A →+* B) (hf : f.TestProperty3)
(hg : g.TestProperty3) : True := by
algebraize [f]
guard_hyp algebraizeInst : @Algebra.TestProperty3 A B _ _ f.toAlgebra
fail_if_success
guard_hyp algebraizeInst_1
trivial
/- make sure the tactic is able to see through assigned metavariables -/
example (A B : Type*) [CommRing A] [CommRing B] (f : A →+* B) : f.TestProperty3 → True := by
refine @id (?P → True) ?h
intro hf -- the type of this variable is `?P := f.TestProperty3`, rather than just `f.TestProperty3`
algebraize [f]
guard_hyp algebraizeInst : @Algebra.TestProperty3 A B _ _ f.toAlgebra
trivial
/- make sure the tactic is able to see through assigned metavariables -/
example (A B : Type*) [CommRing A] [CommRing B] (f : A →+* B) : f.TestProperty3 ↔ (@Algebra.TestProperty3 A B _ _ f.toAlgebra) := by
constructor
· intro hf -- the type of this variable is `?P := f.TestProperty3`, rather than just `f.TestProperty3`
algebraize [f]
guard_hyp algebraizeInst : @Algebra.TestProperty3 A B _ _ f.toAlgebra
exact algebraizeInst
· exact fun x => x.out
example (n m : ℕ) (A B : Type*) [CommRing A] [CommRing B] (f g : A →+* B) (hf : f.TestProperty4 n)
(hg : g.TestProperty4 m) : True := by
algebraize [f]
guard_hyp algebraizeInst : Algebra.TestProperty4 n A B
fail_if_success
guard_hyp algebraizeInst_1
trivial
example (A B : Type*) [CommRing A] [CommRing B] (f g : A →+* B) (hf : f.TestProperty5)
(hg : g.TestProperty5) : True := by
algebraize [f]
guard_hyp algebraizeInst : @Module.TestProperty5 A B _ _ f.toModule
fail_if_success
guard_hyp algebraizeInst_1
trivial
/-- Synthesize from morphism property of a composition (and check that tower is also synthesized). -/
example (A B C : Type*) [CommRing A] [CommRing B] [CommRing C] (f : A →+* B) (g : B →+* C)
(hfg : (g.comp f).TestProperty1) : True := by
fail_if_success -- Check that this instance is not available by default
have h : Algebra.Flat A C := inferInstance
fail_if_success
have h : IsScalarTower A B C := inferInstance
algebraize [f, g, g.comp f]
guard_hyp algebraizeInst : Algebra.TestProperty1 A C
guard_hyp scalarTowerInst := IsScalarTower.of_algebraMap_eq' rfl
trivial
section
/- Test that the algebraize tactic also works on non-RingHom types -/
structure Bar (A B : Type*) [CommRing A] [CommRing B] where
f : A →+* B
@[algebraize testProperty1_of_bar]
def Bar.TestProperty1 {A B : Type*} [CommRing A] [CommRing B] (b : Bar A B) : Prop :=
∀ z, b.f z = 0
lemma testProperty1_of_bar {A B : Type*} [CommRing A] [CommRing B] (b : Bar A B) (h : b.TestProperty1) :
@Algebra.TestProperty1 A B _ _ b.f.toAlgebra := @Algebra.TestProperty1.mk A B _ _ b.f.toAlgebra h
@[algebraize testProperty2_of_bar]
def Bar.testProperty2 {A B : Type*} [CommRing A] [CommRing B] (b : Bar A B) : Prop :=
letI : Algebra A B := b.f.toAlgebra;
∀ (r : A) (M : B), r • M = 0
lemma testProperty2_of_bar {A B : Type*} [CommRing A] [CommRing B] (b : Bar A B) (h : b.testProperty2) :
@Module.TestProperty2 A B _ _ b.f.toAlgebra.toModule :=
@Module.TestProperty2.mk A B _ _ b.f.toAlgebra.toModule h
example {A B : Type*} [CommRing A] [CommRing B] (b c : Bar A B) (hb : b.TestProperty1)
(hc : c.TestProperty1) : True := by
algebraize [b.f]
guard_hyp algebraizeInst : @Algebra.TestProperty1 A B _ _ b.f.toAlgebra
fail_if_success -- make sure that only arguments are used
guard_hyp algebraizeInst_1 : @Algebra.testProperty1 A B _ _ c.f.toAlgebra
trivial
example {A B : Type*} [CommRing A] [CommRing B] (b c : Bar A B) (hb : b.testProperty2)
(hc : c.testProperty2) : True := by
algebraize [b.f]
guard_hyp algebraizeInst : @Module.TestProperty2 A B _ _ b.f.toAlgebra.toModule
fail_if_success
guard_hyp algebraizeInst_1 --: @Module.testProperty2 A B _ _ c.f.toAlgebra.toModule
trivial
structure Buz (A B : Type*) [CommRing A] [CommRing B] where
x : (A →+* B) ⊕ (A →+* B)
@[algebraize testProperty1_of_buz_inl]
def Buz.TestProperty1 {A B : Type*} [CommRing A] [CommRing B] (b : Buz A B) :=
b.x.elim (@Algebra.TestProperty1 A B _ _ ·.toAlgebra) (fun _ => False)
lemma testProperty1_of_buz_inl {A B : Type*} [CommRing A] [CommRing B] (f : A →+* B) :
Buz.TestProperty1 ⟨.inl f⟩ → @Algebra.TestProperty1 A B _ _ f.toAlgebra := id
-- check that this also works when the argument *contains* a ringhom
example {A B : Type*} [CommRing A] [CommRing B] (f g : A →+* B)
(hf : Buz.TestProperty1 ⟨.inl f⟩) (hg : Buz.TestProperty1 ⟨.inl g⟩) : True := by
algebraize [f]
guard_hyp algebraizeInst : @Algebra.TestProperty1 A B _ _ f.toAlgebra
fail_if_success
guard_hyp algebraizeInst_1 --: @Algebra.testProperty1 A B _ _ g.toAlgebra
trivial
-- check that there is no issue with trying the lemma on a mismatching argument.
example {A B : Type*} [CommRing A] [CommRing B] (f : A →+* B)
(hf : Buz.TestProperty1 ⟨.inr f⟩) : True := by
algebraize [f] -- this could error if it tried applying `testProperty1_ofBuz_inl` to `hf`
fail_if_success
guard_hyp algebraizeInst
trivial
end |
.lake/packages/mathlib/MathlibTest/delabLinearIndependent.lean | import Mathlib.LinearAlgebra.LinearIndependent.Defs
set_option linter.style.setOption false
set_option pp.unicode.fun true
set_option linter.style.commandStart false
variable {K V : Type*} [DivisionRing K] [AddCommGroup V] [Module K V] {s : Set V} {x : V}
variable (h : LinearIndependent K (fun b => b : s → V)) in
/-- info: h : LinearIndependent K fun (b : ↑s) ↦ ↑b -/
#guard_msgs in #check h
variable (h : LinearIndependent K (Subtype.val : s → V)) in
/-- info: h : LinearIndependent K Subtype.val -/
#guard_msgs in #check h
variable (h : LinearIndependent K (by exact Subtype.val : s → V)) in
/-- info: h : LinearIndependent (ι := ↑s) K Subtype.val -/
#guard_msgs in #check h
variable (h : LinearIndependent K (fun b => (fun b => b : s → V) b)) in
/-- info: h : LinearIndependent K fun (b : ↑s) ↦ (fun b ↦ ↑b) b -/
#guard_msgs in #check h |
.lake/packages/mathlib/MathlibTest/basicTactics.lean | import Mathlib.Tactic.Basic
import Batteries.Tactic.Init
example : ∀ a b : Nat, a = b → b = a := by
introv h
exact h.symm
set_option linter.unusedTactic false in
example (n : Nat) : n = n := by
induction n
exacts [rfl, rfl]
exacts []
set_option linter.unusedVariables false in
example (n : Nat) : Nat := by
guard_hyp n : Nat
let m : Nat := 1
guard_hyp m := 1
guard_hyp m : Nat := 1
guard_target = Nat
exact 0
example (a b : Nat) : a ≠ b → ¬ a = b := by
intros
by_contra H
contradiction
example (a b : Nat) : ¬¬ a = b → a = b := by
intros
by_contra H
contradiction
example (p _q : Prop) : ¬¬ p → p := by
intros
by_contra H
contradiction
-- Test `iterate n ...`
example (n m : Nat) : Unit := by
cases n
cases m
iterate 3 exact ()
-- Test `iterate ...`, which should repeat until failure.
example (n m : Nat) : Unit := by
cases n
cases m
iterate exact ()
set_option linter.unusedTactic false in
example (n : Nat) : Nat := by
iterate exact () -- silently succeeds, after iterating 0 times
iterate exact n
example (p q r s : Prop) : p → q → r → s → (p ∧ q) ∧ (r ∧ s ∧ p) ∧ (p ∧ r ∧ q) := by
intros
repeat' constructor
repeat' assumption
example (p q : Prop) : p → q → (p ∧ q) ∧ (p ∧ q ∧ p) := by
intros
constructor
fail_if_success any_goals assumption
all_goals constructor
any_goals assumption
constructor
any_goals assumption |
.lake/packages/mathlib/MathlibTest/Check.lean | import Mathlib.Tactic.Check
/- Override metavariable delaborator for natural metavariables to print `?m` instead
of including a unique number, for `#guard_msgs`. -/
open Lean PrettyPrinter Delaborator in @[delab mvar] def delabMVar : Delab := do
let kind ← (← SubExpr.getExpr).mvarId!.getKind
unless kind.isNatural do failure
`(?m)
set_option linter.unusedTactic false
set_option linter.unusedVariables false
/-!
Basic check of `#check`
-/
/-- info: x + y : Nat -/
#guard_msgs in
example (x y : Nat) : True := by
#check x + y
trivial
/-!
`#check` is ok with metavariables
and `have := e` is not a substitute for `#check`
-/
/-- info: x + ?m✝ : Nat -/
#guard_msgs in
example (x : Nat) : True := by
#check x + _
trivial
/--
error: don't know how to synthesize placeholder
context:
x : Nat
⊢ Nat
---
error: unsolved goals
x : Nat
⊢ True
-/
#guard_msgs in
example (x : Nat) : True := by
have := x + _
/-!
`#check` cannot be used to accidentally assign metavariables, since it saves the state.
This is in contrasted against `have`.
-/
/--
info: rfl : x = x
---
error: unsolved goals
x : Nat
y : Nat := ?a
⊢ True
case a
x : Nat
⊢ Nat
---
trace: x : Nat
y : Nat := ?a
⊢ True
case a
x : Nat
⊢ Nat
-/
#guard_msgs in
example (x : Nat) : True := by
let y : Nat := ?a
#check (by refine rfl : ?a = x)
trace_state
/--
error: unsolved goals
x : Nat
y : Nat := x
this : x = x
⊢ True
---
trace: x : Nat
y : Nat := x
this : x = x
⊢ True
-/
#guard_msgs in
example (x : Nat) : True := by
let y : Nat := ?a
have := (by refine rfl : ?a = x)
trace_state |
.lake/packages/mathlib/MathlibTest/norm_cast.lean | /-
Tests for norm_cast
-/
import Mathlib.Tactic.Ring
import Mathlib.Data.Complex.Basic
import Mathlib.Data.ENNReal.Inv
-- set_option trace.Tactic.norm_cast true
-- set_option trace.Meta.Tactic.simp true
set_option autoImplicit true
set_option linter.unusedVariables false
variable (an bn cn dn : ℕ) (az bz cz dz : ℤ)
variable (aq bq cq dq : ℚ)
variable (ar br cr dr : ℝ) (ac bc cc dc : ℂ)
example : (an : ℤ) = bn → an = bn := by intro h; exact mod_cast h
example : an = bn → (an : ℤ) = bn := by intro h; exact mod_cast h
example : az = bz ↔ (az : ℚ) = bz := by norm_cast
example : (aq : ℝ) = br ↔ (aq : ℂ) = br := by norm_cast
example : (an : ℚ) = bz ↔ (an : ℂ) = bz := by norm_cast
example : (((an : ℤ) : ℚ) : ℝ) = bq ↔ ((an : ℚ) : ℂ) = (bq : ℝ) := by norm_cast
example : (an : ℤ) < bn ↔ an < bn := by norm_cast
example : (an : ℚ) < bz ↔ (an : ℝ) < bz := by norm_cast
example : ((an : ℤ) : ℝ) < bq ↔ (an : ℚ) < bq := by norm_cast
example : (an : ℤ) ≠ (bn : ℤ) ↔ an ≠ bn := by norm_cast
-- zero and one cause special problems
example : 0 < (bq : ℝ) ↔ 0 < bq := by norm_cast
example : az > (1 : ℕ) ↔ az > 1 := by norm_cast
example : az > (0 : ℕ) ↔ az > 0 := by norm_cast
example : (an : ℤ) ≠ 0 ↔ an ≠ 0 := by norm_cast
example : aq < (1 : ℕ) ↔ (aq : ℚ) < (1 : ℤ) := by norm_cast
example : aq < (1 : ℕ) ↔ (aq : ℝ) < (1 : ℤ) := by norm_cast
example : (an : ℤ) + bn = (an + bn : ℕ) := by norm_cast
example : (an : ℂ) + bq = ((an + bq) : ℚ) := by norm_cast
example : (((an : ℤ) : ℚ) : ℝ) + bn = (an + (bn : ℤ)) := by norm_cast
example (h : ((an + bn : ℕ) : ℤ) = (an : ℤ) + (bn : ℤ)) : True := by
push_cast at h
guard_hyp h : (an : ℤ) + (bn : ℤ) = (an : ℤ) + (bn : ℤ)
trivial
example (h : ((an * bn : ℕ) : ℤ) = (an : ℤ) * (bn : ℤ)) : True := by
push_cast at h
guard_hyp h : (an : ℤ) * (bn : ℤ) = (an : ℤ) * (bn : ℤ)
trivial
example : (((((an : ℚ) : ℝ) * bq) + (cq : ℝ) ^ dn) : ℂ) = (an : ℂ) * (bq : ℝ) + cq ^ dn := by
norm_cast
example : ((an : ℤ) : ℝ) < bq ∧ (cr : ℂ) ^ 2 = dz ↔ (an : ℚ) < bq ∧ ((cr ^ 2) : ℂ) = dz := by
norm_cast
--testing numerals
example : ((42 : ℕ) : ℤ) = 42 := by norm_cast
example : ((42 : ℕ) : ℂ) = 42 := by norm_cast
example : ((42 : ℤ) : ℚ) = 42 := by norm_cast
example : ((42 : ℚ) : ℝ) = 42 := by norm_cast
structure p (n : ℤ)
example : p 42 := by
norm_cast
guard_target = p 42
exact ⟨⟩
example (h : (an : ℝ) = 0) : an = 0 := mod_cast h
example (h : (an : ℝ) = 42) : an = 42 := mod_cast h
example (h : (an + 42) ≠ 42) : (an : ℝ) + 42 ≠ 42 := mod_cast h
example (n : ℤ) (h : n + 1 > 0) : ((n + 1 : ℤ) : ℚ) > 0 := mod_cast h
-- testing the heuristic
example (h : bn ≤ an) : an - bn = 1 ↔ (an - bn : ℤ) = 1 := by norm_cast
example (h : (cz : ℚ) = az / bz) : (cz : ℝ) = az / bz := by assumption_mod_cast
namespace hidden
def WithZero (α) := Option α
@[coe]
def WithZero.of (a : α) : WithZero α := some a
instance : CoeTail α (WithZero α) := ⟨WithZero.of⟩
instance : Zero (WithZero α) := ⟨none⟩
instance [One α] : One (WithZero α) := ⟨some 1⟩
instance [Mul α] : MulZeroClass (WithZero α) where
mul o₁ o₂ := o₁.bind fun a => o₂.map fun b => a * b
zero_mul a := rfl
mul_zero a := by cases a <;> rfl
@[norm_cast] lemma coe_one [One α] : ((1 : α) : WithZero α) = 1 := rfl
@[norm_cast] lemma coe_inj {a b : α} : (a : WithZero α) = b ↔ a = b :=
Option.some_inj
@[norm_cast] lemma mul_coe [Mul α] (a b : α) :
((a * b : α) : WithZero α) = (a : WithZero α) * b := rfl
example [Mul α] [One α] (x y : α) (h : (x : WithZero α) * y = 1) : x * y = 1 := mod_cast h
end hidden
example (k : ℕ) {x y : ℕ} :
(x * x + y * y : ℤ) - ↑((x * y + 1) * k) = ↑y * ↑y - ↑k * ↑x * ↑y + (↑x * ↑x - ↑k) := by
push_cast
ring
example (k : ℕ) {x y : ℕ} (h : ((x + y + k : ℕ) : ℤ) = 0) : x + y + k = 0 := by
push_cast at h
guard_hyp h : (x : ℤ) + y + k = 0
assumption_mod_cast
example (a b : ℕ) (h2 : ((a + b + 0 : ℕ) : ℤ) = 10) :
((a + b : ℕ) : ℤ) = 10 := by
push_cast
push_cast [Int.add_zero] at h2
exact h2
-- example {x : ℚ} : ((x + 42 : ℚ) : ℝ) = x + 42 := by push_cast
namespace ENNReal
lemma half_lt_self_bis {a : ℝ≥0∞} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a := by
lift a to NNReal using ht
have h : (2 : ℝ≥0∞) = ((2 : NNReal) : ℝ≥0∞) := rfl
have h' : (2 : NNReal) ≠ 0 := two_ne_zero
rw [h, ← coe_div h', coe_lt_coe] -- `norm_cast` fails to apply `coe_div`
norm_cast at hz
exact NNReal.half_lt_self hz
end ENNReal
lemma b (_h g : true) : true ∧ true := by
constructor
assumption_mod_cast
assumption_mod_cast |
.lake/packages/mathlib/MathlibTest/ExtractGoal.lean | import Mathlib.Tactic.ExtractGoal
import Mathlib.Order.Basic
import Mathlib.Data.Nat.Basic
set_option linter.style.setOption false
set_option pp.unicode.fun true
set_option autoImplicit true
set_option linter.unusedVariables false
-- the example in the documentation for the tactic.
/-- info: theorem _example.extracted_1 (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := sorry -/
#guard_msgs (info) in
example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := by
extract_goal
exact h₀.trans h₁
/-- info: theorem _example.extracted_1 (i j k : ℕ) (h₁ : j ≤ k) : i ≤ k := sorry -/
#guard_msgs (info) in
example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := by
extract_goal h₁
exact h₀.trans h₁
-- an example with all binder types
/--
info: theorem _example.extracted_1.{v, u} {α : Type u} {β : Type v} [h : Sub β] (f : α → β) (a : α) {b : β} :
f a - b = f a - b := sorry
-/
#guard_msgs in
example {α : Type u} {β : Type v} [Add α] [h : Sub β] (f : α → β) ⦃_g : ℤ⦄ (a : α) {b : β} :
f a - b = f a - b := by
extract_goal
rfl
-- an example with a hygienic variable
/-- info: theorem _example.extracted_1 (n : ℕ) : n + 1 = n + 1 := sorry -/
#guard_msgs in
example (n : ℕ) : n = n := by
cases n
rfl
extract_goal
rfl
-- an example with auto-implicit `Sort` and variable
/-- info: theorem _example.extracted_1.{u_1} {α : Sort u_1} {n : α} : n = n := sorry -/
#guard_msgs in
example : n = n := by
extract_goal
rfl
/--
info: theorem _example.extracted_1 {z : Int} :
@Exists.{1} Nat fun (n : Nat) ↦ @Eq.{1} Int (@Nat.cast.{0} Int instNatCastInt n) z := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example {z : Int} : ∃ n : Nat, ↑n = z := by
set_option pp.all true in
extract_goal
sorry
/--
info: theorem foo : True := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example (n : ℕ) : True := by
extract_goal using foo
sorry
/--
info: theorem foo (n : ℕ) : True := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example (n : ℕ) : True := by
extract_goal n using foo
sorry
/-- error: Unknown identifier `k` -/
#guard_msgs in
example (n : ℕ) : True := by
extract_goal k
/--
info: theorem _example.extracted_1 (n : ℕ) : True := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example (n : ℕ) : True := by
extract_goal *
sorry
-- Clears `i` since neither `n` nor the goal depends on it.
/--
info: theorem _example.extracted_1 (n : ℕ) : True := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example (n : ℕ) (i : Fin n) : True := by
extract_goal n
sorry
/--
info: theorem _example.extracted_1 (n : ℕ) (i : Fin n) : True := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example (n : ℕ) (i : Fin n) : True := by
extract_goal i
sorry
-- Contradiction proof gives full context:
/--
info: theorem _example.extracted_1 (h : 1 = 2) : False := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example (h : 1 = 2) : False := by
extract_goal
sorry
-- Check mdata is cleared:
/--
info: theorem _example.extracted_1 (h : 1 = 2) : False := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example : False := by
have h : 1 = 2 := sorry
extract_goal
sorry
-- Check that fvar elaboration is with respect to the main local context
/--
info: theorem _example.extracted_1 (h : 1 = 2) : False := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example : 1 = 2 → False := by
intro h
extract_goal h
sorry
-- Check that sets local context correctly
/--
info: theorem _example.extracted_1 (m : ℕ) : m < m + 1 := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example : ∀ n, n < n + 1 := by
intro m
extract_goal
sorry
-- Throwing metavariables into the terms
/--
info: theorem _example.extracted_1 (m : ℕ) (this : m < m.succ.succ) : m < m + 1 := sorry
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example : ∀ n, n < n + 1 := by
intro m
show _
have : m < _ := Nat.lt.step (Nat.lt.base m)
extract_goal
sorry |
.lake/packages/mathlib/MathlibTest/FunLike.lean | import Mathlib.Data.FunLike.Basic
variable {F α β : Sort*} [i : FunLike F α β] (f : F) (a : α)
/-- info: f a : β -/
#guard_msgs in #check f a |
.lake/packages/mathlib/MathlibTest/Clear_.lean | import Mathlib.Tactic.Clear_
import Mathlib.Tactic.Replace
set_option linter.unusedTactic false
-- Most basic test
example (_delete_this : Nat) : Nat := by
clear_
fail_if_success assumption
exact 0
-- Confirms that clear_ does not delete class instances
example [_dont_delete_this : Inhabited Nat] : Inhabited Nat := by
clear_
assumption
-- Confirms that clear_ clears _delete_this but not dont_delete_this
example (_delete_this : Nat) (dont_delete_this : Int) : Nat := by
clear_
fail_if_success assumption
exact dont_delete_this.toNat
-- Confirms that clear_ can clear hypotheses even when they have dependencies
example (_delete_this : Type) (_delete_this_dep : _delete_this)
(_delete_this_rw : _delete_this = Nat)
(_delete_this_dep_dep : _delete_this_dep = _delete_this_dep) : Nat := by
clear_
fail_if_success
rw [← _delete_this_rw]
exact 0
-- Confirms that clear_ does not clear hypotheses
-- when they have dependencies that should not be cleared
example (_dont_delete_this : Type) (dep : _dont_delete_this) : _dont_delete_this := by
clear_
assumption
-- Confirms that clear_ does not break the goal
example (_dont_delete_this : Type) : _dont_delete_this = _dont_delete_this := by
clear_
rfl
-- Confirms that clear_ clears all that it can even if some underscored hypotheses cannot be cleared
example (_dont_delete_this : Type) (_delete_this : _dont_delete_this = _dont_delete_this) :
_dont_delete_this = _dont_delete_this := by
clear_
fail_if_success assumption
rfl |
.lake/packages/mathlib/MathlibTest/observe.lean | import Mathlib.Data.Nat.Prime.Factorial
import Mathlib.Data.Nat.Factorial.Basic
open Nat
set_option maxHeartbeats 7000 in
theorem euclid (n : ℕ) : ∃ N, n < N ∧ N.Prime := by
let N := n.factorial + 1
let p := minFac N
use p
have prime : p.Prime := by
apply minFac_prime
observe : n.factorial > 0
omega
constructor
· by_contra!
observe : p ∣ n.factorial
observe : p ∣ N
observe : p ∣ 1
observe : ¬ p ∣ 1
contradiction
· exact prime |
.lake/packages/mathlib/MathlibTest/fin_cases.lean | import Mathlib.Tactic.FinCases
import Mathlib.Tactic.NormNum.Basic
import Mathlib.Order.Interval.Finset.Nat
example {x : Nat} (h : x ∈ [0, 2, 37]) : x ≤ 57 := by
fin_cases h
repeat decide
example {x : Nat} (h : x ∈ [0, 2, 37]) : x = 0 ∨ x = 2 ∨ x = 37 := by
fin_cases h
repeat simp
example {x : Nat} (h : x ∈ List.range 5) : x ≤ 4 := by
fin_cases h
repeat decide
example {p : Fin 4 → Prop} (i : Fin 4) (h : p i) : p i := by
fin_cases i
repeat exact h
example (f : Nat → Prop) (p : Fin 3) (h0 : f 0) (h1 : f 1) (h2 : f 2) : f p.val := by
fin_cases p
all_goals
assumption
example (f : Nat → Prop) (p : Fin 0) : f p.val := by
fin_cases p
example (x2 : Fin 2) (x3 : Fin 3) : True := by
fin_cases x2, x3
all_goals trivial
-- Checking that `fin_cases` can handle a metavariable for the type
example (p : ℕ) (h2 : 2 < p) (h5 : p < 5) : p = 3 ∨ p = 4 := by
have hp : ?_ := ?foo
case foo => exact (Finset.mem_Ioo).2 ⟨h2, h5⟩
fin_cases hp
· norm_num
· norm_num
-- Check naming of cases
/--
trace: case «0».«0»
⊢ True
case «0».«1»
⊢ True
case «1».«0»
⊢ True
case «1».«1»
⊢ True
-/
#guard_msgs in
example (x y : Fin 2): True := by
fin_cases x, y
trace_state
all_goals trivial
-- TODO Restore the remaining tests from mathlib3:
-- Some of these test the `with` and `using` clauses which haven't been re-implemented.
set_option linter.unusedVariables false in
example (x2 : Fin 2) (x3 : Fin 3) (n : Nat) (y : Fin n) : x2.val * x3.val = x3.val * x2.val := by
fin_cases x2 <;> fin_cases x3
fail_if_success
fin_cases y
all_goals rfl
-- example (x : ℕ) (h : x ∈ [2,3,5,7]) : True := by
-- fail_if_success
-- fin_cases h with [3,3,5,7]
-- trivial
-- example (x : List Nat) (h : x ∈ [[1],[2]]) : x.length = 1 := by
-- fin_cases h with [[1],[1+1]]
-- · simp
-- · guard_target = [1 + 1].length = 1
-- simp
-- -- testing that `with` arguments are elaborated with respect to the expected type:
-- example (x : Int) (h : x ∈ ([2,3] : List Int)) : x = 2 ∨ x = 3 := by
-- fin_cases h with [2,3]
-- all_goals simp
-- example (n : ℕ) (h : n % 3 ∈ [0,1]) : True := by
-- fin_cases h
-- · guard_hyp h : n % 3 = 0
-- trivial
-- · guard_hyp h : n % 3 = 1
-- trivial
-- instance (n : ℕ) : Decidable (Nat.Prime n) := decidablePrime_1 n
-- example (x : ℕ) (h : x ∈ (List.range 10).filter Nat.prime) : x = 2 ∨ x = 3 ∨ x = 5 ∨ x = 7 := by
-- fin_cases h <;> decide
-- open Equiv.Perm
-- example (x : (Σ (a : Fin 4), Fin 4)) (h : x ∈ finPairsLT 4) : x.1.val < 4 := by
-- fin_cases h; simp
-- any_goals exact dec_trivial
-- /-
-- In some circumstances involving `let`,
-- the temporary hypothesis that `fin_cases` creates does not get deleted.
-- We test that this is correctly named and that the name can be changed.
-- Note: after `fin_cases`, we have `this : (a : Fin 3) = (0 : Fin (2 + 1))`
-- for some reason. I don't know why, and it complicates the test.
-- -/
-- example (f : ℕ → Fin 3) : true := by
-- let a := f 3
-- fin_cases a
-- guard_hyp a := f 3
-- guard_hyp this : a = (0 : Fin (2 + 1))
-- trivial; trivial
-- let b := f 2
-- fin_cases b using what
-- guard_hyp what : b = (0 : Fin (2 + 1))
-- all_goals trivial
-- /-
-- The behavior above can be worked around with `fin_cases with`.
-- -/
-- example (f : ℕ → Fin 3) : true := by
-- let a := f 3
-- fin_cases a with [0, 1, 2]
-- guard_hyp a := f 3
-- guard_hyp this : a = 0
-- trivial
-- guard_hyp this : a = 1
-- trivial
-- guard_hyp this : a = 2
-- let b := f 2
-- fin_cases b with [0, 1, 2] using what
-- guard_hyp what : b = 0
-- all_goals trivial |
.lake/packages/mathlib/MathlibTest/Replace.lean | import Mathlib.Tactic.Replace
set_option linter.unusedVariables false
private axiom test_sorry : ∀ {α}, α
/-- Test the `:=` syntax works -/
example {A B : Type} (h : A) (f : A → B) : B := by
replace h := f h
exact h
-- tests without `:=`, creating a new subgoal
example (z : Int) : Nat := by
replace z : Nat
exact 0
assumption
example : True := by
have : 1 + 1 = 2 := by simp +arith
replace : 2 + 2 = 4
simp +arith
trivial
-- Regression test. `replace h` used to close goal and leave metavariables.
-- Note that `replace h` does *not* delete `h` in this case because the type of the new `h`
-- is a metavariable whose context includes the old `h`.
example (h : True) : False := by
guard_hyp h : True
replace h
· exact true
guard_hyp h : Bool
rename_i h'
guard_hyp h' : True
exact test_sorry |
.lake/packages/mathlib/MathlibTest/aesop_cat.lean | import Mathlib.CategoryTheory.Category.Basic
structure Foo where
x : Nat
w : x = 37 := by cat_disch
/-- warning: declaration uses 'sorry' -/
#guard_msgs in
example : Foo where
x := sorry
/--
error: could not synthesize default value for field 'w' of 'Foo' using tactics
---
error: tactic 'aesop' failed, failed to prove the goal after exhaustive search.
Initial goal:
⊢ 35 = 37
Remaining goals after safe rules:
⊢ False
-/
#guard_msgs in
example : Foo where
x := 35 |
.lake/packages/mathlib/MathlibTest/RegularMeasure.lean | import Mathlib.MeasureTheory.Group.Measure
import Mathlib.Topology.Metrizable.Urysohn
/-! Check that typeclass inference knows that a Haar measure on a locally compact second countable
topological group is automatically regular and inner regular. -/
open MeasureTheory Measure
variable {G : Type*} [MeasurableSpace G] [Group G] [TopologicalSpace G]
[IsTopologicalGroup G] [LocallyCompactSpace G] [SecondCountableTopology G] [BorelSpace G]
(μ : Measure G) [IsHaarMeasure μ]
example : Regular μ := inferInstance
example : InnerRegular μ := inferInstance
/- Check that typeclass inference works to guarantee regularity and inner regularity in
interesting situations. -/
variable {α : Type*} [TopologicalSpace α] [MeasurableSpace α] [LocallyCompactSpace α]
[RegularSpace α] [BorelSpace α] [SecondCountableTopology α]
example (μ : Measure α) [IsFiniteMeasureOnCompacts μ] : Regular μ := inferInstance
example (μ : Measure α) [IsFiniteMeasureOnCompacts μ] : InnerRegular μ := inferInstance |
.lake/packages/mathlib/MathlibTest/ModuleCasing.lean | import Mathlib.Tactic.Linter.TextBased
/-!
Unit tests for the module name case check in the text-based linters.
-/
open Lean.Linter Mathlib.Linter.TextBased
/-- Some unit tests for `modulesNotUpperCamelCase` -/
def testModulesNotUpperCamelCase : IO Unit := do
-- Explicitly enable the linter, although it is enabled by default.
let opts : LinterOptions := {
toOptions := linter.modulesUpperCamelCase.set {} true
linterSets := {}
}
assert!((← modulesNotUpperCamelCase opts #[]) == 0)
assert!((← modulesNotUpperCamelCase opts #[`Mathlib.Fine]) == 0)
assert!((← modulesNotUpperCamelCase opts #[`Mathlib.AlsoFine_]) == 0)
assert!((← modulesNotUpperCamelCase opts #[`Mathlib.NotFine_.Foo]) == 1)
assert!((← modulesNotUpperCamelCase opts #[`bad_module]) == 1)
assert!((← modulesNotUpperCamelCase opts #[`GoodName, `bad_module, `bad_module]) == 2)
assert!((← modulesNotUpperCamelCase opts #[`Mathlib.BadModule__]) == 1)
assert!((← modulesNotUpperCamelCase opts #[`Mathlib.lowerCase]) == 1)
assert!((← modulesNotUpperCamelCase opts #[`Mathlib.snake_case]) == 1)
/--
info: error: module name 'Mathlib.NotFine_.Foo' is not in 'UpperCamelCase': it should be 'Mathlib.NotFine.Foo' instead
error: module name 'bad_module' is not in 'UpperCamelCase': it should be 'BadModule' instead
error: module name 'bad_module' is not in 'UpperCamelCase': it should be 'BadModule' instead
error: module name 'bad_module' is not in 'UpperCamelCase': it should be 'BadModule' instead
error: module name 'Mathlib.BadModule__' is not in 'UpperCamelCase': it should be 'Mathlib.BadModule_' instead
error: module name 'Mathlib.lowerCase' is not in 'UpperCamelCase': it should be 'Mathlib.LowerCase' instead
error: module name 'Mathlib.snake_case' is not in 'UpperCamelCase': it should be 'Mathlib.SnakeCase' instead
-/
#guard_msgs in
#eval testModulesNotUpperCamelCase |
.lake/packages/mathlib/MathlibTest/FindSyntax.lean | import Mathlib.Tactic.FindSyntax
infix:65 " #find_syntax_add " => Nat.add
/--
info: Found 2 uses among over 800 syntax declarations
In `MathlibTest.FindSyntax`:
«term_#find_syntax_add_»: '#find_syntax_add'
In `Mathlib.Tactic.FindSyntax`:
Mathlib.FindSyntax.«command#find_syntax_Approx»: '#find_syntax _ approx'
-/
#guard_msgs in
#find_syntax "#find_syntax" approx -- an `infix` in two files, one being the current one
/--
info: Found 1 use among over 800 syntax declarations
In `Init.Notation`:
«term_∘_»: '∘'
-/
#guard_msgs in
#find_syntax "∘" approx -- an `infixr`
/--
info: Found 1 use among over 800 syntax declarations
In `Init.Notation`:
«term_∣_»: '∣'
-/
#guard_msgs in
#find_syntax "∣" approx -- an `infix`
/--
info: Found 2 uses among over 800 syntax declarations
In `Init.Notation`:
«stx_,*»: ',*'
«stx_,*,?»: ',*,?'
-/
#guard_msgs in
#find_syntax ",*" approx -- generated by a `macro`
/--
info: Found 1 use among over 800 syntax declarations
In `Init.Notation`:
«term~~~_»: '~~~'
-/
#guard_msgs in
#find_syntax "~~~" approx -- a `prefix`
/--
info: Found 15 uses among over 800 syntax declarations
In `Init.Tactics`:
Lean.Parser.Tactic.mrefineMacro: 'mrefine'
Lean.Parser.Tactic.refine: 'refine'
Lean.Parser.Tactic.refine': 'refine''
Lean.Parser.Tactic.tacticRefine_lift'_: 'refine_lift''
Lean.Parser.Tactic.tacticRefine_lift_: 'refine_lift'
In `Std.Tactic.Do.Syntax`:
Lean.Parser.Tactic.mrefine: 'mrefine'
Lean.Parser.Tactic.«mrefinePat#_»: '#'
Lean.Parser.Tactic.«mrefinePat%_»: '%'
Lean.Parser.Tactic.«mrefinePat(_)»: '( _ )'
Lean.Parser.Tactic.mrefinePat?_: '?'
Lean.Parser.Tactic.mrefinePats: ','
Lean.Parser.Tactic.«mrefinePat⌜_⌝»: '⌜ _ ⌝'
Lean.Parser.Tactic.«mrefinePat□_»: '□'
Lean.Parser.Tactic.«mrefinePat⟨_⟩»: '⟨ _ ⟩'
Lean.Parser.Tactic.mrefinePat.quot: '`(mrefinePat| _ )'
-/
#guard_msgs in
#find_syntax "refine" approx -- a `nonReservedSymbol` |
.lake/packages/mathlib/MathlibTest/UnusedTactic.lean | import Mathlib.Tactic.Linter.UnusedTactic
import Mathlib.Tactic.AdaptationNote
example (h : 0 + 1 = 0) : False := by
change 1 = 0 at h
simp at h
example : 0 + 1 = 1 := by
change 1 = 1
rfl
/--
warning: 'change 1 = 1' tactic does nothing
Note: This linter can be disabled with `set_option linter.unusedTactic false`
-/
#guard_msgs in
example : 1 = 1 := by
change 1 = 1
rfl
def why2 : True → True := (by refine ·)
example : True := by
#adaptation_note /-- hi -/
exact .intro
-- both `;` and `<;>` are unseen by the linter
example : True ∧ True := by
constructor <;> trivial;
set_option linter.unusedTactic true
/--
warning: 'congr' tactic does nothing
Note: This linter can be disabled with `set_option linter.unusedTactic false`
---
warning: 'done' tactic does nothing
Note: This linter can be disabled with `set_option linter.unusedTactic false`
-/
#guard_msgs in
-- the linter notices that `congr` is unused
example : True := by
congr
constructor
done
section allowing_more_unused_tactics
/-- info: The `SyntaxNodeKind` is 'Lean.Parser.Tactic.refine'. -/
#guard_msgs in
#show_kind refine _
/-- info: The `SyntaxNodeKind` is 'Lean.Parser.Tactic.skip'. -/
#guard_msgs in
#show_kind skip
/--
error: Unknown constant `skip`
The command `#show_kind skip` may help to find the correct `SyntaxNodeKind`.
-/
#guard_msgs in
#allow_unused_tactic rfl skip
-- test that allowing more unused tactics has the desired effect of silencing the linter
#allow_unused_tactic Lean.Parser.Tactic.done Lean.Parser.Tactic.skip
#guard_msgs in
example : True := by
skip
constructor
done
end allowing_more_unused_tactics |
.lake/packages/mathlib/MathlibTest/tactic_timeout.lean | import Mathlib.Tactic.Linarith
/-!
# Test that tactics respond to a cancellation request
-/
variable {α}
open Lean Elab Tactic
/-! versions of try/catch that catch `interrupted` too -/
section catch_interrupted
attribute [-instance]
Lean.instMonadExceptOfExceptionCoreM Lean.Elab.Tactic.instMonadExceptExceptionTacticM
def Meta.tryCatchAll (m : MetaM α) (h : Exception → MetaM α) : MetaM α := tryCatch m h
def Term.tryCatchAll (m : TermElabM α) (h : Exception → TermElabM α) : TermElabM α := tryCatch m h
def Tactic.tryCatchAll (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do
let b ← saveState
try x catch ex => b.restore; h ex
end catch_interrupted
section test_infra
def Tactic.withTimeout (ms : UInt32) (t : TacticM α) : TacticM (α ⊕ Nat) := do
let tk ← IO.CancelToken.new
withTheReader Core.Context (fun s => { s with cancelTk? := some tk }) do
let t0 ← IO.monoMsNow
let watchdog ← IO.asTask do
IO.sleep ms
tk.set
let r ← Tactic.tryCatchAll (.inl <$> t)
(fun e => do
IO.cancel watchdog
if !e.isInterrupt || !(← tk.isSet) then
throw e
else
let duration := (← IO.monoMsNow) - t0
return .inr duration)
IO.cancel watchdog
return r
/-- `with_timeout 100 => tac` allows `tac` only 100ms to run. -/
elab "with_timeout " ms:num "=>" tac:tacticSeq : tactic => do
let ms := ms.getNat.toUInt32
if let .inr _duration ← Tactic.withTimeout ms (evalTactic tac) then
throwError f!"Tactic took more than {ms}ms"
set_option linter.unusedTactic false
/-- error: Tactic took more than 500ms -/
#guard_msgs in
example : True := by
with_timeout 500 =>
sleep 1000
trivial
example: True := by
with_timeout 500 =>
sleep 100
trivial
end test_infra
/-- `check_timeouts 100 => tac` checks that `tac` never goes longer than `100ms` without checking
for cancellation. -/
elab "check_timeouts " tol_ms:num "=>" tac:tacticSeq : tactic => do
let mut t := 0
let tol_ms := tol_ms.getNat
repeat do
if let .inr duration ← Tactic.withTimeout t.toUInt32 (evalTactic tac) then
if duration > t + tol_ms then
logError f!"Tactic took much more than {t}ms ({duration}ms)"
trace[debug] "Tactic overran from {t}ms to {duration}ms"
else
break
t := t + tol_ms
set_option maxHeartbeats 0
set_option linter.unusedTactic false
set_option linter.unusedVariables false
theorem linear_combination_with_10_terms
(a b c d e f g h i j : Int)
(h0 : -e + g + -h + i = 0)
(h1 : b + -d + -e + f + g + i = 0)
(h2 : -b + j = 0)
(h3 : c + d + -f + -i = 0)
(h4 : b + c + e + -g + -h + i + j = 0)
(h5 : -a + b + d + f + -h + -i = 0)
(h6 : a + d + e + -g + -h = 0)
(h7 : -a + d + -f + -h + j = 0)
(h8 : a + -d + e + f + g + h + -i + j = 0)
(h9 : -a + b + c + -e + -f + h + j = 0) :
-2*a + b + 2*c + d + -3*f + -g + 3*h + -3*i = 0 := by
check_timeouts 250 => nlinarith |
.lake/packages/mathlib/MathlibTest/DoubleUnderscore.lean | import Mathlib.Tactic.Linter.Style
set_option linter.style.nameCheck true
variable (n : Nat)
-- this notation generates the declaration `«term__,»` that has a double underscore,
-- but is allowed by `linter.style.nameCheck`.
notation "_" n "," => Nat.succ n
/-- info: `«term__,» : Lean.Name -/
#guard_msgs in
#check `«term__,»
/--
warning: The declaration 'double__underscore' contains '__', which does not follow the mathlib naming conventions. Consider using single underscores instead.
Note: This linter can be disabled with `set_option linter.style.nameCheck false`
-/
#guard_msgs in
def double__underscore : Unit := () |
.lake/packages/mathlib/MathlibTest/borelize.lean | import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic
set_option autoImplicit true
example [TopologicalSpace α] [inst : MeasurableSpace α] [BorelSpace α] :
MeasurableSet (∅ : Set α) := by
guard_target = @MeasurableSet α inst ∅
borelize α
guard_target = @MeasurableSet α (borel α) ∅
apply MeasurableSet.empty
example [TopologicalSpace α] : True := by
borelize α
have h : MeasurableSet (∅ : Set α) := MeasurableSet.empty
guard_hyp h : @MeasurableSet α (borel α) ∅
trivial
example : True := by
obtain ⟨α, ⟨hα⟩⟩ : ∃ α : Type, Nonempty (TopologicalSpace α) := ⟨ℕ, ⟨inferInstance⟩⟩
borelize α
have h : MeasurableSet (∅ : Set α) := MeasurableSet.empty
guard_hyp h : @MeasurableSet α (borel α) ∅
trivial
example : True := by
set α := ℕ
borelize α
have h : MeasurableSet (∅ : Set α) := MeasurableSet.empty
guard_hyp h : @MeasurableSet α (borel α) ∅
trivial
example : True := by
have h1 : MeasurableSet (∅ : Set ℕ) := MeasurableSet.empty
guard_hyp h1 : @MeasurableSet ℕ Nat.instMeasurableSpace ∅
borelize ℕ
have h2 : MeasurableSet (∅ : Set ℕ) := MeasurableSet.empty
guard_hyp h2 : @MeasurableSet ℕ (borel ℕ) ∅
trivial |
.lake/packages/mathlib/MathlibTest/LongFile.lean | import Mathlib.Tactic.Linter.Style
/-
# Testing the `longFile` linter
Things to note:
* `set_option linter.style.longFile 0` disables the linter, allowing us to set a value smaller than
`linter.style.longFileDefValue` without triggering the warning for setting a small value
for the option;
* `guard_msgs ... in #exit` and `set_option ... in #exit` allow processing of the file *beyond*
`#exit`, since they wrap `#exit` inside an anonymous section,
making Lean active again *after* that anonymous section.
-/
section longFile
/--
warning: The default value of the `longFile` linter is 1500.
The current value of 1500 does not exceed the allowed bound.
Please, remove the `set_option linter.style.longFile 1500`.
Note: This linter can be disabled with `set_option linter.style.longFile 0`
-/
#guard_msgs in
-- Do not allow setting a `longFile` linter option if the file does not exceed the `defValue`
set_option linter.style.longFile 1500
/--
warning: using 'exit' to interrupt Lean
---
warning: The default value of the `longFile` linter is 50.
This file is 42 lines long which does not exceed the allowed bound.
Please, remove the `set_option linter.style.longFile 60`.
Note: This linter can be disabled with `set_option linter.style.longFile 0`
-/
#guard_msgs in
-- Do not allow unnecessarily increasing the `longFile` linter option
set_option linter.style.longFileDefValue 50 in
set_option linter.style.longFile 60 in
#exit
/--
warning: using 'exit' to interrupt Lean
---
warning: This file is 58 lines long, but the limit is 20.
You can extend the allowed length of the file using `set_option linter.style.longFile 200`.
You can completely disable this linter by setting the length limit to `0`.
Note: This linter can be disabled with `set_option linter.style.longFile 0`
-/
#guard_msgs in
-- We test that the `longFile` linter warns when a file exceeds the allowed value.
set_option linter.style.longFileDefValue 10 in
set_option linter.style.longFile 20 in
#exit
/-- warning: using 'exit' to interrupt Lean -/
#guard_msgs in
-- Check that the `candidate` value is allowed
set_option linter.style.longFileDefValue 10 in
set_option linter.style.longFile 200 in
#exit
/-- warning: using 'exit' to interrupt Lean -/
#guard_msgs in
-- Check that the `candidate - 100` value is allowed
set_option linter.style.longFileDefValue 10 in
set_option linter.style.longFile 100 in
#exit
/--
warning: using 'exit' to interrupt Lean
---
warning: This file is 86 lines long. The current limit is 101, but it is expected to be 200:
`set_option linter.style.longFile 200`.
Note: This linter can be disabled with `set_option linter.style.longFile 0`
-/
#guard_msgs in
-- Check that a value different from `candidate` or `candidate - 100` value is not allowed
set_option linter.style.longFileDefValue 10 in
set_option linter.style.longFile 101 in
#exit
-- The following test is a little artificial: it follows a path in the code that should only
-- be accessible after modifying the linter options appropriately.
-- Specifically, in the line `if lastLine ≤ defValue && defValue < linterBound then`, the failure
-- of *only* the second condition would produce the error message below
set_option linter.style.longFileDefValue 400
set_option linter.style.longFile 500
set_option linter.style.longFileDefValue 1000
/--
warning: using 'exit' to interrupt Lean
---
warning: This file is 104 lines long. The current limit is 500, but it is expected to be 1000:
`set_option linter.style.longFile 1000`.
Note: This linter can be disabled with `set_option linter.style.longFile 0`
-/
#guard_msgs in
#exit
/-
warning: using 'exit' to interrupt Lean
---
warning: The default value of the `longFile` linter is 1000.
This file is 95 lines long which does not exceed the allowed bound.
Please, remove the `set_option linter.style.longFile 500`.
-/
set_option linter.style.longFileDefValue 2000
/--
warning: The default value of the `longFile` linter is 2000.
The current value of 1999 does not exceed the allowed bound.
Please, remove the `set_option linter.style.longFile 1999`.
Note: This linter can be disabled with `set_option linter.style.longFile 0`
-/
#guard_msgs in
-- Do not allow setting a `longFile` linter option if the file does not exceed the `defValue`
set_option linter.style.longFile 1999
end longFile
set_option linter.style.longFileDefValue 400
/--
warning: using 'exit' to interrupt Lean
---
warning: The default value of the `longFile` linter is 400.
This file is 140 lines long which does not exceed the allowed bound.
Please, remove the `set_option linter.style.longFile 5000`.
Note: This linter can be disabled with `set_option linter.style.longFile 0`
-/
#guard_msgs in
set_option linter.style.longFile 5000 in
#exit |
.lake/packages/mathlib/MathlibTest/TermReduce.lean | import Mathlib.Util.TermReduce
-- On command line, tests format functions with => rather than ↦ without this.
set_option linter.style.setOption false
set_option pp.unicode.fun true
/-- info: (fun x ↦ x) true : Bool -/
#guard_msgs in #check (fun x => x) true
/-- info: true : Bool -/
#guard_msgs in #check beta% (fun x => x) true
/-- info: (fun x y ↦ (x, y)) true : Bool → Bool × Bool -/
#guard_msgs in #check (fun (x y : Bool) => (x, y)) true
/-- info: fun y ↦ (true, y) : Bool → Bool × Bool -/
#guard_msgs in #check beta% (fun (x y : Bool) => (x, y)) true
/-- info: (fun x ↦ cond x) true 1 : Nat → Nat -/
#guard_msgs in #check (fun (x : Bool) => cond x) true 1
/-- info: cond true 1 : Nat → Nat -/
#guard_msgs in #check beta% (fun (x : Bool) => cond x) true 1
/-- info: ∀ (i : Nat), 0 ≤ i : Prop -/
#guard_msgs in #check ∀ i : Nat, beta% (fun j => 0 ≤ j) i
/-- info: (fun x1 x2 ↦ x1 && x2) true false : Bool -/
#guard_msgs in #check (· && ·) true false
/-- info: true && false : Bool -/
#guard_msgs in #check beta% (· && ·) true false
abbrev reducibleId : Bool → Bool := fun x => x
/-- info: reducibleId true : Bool -/
#guard_msgs in #check reducibleId true
/-- info: id (id true) : Bool -/
#guard_msgs in #check id (id true)
/-- info: id true : Bool -/
#guard_msgs in #check delta% id (id true)
/-- info: true : Bool -/
#guard_msgs in #check delta% delta% id (id true)
/-- info: true : Bool -/
#guard_msgs in #check delta% delta% by exact id (id true)
/-- info: let x := true; x : Bool -/
#guard_msgs in #check let x := true; x
/-- info: true : Bool -/
#guard_msgs in #check zeta% let x := true; x
/-- info: let x := true; let y := x; y : Bool -/
#guard_msgs in #check let x := true; let y := x; y
/-- info: true : Bool -/
#guard_msgs in #check zeta% let x := true; let y := x; y
/-- info: true : Bool -/
#guard_msgs in #check zeta% by exact let x := true; let y := x; y
class A where
class B extends A where
class C extends A where
instance c : C :=
letI : B := {}
{}
set_option pp.all true in
/-- info: @C.mk A.mk : C -/
#guard_msgs in #check delta% c
set_option pp.all true in
/-- info: @C.mk A.mk : C -/
#guard_msgs in #check reduceProj% delta% c |
.lake/packages/mathlib/MathlibTest/GuardGoalNums.lean | import Mathlib.Tactic.GuardGoalNums
set_option linter.unusedTactic false
example : true ∧ true := by
constructor
guard_goal_nums 2
all_goals {constructor}
example : (true ∧ true) ∧ (true ∧ true) := by
constructor <;> constructor
guard_goal_nums 4
all_goals {constructor} |
.lake/packages/mathlib/MathlibTest/Lint.lean | import Batteries.Tactic.Alias
import Mathlib.Tactic.Linter.Lint
import Mathlib.Tactic.ToAdditive
/--
warning: The namespace 'add' is duplicated in the declaration 'add.add'
Note: This linter can be disabled with `set_option linter.dupNamespace false`
-/
#guard_msgs in
def add.add := True
namespace Foo
/--
warning: The namespace 'Foo' is duplicated in the declaration 'Foo.Foo.foo'
Note: This linter can be disabled with `set_option linter.dupNamespace false`
-/
#guard_msgs in
def Foo.foo := True
/--
warning: The namespace 'add' is duplicated in the declaration 'Foo.add.add'
Note: This linter can be disabled with `set_option linter.dupNamespace false`
-/
#guard_msgs in
set_option linter.dupNamespace true in
@[to_additive] theorem add.mul : True := .intro
-- However, the declaration `Foo.add.add` is present in the environment.
run_cmd Lean.Elab.Command.liftTermElabM do
let decl := (← Lean.getEnv).find? ``Foo.add.add
guard decl.isSome
namespace Nat
/--
warning: The namespace 'Nat' is duplicated in the declaration 'Foo.Nat.Nat.Nats'
Note: This linter can be disabled with `set_option linter.dupNamespace false`
-/
#guard_msgs in
alias Nat.Nats := Nat
end Nat
end Foo
namespace add
/--
warning: The namespace 'add' is duplicated in the declaration 'add.add'
Note: This linter can be disabled with `set_option linter.dupNamespace false`
---
warning: The namespace 'add' is duplicated in the declaration 'add.add'
Note: This linter can be disabled with `set_option linter.dupNamespace false`
-/
#guard_msgs in
export Nat (add add_comm add)
end add
/--
warning: The declaration 'double__underscore' contains '__',
which does not follow the mathlib naming conventions. Consider using single underscores instead.
Note: This linter can be disabled with `set_option linter.style.nameCheck false`
-/
#guard_msgs in
set_option linter.style.nameCheck true in
theorem double__underscore : True := trivial |
.lake/packages/mathlib/MathlibTest/DeprecatedModuleTest.lean | import MathlibTest.DeprecatedModule
/--
warning: We can also give more details about the deprecation
'MathlibTest.DeprecatedModule' has been deprecated: please replace this import by
import Mathlib.Tactic.Linter.DocPrime
import Mathlib.Tactic.Linter.DocString
Note: This linter can be disabled with `set_option linter.deprecated.module false`
---
warning:
'MathlibTest.DeprecatedModule' has been deprecated: please replace this import by
import Mathlib.Tactic.Linter.DocPrime
import Mathlib.Tactic.Linter.DocString
Note: This linter can be disabled with `set_option linter.deprecated.module false`
-/
#guard_msgs in
/-!
This file imports a deprecated module.
-/ |
.lake/packages/mathlib/MathlibTest/DeprecateTo.lean | import Mathlib.Tactic.DeprecateTo
import Mathlib.Tactic.ToAdditive
/--
info: * Pairings:
#[(new_name_mul, mul_easy_deprecated), (new_name_add, add_easy_deprecated)]
Try this:
[apply] /-- I also have a doc-string -/
@[to_additive /-- With its additive doc-string -/
]
theorem new_name_mul : True :=
.intro
⏎
@[deprecated (since := "YYYY-MM-DD")]
alias mul_easy_deprecated := new_name_mul
⏎
@[deprecated (since := "YYYY-MM-DD")]
alias add_easy_deprecated := new_name_add
-/
#guard_msgs in
deprecate to new_name_mul new_name_add "YYYY-MM-DD"
/-- I also have a doc-string -/
@[to_additive /-- With its additive doc-string -/]
theorem mul_easy_deprecated : True := .intro |
.lake/packages/mathlib/MathlibTest/eval_elab.lean | import Mathlib.Tactic.Eval
import Mathlib.Data.Finset.Powerset
import Mathlib.Data.Finset.Sort
import Mathlib.Util.Qq
#guard_expr eval% 2^10 =ₛ 1024
#guard_expr (eval% 2^10 : Int) =ₛ (1024 : Int)
#guard_expr
(eval% Multiset.powerset ({1, 2, 3} : Multiset ℕ)) =
{0, {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}}
-- https://leanprover.zulipchat.com/#narrow/stream/217875-Is-there-code-for-X.3F/topic/How.20to.20simplify.20this.20proof.20without.20using.20a.20have.20statement.3F/near/422294189
section from_zulip
/--
error: failed to synthesize
Lean.ToExpr (Finset (Finset ℕ))
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#guard_msgs in
#check eval% Finset.powerset ({1, 2, 3} : Finset ℕ)
open Lean Qq
/-- `HasInstance (Foo X)` means than an `inst : Foo X` exists. -/
class HasInstance (α : Type u) where
/-- The reflected version of `inst`. -/
expr : Expr
-- this obviously doesn't scale, which is why this is only in the test file
instance : HasInstance (DecidableEq ℕ) :=
⟨q(inferInstanceAs <| DecidableEq ℕ)⟩
instance : HasInstance (DecidableEq (Finset ℕ)) :=
⟨q(inferInstanceAs <| DecidableEq (Finset ℕ))⟩
instance : HasInstance (DecidableEq (Finset (Finset ℕ))) :=
⟨q(inferInstanceAs <| DecidableEq (Finset (Finset ℕ)))⟩
open Qq Lean
/-- `Finset α` can be converted to an expr only if there is some way to find `DecidableEq α`. -/
unsafe nonrec instance Finset.toExpr
{α : Type u} [ToLevel.{u}] [ToExpr α] [HasInstance (DecidableEq α)] : ToExpr (Finset α) :=
haveI u' : Level := Lean.toLevel.{u}
haveI α' : Q(Type u') := Lean.toTypeExpr α
letI : Q(DecidableEq $α') := HasInstance.expr (DecidableEq α)
{ toTypeExpr := q(Finset $α')
toExpr x := show Q(Finset $α') from mkSetLiteralQ q(Finset $α') (x.val.unquot.map toExpr) }
#guard_expr
(eval% Finset.powerset ({1, 2, 3} : Finset ℕ)) =
{∅, {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}}
end from_zulip |
.lake/packages/mathlib/MathlibTest/convert2.lean | import Mathlib.Algebra.BigOperators.Ring.List
import Mathlib.Algebra.Ring.Nat
import Mathlib.Tactic.Convert
set_option linter.unreachableTactic false
-- Prior to https://github.com/leanprover-community/mathlib4/pull/7945 this failed with `(kernel) declaration has metavariables '_example'`.
/--
error: maximum recursion depth has been reached
use `set_option maxRecDepth <num>` to increase limit
use `set_option diagnostics true` to get diagnostic information
-/
#guard_msgs (error) in
example (_h₁ : ((List.range 128).map (fun _ => 0)).sum = 0) : 0 ∣ 1 := by
apply Nat.dvd_of_mul_dvd_mul_left Nat.zero_lt_one
convert Nat.dvd_mul_left 0 1 |
.lake/packages/mathlib/MathlibTest/apply_rules.lean | import Mathlib.Algebra.Order.Field.Basic
set_option autoImplicit true
open Nat
example {a b c d e : Nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) :
a + c * e + a + c + 0 ≤ b + d * e + b + d + e :=
Nat.add_le_add (Nat.add_le_add (Nat.add_le_add
(Nat.add_le_add h1 (Nat.mul_le_mul_right _ h2)) h1) h2) h3
example {a b c d e : Nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) :
a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by
apply_rules [Nat.add_le_add, Nat.mul_le_mul_right]
-- Check that when we supply an iteration bound,
-- `apply_rules` works up to that bound and returns the remaining goals.
example {a b c d e : Nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) :
a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by
apply_rules (config := {maxDepth := 9}) [Nat.add_le_add, Nat.mul_le_mul_right]
guard_target = 0 ≤ e
assumption
-- Check that `apply_rules only` works.
example {P Q : Prop} (p : P) (f : P → Q) : Q := by
apply_rules only [f]
exact p
-- Check that `apply_rules [-p]` works.
example {P Q : Prop} (p : P) (f : P → Q) : Q := by
apply_rules [-p]
exact p
-- Test that metavariables created for implicit arguments don't get stuck
-- This required extra work in Lean 3, but doesn't seem to be a problem in Lean 4.
example (P : Nat → Type) (f : {n : Nat} → P n → P (n + 1)) (g : P 0) : P 2 := by
apply_rules only [f, g]
-- Check that `apply_rules` solves goals that come after goals that it can't solve
example (Q : Type) (f : Nat → Q) : Int × Q := by
apply_rules only [Prod.mk, f]
guard_target = Int
exact 0
guard_target = Nat
exact 37
-- Test that with transparency set to `.reducible`, the tactic will not unfold `/` to the underlying
-- `*` to match the form of the lemma `mul_le_mul`
example [Field α] [LinearOrder α] [IsStrictOrderedRing α] {a b : α} (hb : 0 ≤ b) (hab : a ≤ b) :
a / 2 ≤ b / 2 := by
fail_if_success
apply_rules (config := { transparency := .reducible }) [mul_le_mul]
guard_target = a / 2 ≤ b / 2
exact div_le_div₀ hb hab zero_lt_two le_rfl |
.lake/packages/mathlib/MathlibTest/congrm.lean | import Mathlib.Algebra.Ring.Nat
import Mathlib.Data.Fintype.Card
import Mathlib.Tactic.CongrM
private axiom test_sorry : ∀ {α}, α
namespace Tests.Congrm
set_option autoImplicit true
section docs
/-! These are the examples from the tactic documentation -/
example {a b c d : ℕ} :
Nat.pred a.succ * (d + (c + a.pred)) = Nat.pred b.succ * (b + (c + d.pred)) := by
congrm Nat.pred (Nat.succ ?h1) * (?h2 + ?h3)
case h1 =>
guard_target = a = b
exact test_sorry
case h2 =>
guard_target = d = b
exact test_sorry
case h3 =>
guard_target = c + a.pred = c + d.pred
exact test_sorry
example {a b : ℕ} (h : a = b) : (fun _y : ℕ => ∀ z, a + a = z) = (fun _x => ∀ z, b + a = z) := by
congrm fun x => ∀ w, ?_ + a = w
guard_hyp x : ℕ
guard_hyp w : ℕ
exact h
end docs
example (f : α → Prop) (h : ∀ a, f a ↔ True) : (∀ a : α, f a) ↔ (∀ _ : α, True) := by
fail_if_success congrm f ?_
congrm ∀ x, ?_
guard_hyp x : α
exact h x
example (f : α → Prop) (h : ∀ a, f a = True) : (∀ a : α, f a) ↔ (∀ _ : α, True) := by
congrm ∀ x, $(h _)
example (f : α → Prop) (h : ∀ a, f a ↔ True) : (∀ a : α, f a) ↔ (∀ _ : α, True) := by
congrm ∀ x, $(h _)
example (f : α → α → Prop) (h : ∀ a b, f a b ↔ True) :
(∀ a b, f a b) ↔ (∀ _ _ : α, True) := by
congrm ∀ x y, ?_
exact h x y
example {a b : ℕ} (h : a = b) : (fun y : ℕ => y + a) = (fun x => x + b) := by
congrm fun x => ?_
guard_target = x + a = x + b
rw [h]
example {a b : ℕ} (h : a = b) : (fun y : ℕ => y + a) = (fun x => x + b) := by
congrm fun (x : ℕ) => x + ?_
exact h
example (a b : ℕ) (h : a = b) (f : ℕ → ℕ) : f a = f b := by
congrm f ?_
exact h
example (a b c d : ℕ) (h : a = b) (h' : c = d) (f : ℕ → ℕ → ℕ) : f a c = f b d := by
congrm f ?_ ?_ <;> assumption
example (a b : ℕ) (h : a = b) (f : ℕ → ℕ) : f (f a) = f (f b) := by
congrm f (f ?_)
exact h
example (a b c : ℕ) (h : b = c) : a = b ↔ a = c := by
congrm _ = ?_
exact h
example (a b c : ℕ) (h : b = c) : a = b ↔ a = c := by
fail_if_success congrm b = ?_
congrm a = ?_
exact h
example {b d : ℕ} (h : b = d) : (∀ a, a = b) ↔ (∀ c, c = d) := by
congrm ∀ a, _ = ?_
guard_target = b = d
exact h
example {p q r s : Prop} (pr : p ↔ r) (qs : q ↔ s) : p ∧ q ↔ r ∧ s := by
congrm ?h1 ∧ ?h2
case h1 => guard_target = p ↔ r; assumption
case h2 => guard_target = q ↔ s; assumption
example {f : ℕ → Prop} :
(∃ k, f (3 + 2 + k) ∨ f (8 + 1 + k)) ↔ ∃ k, f (1 + 4 + k) ∨ f (2 + 7 + k) := by
congrm (∃ k, f (?_ + k) ∨ f (?_ + k))
· guard_target =ₛ 3 + 2 = 1 + 4; simp
· guard_target =ₛ 8 + 1 = 2 + 7; simp
example {a b : ℕ} (h : a = b) : (fun _ : ℕ => ∀ z, a + a = z) = (fun _ => ∀ z, b + a = z) := by
congrm fun x => ∀ w, ?_ + a = w
exact h
example (a b c : ℕ) (h : b = c) : a = b ↔ a = c := by
fail_if_success congrm Eq ?_ ?_ ?_
congrm _ = ?_
exact h
example (a b c : ℕ) (h : b = c) : a = b ↔ a = c := by
congrm _ = $h
example (f : α → Prop) (h : ∀ a, f a ↔ True) : (∀ a : α, f a) ↔ (∀ _ : α, True) := by
fail_if_success congrm f ?_
congrm ∀ _, ?_
exact h _
example (α : Nat → Type) (f : (x : Nat) → α x) (h : i = j) : f i ≍ f j := by
congrm f ?_
exact h
def foo (n : Nat) : Nat := 1 + n
@[irreducible] def foo' (n : Nat) : Nat := 1 + n
-- Unfolding
example (n m : Nat) (h : n = m) : foo (2 + n) = foo (2 + m) := by
congrm 1 + (2 + ?_)
exact h
-- Fails unfolding irreducible
example (n m : Nat) (h : n = m) : foo' (2 + n) = foo' (2 + m) := by
fail_if_success congrm 1 + (2 + ?_)
cases h
rfl
-- Reflexive relations
example (a b : Nat) (h : a = b) : 1 + a ≤ 1 + b := by
congrm 1 + ?_
exact h
-- Subsingleton instances
example [Fintype α] [Fintype β] (h : α = β) : Fintype.card α = Fintype.card β := by
congrm Fintype.card ?_
exact h
end Congrm
end Tests |
.lake/packages/mathlib/MathlibTest/TransImports.lean | import Mathlib.Util.TransImports
/--
info: 'MathlibTest.TransImports' has at most 1000 transitive imports
2 starting with "Mathlib.Tactic.Linter.H":
[Mathlib.Tactic.Linter.HashCommandLinter, Mathlib.Tactic.Linter.Header]
-/
#guard_msgs in
#trans_imports "Mathlib.Tactic.Linter.H" at_most 1000 |
.lake/packages/mathlib/MathlibTest/sqrt.lean | import Mathlib.Tactic.Eval
import Mathlib.Tactic.NormNum.NatSqrt
import Mathlib.Data.Rat.NatSqrt.Real
open Nat
/-
Unfortunately this test run extremely slowly under `lake test`, despite on taking a few seconds
in VSCode or under `lake build MathlibTest` or `lake env lean MathlibTest/sqrt.lean`.
While we investigate, we'll turn off the test.
/--
Compute an explicit rational approximation of `√10005`, accurate to 2 million decimal places.
(This is the square root appearing in the Chudnovsky formula for `π`,
see `Mathlib.Analysis.Real.Pi.Chudnovsky`.)
-/
def sqrt_10005_approx : ℚ := eval% ratSqrt 10005 (10^(2 * 10^6))
theorem sqrt_10005_approx_eq : sqrt_10005_approx = ratSqrt 10005 (10^(2 * 10^6)) := by
norm_num [sqrt_10005_approx, ratSqrt]
theorem sqrt_10005 :
√(10005 : ℝ) ∈
Set.Ico (sqrt_10005_approx : ℝ)
(sqrt_10005_approx + 1 / 10^(2 * 10^6) : ℝ) := by
rw [sqrt_10005_approx_eq]
exact_mod_cast realSqrt_mem_Ico 10005 (by norm_num)
-/ |
.lake/packages/mathlib/MathlibTest/cases.lean | import Batteries.Logic
import Mathlib.Tactic.Cases
import Mathlib.Data.Nat.Notation
set_option autoImplicit true
example (x : α × β × γ) : True := by
cases' x with a b; cases' b with b c
guard_hyp a : α
guard_hyp b : β
guard_hyp c : γ
trivial
example {α β γ : Type u} (x : α × β × γ) : True := by
cases' h: x with a b
guard_hyp a : α
guard_hyp b : β × γ
guard_hyp x : α × β × γ
guard_hyp h : x = (a, b)
trivial
noncomputable def my_rec :
{motive : ℕ → Sort u_1} →
(zee : motive 0) →
(soo : (n : ℕ) → motive n → motive (n + 1)) →
(t : ℕ) → motive t := @Nat.rec
example (x : ℕ) : True := by
cases' h: x using my_rec with y
case zee => guard_hyp h : x = 0; trivial
case soo => guard_hyp h : x = y + 1; trivial
inductive Foo (α β)
| A (a : α)
| B (a' : α) (b' : β)
| C (a'' : α) (b'' : β) (c'' : Foo α β)
example (x : Foo α β) : True := by
cases' x with a₀ a₁ _ a₂ b₂ c₂
· guard_hyp a₀ : α; trivial
· guard_hyp a₁ : α; have : β := (by assumption); trivial
· guard_hyp a₂ : α; guard_hyp b₂ : β; guard_hyp c₂ : Foo α β; trivial
inductive Bar : ℕ → Type
| A (a b : Nat) : Bar 1
| B (c d : Nat) : Bar (c + 1) → Bar c
example (x : Bar 0) : True := by
cases' x with a b c d h
· guard_hyp d : ℕ; guard_hyp h : Bar (0 + 1); trivial
example (n : Nat) : n = n := by
induction' n with n ih
· guard_target =ₛ 0 = 0; rfl
· guard_hyp n : Nat; guard_hyp ih : n = n
guard_target =ₛ n + 1 = n + 1; exact congr_arg (· + 1) ih
example (n : Nat) (h : n < 5) : n = n := by
induction' n with n ih
· guard_target =ₛ 0 = 0; rfl
· guard_hyp n : Nat; guard_hyp ih : n < 5 → n = n; guard_hyp h :ₛ n + 1 < 5
guard_target =ₛ n + 1 = n + 1; rfl
set_option linter.unusedVariables false in
example (n : Nat) {m} (h : m < 5) : n = n := by
induction' n with n ih
· guard_target = Nat.zero = Nat.zero; rfl
· guard_hyp n : Nat; guard_hyp ih : n = n; guard_hyp h : m < 5
guard_target = Nat.succ n = Nat.succ n; rfl
example (n : Nat) {m} (h : m < 5) : n = n := by
induction' n with n ih generalizing m
· guard_target = Nat.zero = Nat.zero; rfl
· guard_hyp n : Nat; guard_hyp ih : ∀ {m}, m < 5 → n = n; guard_hyp h : m < 5
guard_target = Nat.succ n = Nat.succ n; rfl
example (n : Nat) : n = n := by
induction' e : n with m ih
· guard_hyp e : n = Nat.zero; guard_target = Nat.zero = Nat.zero; rfl
· guard_hyp m : Nat; guard_hyp ih : n = m → m = m
guard_hyp e : n = Nat.succ m; guard_target = Nat.succ m = Nat.succ m; rfl
example (n : Nat) : n = n := by
induction' e : n using my_rec with m ih
case zee =>
guard_hyp e : n = 0; guard_target = 0 = 0; rfl
case soo =>
guard_hyp m : Nat; guard_hyp ih : n = m → m = m
guard_hyp e : n = m + 1; guard_target = m + 1 = m + 1; rfl
example (x : Foo α Nat) : True := by
induction' x with a a' b' a'' b'' c'' ih
case A => guard_hyp a : α; trivial
case B => guard_hyp a' : α; guard_hyp b' : Nat; trivial
case C => guard_hyp a'' : α; guard_hyp b'' : Nat; guard_hyp c'' : Foo α Nat
guard_hyp ih : True; trivial
example (x : Bar n) : x = x := by
induction' x with a b c d h ih
case A => guard_target = Bar.A a b = Bar.A a b; rfl
case B => guard_hyp h : Bar (c + 1); guard_hyp ih : h = h
guard_target = Bar.B c d h = Bar.B c d h; rfl
example (p q : Prop) : (p → ¬ q) → ¬ (p ∧ q) := by
intro hpnq hpq
apply hpnq
cases' hpq with hp hq
assumption
exact hpq.2
-- Ensure that `induction'` removes generalized variables. Here: `a` and `h`
example (a b : ℕ) (h : a + b = a) : b = 0 := by
induction' a with d hd
· -- Test the generalized vars have been removed
revert h
fail_if_success (guard_hyp a : Nat)
fail_if_success (guard_hyp h : a + b = a)
intro h
-- Sample proof
rw [Nat.zero_add] at h
assumption
· -- Test the generalized vars have been removed
revert h
fail_if_success (guard_hyp a : Nat)
fail_if_success (guard_hyp h : a + b = a)
intro h
-- Sample proof
rw [Nat.succ_add, Nat.succ.injEq] at h
apply hd
assumption
/-- error: unnecessary 'generalizing' argument, variable 'a' is generalized automatically -/
#guard_msgs in
example (n : ℕ) (a : Fin n) : True := by
induction' n generalizing a
/--
error: variable cannot be generalized because target depends on it
m
-/
#guard_msgs in
example (m : ℕ) : True := by
induction' m generalizing m |
.lake/packages/mathlib/MathlibTest/GuardHypNums.lean | import Mathlib.Tactic.GuardHypNums
set_option linter.unusedTactic false
example (a b c : Nat) (_ : a = b) (_ : c = 3) : true := by
guard_hyp_nums 6
trivial
example : true := by
guard_hyp_nums 1
trivial |
.lake/packages/mathlib/MathlibTest/Explode.lean | import Mathlib.Tactic.Explode
import Mathlib.Data.Real.Basic
set_option linter.unusedVariables false
open Lean
/--
info: true_iff : ∀ (p : Prop), (True ↔ p) = p
0 │ │ p ├ Prop
1 │ │ x✝ │ ┌ True ↔ p
2 │ │ trivial │ │ True
3 │1,2 │ Iff.mp │ │ p
4 │1,3 │ ∀I │ (True ↔ p) → p
5 │ │ h │ ┌ p
6 │ │ x✝ │ │ ┌ True
7 │6,5 │ ∀I │ │ True → p
8 │ │ x✝ │ │ ┌ p
9 │8,2 │ ∀I │ │ p → True
10│7,9 │ Iff.intro │ │ True ↔ p
11│5,10│ ∀I │ p → (True ↔ p)
12│4,11│ Iff.intro │ (True ↔ p) ↔ p
13│12 │ propext │ (True ↔ p) = p
14│0,13│ ∀I │ ∀ (p : Prop), (True ↔ p) = p
-/
#guard_msgs in #explode true_iff
set_option linter.style.setOption false
-- On command line, tests format functions with => rather than ↦ without this.
set_option pp.unicode.fun true
theorem lambda : True → True :=
fun a ↦ a
/--
info: lambda : True → True
0│ │ a ├ True
1│0,0│ ∀I │ True → True
-/
#guard_msgs in #explode lambda
theorem application : True ∧ True :=
And.intro True.intro True.intro
/--
info: application : True ∧ True
0│ │ True.intro │ True
1│0,0│ And.intro │ True ∧ True
-/
#guard_msgs in #explode application
theorem theorem_1 : ∀ (p : Prop), p → p :=
fun (p : Prop) ↦ (fun hP : p ↦ hP)
/--
info: theorem_1 : ∀ (p : Prop), p → p
0│ │ p ├ Prop
1│ │ hP ├ p
2│0,1,1│ ∀I │ ∀ (p : Prop), p → p
-/
#guard_msgs in #explode theorem_1
theorem theorem_2 : ∀ (p : Prop) (q : Prop), p → q → p ∧ q :=
fun p ↦ fun q ↦ fun hP ↦ fun hQ ↦ And.intro hP hQ
/--
info: theorem_2 : ∀ (p q : Prop), p → q → p ∧ q
0│ │ p ├ Prop
1│ │ q ├ Prop
2│ │ hP ├ p
3│ │ hQ ├ q
4│2,3 │ And.intro │ p ∧ q
5│0,1,2,3,4│ ∀I │ ∀ (p q : Prop), p → q → p ∧ q
-/
#guard_msgs in #explode theorem_2
theorem theorem_3 (a : Prop) (h : a) : a ↔ True :=
Iff.intro
(fun hl ↦ trivial)
(fun hr ↦ h)
/--
info: theorem_3 : ∀ (a : Prop), a → (a ↔ True)
0│ │ a ├ Prop
1│ │ h ├ a
2│ │ hl │ ┌ a
3│ │ trivial │ │ True
4│2,3 │ ∀I │ a → True
5│ │ hr │ ┌ True
6│5,1 │ ∀I │ True → a
7│4,6 │ Iff.intro │ a ↔ True
8│0,1,7│ ∀I │ ∀ (a : Prop), a → (a ↔ True)
-/
#guard_msgs in #explode theorem_3
theorem theorem_4 : ∀ p q : Prop, (p → q) → (¬q → ¬p) :=
fun U ↦ fun W ↦ fun hPQ ↦ fun hNQ ↦ fun hP ↦ False.elim (hNQ (hPQ hP))
/--
info: theorem_4 : ∀ (p q : Prop), (p → q) → ¬q → ¬p
0│ │ U ├ Prop
1│ │ W ├ Prop
2│ │ hPQ ├ U → W
3│ │ hNQ ├ ¬W
4│ │ hP ├ U
5│2,4 │ ∀E │ W
6│3,5 │ ∀E │ False
7│6 │ False.elim │ False
8│0,1,2,3,4,7│ ∀I │ ∀ (U W : Prop), (U → W) → ¬W → U → False
-/
#guard_msgs in #explode theorem_4
lemma lemma_5 : ∀ p q : Prop, (¬q → ¬p) → (p → q) :=
fun p ↦ fun q ↦
fun hNQNP ↦
fun hP ↦
Or.elim (Classical.em q)
(fun hQ ↦ hQ)
(fun hNQ ↦
let hNP := hNQNP hNQ
False.elim (hNP hP))
/--
info: lemma_5 : ∀ (p q : Prop), (¬q → ¬p) → p → q
0 │ │ p ├ Prop
1 │ │ q ├ Prop
2 │ │ hNQNP ├ ¬q → ¬p
3 │ │ hP ├ p
4 │ │ Classical.em │ q ∨ ¬q
5 │ │ hQ │ ┌ q
6 │5,5 │ ∀I │ q → q
7 │ │ hNQ │ ┌ ¬q
8 │2,7 │ ∀E │ │ ¬p
10│8,3 │ ∀E │ │ False
11│10 │ False.elim │ │ q
12│7,11 │ ∀I │ ¬q → q
13│4,6,12 │ Or.elim │ q
14│0,1,2,3,13│ ∀I │ ∀ (p q : Prop), (¬q → ¬p) → p → q
-/
#guard_msgs in #explode lemma_5
lemma lemma_6 : ∀ p q : Prop, (p → q) → p → q :=
fun p h hpq hp ↦ hpq hp
/--
info: lemma_6 : ∀ (p q : Prop), (p → q) → p → q
0│ │ p ├ Prop
1│ │ h ├ Prop
2│ │ hpq ├ p → h
3│ │ hp ├ p
4│2,3 │ ∀E │ h
5│0,1,2,3,4│ ∀I │ ∀ (p h : Prop), (p → h) → p → h
-/
#guard_msgs in #explode lemma_6
lemma lemma_7 : ∀ p q r : Prop, (p → q) → (p → q → r) → (p → r) :=
fun p q r hq hqr hp ↦
let hq' := hq hp
let hqr' := hqr hp
hqr' hq'
/--
info: lemma_7 : ∀ (p q r : Prop), (p → q) → (p → q → r) → p → r
0 │ │ p ├ Prop
1 │ │ q ├ Prop
2 │ │ r ├ Prop
3 │ │ hq ├ p → q
4 │ │ hqr ├ p → q → r
5 │ │ hp ├ p
6 │3,5 │ ∀E │ q
8 │4,5 │ ∀E │ q → r
10│8,6 │ ∀E │ r
11│0,1,2,3,4,5,10│ ∀I │ ∀ (p q r : Prop), (p → q) → (p → q → r) → p → r
-/
#guard_msgs in #explode lemma_7
lemma lemma_5' : ∀ p q : Prop, (¬q → ¬p) → (p → q) :=
fun p ↦ fun q ↦
fun hNQNP ↦
Or.elim (Classical.em q)
(fun hQ hP ↦ hQ)
(fun hNQ hP ↦
let hNP := hNQNP hNQ
False.elim (hNP hP))
/--
info: lemma_5' : ∀ (p q : Prop), (¬q → ¬p) → p → q
0 │ │ p ├ Prop
1 │ │ q ├ Prop
2 │ │ hNQNP ├ ¬q → ¬p
3 │ │ Classical.em │ q ∨ ¬q
4 │ │ hQ │ ┌ q
5 │ │ hP │ ├ p
6 │4,5,4 │ ∀I │ q → p → q
7 │ │ hNQ │ ┌ ¬q
8 │ │ hP │ ├ p
9 │2,7 │ ∀E │ │ ¬p
11│9,8 │ ∀E │ │ False
12│11 │ False.elim │ │ q
13│7,8,12 │ ∀I │ ¬q → p → q
14│3,6,13 │ Or.elim │ p → q
15│0,1,2,14│ ∀I │ ∀ (p q : Prop), (¬q → ¬p) → p → q
-/
#guard_msgs in #explode lemma_5'
section
variable (p q : Prop)
/--
info: fun hp hnp ↦ hnp hp : p → (p → q) → q
0│ │ hp ├ p
1│ │ hnp ├ p → q
2│1,0 │ ∀E │ q
3│0,1,2│ ∀I │ p → (p → q) → q
-/
#guard_msgs in #explode fun (hp : p) (hnp : p → q) ↦ hnp hp
/--
info: fun hNQNP ↦
Or.elim (Classical.em q) (fun hQ hP ↦ hQ) fun hNQ hP ↦
let hNP := hNQNP hNQ;
False.elim (hNP hP) : (¬q → ¬p) → p → q
0 │ │ hNQNP ├ ¬q → ¬p
1 │ │ Classical.em │ q ∨ ¬q
2 │ │ hQ │ ┌ q
3 │ │ hP │ ├ p
4 │2,3,2 │ ∀I │ q → p → q
5 │ │ hNQ │ ┌ ¬q
6 │ │ hP │ ├ p
7 │0,5 │ ∀E │ │ ¬p
9 │7,6 │ ∀E │ │ False
10│9 │ False.elim │ │ q
11│5,6,10│ ∀I │ ¬q → p → q
12│1,4,11│ Or.elim │ p → q
13│0,12 │ ∀I │ (¬q → ¬p) → p → q
-/
#guard_msgs in #explode fun (hNQNP : ¬q → ¬p) ↦
Or.elim (Classical.em q)
(fun hQ hP ↦ hQ)
(fun hNQ hP ↦
let hNP := hNQNP hNQ
False.elim (hNP hP))
end |
.lake/packages/mathlib/MathlibTest/BinaryRec.lean | import Mathlib.Data.Nat.Bits
def Nat.popcountTR (n : Nat) : Nat :=
n.binaryRec (·) (fun b _ f x ↦ f (x + b.toNat)) 0
/-- info: 1 -/
#guard_msgs in
#eval Nat.popcountTR (2 ^ 20240) |
.lake/packages/mathlib/MathlibTest/matrix.lean | /-
manually ported from
https://github.com/leanprover-community/mathlib/blob/4f4a1c875d0baa92ab5d92f3fb1bb258ad9f3e5b/test/matrix.lean
-/
import Mathlib.GroupTheory.Perm.Fin
import Mathlib.LinearAlgebra.Matrix.Determinant.Basic
import Mathlib.LinearAlgebra.Matrix.Notation
import Qq
set_option linter.style.commandStart false
open Qq
variable {α β : Type} [Semiring α] [Ring β]
namespace Matrix
/-! Test that the dimensions are inferred correctly, even for empty matrices -/
section dimensions
-- set_option pp.universes true
-- set_option pp.all true
section elaborators
open Lean Meta Elab Command
/-- `dims% e` elaborates `e` as a Matrix and returns its dimensions as a `Nat × Nat`. -/
elab "dims% " e:term : term => do
let elem_t ← mkFreshTypeMVar
let m ← mkFreshExprMVar (mkConst ``Nat)
let n ← mkFreshExprMVar (mkConst ``Nat)
let matrix_t := mkAppN (← mkConstWithFreshMVarLevels ``Matrix)
#[mkApp (mkConst ``Fin) m, mkApp (mkConst ``Fin) n, elem_t]
let _ ← Term.elabTermEnsuringType e (some matrix_t)
let m ← instantiateMVars m
let n ← instantiateMVars n
mkAppM ``Prod.mk #[m, n]
end elaborators
-- we test equality of expressions here to ensure that we have `2` and not `1.succ` in the type
#guard_expr dims% !![] =ₛ (0, 0)
#guard_expr dims% !![;] =ₛ (1, 0)
#guard_expr dims% !![;;] =ₛ (2, 0)
#guard_expr dims% !![,] =ₛ (0, 1)
#guard_expr dims% !![,,] =ₛ (0, 2)
#guard_expr dims% !![1] =ₛ (1, 1)
#guard_expr dims% !![1,] =ₛ (1, 1)
#guard_expr dims% !![1;] =ₛ (1, 1)
#guard_expr dims% !![1,2;3,4] =ₛ (2, 2)
end dimensions
section safety
open Lean Meta Elab Command
def mkMatrix (rows : Array (Array Term)) : Term := Unhygienic.run `(!![$[$[$rows],*];*])
def mkColumnVector (elems : Array Term) : Term := Unhygienic.run `(!![$[$elems];*])
-- Check that the `!![$[$[$rows],*];*]` case can deal with empty arrays even though it uses sepBy1
run_elab do
let e ← Term.elabTerm (mkMatrix #[]) q(Matrix (Fin 0) (Fin 0) Nat)
Term.synthesizeSyntheticMVarsUsingDefault
let e ← instantiateMVars e
guard <| e == q(!![] : Matrix (Fin 0) (Fin 0) Nat)
run_elab do
let e ← Term.elabTerm (mkColumnVector #[]) q(Matrix (Fin 0) (Fin 0) Nat)
Term.synthesizeSyntheticMVarsUsingDefault
let e ← instantiateMVars e
guard <| e == q(!![] : Matrix (Fin 0) (Fin 0) Nat)
end safety
#guard !![1;2] = of ![![1], ![2]]
#guard !![1,3] = of ![![1,3]]
#guard !![1,2;3,4] = of ![![1,2], ![3,4]]
#guard !![1,2;3,4;] = of ![![1,2], ![3,4]]
#guard !![1,2,;3,4,] = of ![![1,2], ![3,4]]
section to_expr
open Lean Meta
/-- info: !![1 + 1, 1 + 2; 2 + 1, 2 + 2] : Matrix (Fin 2) (Fin 2) ℕ -/
#guard_msgs in
#check by_elab return Matrix.mkLiteralQ !![q(1 + 1), q(1 + 2); q(2 + 1), q(2 + 2)]
run_elab do
let x := !![1, 2; 3, 4]
guard (← withReducible <| isDefEq (toExpr x) q(!![1, 2; 3, 4]))
end to_expr
section delaborators
/-- info: !![0, 1, 2; 3, 4, 5] : Matrix (Fin 2) (Fin 3) ℕ -/
#guard_msgs in #check (!![0, 1, 2; 3, 4, 5] : Matrix (Fin 2) (Fin 3) ℕ)
/-- info: !![0, 1, 2; 3, 4, 5] 1 1 : ℕ -/
#guard_msgs in #check (!![0, 1, 2; 3, 4, 5] : Matrix (Fin 2) (Fin 3) ℕ) 1 1
/-- info: !![,,,] : Matrix (Fin 0) (Fin 3) ℕ -/
#guard_msgs in #check (!![,,,] : Matrix (Fin 0) (Fin 3) ℕ)
/-- info: !![;;;] : Matrix (Fin 3) (Fin 0) ℕ -/
#guard_msgs in #check (!![;;;] : Matrix (Fin 3) (Fin 0) ℕ)
/-- info: !![] : Matrix (Fin 0) (Fin 0) ℕ -/
#guard_msgs in #check (!![] : Matrix (Fin 0) (Fin 0) ℕ)
end delaborators
example {a a' b b' c c' d d' : α} :
!![a, b; c, d] + !![a', b'; c', d'] = !![a + a', b + b'; c + c', d + d'] := by
simp
example {a a' b b' c c' d d' : β} :
!![a, b; c, d] - !![a', b'; c', d'] = !![a - a', b - b'; c - c', d - d'] := by
simp
example {a a' b b' c c' d d' : α} :
!![a, b; c, d] * !![a', b'; c', d'] =
!![a * a' + b * c', a * b' + b * d'; c * a' + d * c', c * b' + d * d'] := by
simp
example {a b c d x y : α} :
!![a, b; c, d] *ᵥ ![x, y] = ![a * x + b * y, c * x + d * y] := by
simp
/-!
TODO: the below lemmas rely on simp lemmas assuming the indexing numerals are assembled from
`bit0` and `bit1`, so no longer work in Lean 4
-/
/-
example {a b c d : α} : submatrix !![a, b; c, d] ![1, 0] ![0] = !![c; a] := by
ext; simp
-/
example {α : Type _} [CommRing α] {a b c d : α} :
Matrix.det !![a, b; c, d] = a * d - b * c := by
simp? [Matrix.det_succ_row_zero, Fin.sum_univ_succ] says
simp only [det_succ_row_zero, Nat.succ_eq_add_one, Nat.reduceAdd, Fin.isValue, of_apply,
cons_val', cons_val_fin_one, cons_val_zero, det_unique, Fin.default_eq_zero, submatrix_apply,
Fin.succ_zero_eq_one, cons_val_one, Fin.sum_univ_succ, Fin.coe_ofNat_eq_mod, Nat.zero_mod,
pow_zero, one_mul, Fin.zero_succAbove, Finset.univ_unique, Fin.val_succ, Fin.val_eq_zero,
zero_add, pow_one, cons_val_succ, neg_mul, ne_eq, Fin.succ_ne_zero, not_false_eq_true,
Fin.succAbove_ne_zero_zero, Finset.sum_neg_distrib, Finset.sum_const, Finset.card_singleton,
one_smul]
ring
example {α : Type _} [CommRing α] {a b c d e f g h i : α} :
Matrix.det !![a, b, c; d, e, f; g, h, i] =
a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g := by
simp? [Matrix.det_succ_row_zero, Fin.sum_univ_succ] says
simp only [det_succ_row_zero, Nat.succ_eq_add_one, Nat.reduceAdd, Fin.isValue, of_apply,
cons_val', cons_val_fin_one, cons_val_zero, submatrix_apply, Fin.succ_zero_eq_one,
cons_val_one, submatrix_submatrix, det_unique, Fin.default_eq_zero, Function.comp_apply,
Fin.succ_one_eq_two, cons_val, Fin.sum_univ_succ, Fin.coe_ofNat_eq_mod, Nat.zero_mod,
pow_zero, one_mul, Fin.zero_succAbove, Finset.univ_unique, Fin.val_succ, Fin.val_eq_zero,
zero_add, pow_one, neg_mul, ne_eq, Fin.succ_ne_zero, not_false_eq_true,
Fin.succAbove_ne_zero_zero, Finset.sum_neg_distrib, Finset.sum_singleton, cons_val_succ,
Fin.succ_succAbove_one, even_two, Even.neg_pow, one_pow, Finset.sum_const,
Finset.card_singleton, one_smul]
ring
example {R : Type*} [Semiring R] {a b c d : R} :
!![a, b] * (transpose !![c, d]) = !![a * c + b * d] := by
ext i j
fin_cases i
fin_cases j
simp [Matrix.vecHead, Matrix.vecTail]
/- Check that matrix notation works with `row` and `col` -/
example : Matrix.replicateRow _ ![1, 1] = !![1, 1] := by
ext i j
simp
example : Matrix.replicateCol _ ![1, 1] = !![1; 1] := by
ext i j
fin_cases i <;> simp
example (ι : Type*) [Inhabited ι] : Matrix.replicateRow ι (fun (_ : Fin 3) => 0) = 0 := by
simp_all
rfl
example (ι : Type*) [Inhabited ι] : Matrix.replicateCol ι (fun (_ : Fin 3) => 0) = 0 := by
simp_all
rfl
end Matrix |
.lake/packages/mathlib/MathlibTest/PPRoundtrip.lean | import Mathlib.Tactic.Linter.PPRoundtrip
/--
info: "a a"
---
warning: source context
'al " a '
'al " a a\n'
pretty-printed context
Note: This linter can be disabled with `set_option linter.ppRoundtrip false`
-/
#guard_msgs in
set_option linter.ppRoundtrip true in
#eval " a a\n " |>.trim
/--
warning: source context
'rd ¬ fa'
'rd ¬false'
pretty-printed context
Note: This linter can be disabled with `set_option linter.ppRoundtrip false`
-/
#guard_msgs in
set_option linter.ppRoundtrip true in
#guard ¬ false
/--
warning: source context
'le {a: Nat'
'le {a : Na'
pretty-printed context
Note: This linter can be disabled with `set_option linter.ppRoundtrip false`
-/
#guard_msgs in
set_option linter.ppRoundtrip true in
variable {a: Nat}
/--
warning: source context
' {a :Nat}'
' {a : Nat}'
pretty-printed context
Note: This linter can be disabled with `set_option linter.ppRoundtrip false`
-/
#guard_msgs in
set_option linter.ppRoundtrip true in
variable {a :Nat}
/--
info: (fun x1 x2 => x1 + x2) 0 1 : Nat
---
warning: source context
'k (·+·) '
'k (· + ·'
pretty-printed context
Note: This linter can be disabled with `set_option linter.ppRoundtrip false`
-/
#guard_msgs in
set_option linter.ppRoundtrip true in
#check (·+·) 0 1
#guard_msgs in
set_option linter.ppRoundtrip true in
-- check that trailing comments do not trigger the linter
example : 0 = 0 := by
rw [] -- this goal is closed by the `rfl` implied by `rw` |
.lake/packages/mathlib/MathlibTest/GalNotation.lean | import Mathlib.FieldTheory.Galois.Notation
import Mathlib.Algebra.Field.Rat
import Mathlib.Algebra.Field.ULift
/-! Tests for the notation `Gal(L/K)`. -/
universe uR uS uK uL
variable (R : Type uR) (S : Type uS) (K : Type uK) (L : Type uL)
variable [CommSemiring R] [Semiring S] [Algebra R S] [Field K] [Field L] [Algebra K L]
/-! `Gal(S/R)` should always elaborate to `S ≃ₐ[R] S`,
but `S ≃ₐ[R] S` should not pretty print as `Gal(S/R)` because `R` and `S` are not fields. -/
/-- info: S ≃ₐ[R] S : Type uS -/
#guard_msgs in
#check Gal(S/R)
/-! `Gal(L/K)` should pretty print as `Gal(L/K)` when `K` and `L` are fields. -/
/-- info: Gal(L/K) : Type uL -/
#guard_msgs in
#check Gal(L/K)
/-- info: Gal(L/K) : Type uL -/
#guard_msgs in
#check L ≃ₐ[K] L
/-! This should also work for concrete types other than variables -/
/-- info: Gal(ℚ/ℚ) : Type -/
#guard_msgs in
#check Gal(ℚ/ℚ)
/-- info: Gal(ULift.{uL, 0} ℚ/ℚ) : Type uL -/
#guard_msgs in
#check Gal(ULift.{uL} ℚ/ℚ)
/-! This should not see through `abbrev`s and pretty print `AlgEquiv`s between them as `Gal`. -/
/-- A copy of `L` for testing. -/
abbrev Copy := L
/-- info: Gal(Copy L/K) : Type uL -/
#guard_msgs in
#check Gal(Copy L/K)
/-- info: L ≃ₐ[K] Copy L : Type uL -/
#guard_msgs in
#check L ≃ₐ[K] Copy L
/-! `Gal(L/K)` should not pretty print when `pp.explicit` is set to true. -/
set_option pp.explicit true in
/--
info:
@AlgEquiv K L L (@Semifield.toCommSemiring K (@Field.toSemifield K inst✝²))
(@DivisionSemiring.toSemiring L (@Semifield.toDivisionSemiring L (@Field.toSemifield L inst✝¹)))
(@DivisionSemiring.toSemiring L (@Semifield.toDivisionSemiring L (@Field.toSemifield L inst✝¹))) inst✝ inst✝ : Type uL
-/
#guard_msgs in
#check Gal(L/K) |
.lake/packages/mathlib/MathlibTest/BigOps.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Basic
section
variable {ι M : Type*} [CommMonoid M] [AddCommMonoid M] [Fintype ι] {s : Finset ι} {p : ι → Prop}
[DecidablePred p] {f : ι → M}
/-! ### Big operators over a finset -/
/-- info: ∑ i ∈ s, f i : M -/
#guard_msgs in
#check Finset.sum s fun i ↦ f i
/-- info: ∏ i ∈ s, f i : M -/
#guard_msgs in
#check Finset.prod s fun i ↦ f i
/-- info: ∑ i ∈ s with p i, f i : M -/
#guard_msgs in
#check Finset.sum {j ∈ s | p j} fun i ↦ f i
/-- info: ∏ i ∈ s with p i, f i : M -/
#guard_msgs in
#check Finset.prod {j ∈ s | p j} fun i ↦ f i
/-! ### Big operators over a finset with `funBinderTypes` on -/
set_option pp.funBinderTypes true
/-- info: ∑ i : ι, f i : M -/
#guard_msgs in
#check Finset.sum Finset.univ fun i ↦ f i
/-- info: ∏ i : ι, f i : M -/
#guard_msgs in
#check Finset.prod Finset.univ fun i ↦ f i
/-- info: ∑ i : ι with p i, f i : M -/
#guard_msgs in
#check Finset.sum {j | p j} fun i ↦ f i
/-- info: ∏ i : ι with p i, f i : M -/
#guard_msgs in
#check Finset.prod {j | p j} fun i ↦ f i
/-! ### Big operators over a finset with `funBinderTypes` off -/
set_option pp.funBinderTypes false
/-- info: ∑ i, f i : M -/
#guard_msgs in
#check Finset.sum Finset.univ fun i ↦ f i
/-- info: ∏ i, f i : M -/
#guard_msgs in
#check Finset.prod Finset.univ fun i ↦ f i
/-- info: ∑ i with p i, f i : M -/
#guard_msgs in
#check Finset.sum {j | p j} fun i ↦ f i
/-- info: ∏ i with p i, f i : M -/
#guard_msgs in
#check Finset.prod {j | p j} fun i ↦ f i
end |
.lake/packages/mathlib/MathlibTest/simp_confluence.lean | import Mathlib
namespace Set
open Function
variable {α β : Type*}
/-- Without `subset_range_of_surjective`, `image_subset_iff` and `image_preimage_eq` create a simp
confluence issue. -/
example {f : α → β} (s t : Set β) (h : Surjective f) :
f '' (f ⁻¹' s) ⊆ t ↔ f '' (f ⁻¹' s) ⊆ t := by
conv =>
congr
· simp [h, -image_preimage_eq, -subset_range_of_surjective]
· simp [h, -image_subset_iff, -subset_range_of_surjective]
fail_if_success simp [h, -subset_range_of_surjective]
simp [h]
/-- Without `Nonempty.subset_preimage_const`, `image_subset_iff` and `Nonempty.image_const` create a
simp confluence issue. -/
example {s : Set α} (hs : Set.Nonempty s) (t : Set β) (a : β) :
(fun _ => a) '' s ⊆ t ↔ (fun _ => a) '' s ⊆ t := by
conv =>
congr
· simp [hs, -Nonempty.image_const, -Nonempty.subset_preimage_const]
· simp [hs, -image_subset_iff, -Nonempty.subset_preimage_const]
fail_if_success simp [hs, -Nonempty.subset_preimage_const]
simp [hs]
/-- Without `preimage_eq_univ_iff`, `image_subset_iff` and `image_univ` create a
simp confluence issue. -/
example {f : α → β} (s) : f '' univ ⊆ s ↔ f '' univ ⊆ s := by
conv =>
congr
· simp [-image_univ, -preimage_eq_univ_iff]
· simp [-image_subset_iff, -preimage_eq_univ_iff]
fail_if_success simp [-preimage_eq_univ_iff]
simp
end Set |
.lake/packages/mathlib/MathlibTest/fun_prop_dev.lean | import Mathlib.Tactic.FunProp
import Mathlib.Logic.Function.Basic
import Mathlib.Data.FunLike.Basic
import Mathlib.Tactic.SuccessIfFailWithMsg
import Aesop
/-! # Tests for the `fun_prop` tactic
This file is designed for development of fun_prop and does not depend on most of mathlib. It defines
two function properties `Con` and `Lin` which roughly correspond to `Continuity` and `IsLinearMap`.
-/
set_option linter.style.longLine false
open Function
variable {α β γ δ ι : Type _} {E : α → Type _}
instance [Add α] : Add (ι → α) := ⟨fun f g i => f i + g i⟩
axiom silentSorry {α} : α
set_option linter.unusedVariables false
-- define function propositions --
----------------------------------
@[fun_prop] opaque Con {α β} (f : α → β) : Prop
@[fun_prop] opaque Lin {α β} (f : α → β) : Prop
-- state basic lambda calculus rules --
---------------------------------------
-- variable [Obj α] [Obj β] [Obj γ] [Obj δ] [∀ x, Obj (E x)]
@[fun_prop] theorem Con_id : Con (id : α → α) := silentSorry
@[fun_prop] theorem Con_const (y : β) : Con (fun x : α => y) := silentSorry
@[fun_prop] theorem Con_apply (x : α) : Con (fun f : α → β => f x) := silentSorry
@[fun_prop] theorem Con_applyDep (x : α) : Con (fun f : (x' : α) → E x' => f x) := silentSorry
@[fun_prop] theorem Con_comp (f : β → γ) (g : α → β) (hf : Con f) (hg : Con g) : Con (fun x => f (g x)) := silentSorry
-- @[fun_prop] theorem Con_let (f : α → β → γ) (g : α → β) (hf : Con (fun (x,y) => f x y)) (hg : Con g) : Con (fun x => let y:= g x; f x y) := silentSorry
@[fun_prop] theorem Con_pi (f : β → (i : α) → (E i)) (hf : ∀ i, Con (fun x => f x i)) : Con (fun x i => f x i) := silentSorry
-- Lin is missing `const` theorem
@[fun_prop] theorem Lin_id : Lin (fun x : α => x) := silentSorry
@[fun_prop] theorem Lin_const {β} [Zero β] : Lin (fun x : α => (0 : β)) := silentSorry
@[fun_prop] theorem Lin_apply (x : α) : Lin (fun f : α → β => f x) := silentSorry
@[fun_prop] theorem Lin_applyDep (x : α) : Lin (fun f : (x' : α) → E x' => f x) := silentSorry
@[fun_prop] theorem Lin_comp (f : β → γ) (g : α → β) (hf : Lin f) (hg : Lin g) : Lin (f ∘ g) := silentSorry
@[fun_prop] theorem Lin_pi {ι} (f : α → ι → γ) (hf : ∀ i, Lin (fun x => f x i)) : Lin (fun x i => f x i) := silentSorry
-- this is to stress test detection of loops
@[fun_prop]
theorem kaboom (f : α → β) (hf : Con f) : Con f := hf
@[fun_prop]
theorem chabam (f : α → β) (hf : Con f) : Con f := hf
-- transition theorem --
------------------------
@[fun_prop] theorem lin_to_con (f : α → β) (hf : Lin f) : Con f := silentSorry
-- theorems about function in the environment --
------------------------------------------------
@[fun_prop]
theorem prod_mk_Con (fst : α → β) (snd : α → γ) (hfst : Con fst) (hsnd : Con snd)
: Con fun x => (fst x, snd x) := silentSorry
@[fun_prop]
theorem prod_mk_Lin (fst : α → β) (snd : α → γ) (hfst : Lin fst) (hsnd : Lin snd)
: Lin fun x => (fst x, snd x) := silentSorry
-- "simple form" of theorems
@[fun_prop] theorem fst_Con : Con fun x : α×β => x.1 := silentSorry
@[fun_prop] theorem snd_Con : Con fun x : α×β => x.2 := silentSorry
@[fun_prop] theorem add_Con [Add α] : Con (Function.uncurry (fun x y : α => x + y)) := silentSorry
@[fun_prop] theorem add_Lin [Add α] : Lin ↿(fun x y : α => x + y) := silentSorry
-- "compositional form" of theorems
@[fun_prop] theorem fst_Con' (self : α → β×γ) (hself : Con self) : Con fun x => (self x).1 := by fun_prop
@[fun_prop] theorem snd_Con' (self : α → β×γ) (hself : Con self) : Con fun x => (self x).2 := by fun_prop
@[fun_prop] theorem add_Con' [Add β] (x y : α → β) (hx : Con x) (hy : Con y) : Con (fun w => x w + y w) := by fun_prop
@[fun_prop] theorem add_Lin' [Add β] (x y : α → β) (hx : Lin x) (hy : Lin y) : Lin (fun w => x w + y w) := by fun_prop
-- set up hom objects/bundled morphisms --
------------------------------------------
structure ConHom (α β) where
toFun : α → β
con : Con toFun
infixr:25 " ->> " => ConHom
structure LinHom (α β) where
toFun : α → β
lin : Lin toFun
infixr:25 " -o " => LinHom
instance : CoeFun (α ->> β) (fun _ => α → β) where
coe f := f.toFun
instance : FunLike (α -o β) α β where
coe f := f.toFun
coe_injective' := silentSorry
#eval Lean.Elab.Command.liftTermElabM do
Lean.Meta.registerCoercion ``ConHom.toFun
(some { numArgs := 3, coercee := 2, type := .coeFun })
instance : HasUncurry (α ->> β) α β :=
⟨fun f x => f x⟩
instance [HasUncurry β γ δ] : HasUncurry (α ->> β) (α × γ) δ :=
⟨fun f p ↦ ↿(f p.1) p.2⟩
instance : HasUncurry (α -o β) α β :=
⟨fun f x => f x⟩
instance [HasUncurry β γ δ] : HasUncurry (α -o β) (α × γ) δ :=
⟨fun f p ↦ ↿(f p.1) p.2⟩
-- morphism theorems i.e. theorems about `FunLike.coe` --
---------------------------------------------------------
-- this is some form of Cartesian closedness with homs `α ->> β`
@[fun_prop] theorem conHom_con' (f : α → β ->> γ) (g : α → β) (hf : Con f) (hg : Con g) : Con (fun x => (f x) (g x)) := silentSorry
@[fun_prop] theorem conHom_lin_in_fn' (f : α → β ->> γ) (y : β) (hf : Lin f) : Lin (fun x => f x y) := silentSorry
-- analogous theorem with `α -o β` does no hold
@[fun_prop] theorem linHom_lin (f : α -o β) : Lin f := silentSorry
@[fun_prop] theorem linHom_lin_in_fn' (f : α → β -o γ) (y : β) (hf : Lin f) : Lin (fun x => f x y) := silentSorry
def LinHom.mk' (f : α → β) (hf : Lin f := by fun_prop) : α -o β := mk f hf
@[fun_prop] theorem linHom_mk' (f : α → β → γ) (hx : ∀ y, Lin (f · y)) (hy : ∀ x, Lin (f x ·)) : Lin (fun x => LinHom.mk' (f x)) := silentSorry
section Notation
open Lean Syntax Parser
open TSyntax.Compat
macro "fun" xs:explicitBinders " ⊸ " b:term : term => expandExplicitBinders ``LinHom.mk' xs b
macro "fun" xs:explicitBinders " -o " b:term : term => expandExplicitBinders ``LinHom.mk' xs b
end Notation
example [Add β] (f : α → β → γ) (hx : ∀ y, Lin (f · y)) (hy : ∀ x, Lin (f x ·)) :
Lin (fun x => fun y ⊸ f y (x+x)) := by fun_prop
example [Add α] (f : α → α → α → α) (hx : ∀ x y, Lin (f x y ·)) (hy : ∀ x z, Lin (f x · z)) (hz : ∀ y z, Lin (f · y z)) :
Lin (fun x => fun y z ⊸ f z (x+x) y) := by fun_prop
-- the only analogue is this theorem but that is already provable
example (f : α → β -o γ) (g : α → β) (hf : Lin (fun (x,y) => f x y)) (hg : Lin g) : Lin (fun x => (f x) (g x)) := by fun_prop
----------------------------------------------------------------------------------------------------
example (f : α → β → γ) (hf : Con fun (x,y) => f x y) : Con f := by fun_prop
example : Con (fun x : α => x) := by fun_prop
example (y : β) : Con (fun _ : α => y) := by fun_prop
example (x : α) : Con (fun f : α → β => f x) := by fun_prop
example (x : α) : Con (fun f : (x' : α) → E x' => f x) := by fun_prop
example (x : α) (y : β) : Con (fun f : α → β → γ => f x y) := by fun_prop
example (x : α) (y : β) : Con (fun f : α → β → (x' : α) → E x' => f x y x) := by fun_prop
example (y : β) : Con (fun (f : α → β → (x' : α) → E x') x => f x y x) := by fun_prop
example : Con (fun (f : α → β → (x' : α) → E x') x y => f x y x) := by fun_prop
example (x : α) [Add α] : Con (let y := x + x; fun x' : α => x' + y) := by fun_prop
example (f : β → γ) (g : α → β) (hf : Con f) (hg : Con g) : Con (fun x => f (g x)) := by fun_prop
example (f : α → β → γ) (g : α → β) (hf : Con (fun (x,y) => f x y)) (hg : Con g) : Con (fun x => f x (g x)) := by fun_prop
example (f : α → β → γ) (g : α → β) (hf : Con (fun (x,y) => f x y)) (hg : Con g) : Con (fun x => let y := g x; f x y) := by fun_prop
example {ι : Type _} (f : α → ι → γ) (hf : ∀ i, Con (fun x => f x i)) : Con (fun x i => f x i) := by fun_prop
example : Con (fun (f : α → β → γ) x y => f x y) := by fun_prop
example : Con (fun (f : α → β → γ) y x => f x y) := by fun_prop
example : Con (fun (f : α → α → α → α → α) y x => f x y x y) := by fun_prop
-- local hypothesis are assumed to be always in fully applied form
-- so `(hf : Con f)` is not considered valid
-- is this valid assumption?
example (f : α → β → γ) (hf : Con f) : Con f := by fun_prop
example (f : α → β → γ) (hf : Con f) : Con (fun x => f x) := by fun_prop
example (f : α → β → γ) (hf : Con f) : Con (fun x y => f x y) := by fun_prop
example (f : α → β → γ) (hf : Con f) (y) : Con (fun x => f x y) := by fun_prop
example (f : α → β → γ) (hf : Con fun (x,y) => f x y) (x) : Con fun y => f x y := by fun_prop
example (f : α → β → γ) (hf : Con fun (x,y) => f x y) (y) : Con fun x => f x y := by fun_prop
example (f : α → β → γ) (hf : Con fun (x,y) => f x y) : Con f := by fun_prop
example (f : α → β → γ) (hf : Con ↿f) (x : α) : Con fun y => f x y := by fun_prop
example (f : α → β → γ) (hf : Con ↿f) (y : β) : Con fun x => f x y := by fun_prop
example (f : α → β → γ) (hf : Con ↿f) : Con f := by fun_prop
example (f : α → β → γ) (hf : ∀ x, Con fun y => f x y) (x) : Con fun y => f x y := by fun_prop
example (f : α → β → γ) (hf : ∀ x, Con fun y => f x y) (x) : Con (f x) := by fun_prop
example (f : α → β → γ) (hf : ∀ y, Con fun x => f x y) (y) : Con fun x => f x y := by fun_prop
example (f : α → β → γ) (hf : ∀ y, Con fun x => f x y) : Con fun x => f x := by fun_prop
example (f : α → β → γ) (hf : Con fun (x,y) => f x y) (y) : Con fun x => f x y := by fun_prop
example (f : α → β → γ) (hf : Con fun (x,y) => f x y) : Con f := by fun_prop
example (f : α → α → β) (hf : Con fun (x,y) => f x y) : Con (fun x => f x x) := by fun_prop
example (f : α → β → γ → δ) (hf : ∀ x, Con fun (y,z) => f x y z) (x z) : Con (fun y => f x y z) := by fun_prop
example (f : α → β → γ → δ) (hf : ∀ x, Con fun (y,z) => f x y z) (x y) : Con (fun z => f x y z) := by fun_prop
example (f : α → β → γ → δ) (hf : ∀ x, Con fun (y,z) => f x y z) (x) : Con (fun z y => f x y z) := by fun_prop
example (f : α → β → γ → δ) (hf : ∀ x, Con fun (y,z) => f x y z) (x y) : Con (f x y) := by fun_prop
example (f : α → β → γ → δ) (hf : ∀ x, Con fun (y,z) => f x y z) (x) : Con (fun y => f x y) := by fun_prop
example (f : α → Nat → Nat → β) (hf : ∀ i j, Con (f · i j)) : Con (fun x i j => f x (i+j) j) := by fun_prop
example (f : α → Nat → Nat → β) (hf : ∀ i j, Con (f · i j)) (i j) : Con (fun x => f x (i+j) j) := by fun_prop
example (f : α → Nat → Nat → β) (hf : Con f) : Con (fun x i j => f x (i+j) j) := by fun_prop
example (f : α → Nat → Nat → β) (hf : Con f) (i j) : Con (fun x => f x (i+j) j) := by fun_prop
example (f : α → β → γ → δ) (hf : ∀ y, Con fun (x,z) => f x y z) : Con f := by fun_prop
example (f : α → β → γ → δ) (hf : ∀ y, Con fun (x,z) => f x y z) : Con f := by fun_prop
example (f : α → β ->> γ) (hf : Con f) (y) : Con (fun x => f x y) := by fun_prop
example (f : α → β ->> γ) (hf : Con f) : Con (fun x y => f x y) := by fun_prop
example (f : α → β ->> γ) (hf : Con fun (x,y) => f x y) (y) : Con fun x => f x y := by fun_prop
example (f : α → β ->> γ) (hf : Con fun (x,y) => f x y) : Con fun x y => f x y := by fun_prop
example (f : α → β ->> γ) (hf : Con fun (x,y) => f x y) (x) : Con fun y => f x y := by fun_prop
example (f : α → α ->> (α → α)) (hf : Con fun (x,y,z) => f x y z) (x) : Con fun y => f x y := by fun_prop
example (f : α → α ->> (α → α)) (y : α) (hf : Con fun (x,y,z) => f x y z) : Con fun x => f y x x := by fun_prop
example (f : α → α ->> (α → α)) (hf : Con fun (x,y,z) => f x y z) : Con fun x y => f y x x := by fun_prop
example (f : α → β ->> γ) (hf : Con ↿f) (y) : Con fun x => f x y := by fun_prop
example (f : α → β ->> γ) (x) : Con fun y : β => f x := by fun_prop
example (f : α → β ->> γ) (x) : Con fun y : β => (f x : β → γ) := by fun_prop
example (f : α → β ->> γ) (x) : Con fun y => f x y := by fun_prop
example (f : α → α ->> (α → α)) (x) : Con fun y => f x y := by fun_prop
example (f : α → α ->> (α → α)) (hf : Con ↿f) : Con fun x y => f y x x := by fun_prop
example (f : α → β ->> γ) (hf : Con f) : Con ↿f := by fun_prop
section WithAdd
variable [Add α]
example : Con (HAdd.hAdd : α → α → α) := by fun_prop -- under applied constant
example : Con (fun x => (HAdd.hAdd : α → α → α) x) := by fun_prop -- under applied constant
example : Con (fun x => (HAdd.hAdd : ((ι→α) → (ι→α) → (ι→α))) x) := by fun_prop
example : Con (fun x y => (HAdd.hAdd : ((ι→α) → (ι→α) → (ι→α))) x y) := by fun_prop
example : Con (fun x y i => (HAdd.hAdd : ((ι→α) → (ι→α) → (ι→α))) x y i) := by fun_prop
example (y) : Con (fun x i => (HAdd.hAdd : ((ι→α) → (ι→α) → (ι→α))) x y i) := by fun_prop
example (y i) : Con (fun x => (HAdd.hAdd : ((ι→α) → (ι→α) → (ι→α))) x y i) := by fun_prop
end WithAdd
example (f : β → γ) (x) (hf : Lin f) : Lin (fun (g : α → β) => f (g x)) := by fun_prop
-- apply theorems about FunLike.coe
example (f : α ->> β) : Con f := by fun_prop
example (f : α -o β) : Con f := by fun_prop
example (f : α → β) (hf : Lin f) : Con f := by fun_prop
example (f : β → γ) (g : α ->> β) (hf: Con f) : Con (fun x => f (g x)) := by fun_prop
example (f : β ->> γ) (g : α → β) (hg: Con g) : Con (fun x => f (g x)) := by fun_prop
example (f : β -o γ) (g : α → β) (hg : Con g) : Con fun x => f (g x) := by fun_prop
example (f : α → β ->> γ) (hf : Con f) (g : α → β) (hg : Lin g) : Con (fun x => f x (g x)) := by fun_prop
example (f : α → β ->> γ) (hf : Lin (fun (x,y) => f x y)) (g : α → β) (hg : Lin g) : Con (fun x => f x (g x)) := by fun_prop
example (f : α → β ->> γ) (hf : Lin (fun (x,y) => f x y)) (g : α → β) (hg : Lin g) : Lin (fun x => f x (g x)) := by fun_prop
-- remove arguments before applying morphism rules
example (f : α ->> (β → γ)) (y) : Con (fun x => f x y) := by fun_prop
example (g : α → β) (hg : Con g) : Con fun (fx : (β ->> γ)×α) => fx.1 (g fx.2) := by fun_prop
-- sometimes unfold constants
example (f : α → β) (hf : Con f) : Con (fun x => id f x) := by fun_prop
example (f : α → β) (hf : Con f) : Con (fun x => (id id) f x) := by fun_prop
example (f : α → α → α) (hf : Con (fun (x,y) => f x y)) : Con (fun x => id (id f x) x) := by fun_prop
example (f : α → α → α) (hf : Con (fun (x,y) => f x y)) : Con (fun x => (id id) ((id id) f x) x) := by fun_prop
example (f : α → α → α) (hf : Con (fun (x,y) => f x y)) : Con (fun x : α×α => id (f x.1) x.2) := by fun_prop
-- this used to time out
example (f : α → β -o γ) (hf : Lin (fun (x,y) => f x y)) (g : α → β) (hg : Lin g) : Lin (fun x => f x (g x)) := by fun_prop
example : Con fun (a : α ->> α) => a x := by fun_prop
-- this used to crash
example (f : α → (α ->> α)) (hf : Con f) : Con fun x => ((f x) : α → α) := by fun_prop
example : Con (fun f : (α ->> α ->> α) => (f x : α → α)) := by fun_prop
example : Lin (fun f : (α ->> α ->> α) => (f x : α → α)) := by fun_prop
example (y): Lin (fun f : (α ->> α ->> α) => f x y) := by fun_prop
example : Lin (fun f : (α -o α ->> α) => (f x : α → α)) := by fun_prop
example (y): Lin (fun f : (α ->> α -o α) => f x y) := by fun_prop
example (f : α -o α ->> α) (y) : Lin (fun x => f x y) := by fun_prop
example (f : α ->> α -o α ->> α) (y) : Lin (fun x => f y x y) := by fun_prop
example (x) : Con fun (f : α ->> α) => f (f x) := by fun_prop
example (x) : Con fun (f : α ->> α) => f (f (f x)) := by fun_prop
example [Zero α] [Add α] : Lin (fun x : α => (0 : α) + x + (0 : α) + (0 : α) + x) := by fun_prop
noncomputable
def foo : α ->> α ->> α := silentSorry
noncomputable
def bar : α ->> α ->> α := silentSorry
@[fun_prop]
theorem foo_lin : Lin fun x : α => foo x := silentSorry
@[fun_prop]
theorem bar_lin (y) : Lin fun x : α => bar x y := silentSorry
example : Lin (foo : α → α ->> α) := by fun_prop
example : Con (foo : α → α ->> α) := by fun_prop
example : Lin (fun x : α => (foo x : α → α)) := by fun_prop
example : Lin (fun x y : α => foo x y) := by fun_prop
example (y) : Lin (fun x : α => foo x y) := by fun_prop
example : Lin (fun x : α => (bar x : α → α)) := by fun_prop
example : Lin (fun x y : α => bar x y) := by fun_prop
example (y) : Lin (fun x : α => bar x y) := by fun_prop
example : Lin (fun (f : α ->> α) => (f : α → α)) := by fun_prop
example : Con (fun (f : α ->> α) => (f : α → α)) := by fun_prop
example : Lin (fun (f : α -o α) => (f : α → α)) := by fun_prop
example : Con (fun fx : (α ->> β)×α => fx.1 fx.2) := by fun_prop
def iterate (n : Nat) (f : α → α) (x : α) : α :=
match n with
| 0 => x
| n + 1 => iterate n f (f x)
theorem iterate_con (n : Nat) (f : α → α) (hf : Con f) : Con (iterate n f) := by
induction n <;> (simp [iterate]; fun_prop)
example : let f := fun x : α => x; Con f := by fun_prop
example [Add α] : let f := fun x => x + y; ∀ y : α, ∀ z : α, Con fun x => x + f x + z := by fun_prop
example [Add α] : ∀ y : α, let f := fun x => x + y; ∀ z : α, Con fun x => x + f x + z := by fun_prop
-- this is still broken
-- example : ∀ y : α, ∀ z : α, let f := fun x => x + y; Con fun x => x + f x + z := by fun_prop
example [Add β] (f g : α → β) (hf : Con f := by fun_prop) (hg : outParam (Con g)) :
Con (fun x => f x + g x) := by fun_prop
opaque foo1 : α → α := id
opaque foo2 : α → α := id
@[fun_prop]
theorem foo1_lin : Lin (foo1 : α → α) := silentSorry
@[fun_prop]
theorem foo2_lin : Lin (foo2 : α → α) := silentSorry
example : Con (fun x : α => foo1 (foo2 x)) := by fun_prop
def foo3 [Add α] (x : α) := x + x
example [Add α] : Con (fun x : α => foo3 x) := by fun_prop [foo3]
def myUncurry (f : α → β → γ) : α×β → γ := fun (x,y) => f x y
def diag (f : α → α → α) (x : α) := f x x
theorem diag_Con (f : α → α → α) (hf : Con (myUncurry f)) : Con (fun x => diag f x) := by
fun_prop [diag,myUncurry]
namespace MultipleLambdaTheorems
opaque A : Prop
opaque B : Prop
@[local fun_prop] theorem Con_comp' (f : β → γ) (g : α → β) (h : A) : Con (fun x => f (g x)) := silentSorry
@[local fun_prop] theorem Con_comp'' (f : β → γ) (g : α → β) (b : B) : Con (fun x => f (g x)) := silentSorry
example (f : β → γ) (g : α → β) (h : A) : Con (fun x => f (g x)) := by fun_prop (disch := assumption)
example (f : β → γ) (g : α → β) (h : B) : Con (fun x => f (g x)) := by fun_prop (disch := assumption)
end MultipleLambdaTheorems
/-- info: `?m` is not a `fun_prop` goal! -/
#guard_msgs in
#check_failure ((by fun_prop) : ?m)
-- todo: warning should not have mvar id in it
-- /-- warning: `?m.71721` is not a `fun_prop` goal! -/
-- #guard_msgs in
-- #check_failure (by exact add_Con' (by fun_prop) : Con (fun x : α => (x + x) + (x + x)))
example : Con fun ((x, _, _) : α × α × α) => x := by fun_prop
example : Con fun ((_, x, _) : α × α × α) => x := by fun_prop
example : Con fun ((_, _, x) : α × α × α) => x := by fun_prop
example [Add α] : let f := (by exact (fun x : α => x+x)); Con f := by
intro f;
let F := fun x : α => x+x
have : Con F := by fun_prop -- this used to be problematic
fun_prop
def f1 (a : α) := a
def f2 (a : α) := a
/--
error: `fun_prop` was unable to prove `Con fun x => x + f1 x`
Issues:
No theorems found for `f1` in order to prove `Con fun a => f1 a`
-/
#guard_msgs in
example [Add α] : Con (fun x : α => x + f1 x) := by fun_prop
/--
error: `fun_prop` was unable to prove `Con fun x => f1 x + f1 x`
Issues:
No theorems found for `f1` in order to prove `Con fun a => f1 a`
-/
#guard_msgs in
example [Add α] : Con (fun x : α => f1 x + f1 x) := by fun_prop
/--
error: `fun_prop` was unable to prove `Con fun x => f2 x + f1 x`
Issues:
No theorems found for `f2` in order to prove `Con fun a => f2 a`
-/
#guard_msgs in
example [Add α] : Con (fun x : α => f2 x + f1 x) := by fun_prop
def f3 (a : α) := a
@[fun_prop]
theorem f3_lin : Lin (fun x : α => f3 x) := by
unfold f3; fun_prop (maxTransitionDepth := 0) (maxSteps := 10)
example : Con (fun x : α => f3 x) := by fun_prop
/--
error: `fun_prop` was unable to prove `Con fun x => f3 x`
Issues:
No theorems found for `f3` in order to prove `Con fun x => f3 x`
-/
#guard_msgs in
example : Con (fun x : α => f3 x) := by fun_prop (maxTransitionDepth := 0)
@[fun_prop] opaque Dif (𝕜:Type) [Add 𝕜] {α β} (f : α → β) : Prop
variable {𝕜 : Type}
@[fun_prop] theorem Dif_id [Add 𝕜] : Dif 𝕜 (id : α → α) := silentSorry
@[fun_prop] theorem Dif_const [Add 𝕜] (y : β) : Dif 𝕜 (fun x : α => y) := silentSorry
@[fun_prop] theorem Dif_apply [Add 𝕜] (x : α) : Dif 𝕜 (fun f : α → β => f x) := silentSorry
@[fun_prop] theorem Dif_applyDep [Add 𝕜] (x : α) : Dif 𝕜 (fun f : (x' : α) → E x' => f x) := silentSorry
@[fun_prop] theorem Dif_comp [Add 𝕜] (f : β → γ) (g : α → β) (hf : Dif 𝕜 f) (hg : Dif 𝕜 g) : Dif 𝕜 (fun x => f (g x)) := silentSorry
@[fun_prop] theorem Dif_pi [Add 𝕜] (f : β → (i : α) → (E i)) (hf : ∀ i, Dif 𝕜 (fun x => f x i)) : Dif 𝕜 (fun x i => f x i) := silentSorry
@[fun_prop]
theorem Dif_Con [Add 𝕜] (f : α → β) (hf : Dif 𝕜 f) : Con f := silentSorry
def f4 (a : α) := a
example (hf : Dif Nat (f4 : α → α)) : Con (f4 : α → α) := by fun_prop (disch:=aesop)
@[fun_prop]
theorem f4_dif : Dif Nat (f4 : α → α) := silentSorry
example (hf : Dif Nat (f4 : α → α)) : Con (f4 : α → α) := by fun_prop (disch:=aesop)
-- Test abbrev transparency
abbrev my_id {α} (a : α) := a
example : Con (fun x : α => my_id x) := by fun_prop
example (f : α → β) (hf : Con (my_id f)) : Con f := by fun_prop
-- Testing some issues with bundled morphisms of multiple arguments
structure Mor where
toFun : Int → Int → Int
hcon : Con (fun (x,y) => toFun x y)
@[fun_prop]
theorem Mor.toFun_Con (m : Mor) (f g : α → Int) (hf : Con f) (g : α → Int) (hg : Con g) :
Con (fun x => m.toFun (f x) (g x)) := by
have := m.hcon
fun_prop
-- Test improved beta reduction of the head function when we interleave lambdas and lets
example [Add α] (a : α) : Con (fun x0 : α =>
(fun x =>
let y := x + x
fun z : α =>
x + y + z) x0 a) := by fun_prop
example [Add α] (a : α) :
let f := (fun x : α =>
let y := x + x
fun z : α =>
x + y + z)
Con (fun x => f x a) := by fun_prop
example [Add α] (a a' : α) : Con (fun x0 : α =>
(fun x =>
let y := x + x
fun z : α =>
let h := x + y + z
fun w =>
w + x + y + z + h) x0 a a') := by fun_prop
-- test that local function is being properly unfolded
example [Add α] (a : α) :
let f := (fun x : α =>
let y := x + x
fun z : α =>
x + y + z)
Con (fun x =>
f x a) := by
fun_prop
-- Test that local theorem is being used
/--
trace: [Meta.Tactic.fun_prop] [✅️] Con fun x => f x y
[Meta.Tactic.fun_prop] [✅️] Con fun x => f x y
[Meta.Tactic.fun_prop] candidate local theorems for f #[this : Con f]
[Meta.Tactic.fun_prop] removing argument to later use this : Con f
[Meta.Tactic.fun_prop] [✅️] applying: Con_comp
[Meta.Tactic.fun_prop] [✅️] Con fun f => f y
[Meta.Tactic.fun_prop] [✅️] applying: Con_apply
[Meta.Tactic.fun_prop] [✅️] Con fun x => f x
[Meta.Tactic.fun_prop] candidate local theorems for f #[this : Con f]
[Meta.Tactic.fun_prop] [✅️] applying: this : Con f
-/
#guard_msgs in
example [Add α] (y : α):
let f := (fun x y : α => x+x+y)
Con (fun x => f x y) := by
intro f
have : Con f := by fun_prop
set_option trace.Meta.Tactic.fun_prop true in
fun_prop
--- pefromance tests - mainly testing fast failure ---
------------------------------------------------------
section PerformanceTests
-- set_option trace.Meta.Tactic.fun_prop true
-- set_option profiler true
variable {R : Type*} [Add R] [∀ n, OfNat R n]
example (f : R → R) (hf : Con f) :
Con (fun x ↦ f (x + 3)) := by fun_prop -- succeeds in 5ms
example (f : R → R) (hf : Con f) :
Con (fun x ↦ (f (x + 3)) + 2) := by fun_prop -- succeeds in 6ms
example (f : R → R) (hf : Con f) :
Con (fun x ↦ (f (x + 3)) + (2 + f (x + 1))) := by fun_prop -- succeeds in 8ms
example (f : R → R) (hf : Con f) :
Con (fun x ↦ (f (x + 3)) + (2 + f (x + 1)) + x) := by fun_prop -- succeeds in 10ms
example (f : R → R) (hf : Con f) :
Con (fun x ↦ (f (x + 3)) + 2 + f (x + 1) + x + 1) := by fun_prop -- succeeds in 11ms
-- This used to fail in exponentially increasing time, up to 6s for the last example
-- We set maxHearthbeats to 1000 such that the last three examples should fail if the exponential
-- blow happen again.
set_option maxHeartbeats 1000 in
example (f : R → R) :
Con (fun x ↦ f (x + 3)) := by
fail_if_success fun_prop
apply silentSorry
example (f : R → R) :
Con (fun x ↦ (f (x + 3)) + 2) := by
fail_if_success fun_prop
apply silentSorry
set_option maxHeartbeats 1000 in
example (f : R → R) :
Con (fun x ↦ ((f (x + 3)) + 2) + f (x + 1)) := by
fail_if_success fun_prop
apply silentSorry
set_option maxHeartbeats 1000 in
example (f : R → R) :
Con (fun x ↦ ((f (x + 3)) + 2) + f (x + 1) + x) := by
fail_if_success fun_prop
apply silentSorry
set_option maxHeartbeats 1000 in
example (f : R → R) :
Con (fun x ↦ ((f (x + 3)) + 2) + f (x + 1) + x + 1) := by
fail_if_success fun_prop
apply silentSorry
end PerformanceTests
/--
info: Con
add_Con, args: [4, 5], form: simple
add_Con', args: [4, 5], form: compositional
-/
#guard_msgs in
#print_fun_prop_theorems HAdd.hAdd Con
def fst (x : α×β) := x.1
def snd (x : α×β) := x.2
-- make sure that `fun_prop` can't see through `fst` and `snd`
example (f : α → β → γ) (hf : Con ↿f) : Con (fun x : α×β => f (fst x) (snd x)) := by
fail_if_success fun_prop
apply silentSorry
-- In the following example, `fun_prop` used to panic with a "loose bvar in expression" error.
@[fun_prop]
opaque AEMeas {α β : Type*} (f : α → β) (μ : Bool) : Prop
opaque foo4 : Bool → Bool
@[fun_prop]
theorem aemeas_foo4 (μ : Bool) : AEMeas foo4 μ := silentSorry
@[fun_prop]
theorem con_foo4 : (∀ μ : Bool, AEMeas foo4 μ) → Con foo4 := silentSorry
example : Con foo4 := by fun_prop |
.lake/packages/mathlib/MathlibTest/TCSynth.lean | import Mathlib
/-!
# Test against slow typeclass synthesis
This file tests against regression in typeclass synthesis speed.
The tests below became fast by the fix in
https://github.com/leanprover/lean4/pull/4085
-/
section
-- Initial issue: https://github.com/leanprover-community/mathlib4/issues/12226
open Complex Filter Bornology
/--
error: failed to synthesize
AddMonoidHomClass (AddGroupSeminorm ℂ) ℂ ℝ
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#guard_msgs in
set_option synthInstance.maxHeartbeats 3000 in
#synth AddMonoidHomClass (AddGroupSeminorm ℂ) ℂ ℝ
set_option synthInstance.maxHeartbeats 3000 in
-- This then results in a near failure (or failure on nightly-testing) of the simpNF linter on
-- `Complex.comap_exp_cobounded` and `Complex.map_exp_comap_re_atTop`:
example : comap exp (cobounded ℂ) = comap re atTop := by simp
end
section
-- Initial issue: https://github.com/leanprover-community/mathlib4/issues/12227
/-- info: Ring.toNonAssocRing.toNonUnitalNonAssocSemiring -/
#guard_msgs in
variable {A : Type} [NormedRing A] [NormedAlgebra ℂ A] [StarRing A]
[CStarRing A] [StarModule ℂ A] (x : A) in
#synth NonUnitalNonAssocSemiring (StarAlgebra.elemental ℂ x)
end
section
open Real in
-- Initial issue: https://github.com/leanprover-community/mathlib4/issues/12229
set_option synthInstance.maxHeartbeats 10000 in
example : Circle.exp (2 * π) = 1 := by simp
end
section
open Complex in
set_option synthInstance.maxHeartbeats 3200 in
-- Initial issue: https://github.com/leanprover-community/mathlib4/issues/12230
example (x : ℝ) : ‖cos x + sin x * I‖ = 1 := by simp
end
section
variable {α m n : Type*}
open Matrix in
set_option synthInstance.maxHeartbeats 2000 in
-- Initial issue: https://github.com/leanprover-community/mathlib4/issues/12231
example [AddCommGroup α] [StarAddMonoid α] [Module ℚ α] (c : ℚ)
(M : Matrix m n α) : (c • M)ᴴ = c • Mᴴ := by simp
end
section
open Equiv in
set_option synthInstance.maxHeartbeats 1000 in
-- Initial issue: https://github.com/leanprover-community/mathlib4/issues/12232
-- reduced from 9000 to 1000 after `@[simp low] map_zero` in https://github.com/leanprover-community/mathlib4/pull/16679 (only 10 needed)
example {n : ℕ} (p : Fin (n + 1)) (e : Perm (Fin n)) :
Equiv.Perm.decomposeFin.symm (p, e) 0 = p := by simp
end
section
variable (σ k : Type*) [Field k] [IsAlgClosed k] [Finite σ] (I : Ideal (MvPolynomial σ k)) in
set_option synthInstance.maxHeartbeats 1000 in
-- synthinstance heartbeat count was reduced from 20000 to 500 in the fix at https://github.com/leanprover-community/mathlib4/pull/21449
-- This fixes the failing simpNF of `MvPolynomial.vanishingIdeal_zeroLocus_eq_radical`
/--
error: failed to synthesize
I.IsPrime
Hint: Additional diagnostic information may be available using the `set_option diagnostics true` command.
-/
#guard_msgs in
#synth I.IsPrime
end |
.lake/packages/mathlib/MathlibTest/measurability.lean | import Mathlib.MeasureTheory.MeasurableSpace.Basic
import Mathlib.MeasureTheory.Constructions.BorelSpace.Basic
import Mathlib.MeasureTheory.Function.SpecialFunctions.Basic
import Mathlib.MeasureTheory.Function.SpecialFunctions.Inner
import Mathlib.MeasureTheory.Function.StronglyMeasurable.Lemmas
open MeasureTheory TopologicalSpace
variable {α β : Type*} [MeasurableSpace α] [MeasurableSpace β]
{f g : α → β} {s₁ s₂ : Set α} {t₁ t₂ : Set β} {μ ν : MeasureTheory.Measure α}
set_option linter.unusedVariables false
-- Test the use of assumption
example (hf : Measurable f) : Measurable f := by measurability
-- Test that intro does not unfold `Measurable`
example : Measurable f → Measurable f := by measurability
-- Test the use of apply_assumption to get (h i) from a hypothesis (h : ∀ i, ...).
example {F : ℕ → α → β} (hF : ∀ i, Measurable (F i)) : Measurable (F 0) := by measurability
example {ι} [Encodable ι] {S₁ S₂ : ι → Set α} (hS₁ : ∀ i, MeasurableSet (S₁ i))
(hS₂ : ∀ i, MeasurableSet (S₂ i)) : MeasurableSet (⋃ i, (S₁ i) ∪ (S₂ i)) := by measurability
-- Tests on sets
example (hs₁ : MeasurableSet s₁) (hs₂ : MeasurableSet s₂) : MeasurableSet (s₁ ∪ s₁) := by
measurability
example {ι} [Encodable ι] {S : ι → Set α} (hs : ∀ i, MeasurableSet (S i)) :
MeasurableSet (⋃ i, S i) := by measurability
example (hf : Measurable f) (hs₁ : MeasurableSet s₁) (ht₂ : MeasurableSet t₂) :
MeasurableSet ((f ⁻¹' t₂) ∩ s₁) := by measurability
-- Strong measurability
section strong_measurability
variable [TopologicalSpace β] [PseudoMetrizableSpace β] [BorelSpace β]
-- Test the use of apply_assumption to get (h i) from a hypothesis (h : ∀ i, ...).
example {F : ℕ → α → β} (hF : ∀ i, StronglyMeasurable (F i)) : Measurable (F 0) := by
measurability
example [Zero β] {F : ℕ → α → β} (hF : ∀ i, AEFinStronglyMeasurable (F i) μ) :
AEMeasurable (F 0) μ := by measurability
example {ι} [Encodable ι] {S₁ S₂ : ι → Set α} (hS₁ : ∀ i, MeasurableSet (S₁ i))
(hS₂ : ∀ i, MeasurableSet (S₂ i)) : MeasurableSet (⋃ i, (S₁ i) ∪ (S₂ i)) := by measurability
end strong_measurability
/-- `ℝ` is a good test case because it verifies many assumptions, hence many lemmas apply and we
are more likely to detect a bad lemma. In a previous version of the tactic, `measurability` got
stuck trying to apply `Set.Finite.MeasurableSet` here. -/
example {a b : ℝ} : MeasurableSet (Set.Icc a b) := by measurability
-- Tests on functions
example [Mul β] [MeasurableMul₂ β] (hf : Measurable f) (c : β) :
Measurable (fun x => c * f x) := by measurability -- uses const_mul, not mul
example [Add β] [MeasurableAdd₂ β] (hf : Measurable f) (hg : Measurable g) :
Measurable (fun x => f x + g x) := by measurability
example [Add β] [MeasurableAdd₂ β] (hf : Measurable f) (hg : AEMeasurable g μ) :
AEMeasurable (fun x => f x + g x) μ := by measurability
example [Div β] [MeasurableDiv₂ β] (hf : Measurable f) (hg : Measurable g)
(ht : MeasurableSet t₂) : MeasurableSet ((fun x => f x / g x) ⁻¹' t₂) := by measurability
example [AddCommMonoid β] [MeasurableAdd₂ β] {s : Finset ℕ} {F : ℕ → α → β}
(hF : ∀ i, Measurable (F i)) : Measurable (∑ i ∈ s, (fun x => F (i+1) x + F i x)) := by
fun_prop
example [AddCommMonoid β] [MeasurableAdd₂ β] {s : Finset ℕ} {F : ℕ → α → β}
(hF : ∀ i, AEMeasurable (F i) μ) : AEMeasurable (∑ i ∈ s, (fun x => F (i+1) x + F i x)) μ := by
measurability
-- even with many assumptions, the tactic is not trapped by a bad lemma
example [TopologicalSpace α] [BorelSpace α] [NormedAddCommGroup β] [BorelSpace β]
[MeasurableAdd₂ β] [MeasurableSub₂ β] {s : Finset ℕ} {F : ℕ → α → β}
(hF : ∀ i, Measurable (F i)) : AEMeasurable (∑ i ∈ s, (fun x => F (i+1) x - F i x)) μ := by
measurability
open scoped RealInnerProductSpace
/- We use a general inner product space to prevent the inner product from being simplified to
multiplication. An earlier version of the tactic failed on the following examples without this
simplification. -/
variable {E : Type*} (v : E) [NormedAddCommGroup E] [InnerProductSpace ℝ E] [MeasurableSpace E]
[OpensMeasurableSpace E] [SecondCountableTopology E]
example : Measurable (fun x : E => Real.exp (2 * ⟪v, x⟫)) := by measurability
example : StronglyMeasurable (fun x : E => Real.exp (2 * ⟪v, x⟫)) := by measurability
example {γ : MeasureTheory.Measure E} :
AEMeasurable (fun x : E => Real.exp (2 * ⟪v, x⟫)) γ := by measurability
example {γ : MeasureTheory.Measure E} :
AEStronglyMeasurable (fun x : E => Real.exp (2 * ⟪v, x⟫)) γ := by measurability
example {γ : MeasureTheory.Measure E} [SigmaFinite γ] :
FinStronglyMeasurable (fun x : E => Real.exp (2 * ⟪v, x⟫)) γ := by measurability
example {γ : MeasureTheory.Measure E} [SigmaFinite γ] :
AEFinStronglyMeasurable (fun x : E => Real.exp (2 * ⟪v, x⟫)) γ := by measurability
/-- An older version of the tactic failed in the presence of a negated hypothesis due to an
internal call to `apply_assumption`. -/
example {ι : Type _} (i k : ι) (hik : i ≠ k) : Measurable (id : α → α) := by measurability
--This search problem loops (StronglyMeasurable -> Measurable -> StronglyMeasurable) but fails
--quickly nevertheless.
--example (f : ℝ → ℝ) : StronglyMeasurable f := by measurability
-- Test that goals involving nested `Measurable` and `MeasurableSet` conditions are solved
example {s t : Set ℝ} {f : ℝ → ℝ} (hs : MeasurableSet s) (hf : Measurable f) :
Measurable (fun x : ℝ => (s ∩ (fun y => s.indicator f y) ⁻¹' s).indicator f (f x)) := by
measurability
-- Test that `measurability` does not solve out-of-scope `fun_prop` goals
example : Continuous (fun x : ℝ => x) := by
fail_if_success measurability
exact continuous_id |
.lake/packages/mathlib/MathlibTest/import_all.lean | import Lean
import Std
import Qq
import Batteries
import Aesop
import ProofWidgets
import Mathlib
import Plausible
/-!
Verify that Mathlib and all its upstream dependencies can be simultaneously imported.
We don't `import Cli` or `import ImportGraph` here as these are only used by scripts,
and may not have been built during CI when we run the tests.
-/ |
.lake/packages/mathlib/MathlibTest/module.lean | import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.LinearCombination
import Mathlib.Tactic.Module
import Mathlib.Tactic.NoncommRing
import Mathlib.Tactic.Positivity
/-! # Tests for the module-normalization tactic -/
open Mathlib.Tactic.LinearCombination
variable {V : Type*} {K : Type*} {t u v w x y z : V} {a b c d e f μ ν ρ : K}
/-! ### `ℕ` (most tests copied from the `abel` tactic) -/
section Nat
variable [AddCommMonoid V]
example : x + (y + x) = x + x + y := by module
example : (3 : ℕ) • x = x + (2 : ℕ) • x := by module
example : 0 + x = x := by module
example (n : ℕ) : n • x = n • x := by module
example (n : ℕ) : 0 + n • x = n • x := by module
example : x + (y + (x + (z + (x + (u + (x + v)))))) = v + u + z + y + 4 • x := by module
example : x + y = y + x := by module
example : x + 2 • x = 2 • x + x := by module
example : x + (y + x) = x + x + y ∨ False := by
left
module
/--
error: unsolved goals
V : Type u_1
K : Type u_2
t u v w x y z : V
a b c d e f μ ν ρ : K
inst✝ : AddCommMonoid V
⊢ 1 = 1
V : Type u_1
K : Type u_2
t u v w x y z : V
a b c d e f μ ν ρ : K
inst✝ : AddCommMonoid V
⊢ 1 = 2 * 1
-/
#guard_msgs in
example : x + y = x + 2 • y := by match_scalars
/--
error: ring failed, ring expressions not equal
V : Type u_1
K : Type u_2
t u v w x y z : V
a b c d e f μ ν ρ : K
inst✝ : AddCommMonoid V
⊢ 1 = 2
-/
#guard_msgs in
example : x + y = x + 2 • y := by module
/-- error: goal x ≠ y is not an equality -/
#guard_msgs in
example : x ≠ y := by module
end Nat
/-! ### `ℤ` (most tests copied from the `abel` tactic) -/
variable [AddCommGroup V]
example : (x + y) - ((y + x) + x) = -x := by module
example : x - 0 = x := by module
example : (3 : ℤ) • x = x + (2 : ℤ) • x := by module
example : x - 2 • y = x - 2 • y := by module
example : (x + y) - ((y + x) + x) = -x := by module
example : x + y + (z + w - x) = y + z + w := by module
example : x + y + z + (z - x - x) = (-1) • x + y + 2 • z := by module
example : -x + x = 0 := by module
example : x - (0 - 0) = x := by module
example : x + (y - x) = y := by module
example : -y + (z - x) = z - y - x := by module
example : x + y = y + x ∧ (↑((1:ℕ) + 1) : ℚ) = 2 := by
constructor
module -- do not focus this tactic: the double goal is the point of the test
guard_target =ₐ (↑((1:ℕ) + 1) : ℚ) = 2
norm_cast
-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Interaction.20of.20abel.20with.20casting/near/319895001
example : True := by
have : ∀ (p q r s : V), s + p - q = s - r - (q - r - p) := by
intro p q r s
module
trivial
example : True := by
have : ∀ (p q r s : V), s + p - q = s - r - (q - r - p) := by
intro p q r s
match_scalars
· decide
· decide
· decide
· decide
trivial
-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Interaction.20of.20abel.20with.20casting/near/319897374
example : y = x + z - (x - y + z) := by
have : True := trivial
module
example : y = x + z - (x - y + z) := by
have : True := trivial
match_scalars <;> decide
/--
error: unsolved goals
V : Type u_1
K : Type u_2
t u v w x y z : V
a b c d e f μ ν ρ : K
inst✝ : AddCommGroup V
⊢ -1 + 1 = 0
-/
#guard_msgs in
example : -x + x = 0 := by
match_scalars
/-! ### Commutative ring -/
section CommRing
variable [CommRing K] [Module K V]
example : a • x + b • x = (a + b) • x := by module
example : a • x - b • x = (a - b) • x := by module
example : a • x - b • y = a • x + (-b) • y := by module
example : 2 • a • x = a • 2 • x := by module
example : a • x - b • y = a • x + (-b) • y := by module
example : (μ - ν) • a • x = (a • μ • x + b • ν • y) - ν • (a • x + b • y) := by module
example : (μ - ν) • b • y = μ • (a • x + b • y) - (a • μ • x + b • ν • y) := by module
-- from https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/smul.20diamond/near/457163013
example : (4 : ℤ) • v = (4 : K) • v := by module
example : (4 : ℕ) • v = (4 : K) • v := by module
-- from https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/linear_combination.20for.20groups/near/437042918
example : (1 + a ^ 2) • (v + w) - a • (a • v - w) = v + (1 + a + a ^ 2) • w := by module
example (h : a = b) : a • x = b • x := by
match_scalars
linear_combination h
example (h : a = b) : a • x = b • x := by
linear_combination (norm := module) h • x
example (h : a ^ 2 + b ^ 2 = 1) : a • (a • x - b • y) + (b • a • y + b • b • x) = x := by
match_scalars
· linear_combination h
· ring
example (h : a ^ 2 + b ^ 2 = 1) : a • (a • x - b • y) + (b • a • y + b • b • x) = x := by
linear_combination (norm := module) h • x
example (h1 : a • x + b • y = 0) (h2 : a • μ • x + b • ν • y = 0) :
(μ - ν) • a • x = 0 ∧ (μ - ν) • b • y = 0 := by
constructor
· linear_combination (norm := module) h2 - ν • h1
· linear_combination (norm := module) μ • h1 - h2
example (h1 : 0 • z + a • x + b • y = 0) (h2 : 0 • ρ • z + a • μ • x + b • ν • y = 0) :
(μ - ν) • a • x = 0 := by
linear_combination (norm := module) h2 - ν • h1
example
(h1 : a • x + b • y + c • z = 0)
(h2 : a • μ • x + b • ν • y + c • ρ • z = 0)
(h3 : a • μ • μ • x + b • ν • ν • y + c • ρ • ρ • z = 0) :
(μ - ν) • (μ - ρ) • a • x = 0 ∧ (μ - ν) • (ν - ρ) • b • y = 0
∧ (μ - ρ) • (ν - ρ) • c • z = 0 := by
refine ⟨?_, ?_, ?_⟩
· linear_combination (norm := module) h3 - (ν + ρ) • h2 + ν • ρ • h1
· linear_combination (norm := module) - h3 + (μ + ρ) • h2 - μ • ρ • h1
· linear_combination (norm := module) h3 - (μ + ν) • h2 + μ • ν • h1
/--
error: ring failed, ring expressions not equal
V : Type u_1
K : Type u_2
t u v w x y z : V
a b c d e f μ ν ρ : K
inst✝² : AddCommGroup V
inst✝¹ : CommRing K
inst✝ : Module K V
⊢ a * 2 = 2
-/
#guard_msgs in
example : 2 • a • x = 2 • x := by module
end CommRing
/-! ### (Noncommutative) ring -/
section Ring
variable [Ring K] [Module K V]
example : a • x + b • x = (b + a) • x := by
match_scalars
noncomm_ring
example : 2 • a • x = a • (2:ℤ) • x := by
match_scalars
noncomm_ring
example (h : a = b) : a • x = b • x := by
match_scalars
simp [h]
example : (a - b) • a • x + b • b • x = a • a • x + b • (-a + b) • x := by
match_scalars
noncomm_ring
end Ring
/-! ### Characteristic-zero field -/
section CharZeroField
variable [Field K] [CharZero K] [Module K V]
example : (2:K)⁻¹ • x + (3:K)⁻¹ • x + (6:K)⁻¹ • x = x := by module
example (h₁ : t - u = -(v - w)) (h₂ : t + u = v + w) : t = w := by
linear_combination (norm := module) (2:K)⁻¹ • h₁ + (2:K)⁻¹ • h₂
end CharZeroField
/-! ### Linearly ordered field -/
section LinearOrderedField
variable [Field K] [LinearOrder K] [IsStrictOrderedRing K] [Module K V]
example (ha : 0 ≤ a) (hb : 0 < b) :
x = (a / (a + b)) • y + (b / (a + b)) • (x + (a / b) • (x - y)) := by
match_scalars
· field_simp
ring
· field_simp
ring
-- From Analysis.Convex.StoneSeparation
example (hab : 0 < a * b + c * d) :
(a * b / (a * b + c * d) * e) • u + (c * d / (a * b + c * d) * f) • v +
((a * b / (a * b + c * d)) • d • x + (c * d / (a * b + c * d)) • b • y) =
(a * b + c * d)⁻¹ • ((a * b * e) • u + ((c * d * f) • v +
((a * b) • d • x + (c * d) • b • y))) := by
match_scalars
· field_simp
· field_simp
· field_simp
· field_simp
example (h₁ : 1 = a ^ 2 + b ^ 2) (h₂ : 1 - a ≠ 0) :
((2 / (1 - a)) ^ 2 * b ^ 2 + 4)⁻¹ • (4:K) • ((2 / (1 - a)) • y)
+ ((2 / (1 - a)) ^ 2 * b ^ 2 + 4)⁻¹ • ((2 / (1 - a)) ^ 2 * b ^ 2 - 4) • x
= a • x + y := by
linear_combination (norm := skip) (h₁ * (b ^ 2 + (1 - a) ^ 2)⁻¹) • (y + (a - 1) • x)
match_scalars
· field_simp
ring
· field_simp
ring
example (h₁ : 1 = a ^ 2 + b ^ 2) (h₂ : 1 - a ≠ 0) :
((2 / (1 - a)) ^ 2 * b ^ 2 + 4)⁻¹ • (4:K) • ((2 / (1 - a)) • y)
+ ((2 / (1 - a)) ^ 2 * b ^ 2 + 4)⁻¹ • ((2 / (1 - a)) ^ 2 * b ^ 2 - 4) • x
= a • x + y := by
match_scalars
· field_simp
linear_combination 4 * h₁
· field_simp
linear_combination 4 * (a - 1) * h₁
end LinearOrderedField |
.lake/packages/mathlib/MathlibTest/ring.lean | import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Ring
private axiom test_sorry : ∀ {α}, α
set_option autoImplicit true
-- We deliberately mock R here so that we don't have to import the deps
axiom Real : Type
notation "ℝ" => Real
@[instance] axiom Real.field : Field ℝ
@[instance] axiom Real.linearOrder : LinearOrder ℝ
@[instance] axiom Real.isStrictOrderedRing : IsStrictOrderedRing ℝ
example {a b c : ℝ} {f : ℝ → ℝ} (h : f (a * c * b) * f (c + b + a) = 1) :
f (a + b + c) * f (b * a * c) = 1 := by
ring_nf at *
exact h
example (x y : ℕ) : x + y = y + x := by ring
example (x y : ℕ) : x + y + y = 2 * y + x := by ring
example (x y : ℕ) : x + id y = y + id x := by ring!
example (x y : ℕ+) : x + y = y + x := by ring
example {α} [CommRing α] (x y : α) : x + y + y - x = 2 * y := by ring
example {α} [CommSemiring α] (x y : α) : (x + y)^2 = x^2 + 2 • x * y + y^2 := by ring
example (x y : ℕ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example (x y : ℕ+) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example (x y : ℝ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example {α} [CommSemiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by ring
example (n : ℕ) : (n / 2) + (n / 2) = 2 * (n / 2) := by ring
example {α} [Field α] [CharZero α] (a : α) : a / 2 = a / 2 := by ring
example {α} [Field α] [LinearOrder α] [IsStrictOrderedRing α] (a b c : α) :
a * (-c / b) * (-c / b) + -c + c = a * (c / b * (c / b)) := by ring
example {α} [Field α] [LinearOrder α] [IsStrictOrderedRing α] (a b c : α) :
b ^ 2 - 4 * c * a = -(4 * c * a) + b ^ 2 := by ring
example {α} [CommSemiring α] (x : α) : x ^ (2 + 2) = x^4 := by ring1
example {α} [CommSemiring α] (x : α) : x ^ (2 + 2) = x^4 := by ring
example {α} [CommRing α] (x : α) : x ^ 2 = x * x := by ring
-- example {α} [CommRing α] (x : α) : x ^ (2 : ℤ) = x * x := by ring
example {α} [Field α] [LinearOrder α] [IsStrictOrderedRing α] (a b c : α) :
b ^ 2 - 4 * c * a = -(4 * c * a) + b ^ 2 := by ring
example {α} [Field α] [LinearOrder α] [IsStrictOrderedRing α] (a b c : α) :
b ^ 2 - 4 * a * c = 4 * a * 0 + b * b - 4 * a * c := by ring
example {α} [CommSemiring α] (x y z : α) (n : ℕ) :
(x + y) * (z * (y * y) + (x * x ^ n + (1 + ↑n) * x ^ n * y)) =
x * (x * x ^ n) + ((2 + ↑n) * (x * x ^ n) * y +
(x * z + (z * y + (1 + ↑n) * x ^ n)) * (y * y)) := by ring
example {α} [CommRing α] (a b c d e : α) :
(-(a * b) + c + d) * e = (c + (d + -a * b)) * e := by ring
example (a n s : ℕ) : a * (n - s) = (n - s) * a := by ring
example {α} [CommRing α] (x : α) : (2 : ℕ) • x = x + x := by ring
example {α} [CommRing α] (x : α) : (2 : ℤ) • x = x + x := by ring
example {α} [CommRing α] (x : α) : (-2 : ℤ) • x = -x - x := by ring
section Rat
variable [Field α]
example (x : ℚ) : x / 2 + x / 2 = x := by ring
example (x : α) : x / 2 = x / 2 := by ring1
example : (1 + 1)⁻¹ = (2⁻¹ : α) := by ring1
example (x : α) : x⁻¹ ^ 2 = (x ^ 2)⁻¹ := by ring1
example (x : α) : x⁻¹ ^ 2 = (x ^ 2)⁻¹ := by ring1
example (x y : α) : x * y⁻¹ = y⁻¹ * x := by ring1
example (x y : α) : (x^2 * y)⁻¹ = (y * x^2)⁻¹ := by ring1
example (x y : α) : (x^2)⁻¹ / y = (y * x^2)⁻¹ := by ring1
example (x y : α) : 3 / (x - x + y)⁻¹ = 3 * (x + y⁻¹ - x)⁻¹ := by ring1
variable [CharZero α]
example (x : α) : x / 2 = x / 2 := by ring
example (x : α) : (x : α) = x * (5/3)*(3/5) := by ring1
end Rat
example (A : ℕ) : (2 * A) ^ 2 = (2 * A) ^ 2 := by ring
example (x y z : ℚ) (hx : x ≠ 0) (hy : y ≠ 0) :
x / (y / z) + y ⁻¹ + 1 / (y * -x) = -1/ (x * y) + (x * z + 1) / y := by
field_simp
ring
example (a b c d x y : ℚ) (hx : x ≠ 0) (hy : y ≠ 0) :
a + b / x - c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x - c) / x) := by
field_simp
ring
example : (876544 : ℤ) * -1 + (1000000 - 123456) = 0 := by ring
example (x : ℝ) (hx : x ≠ 0) :
2 * x ^ 3 * 2 / (24 * x) = x ^ 2 / 6 := by
field_simp
ring
-- As reported at
-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/ring_nf.20failing.20to.20fully.20normalize
example (x : ℤ) (h : x - x + x = 0) : x = 0 := by
ring_nf at h
exact h
-- this proof style is not recommended practice
example (A B : ℕ) (H : B * A = 2) : A * B = 2 := by ring_nf at H ⊢; exact H
example (f : ℕ → ℕ) :
2 + f (2 * f 3 * f 3) + f 3 = 1 + f (f 3 ^ 2 + f 3 * f 3) + 1 + f (2 + 1) := by ring_nf
example (n : ℕ) (m : ℤ) : 2^(n + 1) * m = 2 * 2^n * m := by ring
example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring
example (x y : ℕ) : x + id y = y + id x := by ring!
-- Example with ring discharging the goal
example : 22 + 7 * 4 + 3 * 8 = 0 + 7 * 4 + 46 := by
conv => ring
trivial -- FIXME: not needed in lean 3
-- Example with ring failing to discharge, to normalizing the goal
/--
info: Try this:
[apply] ring_nf
⏎
The `ring` tactic failed to close the goal. Use `ring_nf` to obtain a normal form.
⏎
Note that `ring` works primarily in *commutative* rings. If you have a noncommutative ring, abelian group or module, consider using `noncomm_ring`, `abel` or `module` instead.
-/
#guard_msgs in
example : (22 + 7 * 4 + 3 * 8 = 0 + 7 * 4 + 47) = (74 = 75) := by
conv => ring
trivial
-- Example with ring discharging the goal
example (x : ℕ) : 22 + 7 * x + 3 * 8 = 0 + 7 * x + 46 := by
conv => ring
trivial
-- Example with ring failing to discharge, to normalizing the goal
/--
info: Try this:
[apply] ring_nf
⏎
The `ring` tactic failed to close the goal. Use `ring_nf` to obtain a normal form.
⏎
Note that `ring` works primarily in *commutative* rings. If you have a noncommutative ring, abelian group or module, consider using `noncomm_ring`, `abel` or `module` instead.
-/
#guard_msgs in
example (x : ℕ) : (22 + 7 * x + 3 * 8 = 0 + 7 * x + 46 + 1)
= (7 * x + 46 = 7 * x + 47) := by
conv => ring
trivial
-- check that mdata is consumed
noncomputable def f : Nat → Nat := test_sorry
example (a : Nat) : 1 * f a * 1 = f (a + 0) := by
have ha : a + 0 = a := by ring
rw [ha] -- goal has mdata
ring1
-- check that mdata is consumed by ring_nf
example (a b : ℤ) : a+b=0 ↔ b+a=0 := by
have : 3 = 3 := rfl
ring_nf -- reduced to `True` with mdata
-- Powers in the exponent get evaluated correctly
example (X : ℤ) : (X^5 + 1) * (X^2^3 + X) = X^13 + X^8 + X^6 + X := by ring
-- simulate the type of MvPolynomial
def R : Type u → Type v → Sort (max (u+1) (v+1)) := test_sorry
noncomputable instance : CommRing (R a b) := test_sorry
example (p : R PUnit.{u + 1} PUnit.{v + 1}) : p + 0 = p := by
ring
example (p q : R PUnit.{u + 1} PUnit.{v + 1}) : p + q = q + p := by
ring
example (p : R PUnit.{u + 1} PUnit.{v + 1}) : p + 0 = p := by
ring_nf
example (p q : R PUnit.{u + 1} PUnit.{v + 1}) : p + q = q + p := by
ring_nf
-- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/ring_nf.20returns.20ugly.20literals/near/400988184
example {n : ℝ} :
(n + 1 / 2) ^ 2 * (n + 1 + 1 / 3) = 1 / 3 + n * (19 / 12) + n ^ 2 * (7 / 3) + n ^ 3 := by
-- `conv_lhs` prevents `ring_nf` picking a bad normalization for both sides.
conv_lhs => ring_nf
-- We can't use `guard_target =ₛ` here, as while it does detect stray `OfNat`s, it also complains
-- about differing instance paths.
/--
trace: n : ℝ
_hn : 0 ≤ n
⊢ 1 / 3 + n * (19 / 12) + n ^ 2 * (7 / 3) + n ^ 3 ≤ 1 / 3 + n * (5 / 3) + n ^ 2 * (7 / 3) + n ^ 3
-/
#guard_msgs (trace) in
example {n : ℝ} (_hn : 0 ≤ n) : (n + 1 / 2) ^ 2 * (n + 1 + 1 / 3) ≤ (n + 1 / 3) * (n + 1) ^ 2 := by
ring_nf
trace_state
exact test_sorry
section
abbrev myId (a : ℤ) : ℤ := a
/-
Test that when `ring_nf` normalizes multiple expressions which contain a particular atom, it uses a
form for that atom which is consistent between expressions.
We can't use `guard_hyp h :ₛ` here, as while it does tell apart `x` and `myId x`, it also complains
about differing instance paths.
-/
/--
trace: x : ℤ
R : ℤ → ℤ → Prop
h : R (myId x * 2) (myId x * 2)
⊢ True
-/
#guard_msgs (trace) in
example (x : ℤ) (R : ℤ → ℤ → Prop) : True := by
have h : R (myId x + x) (x + myId x) := test_sorry
ring_nf at h
trace_state
trivial
end
-- new behaviour as of https://github.com/leanprover-community/mathlib4/issues/27562
-- (Previously, because of a metavariable instantiation issue, the tactic succeeded as a no-op.)
/-- error: ring_nf made no progress at h -/
#guard_msgs in
example {R : Type*} [CommSemiring R] {x y : R} : True := by
have h : x + y = 3 := test_sorry
ring_nf at h
-- Test that `ring_nf` doesn't unfold local let expressions, and `ring_nf!` does
set_option linter.unusedTactic false in
example (x : ℝ) (f : ℝ → ℝ) : True := by
let y := x
/-
Two of these fail, and two of these succeed in rewriting the instance, so it's not a good idea
to use `fail_if_success` since the instances could change without warning.
-/
have : x = y := by
ring_nf -failIfUnchanged
ring_nf!
have : x - y = 0 := by
ring_nf -failIfUnchanged
ring_nf!
have : f x = f y := by
ring_nf -failIfUnchanged
ring_nf!
have : f x - f y = 0 := by
ring_nf -failIfUnchanged
ring_nf!
trivial
-- Test that `ring_nf` doesn't get confused about bound variables
example : (fun x : ℝ => x * x^2) = (fun y => y^2 * y) := by
ring_nf
-- Test that `ring` works for division without subtraction
example {R : Type} [Semifield R] [CharZero R] {x : R} : x / 2 + x / 2 = x := by ring |
.lake/packages/mathlib/MathlibTest/Multigoal.lean | import Mathlib.Tactic.Basic
import Mathlib.Tactic.Conv
import Mathlib.Tactic.Linter.Multigoal
import Mathlib.Util.SleepHeartbeats
import Mathlib.Tactic.SuccessIfFailWithMsg
set_option linter.style.multiGoal true
-- A deactivated linter does nothing.
set_option linter.style.multiGoal false in
example : True := by
by_cases 0 = 0
exact .intro
exact .intro
#guard_msgs(drop warning) in
/--
warning: The following tactic starts with 2 goals and ends with 1 goal, 1 of which is not operated on.
exact .intro
Please focus on the current goal, for instance using `·` (typed as "\.").
Note: This linter can be disabled with `set_option linter.style.multiGoal false`
-/
#guard_msgs in
example : True := by
by_cases 0 = 0
exact .intro
exact .intro
#guard_msgs(drop warning) in
/--
warning: The following tactic starts with 2 goals and ends with 1 goal, 1 of which is not operated on.
assumption
Please focus on the current goal, for instance using `·` (typed as "\.").
Note: This linter can be disabled with `set_option linter.style.multiGoal false`
-/
#guard_msgs in
example {n : Nat} (hn : n = 0) : n + 0 = 0 := by
conv =>
congr
rw [← Nat.add_zero 0]
conv_lhs =>
congr
rw [← Nat.add_zero n]
rfl
conv_rhs =>
rw [← Nat.add_zero 0]
congr
rfl
rfl
by_cases 0 = 0
assumption
assumption
set_option linter.unusedTactic false in
#guard_msgs(drop warning) in
/--
warning: The following tactic starts with 2 goals and ends with 1 goal, 1 of which is not operated on.
rfl
Please focus on the current goal, for instance using `·` (typed as "\.").
Note: This linter can be disabled with `set_option linter.style.multiGoal false`
-/
#guard_msgs in
example (p : Prop) (hp : p) : (0 = 0 ∧ p) ∨ 0 = 0 := by
iterate left; decide
repeat' left; decide
refine Or.inl ⟨?_, ?_⟩
rfl
assumption
#guard_msgs(drop warning) in
/--
warning: The following tactic starts with 3 goals and ends with 2 goals, 2 of which are not operated on.
rfl
Please focus on the current goal, for instance using `·` (typed as "\.").
Note: This linter can be disabled with `set_option linter.style.multiGoal false`
---
warning: The following tactic starts with 2 goals and ends with 1 goal, 1 of which is not operated on.
trivial
Please focus on the current goal, for instance using `·` (typed as "\.").
Note: This linter can be disabled with `set_option linter.style.multiGoal false`
-/
#guard_msgs in
example : 0 = 0 ∧ 0 = 0 ∧ 0 = 0 := by
refine ⟨?_, ?_, ?_⟩
rfl
trivial
rfl
example (p : Bool) : 0 = 0 := by
cases p
case' false => rfl
case' true => rfl
#guard_msgs in
-- `assumption'` is allowed, as it is useful precisely when there are multiple active goals.
example (p : Bool) (f : False) {h : 0 = 0} : 0 = 0 ∧ 0 = 1 := by
cases p <;>
constructor
assumption'
any_goals cases f
#guard_msgs in
-- `focus` is ignored.
example : True ∧ True := by
constructor
focus
exact .intro
focus
exact .intro
set_option linter.unusedTactic false in
example : 1 = 1 := by
sleep_heartbeats 1000
rfl
-- We test that a tactic closing all remaining goals does not trigger the linter.
macro "bi_trivial" : tactic => `(tactic| (trivial; trivial))
example : True ∧ True := by
constructor
bi_trivial
-- Exclude `fail_if_success` and `success_if_fail_with_msg` from linting.
example : True := by
fail_if_success done
success_if_fail_with_msg "internal exception #5" done
exact .intro
/-!
Testing that it does not flag tactics that do nothing.
This used to trigger the multigoal linter.
-/
elab "my_skip" : tactic => pure ()
set_option linter.unusedTactic false in
example : True := by
my_skip
trivial
-- Test the linter applies within have statements
#guard_msgs(drop warning) in
/--
warning: The following tactic starts with 2 goals and ends with 1 goal, 1 of which is not operated on.
trivial
Please focus on the current goal, for instance using `·` (typed as "\.").
Note: This linter can be disabled with `set_option linter.style.multiGoal false`
-/
#guard_msgs in
example : true ∧ true := by
have : true ∧ true := by
constructor
trivial
trivial
exact this |
.lake/packages/mathlib/MathlibTest/DefEqTransformations.lean | import Mathlib.Tactic.DefEqTransformations
set_option autoImplicit true
private axiom test_sorry : ∀ {α}, α
namespace Tests
set_option linter.unusedTactic false
example : id (1 = 1) := by
with_reducible whnf
guard_target =ₛ id (1 = 1)
whnf
guard_target =ₛ 1 = 1
rfl
example : (fun x => 1 + x) 1 = 2 := by
beta_reduce
guard_target =ₛ 1 + 1 = 2
rfl
example : (fun x => 1 + x) 2 = (fun y => 2 + y) 3 := by
conv =>
lhs
beta_reduce
guard_target =ₛ 1 + 2
guard_target =ₛ 1 + 2 = (fun y => 2 + y) 3
exact test_sorry
example : 1 + 2 * 3 = 7 := by
reduce
guard_target =ₛ nat_lit 7 = nat_lit 7
rfl
set_option linter.unusedVariables false in
example : let x := 1; let y := 2 + x; 2 + 1 = 3 := by
intro x y
refold_let x
guard_target =ₛ 2 + x = 3
refold_let y
guard_target =ₛ y = 3
rfl
example : 5 = 5 := by
let x := 5
refold_let x
guard_target =ₛ x = x
rfl
example : 2 + 1 = 3 := by
let a : Fin 1 := 0
let x := 1
let b : Fin 1 := 0
refold_let x at *
guard_hyp a :ₛ Fin 1 := 0
guard_hyp b :ₛ Fin x := 0
rfl
example : 1 + 2 = 2 + 1 := by
unfold_projs
guard_target =ₛ Nat.add (nat_lit 1) (nat_lit 2) = Nat.add (nat_lit 2) (nat_lit 1)
rfl
example (m n : Nat) : (m == n) = true := by
unfold_projs
guard_target =ₛ decide (m = n) = true
exact test_sorry
example {α : Type u} (f : α → α) (a : α) :
(fun x => (fun x => f x) x) a = f a := by
eta_reduce
guard_target =ₛ f a = f a
rfl
example (f : Nat → Nat) : (fun a => f a) = (fun a => f (f a)) := by
eta_expand
guard_target =ₛ (fun a => f a) = (fun a => f (f a))
eta_reduce
guard_target =ₛ f = fun a => f (f a)
eta_expand
guard_target =ₛ (fun a => f a) = (fun a => f (f a))
exact test_sorry
example : (fun (a b : Nat) => a + b) = (· + ·) := by
eta_reduce
guard_target =ₛ (HAdd.hAdd : Nat → Nat → Nat) = HAdd.hAdd
eta_expand
guard_target =ₛ (fun (a b : Nat) => a + b) = fun a b => a + b
rfl
example : (fun (a : Nat) => 1 + a) = (1 + ·) := by
eta_reduce
guard_target =ₛ (HAdd.hAdd 1) = HAdd.hAdd 1
eta_expand
guard_target =ₛ (fun a ↦ 1 + a) = fun a ↦ 1 + a
rfl
example (f : Nat → Nat → Nat) : (fun x => f 1 x) 2 = 3 := by
eta_expand
guard_target =ₛ f 1 2 = 3
exact test_sorry
example : (fun (a : Nat) => 1 + a) 2 = (1 + ·) 2 := by
eta_expand
guard_target =ₛ 1 + 2 = 1 + 2
rfl
example (p : Nat × Nat) : (p.1, p.2) = (p.2, p.1) := by
eta_struct
guard_target =ₛ p = (p.2, p.1)
exact test_sorry
example (p : Nat × Nat) : ((p.1, p.2).1, (p.1, p.2).2) = ((p.1, p.2).2, (p.1, p.2).1) := by
eta_struct
guard_target =ₛ p = (p.2, p.1)
exact test_sorry
example (n : Fin 5) : n = ⟨n.1, n.2⟩ := by
eta_struct
guard_target =ₛ n = n
rfl
abbrev _root_.Fin.val2 : Fin n → Nat := Fin.val
abbrev _root_.Fin.prop2 (x : Fin n) : (x : Nat) < n := x.isLt
example (n : Fin 5) : n = ⟨n.val2, n.prop2⟩ := by
eta_struct
guard_target =ₛ n = n
rfl
end Tests |
.lake/packages/mathlib/MathlibTest/fast_instance.lean | import Mathlib.Tactic.FastInstance
import Mathlib.Logic.Function.Defs
import Mathlib.Tactic.Spread
namespace testing
set_option autoImplicit false
-- For debugging:
--set_option trace.Elab.fast_instance true
/-!
Testing a diamond: CommSemigroup
-/
class Mul (α : Type*) where
mul : α → α → α
class Semigroup (α : Type*) extends Mul α where
mul_assoc (x y z : α) : mul x (mul y z) = mul (mul x y) z
class CommMagma (α : Type*) extends Mul α where
mul_comm (x y : α) : mul x y = mul y x
class CommSemigroup (α : Type*) extends Semigroup α, CommMagma α
structure Wrapped (α : Type*) where
val : α
variable {α : Type*}
theorem val_injective : Function.Injective (Wrapped.val (α := α))
| ⟨_⟩, ⟨_⟩, rfl => rfl
instance [Mul α] : Mul (Wrapped α) where mul m n := ⟨Mul.mul m.1 n.1⟩
@[reducible] def Function.Injective.semigroup {α β : Type*} [Mul α] [Semigroup β]
(f : α → β) (hf : Function.Injective f)
(hmul : ∀ x y, f (Mul.mul x y) = Mul.mul (f x) (f y)) :
Semigroup α :=
{ ‹Mul α› with
mul_assoc := fun x y z => by apply hf; rw [hmul, hmul, hmul, hmul, Semigroup.mul_assoc] }
@[reducible] def Function.Injective.commMagma {α β : Type*} [Mul α] [CommMagma β]
(f : α → β) (hf : Function.Injective f)
(hmul : ∀ x y, f (Mul.mul x y) = Mul.mul (f x) (f y)) :
CommMagma α where
mul_comm x y := by
apply hf
rw [hmul, hmul, CommMagma.mul_comm]
@[reducible] def Function.Injective.commSemigroup {α β : Type*} [Mul α] [CommSemigroup β]
(f : α → β) (hf : Function.Injective f)
(hmul : ∀ x y, f (Mul.mul x y) = Mul.mul (f x) (f y)) :
CommSemigroup α where
toSemigroup := Function.Injective.semigroup f hf hmul
__ := Function.Injective.commMagma f hf hmul
instance instSemigroup [Semigroup α] : Semigroup (Wrapped α) :=
fast_instance% Function.Injective.semigroup _ val_injective (fun _ _ => rfl)
instance instCommSemigroup [CommSemigroup α] : CommSemigroup (Wrapped α) :=
fast_instance% Function.Injective.commSemigroup _ val_injective (fun _ _ => rfl)
/--
info: def testing.instSemigroup.{u_1} : {α : Type u_1} → [Semigroup α] → Semigroup (Wrapped α) :=
fun {α} [inst : Semigroup α] => @Semigroup.mk (Wrapped α) (@instMulWrapped α (@Semigroup.toMul α inst)) ⋯
-/
#guard_msgs in
set_option pp.explicit true in
#print instSemigroup
/--
info: def testing.instCommSemigroup.{u_1} : {α : Type u_1} → [CommSemigroup α] → CommSemigroup (Wrapped α) :=
fun {α} [inst : CommSemigroup α] =>
@CommSemigroup.mk (Wrapped α) (@instSemigroup α (@CommSemigroup.toSemigroup α inst)) ⋯
-/
#guard_msgs in
set_option pp.explicit true in
#print instCommSemigroup
/-!
Non-defeq error
-/
instance : Mul Nat := ⟨(· * · )⟩
/--
error: Provided instance
{ mul := fun x y => y * x }
is not defeq to inferred instance
instMulNat
Use `set_option trace.Elab.fast_instance true` to analyze the error.
Trace of fields visited: []
---
info: { mul := fun x y => y * x } : Mul Nat
-/
#guard_msgs in
#check fast_instance% { mul := fun x y => y * x : Mul Nat }
/-!
Checking handling of non-structure classes.
-/
class Dec (p : Prop) where
[dec : Decidable p]
axiom It : Prop
/-- warning: declaration uses 'sorry' -/
#guard_msgs in
abbrev dec1 : Decidable It := isTrue sorry
/-- warning: declaration uses 'sorry' -/
#guard_msgs in
def dec2 : Decidable It := isTrue sorry
/-- info: @Dec.mk It (@isTrue It dec1._proof_1) : Dec It -/
#guard_msgs in
set_option pp.explicit true in
#check fast_instance% { dec := dec1 : Dec It }
/--
error: Provided instance does not reduce to a constructor application
dec2
Reduces to an application of testing.dec2.
This instance is not a structure and not canonical. Use a separate 'instance' command to define it.
Use `set_option trace.Elab.fast_instance true` to analyze the error.
Trace of fields visited: [testing.Dec.dec]
---
info: @Dec.mk It dec2 : Dec It
-/
#guard_msgs in
set_option pp.explicit true in
#check fast_instance% { dec := dec2 : Dec It } |
.lake/packages/mathlib/MathlibTest/notation3.lean | import Mathlib.Util.Notation3
import Mathlib.Data.Nat.Basic
set_option linter.style.setOption false
set_option pp.unicode.fun true
set_option autoImplicit true
namespace Test
-- set_option trace.notation3 true
def Filter (α : Type) : Type := (α → Prop) → Prop
def Filter.atTop [Preorder α] : Filter α := fun _ => True
def Filter.eventually (p : α → Prop) (f : Filter α) := f p
notation3 "∀ᶠ " (...) " in " f ", " r:(scoped p => Filter.eventually p f) => r
/-- info: ∀ᶠ (x : ℕ) (y : ℕ) in Filter.atTop, x < y : Prop -/
#guard_msgs in #check ∀ᶠ (x : Nat) (y) in Filter.atTop, x < y
/-- info: ∀ᶠ (x : ℕ) in Filter.atTop, x < 3 : Prop -/
#guard_msgs in #check ∀ᶠ x in Filter.atTop, x < 3
/-!
Test that `pp.tagAppFns` causes tokens to be tagged with head constant.
-/
open Lean in
def findWithTag (tag : Nat) (f : Format) : List Format :=
match f with
| .nil => []
| .line => []
| .align _ => []
| .text _ => []
| .nest _ f' => findWithTag tag f'
| .append f' f'' => findWithTag tag f' ++ findWithTag tag f''
| .group f' _ => findWithTag tag f'
| .tag t f' => (if t = tag then [f'] else []) ++ findWithTag tag f'
open Lean Elab Term in
def testTagAppFns (n : Name) : TermElabM Unit := do
let stx ← `(∀ᶠ x in Filter.atTop, x < 3)
let e ← elabTermAndSynthesize stx none
let f ← Meta.ppExprWithInfos e
-- Find tags for the constant `n`
let tags : Array Nat := f.infos.foldl (init := #[]) fun tags tag info =>
match info with
| .ofTermInfo info | .ofDelabTermInfo info =>
if info.expr.isConstOf n then
tags.push tag
else
tags
| _ => tags
let fmts := tags.map (findWithTag · f.fmt)
unless fmts.all (!·.isEmpty) do throwError "missing tag"
let fmts := fmts.toList.flatten
logInfo m!"{repr <| fmts.map (·.pretty.trim)}"
section
/-- info: [] -/
#guard_msgs in #eval testTagAppFns ``Filter.eventually
set_option pp.tagAppFns true
/-- info: ["∀ᶠ", "in", ","] -/
#guard_msgs in #eval testTagAppFns ``Filter.eventually
end
-- Testing lambda expressions:
notation3 "∀ᶠ' " f ", " p => Filter.eventually (fun x => (p : _ → _) x) f
/-- info: ∀ᶠ' Filter.atTop, fun x ↦ x < 3 : Prop -/
#guard_msgs in #check ∀ᶠ' Filter.atTop, fun x => x < 3
def foobar (p : α → Prop) (f : Prop) := ∀ x, p x = f
notation3 "∀ᶠᶠ " (...) " in " f ": "
r1:(scoped p => Filter.eventually p f) ", " r2:(scoped p => foobar p r1) => r2
/-- info: ∀ᶠᶠ (x : ℕ) (y : ℕ) in Filter.atTop: x < y, x = y : Prop -/
#guard_msgs in #check ∀ᶠᶠ (x : Nat) (y) in Filter.atTop: x < y, x = y
/-- info: ∀ᶠᶠ (x : ℕ) in Filter.atTop: x < 3, x = 1 : Prop -/
#guard_msgs in #check ∀ᶠᶠ x in Filter.atTop: x < 3, x = 1
/-- info: ∀ᶠᶠ (x : ℕ) in Filter.atTop: x < 3, x = 1 : Prop -/
#guard_msgs in #check foobar (fun x ↦ Eq x 1) (Filter.atTop.eventually fun x ↦ LT.lt x 3)
/-- info: foobar (fun y ↦ y = 1) (∀ᶠ (x : ℕ) in Filter.atTop, x < 3) : Prop -/
#guard_msgs in #check foobar (fun y ↦ Eq y 1) (Filter.atTop.eventually fun x ↦ LT.lt x 3)
notation3 "∃' " (...) ", " r:(scoped p => Exists p) => r
/-- info: ∃' (a : ℕ) (_ : a < 3), a < 3 : Prop -/
#guard_msgs in #check ∃' a < 3, a < 3
/-- info: ∃' (x : ℕ) (_ : x < 3), True : Prop -/
#guard_msgs in #check ∃' _ < 3, True
/-- info: ∃' (x : ℕ) (_ : x < 1) (x_1 : ℕ) (_ : x_1 < 2), x = 0 : Prop -/
#guard_msgs in #check ∃' (x < 1) (_ < 2), x = 0
def func (x : α) : α := x
notation3 "func! " (...) ", " r:(scoped p => func p) => r
/-- info: (func! (x : ℕ → ℕ), x) fun x ↦ x * 2 : ℕ → ℕ -/
#guard_msgs in #check (func! (x : Nat → Nat), x) (· * 2)
structure MyUnit where
notation3 "~{" (x"; "* => foldl (a b => (a, b)) MyUnit) "}~" => x
/-- info: ~{1; true; ~{2}~}~ : ((Type × ℕ) × Bool) × Type × ℕ -/
#guard_msgs in #check ~{1; true; ~{2}~}~
/-- info: ~{}~ : Type -/
#guard_msgs in #check ~{}~
structure MyUnit' where
instance : OfNat MyUnit' (nat_lit 0) := ⟨{}⟩
notation3 "MyUnit'0" => (0 : MyUnit')
/-- info: MyUnit'0 : MyUnit' -/
#guard_msgs in #check (0 : MyUnit')
/-- info: 0 : ℕ -/
#guard_msgs in #check 0
notation3 "%[" (x", "* => foldr (a b => a :: b) []) "]" => x
/-- info: %[1, 2, 3] : List ℕ -/
#guard_msgs in #check %[1, 2, 3]
def foo (a : Nat) (f : Nat → Nat) := a + f a
def bar (a b : Nat) := a * b
notation3 "*[" x "] " (...) ", " v:(scoped c => bar x (foo x c)) => v
/-- info: *[1] (x : ℕ) (y : ℕ), x + y : ℕ -/
#guard_msgs in #check *[1] (x) (y), x + y
/-- info: bar 1 : ℕ → ℕ -/
#guard_msgs in #check bar 1
-- Checking that the `<|` macro is expanded when making matcher
def foo' (a : Nat) (f : Nat → Nat) := a + f a
def bar' (a b : Nat) := a * b
notation3 "*'[" x "] " (...) ", " v:(scoped c => bar' x <| foo' x c) => v
/-- info: *'[1] (x : ℕ) (y : ℕ), x + y : ℕ -/
#guard_msgs in #check *'[1] (x) (y), x + y
/-- info: bar' 1 : ℕ → ℕ -/
#guard_msgs in #check bar' 1
-- Need to give type ascription to `p` so that `p x` elaborates when making matcher
notation3 "MyPi " (...) ", " r:(scoped p => (x : _) → (p : _ → _) x) => r
/-- info: MyPi (x : ℕ) (y : ℕ), x < y : Prop -/
#guard_msgs in #check MyPi (x : Nat) (y : Nat), x < y
-- The notation parses fine, but the delaborator never succeeds, which is expected
def myId (x : α) := x
notation3 "BAD " c "; " (x", "* => foldl (a b => b) c) " DAB" => myId x
/-- info: myId 3 : ℕ -/
#guard_msgs in #check BAD 1; 2, 3 DAB
section
variable (x : Nat)
local notation3 "y" => x + 1
/-- info: y : ℕ -/
#guard_msgs in #check y
/-- info: y : ℕ -/
#guard_msgs in #check x + 1
end
section
variable (α : Type u) [Add α]
local notation3 x " +α " y => (x + y : α)
variable (x y : α)
/-- info: x +α y : α -/
#guard_msgs in #check x +α y
/-- info: x +α y : α -/
#guard_msgs in #check x + y
/-- info: 1 + 2 : ℕ -/
#guard_msgs in #check 1 + 2
end
def idStr : String → String := id
/--
error: Application type mismatch: The argument
Nat.zero
has type
ℕ
but is expected to have type
String
in the application
idStr Nat.zero
---
warning: Was not able to generate a pretty printer for this notation. If you do not expect it to be pretty printable, then you can use `notation3 (prettyPrint := false)`. If the notation expansion refers to section variables, be sure to do `local notation3`. Otherwise, you might be able to adjust the notation expansion to make it matchable; pretty printing relies on deriving an expression matcher from the expansion. (Use `set_option trace.notation3 true` to get some debug information.)
-/
#guard_msgs in
notation3 "error" => idStr Nat.zero
section
/--
warning: Was not able to generate a pretty printer for this notation. If you do not expect it to be
pretty printable, then you can use `notation3 (prettyPrint := false)`. If the notation expansion
refers to section variables, be sure to do `local notation3`. Otherwise, you might be able to adjust
the notation expansion to make it matchable; pretty printing relies on deriving an expression
matcher from the expansion. (Use `set_option trace.notation3 true` to get some debug information.)
-/
#guard_msgs (warning, drop error) in local notation3 "#" n => Fin.mk n (by decide)
end
section
set_option linter.unusedTactic false
local notation3 (prettyPrint := false) "#" n => Fin.mk n (by decide)
example : Fin 5 := #1
/--
error: Tactic `decide` proved that the proposition
6 < 5
is false
-/
#guard_msgs in example : Fin 5 := #6
end
section test_scoped
scoped[MyNotation] notation3 "π" => (3 : Nat)
/-- error: Unknown identifier `π` -/
#guard_msgs in #check π
open scoped MyNotation
/-- info: π : ℕ -/
#guard_msgs in #check π
end test_scoped
/-!
Verifying that delaborator does not match the exact `Inhabited` instance.
Instead, it matches that it's an application of `Inhabited.default` whose first argument is `Nat`.
-/
/--
trace: [notation3] syntax declaration has name Test.termδNat
---
trace: [notation3] Generating matcher for pattern default
[notation3] Matcher creation succeeded; assembling delaborator
[notation3] matcher:
matchApp✝ (matchApp✝ (matchExpr✝ (Expr.isConstOf✝ · `Inhabited.default)) (matchExpr✝ (Expr.isConstOf✝ · `Nat)))
pure✝ >=>
pure✝
[notation3] Creating delaborator for key Mathlib.Notation3.DelabKey.app (some `Inhabited.default) 2
-/
#guard_msgs in
set_option trace.notation3 true in
notation3 "δNat" => (default : Nat)
/-- info: δNat : ℕ -/
#guard_msgs in #check (default : Nat)
/-- info: δNat : ℕ -/
#guard_msgs in #check @default Nat (Inhabited.mk 5)
notation3 "(" "ignorez " "SVP" ")" => Sort _
notation3 "Objet " "mathématique " "supérieur" => Type _
notation3 "Énoncé" => Prop
notation3 "Objet " "mathématique" => Type
/-- info: 1 = 1 : Énoncé -/
#guard_msgs in #check 1 = 1
/-- info: Énoncé : Objet mathématique -/
#guard_msgs in #check Prop
/-- info: Nat : Objet mathématique -/
#guard_msgs in #check Nat
/-- info: Objet mathématique : Objet mathématique supérieur -/
#guard_msgs in #check Type
/-- info: PSum.{u, v} (α : (ignorez SVP)) (β : (ignorez SVP)) : (ignorez SVP) -/
#guard_msgs in #check PSum
end Test |
.lake/packages/mathlib/MathlibTest/ErwQuestion.lean | import Mathlib.Tactic.ErwQuestion
section Single
def f (x : Nat) := x + 1
def a := 37
theorem f_a : f a = 38 := rfl
def b := a
-- make sure that `erw'` is noisy, so that it gets picked up by CI
/-- info: Debugging `erw?` -/
#guard_msgs in
example : f 37 = 38 := by
erw? [f]
/--
error: Tactic `rewrite` failed: Did not find an occurrence of the pattern
f a
in the target expression
f b = 38
⊢ f b = 38
-/
#guard_msgs in
example : f b = 38 := by rw [f_a]
example : f b = 38 := by erw [f_a]
/--
info: Debugging `erw?`
---
info: ❌️ at reducible transparency,
b
and
a
are not defeq, but they are at default transparency.
-/
#guard_msgs in
example : f b = 38 := by erw? [f_a]
set_option tactic.erw?.verbose true in
/--
info: Debugging `erw?`
---
info: ❌️ at reducible transparency,
b
and
a
are not defeq, but they are at default transparency.
---
info: Expression appearing in target:
f b = 38
Expression from `erw`: f a = 38
❌️ at reducible transparency,
f b = 38
and
f a = 38
are not defeq.
✅️ at reducible transparency,
38
and
38
are defeq.
❌️ at reducible transparency,
Eq (f b)
and
Eq (f a)
are not defeq.
❌️ at reducible transparency,
f b
and
f a
are not defeq.
❌️ at reducible transparency,
b
and
a
are not defeq.
-/
#guard_msgs in
example : f b = 38 := by erw? [f_a]
end Single
section Sequence
def c := 38
theorem f_c : f c = 39 := rfl
/--
info: Debugging `erw?`
---
info: ❌️ at reducible transparency,
b
and
a
are not defeq, but they are at default transparency.
---
info: ❌️ at reducible transparency,
f 38
and
f c
are not defeq, but they are at default transparency.
-/
#guard_msgs in
example : f (f b) = 39 := by erw? [f_a, f_c]
end Sequence
section Location
/--
info: Debugging `erw?`
---
info: ❌️ at reducible transparency,
b
and
a
are not defeq, but they are at default transparency.
-/
#guard_msgs in
example (h : f b = c) : c = 38 := by
erw? [f_a] at h
exact h.symm
set_option tactic.erw?.verbose true in
/--
info: Debugging `erw?`
---
info: ❌️ at reducible transparency,
b
and
a
are not defeq, but they are at default transparency.
---
info: Expression appearing in h:
f b = c
Expression from `erw`: f a = c
❌️ at reducible transparency,
f b = c
and
f a = c
are not defeq.
✅️ at reducible transparency,
c
and
c
are defeq.
❌️ at reducible transparency,
Eq (f b)
and
Eq (f a)
are not defeq.
❌️ at reducible transparency,
f b
and
f a
are not defeq.
❌️ at reducible transparency,
b
and
a
are not defeq.
-/
#guard_msgs in
example (h : f b = c) : c = 38 := by
erw? [f_a] at h
exact h.symm
end Location |
.lake/packages/mathlib/MathlibTest/conv.lean | import Mathlib.Tactic.Conv
/-- Testing nested `conv in ... => ...` -/
example (a b c : Nat) : a + b + c = c + a + b := by
conv =>
conv in a + b =>
rw [Nat.add_comm]
guard_target = b + a + c = c + a + b
rw [Nat.add_comm, Nat.add_assoc]
conv in (occs := 4) _ + _ =>
guard_target = a + b
rw [Nat.add_comm]
/-- Testing nested `conv in ... => ...` -/
example (a b : Nat) : (a + b) + (a + b) = (b + a) + (b + a) := by
conv =>
lhs
conv in (occs := *) a + b =>
rw [Nat.add_comm]
guard_target = b + a + (b + a) |
.lake/packages/mathlib/MathlibTest/ring_compare.lean | import Mathlib.Tactic.NormNum.OfScientific
import Mathlib.Tactic.Ring.Compare
import Mathlib.Tactic.Ring.RingNF
open Lean Elab Tactic
elab "ring_le" : tactic => liftMetaFinishingTactic Mathlib.Tactic.Ring.proveLE
elab "ring_lt" : tactic => liftMetaFinishingTactic Mathlib.Tactic.Ring.proveLT
section Nat
variable {x y : ℕ}
example : 3 ≤ (3:ℕ) := by ring_le
example : 1 ≤ (3:ℕ) := by ring_le
example : 0 ≤ (3:ℕ) + 1 := by ring_le
example : x ≤ x := by ring_le
example : x ≤ x + 3 := by ring_le
example : x ≤ 1 + x := by ring_le
example : x + y + 1 ≤ y + x + 3 := by ring_le
example : x + y ≤ y + x + 3 := by ring_le
example : x + y + 1 ≤ y + 4 + x := by ring_le
example : 1 < (3:ℕ) := by ring_lt
example : 0 < (3:ℕ) + 1 := by ring_lt
example : x < x + 3 := by ring_lt
example : x < 1 + x := by ring_lt
example : x + y + 1 < y + x + 3 := by ring_lt
example : x + y < y + x + 3 := by ring_lt
example : x + y + 1 < y + 4 + x := by ring_lt
end Nat
section LinearOrderedField
variable {K : Type*} [Field K] [LinearOrder K] [IsStrictOrderedRing K] {x y : K}
example : (0:K) ≤ 0 := by ring_le
example : 3 ≤ (3:K) := by ring_le
example : 1 ≤ (3:K) := by ring_le
example : -1 ≤ (3:K) := by ring_le
example : 1.5 ≤ (3:K) := by ring_le
example : 0 ≤ x + 3 - x := by ring_le
example : -1 ≤ x - x := by ring_le
example : x + y + 1 ≤ y + x + 3 := by ring_le
example : x + y + 1 ≤ y + x + 1 := by ring_le
example : x + y ≤ y + x + 3 := by ring_le
example : x + y - 3 ≤ y + x := by ring_le
example : x + y - x + 1 ≤ y + (4:K) := by ring_le
example : 1 < (3:K) := by ring_lt
example : -1 < (3:K) := by ring_lt
example : 1.5 < (3:K) := by ring_lt
example : 0 < x + 3 - x := by ring_lt
example : -1 < x - x := by ring_lt
example : x + y + 1 < y + x + 3 := by ring_lt
example : x + y < y + x + 3 := by ring_lt
example : x + y - 3 < y + x := by ring_lt
example : x + y - x + 1 < y + (4:K) := by ring_lt
/- The speed of `Mathlib.Tactic.Ring.proveLE` is very sensitive to how much typeclass inference is
demanded by the lemmas it orchestrates. This example took 1112 heartbeats (and 40 ms on a good
laptop) on an implementation with "minimal" typeclasses everywhere, e.g. lots of
`CovariantClass`/`ContravariantClass`, and takes 662 heartbeats (28 ms on a good laptop) on the
implementation at the time of joining Mathlib (October 2024). -/
set_option maxHeartbeats 750 in
example : x + y - x + 1 ≤ y + (4:K) := by ring_le
/- The speed of `Mathlib.Tactic.Ring.proveLT` is very sensitive to how much typeclass inference is
demanded by the lemmas it orchestrates. This example took 1410 heartbeats (and 48 ms on a good
laptop) on an implementation with "minimal" typeclasses everywhere, e.g. lots of
`CovariantClass`/`ContravariantClass`, and takes 676 heartbeats (28 ms on a good laptop) on the
implementation at the time of joining Mathlib (October 2024). -/
set_option maxHeartbeats 750 in
example : x + y - x + 1 < y + (4:K) := by ring_lt
/--
error: ring failed, ring expressions not equal up to an additive constant
K : Type u_1
inst✝² : Field K
inst✝¹ : LinearOrder K
inst✝ : IsStrictOrderedRing K
x y : K
⊢ 1 + x + y ≤ 3 + y
-/
#guard_msgs in
example : x + y + 1 ≤ y + 3 := by ring_le
/--
error: comparison failed, LHS is larger
K : Type u_1
inst✝² : Field K
inst✝¹ : LinearOrder K
inst✝ : IsStrictOrderedRing K
x y : K
⊢ 4 + x + y ≤ 3 + x + y
-/
#guard_msgs in
example : x + y + 4 ≤ y + x + 3 := by ring_le
/--
error: ring failed, ring expressions not equal up to an additive constant
K : Type u_1
inst✝² : Field K
inst✝¹ : LinearOrder K
inst✝ : IsStrictOrderedRing K
x y : K
⊢ 1 + x + y < 3 + y
-/
#guard_msgs in
example : x + y + 1 < y + 3 := by ring_lt
/--
error: comparison failed, LHS is at least as large
K : Type u_1
inst✝² : Field K
inst✝¹ : LinearOrder K
inst✝ : IsStrictOrderedRing K
x y : K
⊢ 4 + x + y < 4 + x + y
-/
#guard_msgs in
example : x + y + 4 < y + x + 4 := by ring_lt
end LinearOrderedField |
.lake/packages/mathlib/MathlibTest/MfldSetTac.lean | import Mathlib.Logic.Equiv.PartialEquiv
private axiom test_sorry : ∀ {α}, α
/-!
This is a test file for the tactic `mfld_set_tac`. Because this tactic applies a simp-set which
mostly contains lemmas in advanced parts of mathlib, it is currently impossible to truly test it
in realistic conditions. Instead, we create stub definitions and lemmas on objects such as
`OpenPartialHomeomorph`, label them with `mfld_simps` and run tests on those.
-/
open Lean Meta Elab Tactic
/-! ## Syntax of objects and lemmas needed for testing `MfldSetTac` -/
set_option autoImplicit true
section stub_lemmas
structure OpenPartialHomeomorph (α : Type u) (β : Type u) extends PartialEquiv α β
noncomputable
instance OpenPartialHomeomorph.has_coe_to_fun : CoeFun (OpenPartialHomeomorph α β) (fun _ ↦ α → β) :=
test_sorry
noncomputable
def OpenPartialHomeomorph.symm (_e : OpenPartialHomeomorph α β) : OpenPartialHomeomorph β α := test_sorry
@[mfld_simps] lemma OpenPartialHomeomorph.left_inv (e : OpenPartialHomeomorph α β) {x : α}
(_h : x ∈ e.toPartialEquiv.source) :
e.symm (e x) = x :=
test_sorry
@[mfld_simps] theorem OpenPartialHomeomorph.symm_to_PartialEquiv (e : OpenPartialHomeomorph α β) :
e.symm.toPartialEquiv = e.toPartialEquiv.symm :=
test_sorry
@[mfld_simps] lemma OpenPartialHomeomorph.coe_coe (e : OpenPartialHomeomorph α β) :
(e.toPartialEquiv : α → β) = e :=
test_sorry
@[mfld_simps] lemma OpenPartialHomeomorph.coe_coe_symm (e : OpenPartialHomeomorph α β) :
(e.toPartialEquiv.symm : β → α) = (e.symm : β → α) :=
test_sorry
structure ModelWithCorners (𝕜 E H : Type u) extends PartialEquiv H E where
(source_eq : source = Set.univ)
attribute [mfld_simps] ModelWithCorners.source_eq
noncomputable
def ModelWithCorners.symm (_I : ModelWithCorners 𝕜 E H) : PartialEquiv E H := test_sorry
noncomputable
instance ModelWithCorners.has_coe_to_fun : CoeFun (ModelWithCorners 𝕜 E H) (fun _ ↦ H → E) :=
test_sorry
@[mfld_simps] lemma ModelWithCorners.left_inv (I : ModelWithCorners 𝕜 E H) (x : H) :
I.symm (I x) = x :=
test_sorry
@[mfld_simps] lemma ModelWithCorners.to_local_equiv_coe (I : ModelWithCorners 𝕜 E H) :
(I.toPartialEquiv : H → E) = I :=
test_sorry
@[mfld_simps] lemma ModelWithCorners.to_local_equiv_coe_symm (I : ModelWithCorners 𝕜 E H) :
(I.toPartialEquiv.symm : E → H) = I.symm :=
test_sorry
end stub_lemmas
/-! ## Tests for `MfldSetTac` -/
section tests
example (e : PartialEquiv α β) (e' : PartialEquiv β γ) :
(e.trans e').source = e.source ∩ Set.preimage e (e.target ∩ e'.source) := by
mfld_set_tac
example (e : PartialEquiv α β) : (e.trans e.symm).source = e.source := by mfld_set_tac
example (s : Set α) (f : OpenPartialHomeomorph α β) :
f.symm.toPartialEquiv.source ∩ (f.toPartialEquiv.target ∩ Set.preimage f.symm s)
= f.symm.toPartialEquiv.source ∩ Set.preimage f.symm s := by mfld_set_tac
example
{I : ModelWithCorners 𝕜 E H}
{I' : ModelWithCorners 𝕜 E' H'}
{I'' : ModelWithCorners 𝕜 E'' H''}
(e₁ : OpenPartialHomeomorph M H)
(e₂ : OpenPartialHomeomorph M' H')
(e₃ : OpenPartialHomeomorph M'' H'')
{f : M → M'}
{g : M' → M''} :
(Set.preimage (f ∘ ((e₁.toPartialEquiv.trans I.toPartialEquiv).symm))
(e₂.toPartialEquiv.trans I'.toPartialEquiv).source) ⊆
{y : E |
((e₃.toPartialEquiv.trans I''.toPartialEquiv) ∘
(g ∘ f) ∘ ((e₁.toPartialEquiv.trans I.toPartialEquiv).symm)) y
= (((e₃.toPartialEquiv.trans I''.toPartialEquiv : M'' → E'') ∘
g ∘ ((e₂.toPartialEquiv.trans I'.toPartialEquiv).symm)) ∘
(e₂.toPartialEquiv.trans I'.toPartialEquiv : M' → E') ∘
f ∘ ((e₁.toPartialEquiv.trans I.toPartialEquiv).symm)) y} := by
mfld_set_tac
end tests |
.lake/packages/mathlib/MathlibTest/Constructor.lean | import Mathlib.Tactic.Constructor
structure Foo where
a : Type
x : List a
-- fconstructor
example : Foo := by
fconstructor
exact Nat
exact [0,1,2]
-- econstructor
example : Foo := by
econstructor
exact [0,1,2] |
.lake/packages/mathlib/MathlibTest/FindDeprecations.lean | import Mathlib.Tactic.Linter.FindDeprecations
import Mathlib.Tactic.Linter.CommandRanges
/-- info: [134, 170, 171] -/
#guard_msgs in
set_option linter.commandRanges true
/-- info: [215, 223, 224] -/
#guard_msgs in
open Nat
set_option linter.commandRanges false
open Mathlib.Tactic
#guard parseLine "" == none
#guard parseLine "a: []" == some []
#guard parseLine "a: [1, 2, 3]" == some [⟨1⟩, ⟨2⟩, ⟨3⟩]
#guard parseLine "info: File/Path.lean:12:0: [362, 398, 399]" == some [⟨362⟩, ⟨398⟩, ⟨399⟩]
/--
info:
01234567 9
0134567 9
0134569
-/
#guard_msgs in
#eval show Lean.Elab.Term.TermElabM _ from do
let file := "01234567 9"
IO.println s!"\n{file}"
guard <| -- An empty array of changes leaves `file` unchanged
removeRanges file #[] == file
IO.println <| removeRanges file #[⟨⟨2⟩, ⟨3⟩⟩]
guard <| -- Removing a single character not followed by whitespace, removes that character only
removeRanges file #[⟨⟨2⟩, ⟨3⟩⟩] == file.replace "2" ""
IO.println <| removeRanges file #[⟨⟨2⟩, ⟨3⟩⟩, ⟨⟨7⟩, ⟨8⟩⟩]
guard <| -- Also removing a range followed by whitespace, removes the trailing whitespace as well
removeRanges file #[⟨⟨2⟩, ⟨3⟩⟩, ⟨⟨7⟩, ⟨8⟩⟩] == ((file.replace "2" "").replace "7 " "") |
.lake/packages/mathlib/MathlibTest/EuclideanSpace.lean | import Mathlib.Analysis.InnerProductSpace.PiL2
set_option linter.style.commandStart false
#guard_expr !₂[] = WithLp.toLp 2 (V := ∀ _ : Fin 0, _) ![]
#guard_expr !₂[1, 2, 3] = WithLp.toLp 2 (V := ∀ _ : Fin 3, ℕ) ![1, 2, 3]
#guard_expr !₁[1, 2, (3 : ℝ)] = WithLp.toLp 1 (V := ∀ _ : Fin 3, ℝ) ![1, 2, 3]
section delaborator
/-- info: !₂[1, 2, 3] : WithLp 2 (Fin 3 → ℕ) -/
#guard_msgs in
#check !₂[1, 2, 3]
set_option pp.mvars false in
/-- info: !₀[] : WithLp 0 (Fin 0 → ?_) -/
#guard_msgs in
#check !₀[]
section var
variable {p : ENNReal}
/-- info: WithLp.toLp p ![1, 2, 3] : WithLp p (Fin 3 → ℕ) -/
#guard_msgs in#check !ₚ[1, 2, 3]
end var
section tombstoned_var
/- Here the `p` in the subscript is shadowed by a later p; so even if we do
make the delaborator less conservative, it should not fire here since `✝` cannot
be subscripted. -/
variable {p : ENNReal} {x} (hx : x = !ₚ[1, 2, 3]) (p : True)
/-- info: hx : x = WithLp.toLp p✝ ![1, 2, 3] -/
#guard_msgs in #check hx
end tombstoned_var
end delaborator |
.lake/packages/mathlib/MathlibTest/norm_num.lean | import Mathlib.Tactic.NormNum
private axiom test_sorry : ∀ {α}, α
/-!
# Tests for `norm_num` extensions
-/
set_option autoImplicit true
-- We deliberately mock R and C here so that we don't have to import the deps
axiom Real : Type
notation "ℝ" => Real
@[instance] axiom Real.field : Field ℝ
@[instance] axiom Real.linearOrder : LinearOrder ℝ
@[instance] axiom Real.isStrictOrderedRing : IsStrictOrderedRing ℝ
axiom NNReal : Type
notation "ℝ≥0" => NNReal
@[instance] axiom NNReal.semifield : Semifield ℝ≥0
@[instance] axiom NNReal.linearOrder : LinearOrder ℝ≥0
@[instance] axiom NNReal.isStrictOrderedRing : IsStrictOrderedRing ℝ≥0
axiom Complex : Type
notation "ℂ" => Complex
@[instance] axiom Complex.field : Field ℂ
@[instance] axiom Complex.charZero : CharZero ℂ
example : 43 ≤ 74 + (33 : ℤ) := by norm_num1
-- example : 374 + (32 - (2 * 8123) : ℤ) - 61 * 50 = 86 + 32 * 32 - 4 * 5000
-- ∧ 43 ≤ 74 + (33 : ℤ) := by norm_num1
example : ¬ (7-2)/(2*3) ≥ (1:ℝ) + 2/(3^2) := by norm_num1
example : (6:ℝ) + 9 = 15 := by norm_num1
example : (2:ℝ)/4 + 4 = 3*3/2 := by norm_num1
example : (((3:ℝ)/4)-12)<6 := by norm_num1
example : (5:ℝ) ≠ 8 := by norm_num1
example : (10:ℝ) > 7 := by norm_num1
example : (2:ℝ) * 2 + 3 = 7 := by norm_num1
example : (6:ℝ) < 10 := by norm_num1
example : (7:ℝ)/2 > 3 := by norm_num1
example : (4:ℝ)⁻¹ < 1 := by norm_num1
example : ((1:ℝ) / 2)⁻¹ = 2 := by norm_num1
example : 2 ^ 17 - 1 = 131071 := by norm_num1
example : (3 : ℝ) ^ (-2 : ℤ) = 1/9 := by norm_num1
example : (-3 : ℝ) ^ (0 : ℤ) = 1 := by norm_num1
example : (-3 : ℝ) ^ (-1 : ℤ) = -1/3 := by norm_num1
example : (-3 : ℝ) ^ (1 : ℤ) = -3 := by norm_num1
example : (-3 : ℝ) ^ (2 : ℤ) = 9 := by norm_num1
example : (1/3 : ℝ) ^ (2 : ℤ) = 1/9 := by norm_num1
example : (1/3 : ℝ) ^ (-2 : ℤ) = 9 := by norm_num1
example : (-1/3 : ℝ) ^ (-1 : ℤ) = -3 := by norm_num1
example : (3 : ℝ≥0) ^ (2 : ℤ) = 9 := by norm_num1
section InvLit
variable [DivisionRing α]
example : (0 : α)⁻¹ = 0 := by norm_num1
example : (1 : α)⁻¹ = 1 := by norm_num1
example : (-1 : α)⁻¹ = -1 := by norm_num1
end InvLit
example (h : x = 1) : x = (1/5 + 4/5 : ℚ) := by norm_num1; exact h
example (h : x = 1) : x = (5 * 5⁻¹ : ℚ) := by norm_num1; exact h
example (h : x = 1) : x = (6/5 - 1/5 : ℚ) := by norm_num1; exact h
example (h : x = 1) : x = ((6/5) ^ 0 : ℚ) := by norm_num1; exact h
section ConstructorsEtc
example : Int.ofNat 3 = 3 := by norm_num1
example : mkRat 3 4 = 3/4 := by norm_num1
example : mkRat 6 8 = 3/4 := by norm_num1
example : mkRat 5 0 = 0 := by norm_num1
example : mkRat (10 + 6) (5 * 4) = 4/5 := by norm_num1
end ConstructorsEtc
section ScientificNotation
variable [DivisionRing α] [CharZero α]
example : (0.1 : ℚ) = 1/10 := by norm_num1
example : (3.14 : ℚ) = 157/50 := by norm_num1
example : (3.14159 : ℚ) = 314159/100000 := by norm_num1
example : (0.1 : α) = 1/10 := by norm_num1
example : (3.14 : α) = 157/50 := by norm_num1
example : (3.14159 : α) = 314159/100000 := by norm_num1
example : (42e7 : ℚ) = 420000000 := by norm_num1
example : (42e7 : α) = 420000000 := by norm_num1
end ScientificNotation
/-
# `=` and `≠`
-/
section Equality
section Bool
example : True := by norm_num1
example (h : False) : ¬True := by norm_num1; guard_target =ₛ False; exact h
example : ¬¬¬¬True := by norm_num1
example : ¬False := by norm_num1
end Bool
section Nat
variable [AddMonoidWithOne α] [CharZero α]
-- Normalize to True
example : 1 = 1 := by norm_num1
example : 1 ≠ 2 := by norm_num1
example : (1 : α) ≠ 2 := by norm_num1
-- Normalize to False
example : ¬(1 = 2) := by norm_num1
example : ¬((1 : α) = 2) := by norm_num1
example : ¬((1 : α) ≠ 1) := by norm_num1
end Nat
section Semiring
variable [Semiring α] [CharZero α]
example : (1 : α) ≠ 2 := by norm_num1
end Semiring
section Int
variable [Ring α] [CharZero α]
-- Normalize to True
example : (1 : ℤ) = 1 := by norm_num1
example : (-1 : ℤ) = -1 := by norm_num1
example : (1 : α) = 1 := by norm_num1
example : (-1 : α) = -1 := by norm_num1
example : (1 : ℤ) ≠ 2 := by norm_num1
example : (1 : ℤ) ≠ -2 := by norm_num1
example : (-1 : ℤ) ≠ -2 := by norm_num1
example : (1 : α) ≠ 2 := by norm_num1
example : (-1 : α) ≠ 2 := by norm_num1
example : (-1 : α) ≠ -2 := by norm_num1
-- Normalize to False
example : ((1 : ℤ) = 2) = False := by norm_num1
example : ((-1 : ℤ) = 2) = False := by norm_num1
example : ((1 : α) = 2) = False := by norm_num1
example : ((-1 : α) = 2) = False := by norm_num1
example : ((1 : ℤ) ≠ 1) = False := by norm_num1
example : ((-1 : ℤ) ≠ -1) = False := by norm_num1
example : ((1 : α) ≠ 1) = False := by norm_num1
example : ((-1 : α) = 2) = False := by norm_num1
example : Int.natAbs 5 = 5 := by norm_num1
example : Int.natAbs (-5) = 5 := by norm_num1
example : Int.natAbs 0 = 0 := by norm_num1
end Int
section NNRat
open scoped NNRat
variable [DivisionSemiring α] [CharZero α]
-- Normalize to True
example : (1 : ℚ≥0) = 1 := by norm_num1
example : (1/2 : ℚ≥0) = 1/2 := by norm_num1
example : (1 : α) = 1 := by norm_num1
example : (1/2 : α) = 1/2 := by norm_num1
example : (1 : ℚ≥0) ≠ 2 := by norm_num1
example : (1/2 : ℚ≥0) ≠ 1 := by norm_num1
example : (1/2 : ℚ≥0) ≠ 1/3 := by norm_num1
example : (1/2 : ℚ≥0) ≠ 5/2 := by norm_num1
example : (1/2 : α) ≠ 1/3 := by norm_num1
example : (1/2 : α) ≠ 5/2 := by norm_num1
example : (1 : α) / 3 ≠ 0 := by norm_num1
example : (1 : α) / 3 ≠ 2 / 7 := by norm_num1
-- Normalize to False
example : ((1 : ℚ≥0) = 2) = False := by norm_num1
example : ((1/2 : ℚ≥0) = 2) = False := by norm_num1
example : ((1 : α) = 2) = False := by norm_num1
example : ((1/2 : α) = 2) = False := by norm_num1
example : ((1 : ℚ≥0) ≠ 1) = False := by norm_num1
example : ((1/2 : ℚ≥0) ≠ 1/2) = False := by norm_num1
example : ((1/2 : α) ≠ 1/2) = False := by norm_num1
end NNRat
section Rat
variable [DivisionRing α] [CharZero α]
-- Normalize to True
example : (1 : ℚ) = 1 := by norm_num1
example : (-1 : ℚ) = -1 := by norm_num1
example : (1/2 : ℚ) = 1/2 := by norm_num1
example : (-1/2 : ℚ) = -1/2 := by norm_num1
example : (-1/(-2) : ℚ) = -1/(-2) := by norm_num1
example : (1 : α) = 1 := by norm_num1
example : (-1 : α) = -1 := by norm_num1
example : (1/2 : α) = 1/2 := by norm_num1
example : (-1/2 : α) = -1/2 := by norm_num1
example : (-1/(-2) : α) = -1/(-2) := by norm_num1
example : (1 : ℚ) ≠ 2 := by norm_num1
example : (1 : ℚ) ≠ -2 := by norm_num1
example : (-1 : ℚ) ≠ -2 := by norm_num1
example : (1/2 : ℚ) ≠ 1 := by norm_num1
example : (1/2 : ℚ) ≠ -1 := by norm_num1
example : (1/2 : ℚ) ≠ 1/3 := by norm_num1
example : (1/2 : ℚ) ≠ 5/2 := by norm_num1
example : (1/2 : α) ≠ 1/3 := by norm_num1
example : (1/2 : α) ≠ 5/2 := by norm_num1
example : (1/2 : α) ≠ -2 := by norm_num1
example : (-1 : α) ≠ 2 := by norm_num1
example : (1 : α) / 3 ≠ 0 := by norm_num1
example : (1 : α) / 3 ≠ 2 / 7 := by norm_num1
-- Normalize to False
example : ((1 : ℚ) = 2) = False := by norm_num1
example : ((-1 : ℚ) = 2) = False := by norm_num1
example : ((1/2 : ℚ) = 2) = False := by norm_num1
example : ((1 : α) = 2) = False := by norm_num1
example : ((-1 : α) = 2) = False := by norm_num1
example : ((1/2 : α) = 2) = False := by norm_num1
example : ((1 : ℚ) ≠ 1) = False := by norm_num1
example : ((-1 : ℚ) ≠ -1) = False := by norm_num1
example : ((1/2 : ℚ) ≠ 1/2) = False := by norm_num1
example : ((1/2 : α) ≠ 1/2) = False := by norm_num1
end Rat
end Equality
/-
# `<` and `≤`
-/
section Order
section Nat
variable [Semiring α] [PartialOrder α] [IsOrderedRing α] [CharZero α]
-- Normalize to True
example : 1 ≤ 1 := by norm_num1
example : (1 : α) ≤ 2 := by norm_num1
example : 1 < 2 := by norm_num1
example : (1 : α) < 2 := by norm_num1
-- Normalize to False
example : ¬(2 ≤ 1) := by norm_num1
example : ¬((2 : α) ≤ 1) := by norm_num1
example : ¬(1 < 1) := by norm_num1
example : ¬((2 : α) < 2) := by norm_num1
end Nat
section Int
variable [Ring α] [PartialOrder α] [IsOrderedRing α] [Nontrivial α]
-- Normalize to True
example : (1 : ℤ) ≤ 1 := by norm_num1
example : (-1 : ℤ) ≤ -1 := by norm_num1
example : (-1 : ℤ) ≤ 1 := by norm_num1
example : (1 : α) ≤ 1 := by norm_num1
example : (-1 : α) ≤ -1 := by norm_num1
example : (-1 : α) ≤ 1 := by norm_num1
example : (1 : ℤ) < 2 := by norm_num1
example : (-2 : ℤ) < 1 := by norm_num1
example : (-1 : ℤ) < 1 := by norm_num1
example : (1 : α) < 2 := by norm_num1
example : (-1 : α) < 2 := by norm_num1
example : (-1 : α) < 1 := by norm_num1
-- Normalize to False
example : ¬((2 : ℤ) ≤ 1) := by norm_num1
example : ¬((2 : ℤ) ≤ -1) := by norm_num1
example : ¬((2 : α) ≤ 1) := by norm_num1
example : ¬((2 : α) ≤ -1) := by norm_num1
example : ¬((2 : ℤ) < 1) := by norm_num1
example : ¬((2 : ℤ) < -1) := by norm_num1
example : ¬((2 : α) < 1) := by norm_num1
example : ¬((2 : α) < -1) := by norm_num1
end Int
section OrderedCharZeroRing
variable [Ring α] [PartialOrder α] [IsOrderedRing α] [CharZero α]
example : (-1 : α) < 2 := by norm_num1
end OrderedCharZeroRing
section LinearOrderedRing
variable [Ring α] [LinearOrder α] [IsStrictOrderedRing α]
example : (1 : α) ≤ 1 := by norm_num1
example : (-1 : α) ≤ -1 := by norm_num1
example : (-1 : α) ≤ 1 := by norm_num1
example : (1 : α) < 2 := by norm_num1
example : (-1 : α) < 2 := by norm_num1
example : (-1 : α) < 1 := by norm_num1
end LinearOrderedRing
section Rat
variable [Field α] [LinearOrder α] [IsStrictOrderedRing α] [Nontrivial α]
-- Normalize to True
example : (1 : ℚ) ≤ 1 := by norm_num1
example : (-1 : ℚ) ≤ -1 := by norm_num1
example : (-1 : ℚ) ≤ 1 := by norm_num1
example : (-1/2 : ℚ) ≤ 1 := by norm_num1
example : (1/2 : ℚ) ≤ 5/4 := by norm_num1
example : (1 : α) ≤ 1 := by norm_num1
example : (-1 : α) ≤ -1 := by norm_num1
example : (-1 : α) ≤ 1 := by norm_num1
example : (-1/2 : α) ≤ 1 := by norm_num1
example : (1/2 : α) ≤ 5/4 := by norm_num1
example : (1 : ℤ) < 2 := by norm_num1
example : (-2 : ℤ) < 1 := by norm_num1
example : (-1 : ℤ) < 1 := by norm_num1
example : (-1/2 : ℚ) < 1 := by norm_num1
example : (1/2 : ℚ) < 5/4 := by norm_num1
example : (1 : α) < 2 := by norm_num1
example : (-1 : α) < 2 := by norm_num1
example : (-1 : α) < 1 := by norm_num1
example : (-1/2 : α) < 1 := by norm_num1
example : (1/2 : α) < 5/4 := by norm_num1
-- Normalize to False
example : ¬((2 : ℚ) ≤ 1) := by norm_num1
example : ¬((2 : ℚ) ≤ -1) := by norm_num1
example : ¬((1/2 : ℚ) ≤ -1) := by norm_num1
example : ¬((2 : α) ≤ 1) := by norm_num1
example : ¬((2 : α) ≤ -1) := by norm_num1
example : ¬((1/2 : α) ≤ -1) := by norm_num1
example : ¬((2 : ℚ) < 1) := by norm_num1
example : ¬((2 : ℚ) < -1) := by norm_num1
example : ¬((1/2 : ℚ) < -1) := by norm_num1
example : ¬((2 : α) < 1) := by norm_num1
example : ¬((2 : α) < -1) := by norm_num1
example : ¬((1/2 : α) < -1) := by norm_num1
end Rat
end Order
example : (1:ℂ) ≠ 2 := by norm_num1
example : (1:ℂ) / 3 ≠ 2 / 7 := by norm_num1
example : (1:ℝ) ≠ 2 := by norm_num1
example : (5 / 2:ℕ) = 2 := by norm_num1
example : (5 / -2:ℤ) < -1 := by norm_num1
example : (0 + 1) / 2 < 0 + 1 := by norm_num1
example : Nat.succ (Nat.succ (2 ^ 3)) = 10 := by norm_num1
example : 10 = (-1 : ℤ) % 11 := by norm_num1
example : (12321 - 2 : ℤ) = 12319 := by norm_num1
example : (63:ℚ) ≥ 5 := by norm_num1
example (x : ℤ) (h : 1000 + 2000 < x) : 100 * 30 < x := by
norm_num at *; exact h
set_option linter.unusedVariables false in
example {P : ℝ → Prop} (h1 : P (3 * 9 + 2)) (h2 : P (12 - 6 ^ 2)) : P (7 + 7) := by
norm_num at *
guard_hyp h1 : P 29
guard_hyp h2 : P (-24)
guard_target = P 14
exact test_sorry
example : (1103 : ℤ) ≤ (2102 : ℤ) := by norm_num1
example : (110474 : ℤ) ≤ (210485 : ℤ) := by norm_num1
example : (11047462383473829263 : ℤ) ≤ (21048574677772382462 : ℤ) := by norm_num1
example : (210485742382937847263 : ℤ) ≤ (1104857462382937847262 : ℤ) := by norm_num1
example : (210485987642382937847263 : ℕ) ≤ (11048512347462382937847262 : ℕ) := by norm_num1
example : (210485987642382937847263 : ℚ) ≤ (11048512347462382937847262 : ℚ) := by norm_num1
example : (2 * 12868 + 25705) * 11621 ^ 2 ≤ 23235 ^ 2 * 12868 := by norm_num1
-- example (x : ℕ) : ℕ := by
-- let n : ℕ := by apply_normed (2^32 - 71)
-- exact n
set_option linter.unusedVariables false in
example (a : ℚ) (h : 3⁻¹ * a = a) : True := by
norm_num1 at h
guard_hyp h : 1 / 3 * a = a
trivial
example (h : (5 : ℤ) ∣ 2) : False := by norm_num1 at h
example (h : False) : False := by norm_num1 at h
example : True := by norm_num1
-- example : True ∧ True := by norm_num1
/-!
## Nat operations
-/
section Nat.sub
example : 10 - 1 = 9 := by norm_num1
example : 12 - 5 = 3 + 4 := by norm_num1
example : 5 - 20 = 0 := by norm_num1
example : 0 - 2 = 0 := by norm_num1
example : 4 - (5 - 10) = 2 + (3 - 1) := by norm_num1
example : 0 - 0 = 0 := by norm_num1
example : 100 - 100 = 0 := by norm_num1
example : 5 * (2 - 3) = 0 := by norm_num1
example : 10 - 5 * 5 + (7 - 3) * 6 = 27 - 3 := by norm_num1
end Nat.sub
section Nat.mod
example : 10 % 1 = 0 := by norm_num1
example : 5 % 4 = 1 := by norm_num1
example : (9 % 4) % (12 % 8) = 1 := by norm_num1
example : 0 % 10 = 0 := by norm_num1
example : 10 % 0 = 10 := by norm_num1
example : 1 % 1 = 0 := by norm_num1
end Nat.mod
section Nat.div
example : 10 / 1 = 10 := by norm_num1
example : 5 / 4 = 1 := by norm_num1
example : 9 / 4 = 2 := by norm_num1
example : 0 / 1 = 0 := by norm_num1
example : 10 / 9 = 1 := by norm_num1
example : 1099 / 100 = 10 := by norm_num1
end Nat.div
/-!
## Numbers in algebraic structures
-/
noncomputable def foo : ℝ := 1
example : foo = 1 := by norm_num [foo]
section
variable [AddMonoidWithOne α]
example : (1 + 0 : α) = (0 + 1 : α) := by norm_num1
example : (0 + (2 + 3) + 1 : α) = 6 := by norm_num1
end
section
variable [Semiring α]
example : (70 * (33 + 2) : α) = 2450 := by norm_num1
example : (8 + 2 ^ 2 * 3 : α) = 20 := by norm_num1
example : ((2 * 1 + 1) ^ 2 : α) = (3 * 3 : α) := by norm_num1
end
section
variable [Ring α]
example : (-1 : α) * 1 = -1 := by norm_num1
example : (-2 : α) * 1 = -2 := by norm_num1
example : (-2 : α) * -1 = 2 := by norm_num1
example : (-2 : α) * -2 = 4 := by norm_num1
example : (1 : α) * 0 = 0 := by norm_num1
example : ((1 : α) + 1) * 5 = 6 + 4 := by norm_num1
example : (1 : α) = 0 + 1 := by norm_num1
example : (1 : α) = 1 + 0 := by norm_num1
example : (2 : α) = 1 + 1 := by norm_num1
example : (2 : α) = 0 + 2 := by norm_num1
example : (3 : α) = 1 + 2 := by norm_num1
example : (3 : α) = 2 + 1 := by norm_num1
example : (4 : α) = 3 + 1 := by norm_num1
example : (4 : α) = 2 + 2 := by norm_num1
example : (5 : α) = 4 + 1 := by norm_num1
example : (5 : α) = 3 + 2 := by norm_num1
example : (5 : α) = 2 + 3 := by norm_num1
example : (6 : α) = 0 + 6 := by norm_num1
example : (6 : α) = 3 + 3 := by norm_num1
example : (6 : α) = 4 + 2 := by norm_num1
example : (6 : α) = 5 + 1 := by norm_num1
example : (7 : α) = 4 + 3 := by norm_num1
example : (7 : α) = 1 + 6 := by norm_num1
example : (7 : α) = 6 + 1 := by norm_num1
example : 33 = 5 + (28 : α) := by norm_num1
example : (12 : α) = 0 + (2 + 3) + 7 := by norm_num1
example : (105 : α) = 70 + (33 + 2) := by norm_num1
example : (45000000000 : α) = 23000000000 + 22000000000 := by norm_num1
example : (0 : α) - 3 = -3 := by norm_num1
example : (0 : α) - 2 = -2 := by norm_num1
example : (1 : α) - 3 = -2 := by norm_num1
example : (1 : α) - 1 = 0 := by norm_num1
example : (0 : α) - 3 = -3 := by norm_num1
example : (0 : α) - 3 = -3 := by norm_num1
example : (12 : α) - 4 - (5 + -2) = 5 := by norm_num1
example : (12 : α) - 4 - (5 + -2) - 20 = -15 := by norm_num1
example : (0 : α) * 0 = 0 := by norm_num1
example : (0 : α) * 1 = 0 := by norm_num1
example : (0 : α) * 2 = 0 := by norm_num1
example : (2 : α) * 0 = 0 := by norm_num1
example : (1 : α) * 0 = 0 := by norm_num1
example : (1 : α) * 1 = 1 := by norm_num1
example : (2 : α) * 1 = 2 := by norm_num1
example : (1 : α) * 2 = 2 := by norm_num1
example : (2 : α) * 2 = 4 := by norm_num1
example : (3 : α) * 2 = 6 := by norm_num1
example : (2 : α) * 3 = 6 := by norm_num1
example : (4 : α) * 1 = 4 := by norm_num1
example : (1 : α) * 4 = 4 := by norm_num1
example : (3 : α) * 3 = 9 := by norm_num1
example : (3 : α) * 4 = 12 := by norm_num1
example : (4 : α) * 4 = 16 := by norm_num1
example : (11 : α) * 2 = 22 := by norm_num1
example : (15 : α) * 6 = 90 := by norm_num1
example : (123456 : α) * 123456 = 15241383936 := by norm_num1
end
section
variable [Field α] [LinearOrder α] [IsStrictOrderedRing α]
example : (4 : α) / 2 = 2 := by norm_num1
example : (4 : α) / 1 = 4 := by norm_num1
example : (4 : α) / 3 = 4 / 3 := by norm_num1
example : (50 : α) / 5 = 10 := by norm_num1
example : (1056 : α) / 1 = 1056 := by norm_num1
example : (6 : α) / 4 = 3/2 := by norm_num1
example : (0 : α) / 3 = 0 := by norm_num1
example : (3 : α) / 0 = 0 := by norm_num1
example : (9 * 9 * 9) * (12 : α) / 27 = 81 * (2 + 2) := by norm_num1
example : (-2 : α) * 4 / 3 = -8 / 3 := by norm_num1
example : - (-4 / 3) = 1 / (3 / (4 : α)) := by norm_num1
end
-- user command
set_option linter.style.commandStart false
/-- info: True -/
#guard_msgs in #norm_num 1 = 1
example : 1 = 1 := by norm_num1
/-- info: True -/
#guard_msgs in #norm_num 2^4-1 ∣ 2^16-1
example : 2^4-1 ∣ 2^16-1 := by norm_num1
-- #norm_num (3 : Real) ^ (-2 : ℤ) = 1/9
-- example : (3 : Real) ^ (-2 : ℤ) = 1/9 := by norm_num1
section norm_num_cmd_variable
-- [fixme] obsolete?
-- variables (x y : ℕ)
-- #norm_num bit0 x < bit0 (y + x) ↔ 0 < y
-- example : bit0 x < bit0 (y + x) ↔ 0 < y := by norm_num1
-- #norm_num bit0 x < bit0 (y + (2^10%11 - 1) + x) ↔ 0 < y
-- example : bit0 x < bit0 (y + (2^10%11 - 1) + x) ↔ 0 < y := by norm_num1
-- #norm_num bit0 x < bit0 (y + (2^10%11 - 1) + x) + 3*2-6 ↔ 0 < y
-- example : bit0 x < bit0 (y + (2^10%11 - 1) + x) + 3*2-6 ↔ 0 < y := by norm_num1
end norm_num_cmd_variable
section norm_num_erase
example : 3 ^ 3 + 4 = 31 := by norm_num1
set_option linter.unusedTactic false in
attribute [-norm_num] Mathlib.Meta.NormNum.evalPow in
example : 3 ^ 3 + 4 = 31 := by
norm_num1
guard_target =ₛ 3 ^ 3 + 4 = 31
rfl
set_option linter.unusedTactic false in
set_option linter.unusedVariables false in
example {a b : ℚ} (h : a = b) : True := by
norm_num [*] at h
guard_hyp h : a = b
exact trivial
/- Check that the scoping above works: -/
example : 3 ^ 3 + 4 = 31 := by norm_num1
attribute [-norm_num] Mathlib.Meta.NormNum.evalPow
/-
If run, the following commented line of code will produce the error
"'Mathlib.Meta.NormNum.evalPow' does not have [norm_num] attribute".
This checks that the `norm_num` attribute is indeed considered to be erased from
`Mathlib.Meta.NormNum.evalPow` in this scope.
-/
-- attribute [-norm_num] Mathlib.Meta.NormNum.evalPow
end norm_num_erase
-- auto gen tests
variable [Field α] [LinearOrder α] [IsStrictOrderedRing α]
example : ((25 * (1 / 1)) + (30 - 16)) = (39 : α) := by norm_num1
example : ((19 * (- 2 - 3)) / 6) = (-95/6 : α) := by norm_num1
example : - (3 * 28) = (-84 : α) := by norm_num1
example : - - (16 / ((11 / (- - (6 * 19) + 12)) * 21)) = (96/11 : α) := by norm_num1
example : (- (- 21 + 24) - - (- - (28 + (- 21 / - (16 / ((1 * 26) * ((0 * - 11) + 13))))) * 21)) =
(79209/8 : α) := by norm_num1
example : (27 * (((16 + - (12 + 4)) + (22 - - 19)) - 23)) = (486 : α) := by norm_num1
example : - (13 * (- 30 / ((7 / 24) + - 7))) = (-9360/161 : α) := by norm_num1
example : - (0 + 20) = (-20 : α) := by norm_num1
example : (- 2 - (27 + (((2 / 14) - (7 + 21)) + (16 - - - 14)))) = (-22/7 : α) := by norm_num1
example : (25 + ((8 - 2) + 16)) = (47 : α) := by norm_num1
example : (- - 26 / 27) = (26/27 : α) := by norm_num1
example : ((((16 * (22 / 14)) - 18) / 11) + 30) = (2360/77 : α) := by norm_num1
example : (((- 28 * 28) / (29 - 24)) * 24) = (-18816/5 : α) := by norm_num1
example : ((- (18 - ((- - (10 + - 2) - - (23 / 5)) / 5)) - (21 * 22)) -
(((20 / - ((((19 + 18) + 15) + 3) + - 22)) + 14) / 17)) = (-394571/825 : α) := by norm_num1
example : ((3 + 25) - - 4) = (32 : α) := by norm_num1
example : ((1 - 0) - 22) = (-21 : α) := by norm_num1
example : (((- (8 / 7) / 14) + 20) + 22) = (2054/49 : α) := by norm_num1
example : ((21 / 20) - 29) = (-559/20 : α) := by norm_num1
example : - - 20 = (20 : α) := by norm_num1
example : (24 - (- 9 / 4)) = (105/4 : α) := by norm_num1
example : (((7 / ((23 * 19) + (27 * 10))) - ((28 - - 15) * 24)) + (9 / - (10 * - 3))) =
(-1042007/1010 : α) := by norm_num1
example : (26 - (- 29 + (12 / 25))) = (1363/25 : α) := by norm_num1
example : ((11 * 27) / (4 - 5)) = (-297 : α) := by norm_num1
example : (24 - (9 + 15)) = (0 : α) := by norm_num1
example : (- 9 - - 0) = (-9 : α) := by norm_num1
example : (- 10 / (30 + 10)) = (-1/4 : α) := by norm_num1
example : (22 - (6 * (28 * - 8))) = (1366 : α) := by norm_num1
example : ((- - 2 * (9 * - 3)) + (22 / 30)) = (-799/15 : α) := by norm_num1
example : - (26 / ((3 + 7) / - (27 * (12 / - 16)))) = (-1053/20 : α) := by norm_num1
example : ((- 29 / 1) + 28) = (-1 : α) := by norm_num1
example : ((21 * ((10 - (((17 + 28) - - 0) + 20)) + 26)) + ((17 + - 16) * 7)) = (-602 : α) := by
norm_num1
example : (((- 5 - ((24 + - - 8) + 3)) + 20) + - 23) = (-43 : α) := by norm_num1
example : ((- ((14 - 15) * (14 + 8)) + ((- (18 - 27) - 0) + 12)) - 11) = (32 : α) := by norm_num1
example : (((15 / 17) * (26 / 27)) + 28) = (4414/153 : α) := by norm_num1
example : (14 - ((- 16 - 3) * - (20 * 19))) = (-7206 : α) := by norm_num1
example : (21 - - - (28 - (12 * 11))) = (125 : α) := by norm_num1
example : ((0 + (7 + (25 + 8))) * - (11 * 27)) = (-11880 : α) := by norm_num1
example : (19 * - 5) = (-95 : α) := by norm_num1
example : (29 * - 8) = (-232 : α) := by norm_num1
example : ((22 / 9) - 29) = (-239/9 : α) := by norm_num1
example : (3 + (19 / 12)) = (55/12 : α) := by norm_num1
example : - (13 + 30) = (-43 : α) := by norm_num1
example : - - - (((21 * - - ((- 25 - (- (30 - 5) / (- 5 - 5))) /
(((6 + ((25 * - 13) + 22)) - 3) / 2))) / (- 3 / 10)) * (- 8 - 0)) = (-308/3 : α) := by norm_num1
example : - (2 * - (- 24 * 22)) = (-1056 : α) := by norm_num1
example : - - (((28 / - ((- 13 * - 5) / - (((7 - 30) / 16) + 6))) * 0) - 24) = (-24 : α) := by
norm_num1
example : ((13 + 24) - (27 / (21 * 13))) = (3358/91 : α) := by norm_num1
example : ((3 / - 21) * 25) = (-25/7 : α) := by norm_num1
example : (17 - (29 - 18)) = (6 : α) := by norm_num1
example : ((28 / 20) * 15) = (21 : α) := by norm_num1
example : ((((26 * (- (23 - 13) - 3)) / 20) / (14 - (10 + 20))) / ((16 / 6) / (16 * - (3 / 28)))) =
(-1521/2240 : α) := by norm_num1
example : (46 / (- ((- 17 * 28) - 77) + 87)) = (23/320 : α) := by norm_num1
example : (73 * - (67 - (74 * - - 11))) = (54531 : α) := by norm_num1
example : ((8 * (25 / 9)) + 59) = (731/9 : α) := by norm_num1
example : - ((59 + 85) * - 70) = (10080 : α) := by norm_num1
example : (66 + (70 * 58)) = (4126 : α) := by norm_num1
example : (- - 49 * 0) = (0 : α) := by norm_num1
example : ((- 78 - 69) * 9) = (-1323 : α) := by norm_num1
example : - - (7 - - (50 * 79)) = (3957 : α) := by norm_num1
example : - (85 * (((4 * 93) * 19) * - 31)) = (18624180 : α) := by norm_num1
example : (21 + (- 5 / ((74 * 85) / 45))) = (26373/1258 : α) := by norm_num1
example : (42 - ((27 + 64) + 26)) = (-75 : α) := by norm_num1
example : (- ((38 - - 17) + 86) - (74 + 58)) = (-273 : α) := by norm_num1
example : ((29 * - (75 + - 68)) + (- 41 / 28)) = (-5725/28 : α) := by norm_num1
example : (- - (40 - 11) - (68 * 86)) = (-5819 : α) := by norm_num1
example : (6 + ((65 - 14) + - 89)) = (-32 : α) := by norm_num1
example : (97 * - (29 * 35)) = (-98455 : α) := by norm_num1
example : - (66 / 33) = (-2 : α) := by norm_num1
example : - ((94 * 89) + (79 - (23 - (((- 1 / 55) + 95) * (28 - (54 / - - - 22)))))) =
(-1369070/121 : α) := by norm_num1
example : (- 23 + 61) = (38 : α) := by norm_num1
example : - (93 / 69) = (-31/23 : α) := by norm_num1
example : (- - ((68 / (39 + (((45 * - (59 - (37 + 35))) / (53 - 75)) -
- (100 + - (50 / (- 30 - 59)))))) - (69 - (23 * 30))) / (57 + 17)) = (137496481/16368578 : α) := by
norm_num1
example : (- 19 * - - (75 * - - 41)) = (-58425 : α) := by norm_num1
example : ((3 / ((- 28 * 45) * (19 + ((- (- 88 - (- (- 1 + 90) + 8)) + 87) * 48)))) + 1) =
(1903019/1903020 : α) := by norm_num1
example : ((- - (28 + 48) / 75) + ((- 59 - 14) - 0)) = (-5399/75 : α) := by norm_num1
example : (- ((- (((66 - 86) - 36) / 94) - 3) / - - (77 / (56 - - - 79))) + 87) =
(312254/3619 : α) := by norm_num1
example : 2 ^ 13 - 1 = Int.ofNat 8191 := by norm_num1
set_option linter.unusedTactic false in
-- Since https://github.com/leanprover/lean4/pull/4177
-- `simp` will continue even if given invalid theorem names (but generates an error)
-- and this felicitously applies to `norm_num` too.
-- Previous this was a `fail_if_success` test, but now we just check for the error.
/-- error: Unknown identifier `this_doesnt_exist` -/
#guard_msgs in
example : 1 + 1 = 2 := by
norm_num [this_doesnt_exist]
done
example : 1 + 100 + a = a + 101 := by
norm_num [add_comm]
def R : Type u → Type v → Sort (max (u+1) (v+1)) := test_sorry
noncomputable instance : Field (R a b) := test_sorry
noncomputable instance : LinearOrder (R a b) := test_sorry
noncomputable instance : IsStrictOrderedRing (R a b) := test_sorry
example : (1 : R PUnit.{u+1} PUnit.{v+1}) <= 2 := by
norm_num
-- Check that we avoid deep recursion in evaluating large powers.
-- This used to be 10^40000000, but Lean's non-GMP multiplication is
-- asymptotically slower than the GMP implementation.
-- It would be great to fix that, and restore this test.
example : 10^400000 = 10^400000 := by norm_num
theorem large1 {α} [Ring α] : 2^(2^2000) + (2*2) - 2^(2^2000) = (4 : α) := by
-- large powers ignored rather than hanging
set_option exponentiation.threshold 20 in
norm_num1 -- TODO: this should warn, but the warning is discarded
simp only [add_sub_cancel_left] |
.lake/packages/mathlib/MathlibTest/hintAll.lean | import Mathlib.Algebra.Order.Floor.Semifield
import Mathlib.Analysis.Normed.Group.Basic
import Mathlib.Data.ENNReal.Basic
import Mathlib.Data.Nat.Prime.Defs
import Mathlib.Tactic.Abel
import Mathlib.Tactic.Bound
import Mathlib.Tactic.Common
import Mathlib.Tactic.ComputeDegree
import Mathlib.Tactic.Field
import Mathlib.Tactic.FieldSimp
import Mathlib.Tactic.Finiteness
import Mathlib.Tactic.GCongr
import Mathlib.Tactic.Group
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.NoncommRing
import Mathlib.Tactic.NormNum.Core
import Mathlib.Tactic.Positivity.Core
import Mathlib.Tactic.Ring.RingNF
import Mathlib.Tactic.TautoSet
/--
info: Try these:
[apply] 🎉 trivial
[apply] norm_num
Remaining subgoals:
⊢ False
-/
#guard_msgs in
example (h : 1 < 0) : False := by hint
/--
info: Try these:
[apply] 🎉 simp_all only [forall_const]
[apply] norm_num
Remaining subgoals:
⊢ Q
[apply] group
Remaining subgoals:
⊢ Q
-/
#guard_msgs in
example {P Q : Prop} (p : P) (f : P → Q) : Q := by hint
/--
info: Try these:
[apply] 🎉 simp_all only [and_self]
[apply] norm_num
Remaining subgoals:
⊢ Q ∧ P ∧ R
[apply] group
Remaining subgoals:
⊢ Q ∧ P ∧ R
-/
#guard_msgs in
example {P Q R : Prop} (x : P ∧ Q ∧ R ∧ R) : Q ∧ P ∧ R := by hint
/--
info: Try these:
[apply] 🎉 exact Std.not_gt_of_lt h
[apply] intro
Remaining subgoals:
⊢ False
[apply] norm_num
Remaining subgoals:
⊢ a ≤ b
[apply] group
Remaining subgoals:
⊢ ¬b < a
[apply] simp_all only [not_lt]
Remaining subgoals:
⊢ a ≤ b
-/
#guard_msgs in
example {a b : ℚ} (h : a < b) : ¬ b < a := by hint
/--
info: Try these:
[apply] 🎉 ring
[apply] noncomm_ring
Remaining subgoals:
⊢ 1369 • 1 - 1225 • 1 = 72 • 2
-/
#guard_msgs in
example : 37^2 - 35^2 = 72 * 2 := by hint
/--
info: Try these:
[apply] 🎉 decide
[apply] ring_nf
Remaining subgoals:
⊢ Nat.Prime 37
[apply] norm_num
Remaining subgoals:
⊢ Nat.Prime 37
-/
#guard_msgs in
example : Nat.Prime 37 := by hint
/--
info: Try these:
[apply] 🎉 grind
[apply] ring_nf
Remaining subgoals:
⊢ ∃ x, P x ∧ 0 ≤ x
[apply] norm_num
Remaining subgoals:
⊢ ∃ x, P x
[apply] group
Remaining subgoals:
⊢ ∃ x, P x ∧ 0 ≤ x
[apply] simp_all only [zero_le, and_true]
Remaining subgoals:
⊢ ∃ x, P x
-/
#guard_msgs in
example {P : Nat → Prop} (h : { x // P x }) : ∃ x, P x ∧ 0 ≤ x := by hint
section multiline_hint
local macro "this_is_a_multiline_exact" ppLine t:term : tactic => `(tactic| exact $t)
local elab tk:"long_trivial" : tactic => do
let triv := Lean.mkIdent ``trivial
let actual ← `(tactic| this_is_a_multiline_exact $triv)
Lean.Meta.Tactic.TryThis.addSuggestion tk { suggestion := .tsyntax actual}
Lean.Elab.Tactic.evalTactic actual
register_hint 1000 long_trivial
/--
info: Try these:
[apply] 🎉 long_trivial
-/
#guard_msgs in
example : True := by
hint
end multiline_hint
section finiteness
/--
info: Try these:
[apply] 🎉 finiteness
-/
#guard_msgs in
open ENNReal in
example : (1 : ℝ≥0∞) < ∞ := by hint
end finiteness
section tauto_set
register_hint 1000 tauto_set
/--
info: Try these:
[apply] 🎉 tauto_set
-/
#guard_msgs in
example {α} (A B C : Set α) (h1 : A ⊆ B ∪ C) : (A ∩ B) ∪ (A ∩ C) = A := by hint
/--
info: Try these:
[apply] aesop
Remaining subgoals:
⊢ False
[apply] ring_nf
Remaining subgoals:
⊢ 2 ≤ 1
[apply] norm_num
Remaining subgoals:
⊢ False
[apply] group
Remaining subgoals:
⊢ 2 ≤ 1
[apply] simp_all only [Nat.not_ofNat_le_one]
Remaining subgoals:
⊢ False
---
warning: declaration uses 'sorry'
-/
#guard_msgs in
example : 2 ≤ 1 := by hint
section compute_degree
/--
info: Try these:
[apply] 🎉 compute_degree
-/
#guard_msgs in
open Polynomial in
example : natDegree ((X + 1) : Nat[X]) ≤ 1 := by hint
end compute_degree
section field_simp
#adaptation_note
/--
As of nightly-2025-08-27,
this test no longer reports `field_simp` amongst the successful tactics.
-/
/--
info: Try these:
[apply] 🎉 exact Units.divp_add_divp_same a b u₁
[apply] ring_nf
Remaining subgoals:
⊢ a /ₚ u₁ + b /ₚ u₁ = (a + b) /ₚ u₁
[apply] abel_nf
Remaining subgoals:
⊢ a /ₚ u₁ + b /ₚ u₁ = (a + b) /ₚ u₁
[apply] norm_num
Remaining subgoals:
⊢ a /ₚ u₁ + b /ₚ u₁ = (a + b) /ₚ u₁
[apply] group
Remaining subgoals:
⊢ a /ₚ u₁ + b /ₚ u₁ = (a + b) /ₚ u₁
-/
#guard_msgs in
example (R : Type) (a b : R) [CommRing R] (u₁ : Rˣ) : a /ₚ u₁ + b /ₚ u₁ = (a + b) /ₚ u₁ := by hint
end field_simp
-- This test was originally here to ensure `finiteness` closed the goal,
-- but apparently `tauto_set` also works.
/--
info: Try these:
[apply] 🎉 tauto_set
-/
#guard_msgs in
open ENNReal in
example : (1 : ℝ≥0∞) < ∞ := by hint |
.lake/packages/mathlib/MathlibTest/fun_prop.lean | import Mathlib.MeasureTheory.MeasurableSpace.Basic
import Mathlib.MeasureTheory.Constructions.BorelSpace.ContinuousLinearMap
import Mathlib.MeasureTheory.Constructions.BorelSpace.Real
import Mathlib.Analysis.Calculus.ContDiff.Basic
import Mathlib.Topology.Constructions
import Mathlib.Tactic.FunProp
open Mathlib
/-!
The first step in using `fun_prop` is to mark desired function property with `fun_prop` attribute.
In this example we work with `Measurable`.
-/
attribute [fun_prop] Measurable
/-!
Now we can start marking theorems about `Measurable` with the attribute `@[fun_prop]`.
It is best to start with the basic lambda calculus rules. There are five of these rules in total
- identity rule `Measurable fun x => x`
- constant rule `Measurable fun x => y`
- composition rule `Measurable f → Measurable g → Measurable fun x => f (g x)`
- apply rule `Measurable fun f => f x`
- pi rule `∀ i, Measurable (f · i) → Measurable fun x i => f x i`
You do not have to provide them all. For example `IsLinearMap` does not have the constant rule.
However, to have any hope at using `fun_prop` successfully you need to at least provide identity
and composition rule.
-/
attribute [fun_prop]
measurable_id'
measurable_const
Measurable.comp'
measurable_pi_apply
measurable_pi_lambda
/-!
Measurability also behaves nicely with respect to taking products.
Let's mark the product constructor.
-/
attribute [fun_prop]
Measurable.prodMk -- Measurable f → Measurable g → Measurable fun x => (f x, g x)
/-!
When it comes to product projection, their properties are usually stated in two different ways
```
measurable_fst : Measurable fun x => Prod.fst x
```
or
```
Measurable.fst : Measurable f → Measurable fun x => Prod.fst (f x)
```
The tactic `fun_prop` can work with both versions;
it should be sufficient to provide just one of them.
It does not hurt to provide both of them though.
-/
attribute [fun_prop]
measurable_fst
Measurable.fst
measurable_snd
Measurable.snd
/-!
A silly example on which `measurability` fails and `fun_prop` succeeds. Let's turn on tracing
to see what is going on
set_option trace.Meta.Tactic.fun_prop true in
-/
example {α} [MeasurableSpace α] (f : α → α → α) (hf : Measurable fun (x, y) ↦ f x y) (a : α) :
Measurable (fun x => (f x a, f (f x x) (f (f x x) x))) := by
-- This now takes longer than 200,000 heartbeats to fail, so I've commented it out.
-- fail_if_success measurability
fun_prop
/-!
To give more complicated examples we mark theorems about arithmetic operations with `@[fun_prop]`
Again we mark both versions of theorems. Internally `fun_prop` says that theorems like
`measurable_add` are in "uncurried form" and theorems like `Measurable.add` are in compositional
form.
-/
attribute [fun_prop]
measurable_add
measurable_sub
measurable_mul
measurable_neg
measurable_div
measurable_smul
Measurable.add
Measurable.sub
Measurable.mul
Measurable.neg
Measurable.div
Measurable.smul
/-!
An example of measurability of some arithmetic function
-/
example : Measurable fun x : ℝ => (x * x - 1) / x + (x - x*x) := by fun_prop
/-!
So far we talked about two types of theorems:
1. theorems about basic lambda calculus terms
2. theorems about defined functions
There are two other kinds of theorems `fun_prop` can work with:
3. transition theorems - theorems that imply e.g. measurability from continuity
4. morphism theorems - theorems talking about bundles
When you mark a theorem with `@[fun_prop]` attribute you can check the type of the
theorem by turning on the option `trace.Meta.Tactic.fun_prop.attr`.
-/
/-!
Transition theorems prove one function property from another. We already mentioned
that continuity implies measurability but there are many more. For example differentiability
implies continuity, linear map between finitely-dimensional spaces is continuous etc.
The theorem proving measurability from continuity is `Continuous.measurable` so let's
mark it with `@[fun_prop]`
-/
attribute [fun_prop]
Continuous.measurable -- Continuous f → Measurable f
/-!
For this theorem to be used properly we also need to set up `Continuous` with `fun_prop`.
The bare bones setup is
-/
attribute [fun_prop]
Continuous
continuous_id'
continuous_const
Continuous.comp'
continuous_pi
continuous_apply
Continuous.prodMk
Continuous.fst
Continuous.snd
/-!
Now we can prove one of the earlier examples assuming the function is continuous instead of
measurable.
-/
example (f : ℝ → ℝ → ℝ) (hf : Continuous fun (x, y) ↦ f x y) (a : ℝ) :
Measurable (fun x => (f x a, f (f x x) (f (f x x) x))) := by fun_prop
/-!
To keep `fun_prop` performant it is important to keep these "transition theorems" in the form
`P f → Q f` i.e. the conclusion has to talk about a single free variable `f`. Furthermore,
the "transition theorems" should **not** form a cycle.
-/
/-!
Lastly there are "morphism theorems". These are really just theorems about the properties of
`DFunLike.coe` and are treated somewhat specially.
Let's make continuous linear maps work with measurability. The function `DFunLike.coe` is
a function of two arguments `f : E →L[K] F` and `x : E`. Mathlib currently states
measurability of `DFunLike.coe` in `f` and `x` separately.
The theorem `ContinuousLinearMap.measurable` states measurability in `x` in uncurried form.
The theorem `ContinuousLinearMap.measurable_comp` states measurability in `x` in compositional form.
The theorem `ContinuousLinearMap.measurable_apply` states measurability in `f` in uncurried form.
The theorem `Measurable.apply_continuousLinearMap` states measurability in `f` in compositional
form.
-/
set_option linter.style.longLine false in
attribute [fun_prop]
ContinuousLinearMap.measurable -- Measurable fun (x : E) => DFunLike.coe L x
ContinuousLinearMap.measurable_comp -- Measurable φ → Measurable fun (x : E) => DFunLike.coe L (φ x)
ContinuousLinearMap.measurable_apply -- Measurable fun (f : E →L[K] F) => DFunLike.coe f x
Measurable.apply_continuousLinearMap -- Measurable L → Measurable fun (x : α) => DFunLike.coe (L x) v
/-!
A silly example that everything together works as expected
-/
example (f : ℝ → ℝ → (ℝ →L[ℝ] ℝ)) (hf : Continuous (fun (x, y) ↦ f x y)) :
Measurable fun x => (f (x / x) (x * x) 1 + x) := by fun_prop
set_option linter.style.longLine false in
/-!
In the current state of `fun_prop`, morphism theorems **have to** be stated in compositional form.
Sometimes they might work in uncurried form but `fun_prop` is not designed that way right now.
In other cases the function property of `DFunLike.coe` can be stated jointly in `f` and `x`.
This is the case of `ContDiff n` and continuous linear maps. The theorem is `ContDiff.clm_apply`.
#check ContDiff.clm_apply -- {f : E → F →L[K] G} → {g : E → F} → ContDiff K n f → ContDiff K n g → ContDiff K n fun x => DFunLike.coe (f x) (g x)
If possible, `fun_prop` theorem about `DFunLike.coe` should be state in this way.
That should be all about `fun_prop`, I hope you will enjoy using it :)
-/ |
.lake/packages/mathlib/MathlibTest/byContra.lean | -- tests for by_contra! tactic
import Mathlib.Tactic.ByContra
import Mathlib.Tactic.Rename
import Mathlib.Tactic.Set
import Mathlib.Algebra.Notation.Defs
import Mathlib.Data.Nat.Basic
import Mathlib.Order.Basic
set_option autoImplicit true
example (a b : ℕ) (foo : False) : a < b := by
by_contra!
guard_hyp this : b ≤ a
exact foo
example (a b : ℕ) (h : False) : a < b := by
by_contra! foo
revert foo; change b ≤ a → False; intro;
exact h
example (a b : ℕ) (h : False) : a < b := by
by_contra! foo : ¬ a < b -- can avoid push_neg
guard_hyp foo : ¬ a < b
exact h
example : 1 < 2 := by
by_contra!
guard_hyp this : 2 ≤ 1
contradiction
example (_p : Prop) (bar : False) : ¬ ¬ ¬ ¬ ¬ ¬ P := by
by_contra! foo : ¬ ¬ ¬ P -- normalises to ¬ P, as does ¬ (goal).
guard_hyp foo : ¬ ¬ ¬ P
exact bar
example (_p : Prop) (bar : False) : ¬ ¬ ¬ ¬ ¬ ¬ P := by
by_contra! : ¬ ¬ ¬ P
guard_hyp this : ¬ ¬ ¬ P
exact bar
variable [LinearOrder α] [One α] [Mul α]
example (x : α) (f : False) : x ≤ 1 := by
set a := x * x
by_contra! h
guard_hyp h : 1 < x
assumption
example (x : α) (f : False) : x ≤ 1 := by
let _a := x * x
by_contra! h
guard_hyp h : 1 < x
assumption
example (x : α) (f : False) : x ≤ 1 := by
set a := x * x
have : a ≤ a := le_rfl
by_contra! h
guard_hyp h : 1 < x
assumption |
.lake/packages/mathlib/MathlibTest/LintStyle.lean | import Mathlib.Tactic.Linter.Style
import Mathlib.Order.SetNotation
/-! Tests for all the style linters. -/
/-! Tests for the `setOption` linter -/
section setOption
set_option linter.style.setOption true
-- All types of options are supported: Boolean, numeric and string-valued.
-- On the top level, i.e. as commands.
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option pp.all'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
set_option pp.all true
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option profiler'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
set_option profiler false
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option pp.all'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
set_option pp.all false
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option profiler.threshold'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
set_option profiler.threshold 50
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option trace.profiler.output'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
set_option trace.profiler.output "foo"
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option debug.moduleNameAtTimeout'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
set_option debug.moduleNameAtTimeout false
-- The lint does not fire on arbitrary options.
set_option autoImplicit false
-- We also cover set_option tactics.
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option pp.all'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
lemma tactic : True := by
set_option pp.all true in
trivial
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option pp.raw.maxDepth'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
lemma tactic2 : True := by
set_option pp.raw.maxDepth 32 in
trivial
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option pp.all'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
lemma tactic3 : True := by
set_option pp.all false in
trivial
/--
warning: Setting options starting with 'debug', 'pp', 'profiler', 'trace' is only intended
for development and not for final code. If you intend to submit this contribution to the
Mathlib project, please remove 'set_option trace.profiler.output'.
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
lemma tactic4 : True := by
set_option trace.profiler.output "foo" in
trivial
-- This option is not affected, hence does not throw an error.
set_option autoImplicit true in
lemma foo' : True := trivial
-- TODO: add terms for the term form
/--
warning: Unscoped option maxHeartbeats is not allowed:
Please scope this to individual declarations, as in
```
set_option maxHeartbeats in
-- comment explaining why this is necessary
example : ... := ...
```
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
set_option maxHeartbeats 20
#guard_msgs in
set_option maxHeartbeats 20 in
section
end
/--
warning: Unscoped option synthInstance.maxHeartbeats is not allowed:
Please scope this to individual declarations, as in
```
set_option synthInstance.maxHeartbeats in
-- comment explaining why this is necessary
example : ... := ...
```
Note: This linter can be disabled with `set_option linter.style.setOption false`
-/
#guard_msgs in
set_option synthInstance.maxHeartbeats 20
#guard_msgs in
set_option synthInstance.maxHeartbeats 20 in
section
end
end setOption
section cdotLinter
set_option linter.style.cdot true
set_option linter.globalAttributeIn false in
/--
warning: Please, use '·' (typed as `\.`) instead of '.' as 'cdot'.
Note: This linter can be disabled with `set_option linter.style.cdot false`
---
warning: Please, use '·' (typed as `\.`) instead of '.' as 'cdot'.
Note: This linter can be disabled with `set_option linter.style.cdot false`
---
warning: Please, use '·' (typed as `\.`) instead of '.' as 'cdot'.
Note: This linter can be disabled with `set_option linter.style.cdot false`
-/
#guard_msgs in
attribute [instance] Int.add in
instance : Inhabited Nat where
default := by
. have := 0
· have : Nat → Nat → Nat := (· + .)
. exact 0
/--
warning: Please, use '·' (typed as `\.`) instead of '.' as 'cdot'.
Note: This linter can be disabled with `set_option linter.style.cdot false`
-/
#guard_msgs in
example : Add Nat where add := (. + ·)
/--
warning: Please, use '·' (typed as `\.`) instead of '.' as 'cdot'.
Note: This linter can be disabled with `set_option linter.style.cdot false`
-/
#guard_msgs in
example : Add Nat where add := (. + ·)
/--
warning: Please, use '·' (typed as `\.`) instead of '.' as 'cdot'.
Note: This linter can be disabled with `set_option linter.style.cdot false`
---
warning: This central dot `·` is isolated; please merge it with the next line.
Note: This linter can be disabled with `set_option linter.style.cdot false`
---
warning: This central dot `·` is isolated; please merge it with the next line.
Note: This linter can be disabled with `set_option linter.style.cdot false`
-/
#guard_msgs in
example : Nat := by
have : Nat := by
·
-- some empty have
have := 0
·
-- another
have := 1
. exact 2
exact 0
#guard_msgs in
example : True := by
have : Nat := by
-- This is how code should look: no error.
· -- comment
exact 37
trivial
end cdotLinter
set_option linter.style.dollarSyntax true
set_option linter.globalAttributeIn false in
/--
warning: Please use '<|' instead of '$' for the pipe operator.
Note: This linter can be disabled with `set_option linter.style.dollarSyntax false`
---
warning: Please use '<|' instead of '$' for the pipe operator.
Note: This linter can be disabled with `set_option linter.style.dollarSyntax false`
-/
#guard_msgs in
attribute [instance] Int.add in
instance (f g : Nat → Nat) : Inhabited Nat where
default := by
· have := 0
· have : Nat := f $ g $ 0
· exact 0
section lambdaSyntaxLinter
set_option linter.style.lambdaSyntax true
/--
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
-/
#guard_msgs in
example : ℕ → ℕ := λ _ ↦ 0
/--
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
-/
#guard_msgs in
def foo : Bool := by
let _f : ℕ → ℕ := λ _ ↦ 0
exact true
example : ℕ → ℕ := fun n ↦ n - 1
/--
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
-/
#guard_msgs in
example : ℕ → ℕ := by exact λ n ↦ 3 * n + 1
/--
warning: declaration uses 'sorry'
---
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
---
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
---
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
-/
#guard_msgs in
example : ℕ → ℕ → ℕ → ℕ := by
have (n : ℕ) : True := trivial
have : (Set.univ : Set ℕ) = ⋃ (i : ℕ), (Set.iUnion λ j ↦ ({0, j} : Set ℕ)) := sorry
have : ∃ m : ℕ, ⋃ i : ℕ, (Set.univ : Set ℕ) = ∅ := sorry
exact λ _a ↦ fun _b ↦ λ _c ↦ 0
/--
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
---
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
---
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
-/
#guard_msgs in
example : True := by
have : 0 = 0 ∧ 0 = 0 ∧ 1 + 3 = 4 := by
refine ⟨by trivial, by
let _f := λ n : ℕ ↦ 0;
have : ℕ := by
· -- comment
· have := λ k : ℕ ↦ -5
· exact 0
refine ⟨by trivial, have := λ k : ℕ ↦ -5; by simp⟩
⟩
trivial
-- Code such as the following would require walking the infotree instead:
-- the inner set_option is ignore (in either direction).
-- As this seems unlikely to occur by accident and its use is dubious, we don't worry about this.
/--
warning: Please use 'fun' and not 'λ' to define anonymous functions.
The 'λ' syntax is deprecated in mathlib4.
Note: This linter can be disabled with `set_option linter.style.lambdaSyntax false`
-/
#guard_msgs in
example : ℕ → ℕ := λ _ ↦ 0
set_option linter.style.lambdaSyntax false
#guard_msgs in
example : ℕ → ℕ := λ _ ↦ 0
end lambdaSyntaxLinter
set_option linter.style.longLine true
/--
warning: This line exceeds the 100 character limit, please shorten it!
Note: This linter can be disabled with `set_option linter.style.longLine false`
-/
#guard_msgs in
/-! -/
#guard_msgs in
-- Lines with more than 100 characters containing URLs are allowed.
/-! http -/
set_option linter.style.longLine true
-- The *argument* of `#guard_msgs` is *not* exempt from the linter.
/--
warning: This line exceeds the 100 character limit, please shorten it!
Note: This linter can be disabled with `set_option linter.style.longLine false`
-/
#guard_msgs in #guard true
-- However, the *doc-string* of #guard_msgs is exempt from the linter:
-- these are automatically generated, hence linting them is not helpful.
/--
info: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
-/
#guard_msgs in
#eval List.range 27
-- TODO: this used to error about the 100 character limit (mentioning string gaps),
-- restore this test!
/-- info: " \" " : String -/
#guard_msgs in
#check " \" \
"
/- Tests for the `openClassical` linter -/
section openClassical
set_option linter.style.openClassical true
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements
which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open Classical
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements
which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open Nat Classical Nat
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements
which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open Classical hiding choose
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements
which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open Classical hiding choose axiomOfChoice
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements
which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open Classical renaming choose -> foo, byCases -> bar
-- Only opening specific items.
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements
which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open Classical (choose)
-- `open scoped Classical` is also linted
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements
which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open scoped Classical
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
---
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open scoped Int Classical Nat Classical
-- `open ... in` is *not* linted.
#guard_msgs in
open Classical (choose) in
def bar : Nat := 1
#guard_msgs in
open scoped Classical in
def baz : Nat := 1
-- After one `open Classical` statement, the linter does not fire on subsequent declarations.
/--
warning: please avoid 'open (scoped) Classical' statements: this can hide theorem statements which would be better stated with explicit decidability statements.
Instead, use `open Classical in` for definitions or instances, the `classical` tactic for proofs.
For theorem statements, either add missing decidability assumptions or use `open Classical in`.
Note: This linter can be disabled with `set_option linter.style.openClassical false`
-/
#guard_msgs in
open Classical
#guard_msgs in
def aux : Nat := 1
#guard_msgs in
def aux' : Nat := 1
end openClassical
/- Tests for the `show` linter -/
section showLinter
set_option linter.style.show true
-- The linter doesn't complain if the goal stays the same
#guard_msgs in
example : 1 + 2 = 3 := by
show 1 + 2 = 3
rfl
-- Binder names are ignored
#guard_msgs in
example : ∀ a : Nat, a = a := by
show ∀ b : Nat, b = b
intro
rfl
-- Goal changes are linted
/--
warning: The `show` tactic should only be used to indicate intermediate goal states for readability.
However, this tactic invocation changed the goal. Please use `change` instead for these purposes.
Note: This linter can be disabled with `set_option linter.style.show false`
-/
#guard_msgs in
example : (fun a => a) 1 = 1 := by
show 1 = 1
rfl
-- Assigning meta-variables in the goal is also linted
/--
warning: The `show` tactic should only be used to indicate intermediate goal states for readability.
However, this tactic invocation changed the goal. Please use `change` instead for these purposes.
Note: This linter can be disabled with `set_option linter.style.show false`
-/
#guard_msgs in
example := by
show 1 = 1
rfl
end showLinter |
.lake/packages/mathlib/MathlibTest/IsBoundedDefault.lean | import Mathlib.Data.EReal.Basic
import Mathlib.Order.LiminfLimsup
open Filter
variable {α : Type*} {f : Filter α} {u v : α → EReal} (h : u ≤ᶠ[f] v)
-- proof term
example : limsup u f ≤ limsup v f := limsup_le_limsup h
-- exact
example : limsup u f ≤ limsup v f := by exact limsup_le_limsup h
-- apply
example : limsup u f ≤ limsup v f := by apply limsup_le_limsup h |
.lake/packages/mathlib/MathlibTest/Group.lean | import Mathlib.Tactic.Group
variable {G : Type} [Group G]
example (a b c : G) : c*(a*b)*(b⁻¹*a⁻¹)*c = c*c := by group
example (a b c : G) : (b*c⁻¹)*c*(a*b)*(b⁻¹*a⁻¹)*c = b*c := by group
example (a b c : G) : c⁻¹*(b*c⁻¹)*c*(a*b)*(b⁻¹*a⁻¹*b⁻¹)*c = 1 := by group
-- The following is known as the Hall-Witt identity,
-- see e.g.
-- https://en.wikipedia.org/wiki/Three_subgroups_lemma#Proof_and_the_Hall%E2%80%93Witt_identity
example (g h k : G) : g*⁅⁅g⁻¹,h⁆,k⁆*g⁻¹*k*⁅⁅k⁻¹,g⁆,h⁆*k⁻¹*h*⁅⁅h⁻¹,k⁆,g⁆*h⁻¹ = 1 := by group
example (a : G) : a^2*a = a^3 := by group
example (n m : ℕ) (a : G) : a^n*a^m = a^(n+m) := by group
example (a b c : G) : c*(a*b^2)*((b*b)⁻¹*a⁻¹)*c = c*c := by group
example (n : ℕ) (a : G) : a^n*(a⁻¹)^n = 1 := by group
example (a : G) : a^2*a⁻¹*a⁻¹ = 1 := by group
example (n m : ℕ) (a : G) : a^n*a^m = a^(m+n) := by group
example (n : ℕ) (a : G) : a^(n-n) = 1 := by group
example (n : ℤ) (a : G) : a^(n-n) = 1 := by group
example (n : ℤ) (a : G) (h : a ^ (n * (n + 1) - n - n ^ 2) = a) : a = 1 := by
group at h
exact h.symm
example (a b c d : G) (h : c = (a * b ^ 2) * ((b * b)⁻¹ * a⁻¹) * d) : a*c*d⁻¹ = a := by
group at h
rw [h]
group
-- The next example can be expanded to require an arbitrarily high number of alternations
-- between simp and ring
example (n m : ℤ) (a b : G) : a^(m-n)*b^(m-n)*b^(n-m)*a^(n-m) = 1 := by group
example (n : ℤ) (a b : G) : a^n*b^n*a^n*a^n*a^(-n)*a^(-n)*b^(-n)*a^(-n) = 1 := by group
-- Test that group deals with `1⁻¹` properly
example (x y : G) : (x⁻¹ * (x * y) * y⁻¹)⁻¹ = 1 := by group
set_option linter.unusedTactic false in
example (x : G) (h : x = 1) : x = 1 := by
group
exact h |
.lake/packages/mathlib/MathlibTest/SplitIfs.lean | import Mathlib.Tactic.SplitIfs
example (x : Nat) (p : Prop) [Decidable p] : x = if p then x else x := by
split_ifs with h1
· rfl
· rfl
example (x y : Nat) (p : Prop) [Decidable p] (h : if p then x = y else y = x) : x = y := by
split_ifs at h
· exact h
· exact h.symm
example (x : Nat) (p q : Prop) [Decidable p] [Decidable q] :
x = if p then (if q then x else x) else x := by
split_ifs
· rfl
· rfl
· rfl
example (x : Nat) (p : Prop) [Decidable p] :
x = if (if p then False else True) then x else x := by
split_ifs
· rfl
· rfl
· rfl
example (p : Prop) [Decidable p] : if if ¬p then p else True then p else ¬p := by
split_ifs with h
· exact h
· exact h
theorem foo (p q : Prop) [Decidable p] [Decidable q] :
if if if p then ¬p else q then p else q then q else ¬p ∨ ¬q := by
split_ifs with h1 h2 h3
· exact h2
· exact Or.inr h2
· exact Or.inl h1
· exact Or.inr h3
/-- info: 'foo' does not depend on any axioms -/
#guard_msgs in #print axioms foo
example (p : Prop) [Decidable p] (h : (if p then 1 else 2) > 3) : False := by
split_ifs at h
cases h
· case pos.step h => cases h
· case neg h =>
cases h
case step h =>
cases h
case step h => cases h
example (p : Prop) [Decidable p] (x : Nat) (h : (if p then 1 else 2) > x) :
x < (if ¬p then 1 else 0) + 1 := by
split_ifs at * <;> assumption
example (p : Prop) [Decidable p] : if if ¬p then p else True then p else ¬p := by
split_ifs <;>
assumption
example (p q : Prop) [Decidable p] [Decidable q] :
if if if p then ¬p else q then p else q then q else ¬p ∨ ¬q := by
split_ifs <;>
simp [*]
example : True := by
fail_if_success { split_ifs }
trivial
open scoped Classical in
set_option linter.unusedVariables false in
example (P Q : Prop) (w : if P then (if Q then true else true) else true = true) : true := by
split_ifs at w
-- check that we've fully split w into three subgoals
· trivial
· trivial
· trivial
set_option linter.unusedTactic false in
example (u : Nat) : (if u = u then 0 else 1) = 0 := by
have h : u = u := by rfl
split_ifs
-- only one goal here
rfl
done |
.lake/packages/mathlib/MathlibTest/AesopUnusedTactic.lean | import Aesop
import Mathlib.Tactic.Linter.UnusedTactic
set_option linter.unusedTactic true
/-
The unused tactic linter should not consider tactics unused if they appear in
Aesop's `add_aesop_rules` command...
-/
add_aesop_rules safe (by simp)
/-
... or in an `add` clause.
-/
example : True := by
aesop (add safe (by simp)) |
.lake/packages/mathlib/MathlibTest/SwapVar.lean | import Mathlib.Tactic.Basic
import Mathlib.Tactic.SwapVar
example {P Q : Prop} (q : P) (p : Q) : P ∧ Q := by
swap_var p ↔ q
exact ⟨p, q⟩
example {a b : Nat} (h : a = b) : a = b ∧ a = a := by
swap_var a ↔ b
guard_hyp h : b = a
guard_target = b = a ∧ b = b
exact ⟨h, Eq.refl b⟩
example {a b c d : Nat} (h : a = b ∧ c = d) : a = b ∧ c = d := by
swap_var a ↔ b, b c
guard_target = c = a ∧ b = d
exact h |
.lake/packages/mathlib/MathlibTest/TypeCheck.lean | import Mathlib.Tactic.TypeCheck
set_option linter.unusedTactic false
/-- A term where `inferType` returns `Prop`, but which does not type check. -/
elab "wrong" : term =>
return Lean.mkApp2 (.const ``id [.zero]) (.sort .zero) (.app (.sort .zero) (.sort .zero))
/--
info: Type
---
info: Bool
---
info: Nat
---
info: Nat
---
info: Prop
---
info: Prop
---
info: Nat → Nat
---
info: List Nat
-/
#guard_msgs in
example : True := by
type_check Nat -- Type
type_check Bool.true -- Bool
type_check nat_lit 1 -- Nat
type_check (1 : Nat) -- Nat
type_check (True :) -- Prop
type_check ∀ x y : Nat, x = y -- Prop
type_check fun x : Nat => 2 * x + 1 -- Nat -> Nat
type_check [1]
fail_if_success type_check wrong
trivial |
.lake/packages/mathlib/MathlibTest/rsuffices.lean | import Mathlib.Tactic.RSuffices
import Mathlib.Tactic.ExistsI
import Mathlib.Algebra.Ring.Nat
import Mathlib.Data.Set.Defs
set_option autoImplicit true
/-- These next few are duplicated from `rcases/obtain` tests, with the goal order swapped. -/
example : True := by
rsuffices ⟨n : ℕ, h : n = n, -⟩ : ∃ n : ℕ, n = n ∧ True
· guard_hyp n : ℕ
guard_hyp h : n = n
trivial
· existsi 0
simp
example : True := by
rsuffices : ∃ n : ℕ, n = n ∧ True
· trivial
· existsi 0
simp
example : True := by
rsuffices (h : True) | ⟨⟨⟩⟩ : True ∨ False
· guard_hyp h : True
trivial
· left
trivial
example (x y : α × β) : True := by
rsuffices ⟨⟨a, b⟩, c, d⟩ : (α × β) × (α × β)
· guard_hyp a : α
guard_hyp b : β
guard_hyp c : α
guard_hyp d : β
trivial
· exact ⟨x, y⟩
-- This test demonstrates why `swap` is not used in the implementation of `rsuffices`:
-- it would make the _second_ goal the one requiring ⟨x, y⟩, not the last one.
example (x y : α ⊕ β) : True := by
rsuffices ⟨a|b, c|d⟩ : (α ⊕ β) × (α ⊕ β)
· guard_hyp a : α
guard_hyp c : α
trivial
· guard_hyp a : α
guard_hyp d : β
trivial
· guard_hyp b : β
guard_hyp c : α
trivial
· guard_hyp b : β
guard_hyp d : β
trivial
exact ⟨x, y⟩
protected def Set.foo {α β} (_ : Set α) (_ : Set β) : Set (α × β) := ∅
example {α} (V : Set α) (w : True → ∃ p, p ∈ (V.foo V) ∩ (V.foo V)) : True := by
rsuffices ⟨_, _⟩ : ∃ p, p ∈ (V.foo V) ∩ (V.foo V)
· trivial
· exact w trivial |
.lake/packages/mathlib/MathlibTest/FBinop.lean | import Mathlib.Tactic.FBinop
import Mathlib.Data.Set.Prod
import Mathlib.Data.Finset.Prod
import Mathlib.Data.SetLike.Basic
private axiom test_sorry : ∀ {α}, α
universe u v w
set_option autoImplicit true
namespace FBinopTests
/-- Notation type class for the set product `×ˢ`. -/
class SProd' (α : Type u) (β : Type v) (γ : outParam (Type w)) where
/-- The Cartesian product `s ×ˢ t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
sprod : α → β → γ
-- This notation binds more strongly than (pre)images, unions and intersections.
@[inherit_doc SProd'.sprod] infixr:82 " ×ˢ' " => SProd'.sprod
macro_rules | `($x ×ˢ' $y) => `(fbinop% SProd'.sprod $x $y)
@[default_instance]
instance : SProd' (Set α) (Set β) (Set (α × β)) := ⟨Set.prod⟩
instance : SProd' (Finset α) (Finset β) (Finset (α × β)) := ⟨Finset.product⟩
-- set_option trace.Elab.fbinop true
-- These work without `fbinop%`. They're tests that we haven't broken anything.
example (s : Set α) (t : Set β) : s ×ˢ' t = s ×ˢ' t := rfl
example {α : Type u} {β : Type v} (s : Finset α) (t : Finset β) : s ×ˢ' t = s ×ˢ' t := rfl
example (f : α × α → β) (s : Set (α × α)) : s.InjOn f := test_sorry
example (f : α × α → β) (s t : Set α) : (s ×ˢ' t).InjOn f := test_sorry
example (f : α × α → β) (s t : Finset α) : (s ×ˢ' t : Set (α × α)).InjOn f := test_sorry
example (f : α × α → β) (s t : Finset α) : (s ×ˢ' t : Set _).InjOn f := test_sorry
example (f : α × α → β) (s t : Finset α) : (s ×ˢ' t : Set _).InjOn f := test_sorry
example (f : α × α → β) (s t : Finset α) : ((s : Set _) ×ˢ' (t : Set _)).InjOn f := test_sorry
example (f : α × α → β) (s t : Finset α) : ((s : Set _) ×ˢ' (t : Set _)).InjOn f := test_sorry
example (f : α × α → β) (s t : Finset α) : Set.InjOn f (s ×ˢ' t) := test_sorry
axiom Nat.card : Sort u → Nat
example (s : Finset α) (t : Finset γ) : Nat.card (s ×ˢ' t) = 0 := test_sorry
example (s : Set α) (t : Set (α × ℕ)) : s ×ˢ' {n | 0 < n} = t := test_sorry
example (s : Set α) (t : Set (α × ℕ)) : s ×ˢ' {1, 2, 3} = t := test_sorry
example (s : Set α) (t : Set (ℕ × α)) : {1, 2, 3} ×ˢ' s = t := test_sorry
-- These need `fbinop%`. (Comment out `macro_rules` above to check.)
example {α : Type u} {β : Type v} (s : Finset α) (t : Set β) : s ×ˢ' t = s ×ˢ' t := rfl
example (s : Finset α) (t : Finset (α × ℕ)) : s ×ˢ' {1, 2, 3} = t := test_sorry
example (s : Finset α) (t : Finset (ℕ × α)) : {1, 2, 3} ×ˢ' s = t := test_sorry
example (s : Finset α) (_t : Finset (ℕ × α)) : ({1, 2, 3} ×ˢ' s).card = 22 := test_sorry
/--
info: {1, 2, 3} ×ˢ' {4, 5, 6} : Finset (ℕ × ℕ)
-/
#guard_msgs in
#check ({1,2,3} ×ˢ' {4,5,6} : Finset _)
example (s : Finset α) (t : Set β) (u : Finset γ) : Nat.card (s ×ˢ' t ×ˢ' u) = 0 := test_sorry
example (s : Finset α) (t : Finset β) :
(↑(s ×ˢ' t) : Set _) = (s : Set α) ×ˢ' t := Finset.coe_product s t
structure SubObj (X : Type _) where
carrier : Set X
instance : SetLike (SubObj X) X where
coe s := s.carrier
coe_injective' p q h := by cases p; cases q; congr
-- Note: this easily works because the last argument of `SubObj` is a type.
def SubObj.prod (s : SubObj X) (t : SubObj Y) : SubObj (X × Y) where
carrier := s ×ˢ' t
/-- Modeling subobjects of algebraic types, which have an instance argument after the type. -/
structure DecSubObj (X : Type _) [DecidableEq X] where
carrier : Set X
instance [DecidableEq X] : SetLike (DecSubObj X) X where
coe s := s.carrier
coe_injective' p q h := by cases p; cases q; congr
-- Note: this is testing instance arguments after the type.
def DecSubObj.prod [DecidableEq X] [DecidableEq Y] (s : DecSubObj X) (t : DecSubObj Y) :
DecSubObj (X × Y) where
carrier := s ×ˢ' t
end FBinopTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.