blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
139
content_id
stringlengths
40
40
detected_licenses
listlengths
0
16
license_type
stringclasses
2 values
repo_name
stringlengths
7
55
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
6 values
visit_date
int64
1,471B
1,694B
revision_date
int64
1,378B
1,694B
committer_date
int64
1,378B
1,694B
github_id
float64
1.33M
604M
star_events_count
int64
0
43.5k
fork_events_count
int64
0
1.5k
gha_license_id
stringclasses
6 values
gha_event_created_at
int64
1,402B
1,695B
gha_created_at
int64
1,359B
1,637B
gha_language
stringclasses
19 values
src_encoding
stringclasses
2 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
3
6.4M
extension
stringclasses
4 values
content
stringlengths
3
6.12M
e9dc022b1d969e461bfab7848539b1ce906371fa
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/exposed.lean
c8e7f15e4f45b5849669e80b8c0fc986d9c9f7f6
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,773
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.extreme import analysis.convex.function import topology.algebra.module.basic import topology.order.basic /-! # Exposed sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines exposed sets and exposed points for sets in a real vector space. An exposed subset of `A` is a subset of `A` that is the set of all maximal points of a functional (a continuous linear map `E → 𝕜`) over `A`. By convention, `∅` is an exposed subset of all sets. This allows for better functoriality of the definition (the intersection of two exposed subsets is exposed, faces of a polytope form a bounded lattice). This is an analytic notion of "being on the side of". It is stronger than being extreme (see `is_exposed.is_extreme`), but weaker (for exposed points) than being a vertex. An exposed set of `A` is sometimes called a "face of `A`", but we decided to reserve this terminology to the more specific notion of a face of a polytope (sometimes hopefully soon out on mathlib!). ## Main declarations * `is_exposed 𝕜 A B`: States that `B` is an exposed set of `A` (in the literature, `A` is often implicit). * `is_exposed.is_extreme`: An exposed set is also extreme. ## References See chapter 8 of [Barry Simon, *Convexity*][simon2011] ## TODO Define intrinsic frontier/interior and prove the lemmas related to exposed sets and points. Generalise to Locally Convex Topological Vector Spaces™ More not-yet-PRed stuff is available on the branch `sperner_again`. -/ open_locale classical affine big_operators open set section preorder_semiring variables (𝕜 : Type*) {E : Type*} [topological_space 𝕜] [semiring 𝕜] [preorder 𝕜] [add_comm_monoid E] [topological_space E] [module 𝕜 E] {A B : set E} /-- A set `B` is exposed with respect to `A` iff it maximizes some functional over `A` (and contains all points maximizing it). Written `is_exposed 𝕜 A B`. -/ def is_exposed (A B : set E) : Prop := B.nonempty → ∃ l : E →L[𝕜] 𝕜, B = {x ∈ A | ∀ y ∈ A, l y ≤ l x} end preorder_semiring section ordered_ring variables {𝕜 : Type*} {E : Type*} [topological_space 𝕜] [ordered_ring 𝕜] [add_comm_monoid E] [topological_space E] [module 𝕜 E] {l : E →L[𝕜] 𝕜} {A B C : set E} {X : finset E} {x : E} /-- A useful way to build exposed sets from intersecting `A` with halfspaces (modelled by an inequality with a functional). -/ def continuous_linear_map.to_exposed (l : E →L[𝕜] 𝕜) (A : set E) : set E := {x ∈ A | ∀ y ∈ A, l y ≤ l x} lemma continuous_linear_map.to_exposed.is_exposed : is_exposed 𝕜 A (l.to_exposed A) := λ h, ⟨l, rfl⟩ lemma is_exposed_empty : is_exposed 𝕜 A ∅ := λ ⟨x, hx⟩, by { exfalso, exact hx } namespace is_exposed protected lemma subset (hAB : is_exposed 𝕜 A B) : B ⊆ A := begin rintro x hx, obtain ⟨_, rfl⟩ := hAB ⟨x, hx⟩, exact hx.1, end @[refl] protected lemma refl (A : set E) : is_exposed 𝕜 A A := λ ⟨w, hw⟩, ⟨0, subset.antisymm (λ x hx, ⟨hx, λ y hy, by exact le_refl 0⟩) (λ x hx, hx.1)⟩ protected lemma antisymm (hB : is_exposed 𝕜 A B) (hA : is_exposed 𝕜 B A) : A = B := hA.subset.antisymm hB.subset /- `is_exposed` is *not* transitive: Consider a (topologically) open cube with vertices `A₀₀₀, ..., A₁₁₁` and add to it the triangle `A₀₀₀A₀₀₁A₀₁₀`. Then `A₀₀₁A₀₁₀` is an exposed subset of `A₀₀₀A₀₀₁A₀₁₀` which is an exposed subset of the cube, but `A₀₀₁A₀₁₀` is not itself an exposed subset of the cube. -/ protected lemma mono (hC : is_exposed 𝕜 A C) (hBA : B ⊆ A) (hCB : C ⊆ B) : is_exposed 𝕜 B C := begin rintro ⟨w, hw⟩, obtain ⟨l, rfl⟩ := hC ⟨w, hw⟩, exact ⟨l, subset.antisymm (λ x hx, ⟨hCB hx, λ y hy, hx.2 y (hBA hy)⟩) (λ x hx, ⟨hBA hx.1, λ y hy, (hw.2 y hy).trans (hx.2 w (hCB hw))⟩)⟩, end /-- If `B` is a nonempty exposed subset of `A`, then `B` is the intersection of `A` with some closed halfspace. The converse is *not* true. It would require that the corresponding open halfspace doesn't intersect `A`. -/ lemma eq_inter_halfspace' {A B : set E} (hAB : is_exposed 𝕜 A B) (hB : B.nonempty) : ∃ l : E →L[𝕜] 𝕜, ∃ a, B = {x ∈ A | a ≤ l x} := begin obtain ⟨l, rfl⟩ := hAB hB, obtain ⟨w, hw⟩ := hB, exact ⟨l, l w, subset.antisymm (λ x hx, ⟨hx.1, hx.2 w hw.1⟩) (λ x hx, ⟨hx.1, λ y hy, (hw.2 y hy).trans hx.2⟩)⟩, end /-- For nontrivial `𝕜`, if `B` is an exposed subset of `A`, then `B` is the intersection of `A` with some closed halfspace. The converse is *not* true. It would require that the corresponding open halfspace doesn't intersect `A`. -/ lemma eq_inter_halfspace [nontrivial 𝕜] {A B : set E} (hAB : is_exposed 𝕜 A B) : ∃ l : E →L[𝕜] 𝕜, ∃ a, B = {x ∈ A | a ≤ l x} := begin obtain rfl | hB := B.eq_empty_or_nonempty, { refine ⟨0, 1, _⟩, rw [eq_comm, eq_empty_iff_forall_not_mem], rintro x ⟨-, h⟩, rw continuous_linear_map.zero_apply at h, have : ¬ ((1:𝕜) ≤ 0) := not_le_of_lt zero_lt_one, contradiction }, exact hAB.eq_inter_halfspace' hB, end protected lemma inter [has_continuous_add 𝕜] {A B C : set E} (hB : is_exposed 𝕜 A B) (hC : is_exposed 𝕜 A C) : is_exposed 𝕜 A (B ∩ C) := begin rintro ⟨w, hwB, hwC⟩, obtain ⟨l₁, rfl⟩ := hB ⟨w, hwB⟩, obtain ⟨l₂, rfl⟩ := hC ⟨w, hwC⟩, refine ⟨l₁ + l₂, subset.antisymm _ _⟩, { rintro x ⟨⟨hxA, hxB⟩, ⟨-, hxC⟩⟩, exact ⟨hxA, λ z hz, add_le_add (hxB z hz) (hxC z hz)⟩ }, rintro x ⟨hxA, hx⟩, refine ⟨⟨hxA, λ y hy, _⟩, hxA, λ y hy, _⟩, { exact (add_le_add_iff_right (l₂ x)).1 ((add_le_add (hwB.2 y hy) (hwC.2 x hxA)).trans (hx w hwB.1)) }, { exact (add_le_add_iff_left (l₁ x)).1 (le_trans (add_le_add (hwB.2 x hxA) (hwC.2 y hy)) (hx w hwB.1)) } end lemma sInter [has_continuous_add 𝕜] {F : finset (set E)} (hF : F.nonempty) (hAF : ∀ B ∈ F, is_exposed 𝕜 A B) : is_exposed 𝕜 A (⋂₀ F) := begin revert hF F, refine finset.induction _ _, { rintro h, exfalso, exact not_nonempty_empty h }, rintro C F _ hF _ hCF, rw [finset.coe_insert, sInter_insert], obtain rfl | hFnemp := F.eq_empty_or_nonempty, { rw [finset.coe_empty, sInter_empty, inter_univ], exact hCF C (finset.mem_singleton_self C) }, exact (hCF C (finset.mem_insert_self C F)).inter (hF hFnemp (λ B hB, hCF B(finset.mem_insert_of_mem hB))), end lemma inter_left (hC : is_exposed 𝕜 A C) (hCB : C ⊆ B) : is_exposed 𝕜 (A ∩ B) C := begin rintro ⟨w, hw⟩, obtain ⟨l, rfl⟩ := hC ⟨w, hw⟩, exact ⟨l, subset.antisymm (λ x hx, ⟨⟨hx.1, hCB hx⟩, λ y hy, hx.2 y hy.1⟩) (λ x ⟨⟨hxC, _⟩, hx⟩, ⟨hxC, λ y hy, (hw.2 y hy).trans (hx w ⟨hC.subset hw, hCB hw⟩)⟩)⟩, end lemma inter_right (hC : is_exposed 𝕜 B C) (hCA : C ⊆ A) : is_exposed 𝕜 (A ∩ B) C := begin rw inter_comm, exact hC.inter_left hCA, end protected lemma is_closed [order_closed_topology 𝕜] {A B : set E} (hAB : is_exposed 𝕜 A B) (hA : is_closed A) : is_closed B := begin obtain rfl | hB := B.eq_empty_or_nonempty, { simp }, obtain ⟨l, a, rfl⟩ := hAB.eq_inter_halfspace' hB, exact hA.is_closed_le continuous_on_const l.continuous.continuous_on, end protected lemma is_compact [order_closed_topology 𝕜] [t2_space E] {A B : set E} (hAB : is_exposed 𝕜 A B) (hA : is_compact A) : is_compact B := is_compact_of_is_closed_subset hA (hAB.is_closed hA.is_closed) hAB.subset end is_exposed variables (𝕜) /-- A point is exposed with respect to `A` iff there exists an hyperplane whose intersection with `A` is exactly that point. -/ def set.exposed_points (A : set E) : set E := {x ∈ A | ∃ l : E →L[𝕜] 𝕜, ∀ y ∈ A, l y ≤ l x ∧ (l x ≤ l y → y = x)} variables {𝕜} lemma exposed_point_def : x ∈ A.exposed_points 𝕜 ↔ x ∈ A ∧ ∃ l : E →L[𝕜] 𝕜, ∀ y ∈ A, l y ≤ l x ∧ (l x ≤ l y → y = x) := iff.rfl lemma exposed_points_subset : A.exposed_points 𝕜 ⊆ A := λ x hx, hx.1 @[simp] lemma exposed_points_empty : (∅ : set E).exposed_points 𝕜 = ∅ := subset_empty_iff.1 exposed_points_subset /-- Exposed points exactly correspond to exposed singletons. -/ lemma mem_exposed_points_iff_exposed_singleton : x ∈ A.exposed_points 𝕜 ↔ is_exposed 𝕜 A {x} := begin use λ ⟨hxA, l, hl⟩ h, ⟨l, eq.symm $ eq_singleton_iff_unique_mem.2 ⟨⟨hxA, λ y hy, (hl y hy).1⟩, λ z hz, (hl z hz.1).2 (hz.2 x hxA)⟩⟩, rintro h, obtain ⟨l, hl⟩ := h ⟨x, mem_singleton _⟩, rw [eq_comm, eq_singleton_iff_unique_mem] at hl, exact ⟨hl.1.1, l, λ y hy, ⟨hl.1.2 y hy, λ hxy, hl.2 y ⟨hy, λ z hz, (hl.1.2 z hz).trans hxy⟩⟩⟩, end end ordered_ring section linear_ordered_ring variables {𝕜 : Type*} {E : Type*} [topological_space 𝕜] [linear_ordered_ring 𝕜] [add_comm_monoid E] [topological_space E] [module 𝕜 E] {A B C : set E} namespace is_exposed protected lemma convex (hAB : is_exposed 𝕜 A B) (hA : convex 𝕜 A) : convex 𝕜 B := begin obtain rfl | hB := B.eq_empty_or_nonempty, { exact convex_empty }, obtain ⟨l, rfl⟩ := hAB hB, exact λ x₁ hx₁ x₂ hx₂ a b ha hb hab, ⟨hA hx₁.1 hx₂.1 ha hb hab, λ y hy, ((l.to_linear_map.concave_on convex_univ).convex_ge _ ⟨mem_univ _, hx₁.2 y hy⟩ ⟨mem_univ _, hx₂.2 y hy⟩ ha hb hab).2⟩, end protected lemma is_extreme (hAB : is_exposed 𝕜 A B) : is_extreme 𝕜 A B := begin refine ⟨hAB.subset, λ x₁ hx₁A x₂ hx₂A x hxB hx, _⟩, obtain ⟨l, rfl⟩ := hAB ⟨x, hxB⟩, have hl : convex_on 𝕜 univ l := l.to_linear_map.convex_on convex_univ, have hlx₁ := hxB.2 x₁ hx₁A, have hlx₂ := hxB.2 x₂ hx₂A, refine ⟨⟨hx₁A, λ y hy, _⟩, ⟨hx₂A, λ y hy, _⟩⟩, { have := @convex_on.le_left_of_right_le 𝕜 E 𝕜 _ _ _, rw hlx₁.antisymm (hl.le_left_of_right_le (mem_univ _) (mem_univ _) hx hlx₂), exact hxB.2 y hy }, { rw hlx₂.antisymm (hl.le_right_of_left_le (mem_univ _) (mem_univ _) hx hlx₁), exact hxB.2 y hy } end end is_exposed lemma exposed_points_subset_extreme_points : A.exposed_points 𝕜 ⊆ A.extreme_points 𝕜 := λ x hx, mem_extreme_points_iff_extreme_singleton.2 (mem_exposed_points_iff_exposed_singleton.1 hx).is_extreme end linear_ordered_ring
42f526ff79d917aa51d4d775abe09108d5d2080e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/group.lean
5cabfaad80da65c2e3772295b4ae9af2e684bf10
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
1,926
lean
import tactic.group variables {G : Type} [group G] example (a b c d : G) : c *(a*b)*(b⁻¹*a⁻¹)*c = c*c := by group example (a b c d : G) : (b*c⁻¹)*c *(a*b)*(b⁻¹*a⁻¹)*c = b*c := by group example (a b c d : G) : c⁻¹*(b*c⁻¹)*c *(a*b)*(b⁻¹*a⁻¹*b⁻¹)*c = 1 := by group def commutator {G} [group G] : G → G → G := λ g h, g * h * g⁻¹ * h⁻¹ def commutator3 {G} [group G] : G → G → G → G := λ g h k, commutator (commutator g h) k -- 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 * (commutator3 g⁻¹ h k) * g⁻¹ * k * (commutator3 k⁻¹ g h) * k⁻¹ * h * (commutator3 h⁻¹ k g) * h⁻¹ = 1 := by { dsimp [commutator3, commutator], 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 d : G) : c *(a*b^2)*((b*b)⁻¹*a⁻¹)*c = c*c := by group example (n m : ℕ) (a : G) : a^n*(a⁻¹)^n = 1 := by group example (n m : ℕ) (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 := begin group at h, exact h.symm, end example (a b c d : G) (h : c = (a*b^2)*((b*b)⁻¹*a⁻¹)*d) : a*c*d⁻¹ = a := begin group at h, rw h, group, end -- The next example can be expand to require an arbitrarily high number of alternation -- between simp and ring example (n m : ℤ) (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 example (x : G) (h : x = 1) : x = 1 := begin group, exact h, end
2d4f0b71d566d51fdfe44c093641dcaa1d750cf0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/pp_tagged.lean
c2f7c808ca8847b07718ace3ed38f90691c1d55e
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,685
lean
open widget.interactive_expression constant f : nat → nat → nat → nat constants w x y z : nat #eval (sf.of_eformat <$> tactic.pp_tagged `(f x y z)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(x + y + z)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(x = y)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `((x,y))) >>= tactic.trace -- fa, a #eval (sf.of_eformat <$> tactic.pp_tagged `((w,x,y,z))) >>= tactic.trace -- fa, afa, aafa, aaa #eval (sf.of_eformat <$> tactic.pp_tagged `({x : nat | false})) >>= tactic.trace -- at, ab #eval (sf.of_eformat <$> tactic.pp_tagged `({w, x, y, z} : set nat)) >>= tactic.trace -- fa, afa, aafa, aaaa #eval (sf.of_eformat <$> tactic.pp_tagged `((int.of_nat = coe))) >>= tactic.trace constant bar [inhabited ℕ] [inhabited ℕ] : ℕ → ℤ constant foo (α : Type) [inhabited ℕ] [inhabited ℕ] : ℕ → ℤ #eval (sf.of_eformat <$> tactic.pp_tagged `((int.of_nat = bar))) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `((int.of_nat = (foo nat)))) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(∃ (x : nat), x = x)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(∃ (x y z: nat), x = x)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(∃ (x > 0), x = x)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(λ (x > 0), x = x)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(Π (x > 0), x = x)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(have x: _, from trivial, x = x)) >>= tactic.trace #eval (sf.of_eformat <$> tactic.pp_tagged `(suffices x: _, from trivial, x = x)) >>= tactic.trace
44ff4bebbab74c3df1443fc0e768371381d35ac0
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/free_monoid.lean
dda57f1b57d387c3f7e21e1bec501ffdd1db594b
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
4,477
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Yury Kudryashov -/ import data.equiv.basic import data.list.basic /-! # Free monoid over a given alphabet ## Main definitions * `free_monoid α`: free monoid over alphabet `α`; defined as a synonym for `list α` with multiplication given by `(++)`. * `free_monoid.of`: embedding `α → free_monoid α` sending each element `x` to `[x]`; * `free_monoid.lift`: natural equivalence between `α → M` and `free_monoid α →* M` * `free_monoid.map`: embedding of `α → β` into `free_monoid α →* free_monoid β` given by `list.map`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {M : Type*} [monoid M] {N : Type*} [monoid N] /-- Free monoid over a given alphabet. -/ @[to_additive "Free nonabelian additive monoid over a given alphabet"] def free_monoid (α) := list α namespace free_monoid @[to_additive] instance : monoid (free_monoid α) := { one := [], mul := λ x y, (x ++ y : list α), mul_one := by intros; apply list.append_nil, one_mul := by intros; refl, mul_assoc := by intros; apply list.append_assoc } @[to_additive] instance : inhabited (free_monoid α) := ⟨1⟩ @[to_additive] lemma one_def : (1 : free_monoid α) = [] := rfl @[to_additive] lemma mul_def (xs ys : list α) : (xs * ys : free_monoid α) = (xs ++ ys : list α) := rfl /-- Embeds an element of `α` into `free_monoid α` as a singleton list. -/ @[to_additive "Embeds an element of `α` into `free_add_monoid α` as a singleton list." ] def of (x : α) : free_monoid α := [x] @[to_additive] lemma of_def (x : α) : of x = [x] := rfl /-- Recursor for `free_monoid` using `1` and `of x * xs` instead of `[]` and `x :: xs`. -/ @[to_additive "Recursor for `free_add_monoid` using `0` and `of x + xs` instead of `[]` and `x :: xs`."] def rec_on {C : free_monoid α → Sort*} (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : C xs := list.rec_on xs h0 ih attribute [elab_as_eliminator] rec_on free_add_monoid.rec_on @[to_additive] lemma hom_eq ⦃f g : free_monoid α →* M⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := monoid_hom.ext $ λ l, rec_on l (f.map_one.trans g.map_one.symm) $ λ x xs hxs, by simp only [h, hxs, monoid_hom.map_mul] attribute [ext, priority 1500] hom_eq free_add_monoid.hom_eq /-- Equivalence between maps `α → M` and monoid homomorphisms `free_monoid α →* M`. -/ @[to_additive "Equivalence between maps `α → A` and additive monoid homomorphisms `free_add_monoid α →+ A`."] def lift : (α → M) ≃ (free_monoid α →* M) := { to_fun := λ f, ⟨λ l, (l.map f).prod, rfl, λ l₁ l₂, by simp only [mul_def, list.map_append, list.prod_append]⟩, inv_fun := λ f x, f (of x), left_inv := λ f, funext $ λ x, one_mul (f x), right_inv := λ f, hom_eq $ λ x, one_mul (f (of x)) } @[simp, to_additive] lemma lift_symm_apply (f : free_monoid α →* M) : lift.symm f = f ∘ of := rfl @[to_additive] lemma lift_apply (f : α → M) (l : free_monoid α) : lift f l = (l.map f).prod := rfl @[to_additive] lemma lift_comp_of (f : α → M) : (lift f) ∘ of = f := lift.symm_apply_apply f @[simp, to_additive] lemma lift_eval_of (f : α → M) (x : α) : lift f (of x) = f x := congr_fun (lift_comp_of f) x @[simp, to_additive] lemma lift_restrict (f : free_monoid α →* M) : lift (f ∘ of) = f := lift.apply_symm_apply f lemma comp_lift (g : M →* N) (f : α → M) : g.comp (lift f) = lift (g ∘ f) := by { ext, simp } lemma hom_map_lift (g : M →* N) (f : α → M) (x : free_monoid α) : g (lift f x) = lift (g ∘ f) x := monoid_hom.ext_iff.1 (comp_lift g f) x /-- The unique monoid homomorphism `free_monoid α →* free_monoid β` that sends each `of x` to `of (f x)`. -/ @[to_additive "The unique additive monoid homomorphism `free_add_monoid α →+ free_add_monoid β` that sends each `of x` to `of (f x)`."] def map (f : α → β) : free_monoid α →* free_monoid β := { to_fun := list.map f, map_one' := rfl, map_mul' := λ l₁ l₂, list.map_append _ _ _ } @[simp, to_additive] lemma map_of (f : α → β) (x : α) : map f (of x) = of (f x) := rfl @[to_additive] lemma lift_of_comp_eq_map (f : α → β) : lift (λ x, of (f x)) = map f := hom_eq $ λ x, rfl @[to_additive] lemma map_comp (g : β → γ) (f : α → β) : map (g ∘ f) = (map g).comp (map f) := hom_eq $ λ x, rfl end free_monoid
93e02a6fe7fa39e91e03ad9268f0d97c925d8266
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/monoidal/CommMon_.lean
2fe0520065b167e74653e646ed41cff4ecb449fe
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,372
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.braided import category_theory.monoidal.Mon_ /-! # The category of commutative monoids in a braided monoidal category. -/ universes v₁ v₂ u₁ u₂ u open category_theory open category_theory.monoidal_category variables (C : Type u₁) [category.{v₁} C] [monoidal_category.{v₁} C] [braided_category.{v₁} C] /-- A commutative monoid object internal to a monoidal category. -/ structure CommMon_ extends Mon_ C := (mul_comm' : (β_ _ _).hom ≫ mul = mul . obviously) restate_axiom CommMon_.mul_comm' attribute [simp, reassoc] CommMon_.mul_comm namespace CommMon_ /-- The trivial commutative monoid object. We later show this is initial in `CommMon_ C`. -/ @[simps] def trivial : CommMon_ C := { mul_comm' := begin dsimp, rw [braiding_left_unitor, unitors_equal], end ..Mon_.trivial C } instance : inhabited (CommMon_ C) := ⟨trivial C⟩ variables {C} {M : CommMon_ C} instance : category (CommMon_ C) := induced_category.category CommMon_.to_Mon_ @[simp] lemma id_hom (A : CommMon_ C) : Mon_.hom.hom (𝟙 A) = 𝟙 A.X := rfl @[simp] lemma comp_hom {R S T : CommMon_ C} (f : R ⟶ S) (g : S ⟶ T) : Mon_.hom.hom (f ≫ g) = f.hom ≫ g.hom := rfl section variables (C) /-- The forgetful functor from commutative monoid objects to monoid objects. -/ @[derive [full, faithful]] def forget₂_Mon_ : CommMon_ C ⥤ Mon_ C := induced_functor CommMon_.to_Mon_ @[simp] lemma forget₂_Mon_obj_one (A : CommMon_ C) : ((forget₂_Mon_ C).obj A).one = A.one := rfl @[simp] lemma forget₂_Mon_obj_mul (A : CommMon_ C) : ((forget₂_Mon_ C).obj A).mul = A.mul := rfl @[simp] lemma forget₂_Mon_map_hom {A B : CommMon_ C} (f : A ⟶ B) : ((forget₂_Mon_ C).map f).hom = f.hom := rfl end instance unique_hom_from_trivial (A : CommMon_ C) : unique (trivial C ⟶ A) := Mon_.unique_hom_from_trivial A.to_Mon_ open category_theory.limits instance : has_initial (CommMon_ C) := has_initial_of_unique (trivial C) end CommMon_ namespace category_theory.lax_braided_functor variables {C} {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D] [braided_category.{v₂} D] /-- A lax braided functor takes commutative monoid objects to commutative monoid objects. That is, a lax braided functor `F : C ⥤ D` induces a functor `CommMon_ C ⥤ CommMon_ D`. -/ @[simps] def map_CommMon (F : lax_braided_functor C D) : CommMon_ C ⥤ CommMon_ D := { obj := λ A, { mul_comm' := begin dsimp, have := F.braided, slice_lhs 1 2 { rw ←this, }, slice_lhs 2 3 { rw [←category_theory.functor.map_comp, A.mul_comm], }, end, ..F.to_lax_monoidal_functor.map_Mon.obj A.to_Mon_ }, map := λ A B f, F.to_lax_monoidal_functor.map_Mon.map f, } variables (C) (D) /-- `map_CommMon` is functorial in the lax braided functor. -/ def map_CommMon_functor : (lax_braided_functor C D) ⥤ (CommMon_ C ⥤ CommMon_ D) := { obj := map_CommMon, map := λ F G α, { app := λ A, { hom := α.app A.X, } } } end category_theory.lax_braided_functor namespace CommMon_ open category_theory.lax_braided_functor namespace equiv_lax_braided_functor_punit /-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/ @[simps] def lax_braided_to_CommMon : lax_braided_functor (discrete punit.{u+1}) C ⥤ CommMon_ C := { obj := λ F, (F.map_CommMon : CommMon_ _ ⥤ CommMon_ C).obj (trivial (discrete punit)), map := λ F G α, ((map_CommMon_functor (discrete punit) C).map α).app _ } /-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/ @[simps] def CommMon_to_lax_braided : CommMon_ C ⥤ lax_braided_functor (discrete punit.{u+1}) C := { obj := λ A, { obj := λ _, A.X, map := λ _ _ _, 𝟙 _, ε := A.one, μ := λ _ _, A.mul, map_id' := λ _, rfl, map_comp' := λ _ _ _ _ _, (category.id_comp (𝟙 A.X)).symm, }, map := λ A B f, { app := λ _, f.hom, naturality' := λ _ _ _, by { dsimp, rw [category.id_comp, category.comp_id], }, unit' := f.one_hom, tensor' := λ _ _, f.mul_hom, }, } /-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/ @[simps] def unit_iso : 𝟭 (lax_braided_functor (discrete punit.{u+1}) C) ≅ lax_braided_to_CommMon C ⋙ CommMon_to_lax_braided C := nat_iso.of_components (λ F, lax_braided_functor.mk_iso (monoidal_nat_iso.of_components (λ _, F.to_lax_monoidal_functor.to_functor.map_iso (eq_to_iso (by ext))) (by tidy) (by tidy) (by tidy))) (by tidy) /-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/ @[simps] def counit_iso : CommMon_to_lax_braided C ⋙ lax_braided_to_CommMon C ≅ 𝟭 (CommMon_ C) := nat_iso.of_components (λ F, { hom := { hom := 𝟙 _, }, inv := { hom := 𝟙 _, } }) (by tidy) end equiv_lax_braided_functor_punit open equiv_lax_braided_functor_punit /-- Commutative monoid objects in `C` are "just" braided lax monoidal functors from the trivial braided monoidal category to `C`. -/ @[simps] def equiv_lax_braided_functor_punit : lax_braided_functor (discrete punit.{u+1}) C ≌ CommMon_ C := { functor := lax_braided_to_CommMon C, inverse := CommMon_to_lax_braided C, unit_iso := unit_iso C, counit_iso := counit_iso C, } end CommMon_
2b9b7b56e360c7d82d55c61e0fdc598a41b81a7c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/int/gcd.lean
285db2c397222b8a6618de63463e64d7f992fd49
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
14,601
lean
/- Copyright (c) 2018 Guy Leroy. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes Hölzl, Mario Carneiro -/ import data.nat.prime /-! # Extended GCD and divisibility over ℤ ## Main definitions * Given `x y : ℕ`, `xgcd x y` computes the pair of integers `(a, b)` such that `gcd x y = x * a + y * b`. `gcd_a x y` and `gcd_b x y` are defined to be `a` and `b`, respectively. ## Main statements * `gcd_eq_gcd_ab`: Bézout's lemma, given `x y : ℕ`, `gcd x y = x * gcd_a x y + y * gcd_b x y`. -/ /-! ### Extended Euclidean algorithm -/ namespace nat /-- Helper function for the extended GCD algorithm (`nat.xgcd`). -/ def xgcd_aux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ | 0 s t r' s' t' := (r', s', t') | r@(succ _) s t r' s' t' := have r' % r < r, from mod_lt _ $ succ_pos _, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t @[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by simp [xgcd_aux] theorem xgcd_aux_rec {r s t r' s' t'} (h : 0 < r) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by cases r; [exact absurd h (lt_irrefl _), {simp only [xgcd_aux], refl}] /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : ℕ) : ℤ × ℤ := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : ℕ) : ℤ := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : ℕ) : ℤ := (xgcd x y).2 @[simp] theorem gcd_a_zero_left {s : ℕ} : gcd_a 0 s = 0 := by { unfold gcd_a, rw [xgcd, xgcd_zero_left] } @[simp] theorem gcd_b_zero_left {s : ℕ} : gcd_b 0 s = 1 := by { unfold gcd_b, rw [xgcd, xgcd_zero_left] } @[simp] theorem gcd_a_zero_right {s : ℕ} (h : s ≠ 0) : gcd_a s 0 = 1 := begin unfold gcd_a xgcd, induction s, { exact absurd rfl h, }, { simp [xgcd_aux], } end @[simp] theorem gcd_b_zero_right {s : ℕ} (h : s ≠ 0) : gcd_b s 0 = 0 := begin unfold gcd_b xgcd, induction s, { exact absurd rfl h, }, { simp [xgcd_aux], } end @[simp] theorem xgcd_aux_fst (x y) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by simp) (λ x y h IH s t s' t', by simp [xgcd_aux_rec, h, IH]; rw ← gcd_rec) theorem xgcd_aux_val (x y) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1]; cases xgcd_aux x 1 0 y 0 1; refl theorem xgcd_val (x y) : xgcd x y = (gcd_a x y, gcd_b x y) := by unfold gcd_a gcd_b; cases xgcd x y; refl section parameters (x y : ℕ) private def P : ℕ × ℤ × ℤ → Prop | (r, s, t) := (r : ℤ) = x * s + y * t theorem xgcd_aux_P {r r'} : ∀ {s t s' t'}, P (r, s, t) → P (r', s', t') → P (xgcd_aux r s t r' s' t') := gcd.induction r r' (by simp) $ λ a b h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, dsimp [P] at *, rw [int.mod_def], generalize : (b / a : ℤ) = k, rw [p, p'], simp [mul_add, mul_comm, mul_left_comm, add_comm, add_left_comm, sub_eq_neg_add, mul_assoc] end /-- Bézout's lemma: given `x y : ℕ`, `gcd x y = x * a + y * b`, where `a = gcd_a x y` and `b = gcd_b x y` are computed by the extended Euclidean algorithm. -/ theorem gcd_eq_gcd_ab : (gcd x y : ℤ) = x * gcd_a x y + y * gcd_b x y := by have := @xgcd_aux_P x y x y 1 0 0 1 (by simp [P]) (by simp [P]); rwa [xgcd_aux_val, xgcd_val] at this end lemma exists_mul_mod_eq_gcd {k n : ℕ} (hk : gcd n k < k) : ∃ m, n * m % k = gcd n k := begin have hk' := int.coe_nat_ne_zero.mpr (ne_of_gt (lt_of_le_of_lt (zero_le (gcd n k)) hk)), have key := congr_arg (λ m, int.nat_mod m k) (gcd_eq_gcd_ab n k), simp_rw int.nat_mod at key, rw [int.add_mul_mod_self_left, ←int.coe_nat_mod, int.to_nat_coe_nat, mod_eq_of_lt hk] at key, refine ⟨(n.gcd_a k % k).to_nat, eq.trans (int.coe_nat_inj _) key.symm⟩, rw [int.coe_nat_mod, int.coe_nat_mul, int.to_nat_of_nonneg (int.mod_nonneg _ hk'), int.to_nat_of_nonneg (int.mod_nonneg _ hk'), int.mul_mod, int.mod_mod, ←int.mul_mod], end lemma exists_mul_mod_eq_one_of_coprime {k n : ℕ} (hkn : coprime n k) (hk : 1 < k) : ∃ m, n * m % k = 1 := Exists.cases_on (exists_mul_mod_eq_gcd (lt_of_le_of_lt (le_of_eq hkn) hk)) (λ m hm, ⟨m, hm.trans hkn⟩) end nat /-! ### Divisibility over ℤ -/ namespace int /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a : ℤ → ℤ → ℤ | (of_nat m) n := m.gcd_a n.nat_abs | -[1+ m] n := -m.succ.gcd_a n.nat_abs /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b : ℤ → ℤ → ℤ | m (of_nat n) := m.nat_abs.gcd_b n | m -[1+ n] := -m.nat_abs.gcd_b n.succ theorem gcd_eq_gcd_ab : ∀ x y : ℤ, (gcd x y : ℤ) = x * gcd_a x y + y * gcd_b x y | (m : ℕ) (n : ℕ) := nat.gcd_eq_gcd_ab _ _ | (m : ℕ) -[1+ n] := show (_ : ℤ) = _ + -(n+1) * -_, by rw neg_mul_neg; apply nat.gcd_eq_gcd_ab | -[1+ m] (n : ℕ) := show (_ : ℤ) = -(m+1) * -_ + _ , by rw neg_mul_neg; apply nat.gcd_eq_gcd_ab | -[1+ m] -[1+ n] := show (_ : ℤ) = -(m+1) * -_ + -(n+1) * -_, by { rw [neg_mul_neg, neg_mul_neg], apply nat.gcd_eq_gcd_ab } theorem nat_abs_div (a b : ℤ) (H : b ∣ a) : nat_abs (a / b) = (nat_abs a) / (nat_abs b) := begin cases (nat.eq_zero_or_pos (nat_abs b)), {rw eq_zero_of_nat_abs_eq_zero h, simp [int.div_zero]}, calc nat_abs (a / b) = nat_abs (a / b) * 1 : by rw mul_one ... = nat_abs (a / b) * (nat_abs b / nat_abs b) : by rw nat.div_self h ... = nat_abs (a / b) * nat_abs b / nat_abs b : by rw (nat.mul_div_assoc _ (dvd_refl _)) ... = nat_abs (a / b * b) / nat_abs b : by rw (nat_abs_mul (a / b) b) ... = nat_abs a / nat_abs b : by rw int.div_mul_cancel H, end theorem nat_abs_dvd_abs_iff {i j : ℤ} : i.nat_abs ∣ j.nat_abs ↔ i ∣ j := ⟨assume (H : i.nat_abs ∣ j.nat_abs), dvd_nat_abs.mp (nat_abs_dvd.mp (coe_nat_dvd.mpr H)), assume H : (i ∣ j), coe_nat_dvd.mp (dvd_nat_abs.mpr (nat_abs_dvd.mpr H))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : nat.prime p) {m n : ℤ} {k l : ℕ} (hpm : ↑(p ^ k) ∣ m) (hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k+l+1)) ∣ m*n) : ↑(p ^ (k+1)) ∣ m ∨ ↑(p ^ (l+1)) ∣ n := have hpm' : p ^ k ∣ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm, have hpn' : p ^ l ∣ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn, have hpmn' : (p ^ (k+l+1)) ∣ m.nat_abs*n.nat_abs, by rw ←int.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn), let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in hsd.elim (λ hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end) (λ hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end) theorem dvd_of_mul_dvd_mul_left {i j k : ℤ} (k_non_zero : k ≠ 0) (H : k * i ∣ k * j) : i ∣ j := dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, mul_left_cancel' k_non_zero H1⟩) theorem dvd_of_mul_dvd_mul_right {i j k : ℤ} (k_non_zero : k ≠ 0) (H : i * k ∣ j * k) : i ∣ j := by rw [mul_comm i k, mul_comm j k] at H; exact dvd_of_mul_dvd_mul_left k_non_zero H lemma prime.dvd_nat_abs_of_coe_dvd_sq {p : ℕ} (hp : p.prime) (k : ℤ) (h : ↑p ∣ k ^ 2) : p ∣ k.nat_abs := begin apply @nat.prime.dvd_of_dvd_pow _ _ 2 hp, rwa [sq, ← nat_abs_mul, ← coe_nat_dvd_left, ← sq] end /-- ℤ specific version of least common multiple. -/ def lcm (i j : ℤ) : ℕ := nat.lcm (nat_abs i) (nat_abs j) theorem lcm_def (i j : ℤ) : lcm i j = nat.lcm (nat_abs i) (nat_abs j) := rfl theorem gcd_dvd_left (i j : ℤ) : (gcd i j : ℤ) ∣ i := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_left _ _ theorem gcd_dvd_right (i j : ℤ) : (gcd i j : ℤ) ∣ j := dvd_nat_abs.mp $ coe_nat_dvd.mpr $ nat.gcd_dvd_right _ _ theorem dvd_gcd {i j k : ℤ} (h1 : k ∣ i) (h2 : k ∣ j) : k ∣ gcd i j := nat_abs_dvd.1 $ coe_nat_dvd.2 $ nat.dvd_gcd (nat_abs_dvd_abs_iff.2 h1) (nat_abs_dvd_abs_iff.2 h2) theorem gcd_mul_lcm (i j : ℤ) : gcd i j * lcm i j = nat_abs (i * j) := by rw [int.gcd, int.lcm, nat.gcd_mul_lcm, nat_abs_mul] theorem gcd_comm (i j : ℤ) : gcd i j = gcd j i := nat.gcd_comm _ _ theorem gcd_assoc (i j k : ℤ) : gcd (gcd i j) k = gcd i (gcd j k) := nat.gcd_assoc _ _ _ @[simp] theorem gcd_self (i : ℤ) : gcd i i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_left (i : ℤ) : gcd 0 i = nat_abs i := by simp [gcd] @[simp] theorem gcd_zero_right (i : ℤ) : gcd i 0 = nat_abs i := by simp [gcd] @[simp] theorem gcd_one_left (i : ℤ) : gcd 1 i = 1 := nat.gcd_one_left _ @[simp] theorem gcd_one_right (i : ℤ) : gcd i 1 = 1 := nat.gcd_one_right _ theorem gcd_mul_left (i j k : ℤ) : gcd (i * j) (i * k) = nat_abs i * gcd j k := by { rw [int.gcd, int.gcd, nat_abs_mul, nat_abs_mul], apply nat.gcd_mul_left } theorem gcd_mul_right (i j k : ℤ) : gcd (i * j) (k * j) = gcd i k * nat_abs j := by { rw [int.gcd, int.gcd, nat_abs_mul, nat_abs_mul], apply nat.gcd_mul_right } theorem gcd_pos_of_non_zero_left {i : ℤ} (j : ℤ) (i_non_zero : i ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_left (nat_abs j) (nat_abs_pos_of_ne_zero i_non_zero) theorem gcd_pos_of_non_zero_right (i : ℤ) {j : ℤ} (j_non_zero : j ≠ 0) : 0 < gcd i j := nat.gcd_pos_of_pos_right (nat_abs i) (nat_abs_pos_of_ne_zero j_non_zero) theorem gcd_eq_zero_iff {i j : ℤ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := begin rw int.gcd, split, { intro h, exact ⟨nat_abs_eq_zero.mp (nat.eq_zero_of_gcd_eq_zero_left h), nat_abs_eq_zero.mp (nat.eq_zero_of_gcd_eq_zero_right h)⟩ }, { intro h, rw [nat_abs_eq_zero.mpr h.left, nat_abs_eq_zero.mpr h.right], apply nat.gcd_zero_left } end theorem gcd_div {i j k : ℤ} (H1 : k ∣ i) (H2 : k ∣ j) : gcd (i / k) (j / k) = gcd i j / nat_abs k := by rw [gcd, nat_abs_div i k H1, nat_abs_div j k H2]; exact nat.gcd_div (nat_abs_dvd_abs_iff.mpr H1) (nat_abs_dvd_abs_iff.mpr H2) theorem gcd_div_gcd_div_gcd {i j : ℤ} (H : 0 < gcd i j) : gcd (i / gcd i j) (j / gcd i j) = 1 := begin rw [gcd_div (gcd_dvd_left i j) (gcd_dvd_right i j)], rw [nat_abs_of_nat, nat.div_self H] end theorem gcd_dvd_gcd_of_dvd_left {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd i j ∣ gcd k j := int.coe_nat_dvd.1 $ dvd_gcd (dvd.trans (gcd_dvd_left i j) H) (gcd_dvd_right i j) theorem gcd_dvd_gcd_of_dvd_right {i k : ℤ} (j : ℤ) (H : i ∣ k) : gcd j i ∣ gcd j k := int.coe_nat_dvd.1 $ dvd_gcd (gcd_dvd_left j i) (dvd.trans (gcd_dvd_right j i) H) theorem gcd_dvd_gcd_mul_left (i j k : ℤ) : gcd i j ∣ gcd (k * i) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (i j k : ℤ) : gcd i j ∣ gcd (i * k) j := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (i j k : ℤ) : gcd i j ∣ gcd i (k * j) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (i j k : ℤ) : gcd i j ∣ gcd i (j * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {i j : ℤ} (H : i ∣ j) : gcd i j = nat_abs i := nat.dvd_antisymm (by unfold gcd; exact nat.gcd_dvd_left _ _) (by unfold gcd; exact nat.dvd_gcd (dvd_refl _) (nat_abs_dvd_abs_iff.mpr H)) theorem gcd_eq_right {i j : ℤ} (H : j ∣ i) : gcd i j = nat_abs j := by rw [gcd_comm, gcd_eq_left H] theorem ne_zero_of_gcd {x y : ℤ} (hc : gcd x y ≠ 0) : x ≠ 0 ∨ y ≠ 0 := begin contrapose! hc, rw [hc.left, hc.right, gcd_zero_right, nat_abs_zero] end theorem exists_gcd_one {m n : ℤ} (H : 0 < gcd m n) : ∃ (m' n' : ℤ), gcd m' n' = 1 ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, gcd_div_gcd_div_gcd H, (int.div_mul_cancel (gcd_dvd_left m n)).symm, (int.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_gcd_one' {m n : ℤ} (H : 0 < gcd m n) : ∃ (g : ℕ) (m' n' : ℤ), 0 < g ∧ gcd m' n' = 1 ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_gcd_one H in ⟨_, m', n', H, h⟩ theorem pow_dvd_pow_iff {m n : ℤ} {k : ℕ} (k0 : 0 < k) : m ^ k ∣ n ^ k ↔ m ∣ n := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, apply int.nat_abs_dvd_abs_iff.mp, apply (nat.pow_dvd_pow_iff k0).mp, rw [← int.nat_abs_pow, ← int.nat_abs_pow], exact int.nat_abs_dvd_abs_iff.mpr h end /-! ### lcm -/ theorem lcm_comm (i j : ℤ) : lcm i j = lcm j i := by { rw [int.lcm, int.lcm], exact nat.lcm_comm _ _ } theorem lcm_assoc (i j k : ℤ) : lcm (lcm i j) k = lcm i (lcm j k) := by { rw [int.lcm, int.lcm, int.lcm, int.lcm, nat_abs_of_nat, nat_abs_of_nat], apply nat.lcm_assoc } @[simp] theorem lcm_zero_left (i : ℤ) : lcm 0 i = 0 := by { rw [int.lcm], apply nat.lcm_zero_left } @[simp] theorem lcm_zero_right (i : ℤ) : lcm i 0 = 0 := by { rw [int.lcm], apply nat.lcm_zero_right } @[simp] theorem lcm_one_left (i : ℤ) : lcm 1 i = nat_abs i := by { rw int.lcm, apply nat.lcm_one_left } @[simp] theorem lcm_one_right (i : ℤ) : lcm i 1 = nat_abs i := by { rw int.lcm, apply nat.lcm_one_right } @[simp] theorem lcm_self (i : ℤ) : lcm i i = nat_abs i := by { rw int.lcm, apply nat.lcm_self } theorem dvd_lcm_left (i j : ℤ) : i ∣ lcm i j := by { rw int.lcm, apply coe_nat_dvd_right.mpr, apply nat.dvd_lcm_left } theorem dvd_lcm_right (i j : ℤ) : j ∣ lcm i j := by { rw int.lcm, apply coe_nat_dvd_right.mpr, apply nat.dvd_lcm_right } theorem lcm_dvd {i j k : ℤ} : i ∣ k → j ∣ k → (lcm i j : ℤ) ∣ k := begin rw int.lcm, intros hi hj, exact coe_nat_dvd_left.mpr (nat.lcm_dvd (nat_abs_dvd_abs_iff.mpr hi) (nat_abs_dvd_abs_iff.mpr hj)) end end int lemma pow_gcd_eq_one {M : Type*} [monoid M] (x : M) {m n : ℕ} (hm : x ^ m = 1) (hn : x ^ n = 1) : x ^ m.gcd n = 1 := begin cases m, { simp only [hn, nat.gcd_zero_left] }, obtain ⟨x, rfl⟩ : is_unit x, { apply is_unit_of_pow_eq_one _ _ hm m.succ_pos }, simp only [← units.coe_pow] at *, rw [← units.coe_one, ← gpow_coe_nat, ← units.ext_iff] at *, simp only [nat.gcd_eq_gcd_ab, gpow_add, gpow_mul, hm, hn, one_gpow, one_mul] end lemma gcd_nsmul_eq_zero {M : Type*} [add_monoid M] (x : M) {m n : ℕ} (hm : m • x = 0) (hn : n • x = 0) : (m.gcd n) • x = 0 := begin apply multiplicative.of_add.injective, rw [of_add_nsmul, of_add_zero, pow_gcd_eq_one]; rwa [←of_add_nsmul, ←of_add_zero, equiv.apply_eq_iff_eq] end
3d9a3ba16955daa3328a13b794ecca7ba9e25803
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/trick.lean
a04787bd7ebe874bdafab0cfdf78f1b00e6b5070
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
788
lean
import logic definition proj1 (x : num) (y : num) := x definition One : num := 1 (* local num = Const("num") local m = mk_metavar("m", num) local proj1 = Const("proj1") local zero = Const({"num", "zero"}) local one = Const("One") local t1 = proj1(m, one) local t2 = proj1(m, zero) function test_unify(env, m, cs, num_s) local ss = unify(env, cs, name_generator()) local n = 0 for s in ss do print("solution: " .. tostring(s:instantiate(m))) n = n + 1 end if num_s ~= n then print("n: " .. n) end assert(num_s == n) end local env = get_env() print("===============") test_unify(env, m, { mk_eq_cnstr(proj1(m, one), proj1(zero, zero)) }, 1) print("===============") test_unify(env, m, { mk_eq_cnstr(proj1(m, one), proj1(zero, m)) }, 1) *)
023885c516a1c0d70135dd373a6dd9d248192d13
fe84e287c662151bb313504482b218a503b972f3
/src/combinatorics/grid_path.lean
88053b9bc614e3233fbc82851d5faaea80ca23a0
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
666
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland (This is part of an attempt to formalise some material from a basic undergraduate combinatorics course.) An (n,m) - grid path is a path in {0,..,n} × {0,..,m} that starts at (0,0) and ends at (m,m), where each step moves one unit to the right or one unit upwards. The set of (n,m) - grid paths bijects naturally with the set of subsets of size n in {0,...,n+m-1} (by considering which of the steps are horizontal). There is an evident bijection between (n,m) - grid paths and (m,n) - grid paths. -/
27f2e01396ba030d9f3c98fb56c8701866eaef6a
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/calculus/mean_value.lean
378c5e6bcdba240ab2b1faa2de5e33da914c1e2b
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
69,905
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.local_extr import analysis.convex.slope import analysis.convex.topology import data.complex.is_R_or_C /-! # The mean value inequality and equalities In this file we prove the following facts: * `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentiable on a convex set `s` and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with constant `C`; also a variant in which what is bounded by `C` is the norm of the difference of the derivative from a fixed linear map. This lemma and its versions are formulated using `is_R_or_C`, so they work both for real and complex derivatives. * `image_le_of*`, `image_norm_le_of_*` : several similar lemmas deducing `f x ≤ B x` or `∥f x∥ ≤ B x` from upper estimates on `f'` or `∥f'∥`, respectively. These lemmas differ by their assumptions: * `of_liminf_*` lemmas assume that limit inferior of some ratio is less than `B' x`; * `of_deriv_right_*`, `of_norm_deriv_right_*` lemmas assume that the right derivative or its norm is less than `B' x`; * `of_*_lt_*` lemmas assume a strict inequality whenever `f x = B x` or `∥f x∥ = B x`; * `of_*_le_*` lemmas assume a non-strict inequality everywhere on `[a, b)`; * name of a lemma ends with `'` if (1) it assumes that `B` is continuous on `[a, b]` and has a right derivative at every point of `[a, b)`, and (2) the lemma has a counterpart assuming that `B` is differentiable everywhere on `ℝ` * `norm_image_sub_le_*_segment` : if derivative of `f` on `[a, b]` is bounded above by a constant `C`, then `∥f x - f a∥ ≤ C * ∥x - a∥`; several versions deal with right derivative and derivative within `[a, b]` (`has_deriv_within_at` or `deriv_within`). * `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`, then it is a constant on `s`. * `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` : Cauchy's Mean Value Theorem. * `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem. * `domain_mvt` : Lagrange's Mean Value Theorem, applied to a segment in a convex domain. * `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`, `convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`, if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`. * `convex.monotone_on_of_deriv_nonneg`, `convex.antitone_on_of_deriv_nonpos`, `convex.strict_mono_of_deriv_pos`, `convex.strict_anti_of_deriv_neg` : if the derivative of a function is non-negative/non-positive/positive/negative, then the function is monotone/antitone/strictly monotone/strictly monotonically decreasing. * `convex_on_of_deriv_monotone_on`, `convex_on_of_deriv2_nonneg` : if the derivative of a function is increasing or its second derivative is nonnegative, then the original function is convex. * `strict_fderiv_of_cont_diff` : a C^1 function over the reals is strictly differentiable. (This is a corollary of the mean value inequality.) -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set asymptotics continuous_linear_map filter open_locale classical topological_space nnreal /-! ### One-dimensional fencing inequalities -/ /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin change Icc a b ⊆ {x | f x ≤ B x}, set s := {x | f x ≤ B x} ∩ Icc a b, have A : continuous_on (λ x, (f x, B x)) (Icc a b), from hf.prod hB, have : is_closed s, { simp only [s, inter_comm], exact A.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, apply this.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxB : f x ≤ B x, xab⟩ y hy, cases hxB.lt_or_eq with hxB hxB, { -- If `f x < B x`, then all we need is continuity of both sides refine nonempty_of_mem (inter_mem _ (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)), have : ∀ᶠ x in 𝓝[Icc a b] x, f x < B x, from A x (Ico_subset_Icc_self xab) (is_open.mem_nhds (is_open_lt continuous_fst continuous_snd) hxB), have : ∀ᶠ x in 𝓝[Ioi x] x, f x < B x, from nhds_within_le_of_mem (Icc_mem_nhds_within_Ioi xab) this, exact this.mono (λ y, le_of_lt) }, { rcases exists_between (bound x xab hxB) with ⟨r, hfr, hrB⟩, specialize hf' x xab r hfr, have HB : ∀ᶠ z in 𝓝[Ioi x] x, r < (z - x)⁻¹ * (B z - B x), from (has_deriv_within_at_iff_tendsto_slope' $ lt_irrefl x).1 (hB' x xab).Ioi_of_Ici (Ioi_mem_nhds hrB), obtain ⟨z, ⟨hfz, hzB⟩, hz⟩ : ∃ z, ((z - x)⁻¹ * (f z - f x) < r ∧ r < (z - x)⁻¹ * (B z - B x)) ∧ z ∈ Ioc x y, from ((hf'.and_eventually HB).and_eventually (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)).exists, refine ⟨z, _, hz⟩, have := (hfz.trans hzB).le, rwa [mul_le_mul_left (inv_pos.2 $ sub_pos.2 hz.1), hxB, sub_le_sub_iff_right] at this } end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by `B'`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_le_deriv_boundary {f : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) -- `bound` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ B' x` (bound : ∀ x ∈ Ico a b, ∀ r, B' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin have Hr : ∀ x ∈ Icc a b, ∀ r > 0, f x ≤ B x + r * (x - a), { intros x hx r hr, apply image_le_of_liminf_slope_right_lt_deriv_boundary' hf bound, { rwa [sub_self, mul_zero, add_zero] }, { exact hB.add (continuous_on_const.mul (continuous_id.continuous_on.sub continuous_on_const)) }, { assume x hx, exact (hB' x hx).add (((has_deriv_within_at_id x (Ici x)).sub_const a).const_mul r) }, { assume x hx _, rw [mul_one], exact (lt_add_iff_pos_right _).2 hr }, exact hx }, assume x hx, have : continuous_within_at (λ r, B x + r * (x - a)) (Ioi 0) 0, from continuous_within_at_const.add (continuous_within_at_id.mul continuous_within_at_const), convert continuous_within_at_const.closure_le _ this (Hr x hx); simp end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf (λ x hx r hr, (hf' x hx).liminf_right_slope_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x ≤ B' x` on `[a, b)`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_le_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f' x ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary hf ha hB hB' $ assume x hx r hr, (hf' x hx).liminf_right_slope_le (lt_of_le_of_lt (bound x hx) hr) /-! ### Vector-valued functions `f : ℝ → E` -/ section variables {f : ℝ → E} {a b : ℝ} /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `B` has right derivative at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(∥f z∥ - ∥f x∥) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. -/ lemma image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary {E : Type*} [normed_group E] {f : ℝ → E} {f' : ℝ → ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' (continuous_norm.comp_continuous_on hf) hf' ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary hf (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary (continuous_norm.comp_continuous_on hf) ha hB hB' $ (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le (lt_of_le_of_lt (bound x hx) hr)) /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_le_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- A function on `[a, b]` with the norm of the right derivative bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`. -/ theorem norm_image_sub_le_of_norm_deriv_right_le_segment {f' : ℝ → E} {C : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin let g := λ x, f x - f a, have hg : continuous_on g (Icc a b), from hf.sub continuous_on_const, have hg' : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x, { assume x hx, simpa using (hf' x hx).sub (has_deriv_within_at_const _ _ _) }, let B := λ x, C * (x - a), have hB : ∀ x, has_deriv_at B C x, { assume x, simpa using (has_deriv_at_const x C).mul ((has_deriv_at_id x).sub (has_deriv_at_const x a)) }, convert image_norm_le_of_norm_deriv_right_le_deriv_boundary hg hg' _ hB bound, simp only [g, B], rw [sub_self, norm_zero, sub_self, mul_zero] end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc a b, has_deriv_within_at f (f' x) (Icc a b) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_right_le_segment (λ x hx, (hf x hx).continuous_within_at) (λ x hx, _) bound, exact (hf x $ Ico_subset_Icc_self hx).nhds_within (Icc_mem_nhds_within_Ici hx) end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment {C : ℝ} (hf : differentiable_on ℝ f (Icc a b)) (bound : ∀x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_le_segment' _ bound, exact λ x hx, (hf x hx).has_deriv_within_at end /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc (0:ℝ) 1, has_deriv_within_at f (f' x) (Icc (0:ℝ) 1) x) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥f' x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment' hf bound 1 (right_mem_Icc.2 zero_le_one) /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01 {C : ℝ} (hf : differentiable_on ℝ f (Icc (0:ℝ) 1)) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥deriv_within f (Icc (0:ℝ) 1) x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment hf bound 1 (right_mem_Icc.2 zero_le_one) theorem constant_of_has_deriv_right_zero (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f 0 (Ici x) x) : ∀ x ∈ Icc a b, f x = f a := by simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_right_le_segment hcont hderiv (λ y hy, by rw norm_le_zero_iff) x hx theorem constant_of_deriv_within_zero (hdiff : differentiable_on ℝ f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, deriv_within f (Icc a b) x = 0) : ∀ x ∈ Icc a b, f x = f a := begin have H : ∀ x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ 0 := by simpa only [norm_le_zero_iff] using λ x hx, hderiv x hx, simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_le_segment hdiff H x hx, end variables {f' g : ℝ → E} /-- If two continuous functions on `[a, b]` have the same right derivative and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_has_deriv_right_eq (derivf : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (derivg : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x) (fcont : continuous_on f (Icc a b)) (gcont : continuous_on g (Icc a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin simp only [← @sub_eq_zero _ _ (f _)] at hi ⊢, exact hi ▸ constant_of_has_deriv_right_zero (fcont.sub gcont) (λ y hy, by simpa only [sub_self] using (derivf y hy).sub (derivg y hy)), end /-- If two differentiable functions on `[a, b]` have the same derivative within `[a, b]` everywhere on `[a, b)` and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_deriv_within_eq (fdiff : differentiable_on ℝ f (Icc a b)) (gdiff : differentiable_on ℝ g (Icc a b)) (hderiv : eq_on (deriv_within f (Icc a b)) (deriv_within g (Icc a b)) (Ico a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin have A : ∀ y ∈ Ico a b, has_deriv_within_at f (deriv_within f (Icc a b) y) (Ici y) y := λ y hy, (fdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), have B : ∀ y ∈ Ico a b, has_deriv_within_at g (deriv_within g (Icc a b) y) (Ici y) y := λ y hy, (gdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), exact eq_of_has_deriv_right_eq A (λ y hy, (hderiv hy).symm ▸ B y hy) fdiff.continuous_on gdiff.continuous_on hi end end /-! ### Vector-valued functions `f : E → G` Theorems in this section work both for real and complex differentiable functions. We use assumptions `[is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 G]` to achieve this result. For the domain `E` we also assume `[normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E]` to have a notion of a `convex` set. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` the assumption `[is_scalar_tower ℝ 𝕜 E]` is satisfied automatically. -/ section variables {𝕜 G : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [is_scalar_tower ℝ 𝕜 E] [normed_group G] [normed_space 𝕜 G] {f : E → G} {C : ℝ} {s : set E} {x y : E} {f' : E → E →L[𝕜] G} {φ : E →L[𝕜] G} /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_fderiv_within_le (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := begin letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, letI : is_scalar_tower ℝ 𝕜 G := restrict_scalars.is_scalar_tower _ _ _, /- By composition with `t ↦ x + t • (y-x)`, we reduce to a statement for functions defined on `[0,1]`, for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`. We just have to check the differentiability of the composition and bounds on its derivative, which is straightforward but tedious for lack of automation. -/ have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs), set g : ℝ → E := λ t, x + t • (y - x), have Dg : ∀ t, has_deriv_at g (y-x) t, { assume t, simpa only [one_smul] using ((has_deriv_at_id t).smul_const (y - x)).const_add x }, have segm : Icc 0 1 ⊆ g ⁻¹' s, { rw [← image_subset_iff, ← segment_eq_image'], apply hs.segment_subset xs ys }, have : f x = f (g 0), by { simp only [g], rw [zero_smul, add_zero] }, rw this, have : f y = f (g 1), by { simp only [g], rw [one_smul, add_sub_cancel'_right] }, rw this, have D2: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) (f' (g t) (y - x)) (Icc 0 1) t, { intros t ht, have : has_fderiv_within_at f ((f' (g t)).restrict_scalars ℝ) s (g t), from hf (g t) (segm ht), exact this.comp_has_deriv_within_at _ (Dg t).has_deriv_within_at segm }, apply norm_image_sub_le_of_norm_deriv_le_segment_01' D2, refine λ t ht, le_of_op_norm_le _ _ _, exact bound (g t) (segm $ Ico_subset_Icc_self ht) end /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_fderiv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le {C : ℝ≥0} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := begin rw lipschitz_on_with_iff_norm_sub_le, intros x x_in y y_in, exact hs.norm_image_sub_le_of_norm_has_fderiv_within_le hf bound y_in x_in end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is `K`-Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at` for a version that claims existence of `K` instead of an explicit estimate. -/ lemma convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt (hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) (K : ℝ≥0) (hK : ∥f' x∥₊ < K) : ∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t := begin obtain ⟨ε, ε0, hε⟩ : ∃ ε > 0, ball x ε ∩ s ⊆ {y | has_fderiv_within_at f (f' y) s y ∧ ∥f' y∥₊ < K}, from mem_nhds_within_iff.1 (hder.and $ hcont.nnnorm.eventually (gt_mem_nhds hK)), rw inter_comm at hε, refine ⟨s ∩ ball x ε, inter_mem_nhds_within _ (ball_mem_nhds _ ε0), _⟩, exact (hs.inter (convex_ball _ _)).lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ y hy, (hε hy).1.mono (inter_subset_left _ _)) (λ y hy, (hε hy).2.le) end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt` for a version with an explicit estimate on the Lipschitz constant. -/ lemma convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at (hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) : ∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t := (no_top _).imp $ hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt hder hcont /-- The mean value theorem on a convex set: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_within_le (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_fderiv_within_le {C : ℝ≥0} (hf : differentiable_on 𝕜 f s) (bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s:= hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_le (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_fderiv_le {C : ℝ≥0} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound /-- Variant of the mean value inequality on a convex set, using a bound on the difference between the derivative and a fixed linear map, rather than a bound on the derivative itself. Version with `has_fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_fderiv_within_le' (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := begin /- We subtract `φ` to define a new function `g` for which `g' = 0`, for which the previous theorem applies, `convex.norm_image_sub_le_of_norm_has_fderiv_within_le`. Then, we just need to glue together the pieces, expressing back `f` in terms of `g`. -/ let g := λy, f y - φ y, have hg : ∀ x ∈ s, has_fderiv_within_at g (f' x - φ) s x := λ x xs, (hf x xs).sub φ.has_fderiv_within_at, calc ∥f y - f x - φ (y - x)∥ = ∥f y - f x - (φ y - φ x)∥ : by simp ... = ∥(f y - φ y) - (f x - φ x)∥ : by abel ... = ∥g y - g x∥ : by simp ... ≤ C * ∥y - x∥ : convex.norm_image_sub_le_of_norm_has_fderiv_within_le hg bound hs xs ys, end /-- Variant of the mean value inequality on a convex set. Version with `fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_within_le' (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- Variant of the mean value inequality on a convex set. Version with `fderiv`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_le' (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x - φ∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- If a function has zero Fréchet derivative at every point of a convex set, then it is a constant on this set. -/ theorem convex.is_const_of_fderiv_within_eq_zero (hs : convex ℝ s) (hf : differentiable_on 𝕜 f s) (hf' : ∀ x ∈ s, fderiv_within 𝕜 f s x = 0) (hx : x ∈ s) (hy : y ∈ s) : f x = f y := have bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥ ≤ 0, from λ x hx, by simp only [hf' x hx, norm_zero], by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm] using hs.norm_image_sub_le_of_norm_fderiv_within_le hf bound hx hy theorem is_const_of_fderiv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, fderiv 𝕜 f x = 0) (x y : E) : f x = f y := convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on (λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial end /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_deriv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_deriv_within_le {f f' : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := convex.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_deriv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_has_deriv_within_le {f f' : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hs : convex ℝ s) (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) : lipschitz_on_with C f s := convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv_within` -/ theorem convex.norm_image_sub_le_of_norm_deriv_within_le {f : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥deriv_within f s x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_deriv_within_le {f : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hs : convex ℝ s) (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥deriv_within f s x∥₊ ≤ C) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv`. -/ theorem convex.norm_image_sub_le_of_norm_deriv_le {f : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : ∀ x ∈ s, differentiable_at ℝ f x) (bound : ∀x∈s, ∥deriv f x∥ ≤ C) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_deriv_le {f : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hf : ∀ x ∈ s, differentiable_at ℝ f x) (bound : ∀x∈s, ∥deriv f x∥₊ ≤ C) (hs : convex ℝ s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound /-! ### Functions `[a, b] → ℝ`. -/ section interval -- Declare all variables here to make sure they come in a correct order variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b)) (g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hgd : differentiable_on ℝ g (Ioo a b)) include hab hfc hff' hgc hgg' /-- Cauchy's **Mean Value Theorem**, `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c := begin let h := λ x, (g b - g a) * f x - (f b - f a) * g x, have hI : h a = h b, { simp only [h], ring }, let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)), have hhc : continuous_on h (Icc a b), from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc), rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end omit hfc hgc /-- Cauchy's **Mean Value Theorem**, extended `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 lfa)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 lga)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[Iio b] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (f' c) = (lfb - lfa) * (g' c) := begin let h := λ x, (lgb - lga) * f x - (lfb - lfa) * g x, have hha : tendsto h (𝓝[Ioi a] a) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[Ioi a] a)(𝓝 $ (lgb - lga) * lfa - (lfb - lfa) * lga) := (tendsto_const_nhds.mul hfa).sub (tendsto_const_nhds.mul hga), convert this using 2, ring }, have hhb : tendsto h (𝓝[Iio b] b) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[Iio b] b)(𝓝 $ (lgb - lga) * lfb - (lfb - lfa) * lgb) := (tendsto_const_nhds.mul hfb).sub (tendsto_const_nhds.mul hgb), convert this using 2, ring }, let h' := λ x, (lgb - lga) * f' x - (lfb - lfa) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, { intros x hx, exact ((hff' x hx).const_mul _ ).sub (((hgg' x hx)).const_mul _) }, rcases exists_has_deriv_at_eq_zero' hab hha hhb hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end include hfc omit hgg' /-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) := begin rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff' id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩, use [c, cmem], simp only [_root_.id, pi.one_apply, mul_one] at hc, rw [← hc, mul_div_cancel_left], exact ne_of_gt (sub_pos.2 hab) end omit hff' /-- Cauchy's Mean Value Theorem, `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) g (deriv g) hgc $ λ x hx, ((hgd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at omit hfc /-- Cauchy's Mean Value Theorem, extended `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hdf : differentiable_on ℝ f $ Ioo a b) (hdg : differentiable_on ℝ g $ Ioo a b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 lfa)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 lga)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[Iio b] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (deriv f c) = (lfb - lfa) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope' _ _ hab _ _ (λ x hx, ((hdf x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) (λ x hx, ((hdg x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) hfa hga hfb hgb /-- Lagrange's **Mean Value Theorem**, `deriv` version. -/ lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) := exists_has_deriv_at_eq_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) end interval /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then `f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) : ∀ x y ∈ D, x < y → C * (y - x) < f y - f x := begin assume x y hx hy hxy, have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) }, exact (lt_div_iff (sub_pos.2 hxy)).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than `C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/ theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) : C * (y - x) < f y - f x := convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_gt x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then `f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x := begin assume x y hx hy hxy, cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero], have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'), have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) }, exact (le_div_iff (sub_pos.2 hxy')).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/ theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) : C * (y - x) ≤ f y - f x := convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_ge x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) : ∀ x y ∈ D, x < y → f y - f x < C * (y - x) := begin assume x y hx hy hxy, have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_lt_neg_iff], exact lt_hf' x hx }, simpa [-neg_lt_neg_iff] using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/ theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) : f y - f x < C * (y - x) := convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on (λ x _, lt_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then `f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) : ∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) := begin assume x y hx hy hxy, have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_le_neg_iff], exact le_hf' x hx }, simpa [-neg_le_neg_iff] using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/ theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) : f y - f x ≤ C * (y - x) := convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on (λ x _, le_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then `f` is a strictly monotone function on `D`. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly positive. -/ theorem convex.strict_mono_on_of_deriv_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : ∀ x ∈ interior D, 0 < deriv f x) : strict_mono_on f D := begin rintro x hx y hy, simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf _ hf' x y hx hy, exact λ z hz, (differentiable_at_of_deriv_ne_zero (hf' z hz).ne').differentiable_within_at, end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then `f` is a strictly monotone function. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly positive. -/ theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf' : ∀ x, 0 < deriv f x) : strict_mono f := strict_mono_on_univ.1 $ convex_univ.strict_mono_on_of_deriv_pos (λ z _, (differentiable_at_of_deriv_ne_zero (hf' z).ne').differentiable_within_at .continuous_within_at) (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then `f` is a monotone function on `D`. -/ theorem convex.monotone_on_of_deriv_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) : monotone_on f D := λ x hx y hy hxy, by simpa only [zero_mul, sub_nonneg] using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg x y hx hy hxy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then `f` is a monotone function. -/ theorem monotone_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) : monotone f := monotone_on_univ.1 $ convex_univ.monotone_on_of_deriv_nonneg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then `f` is a strictly antitone function on `D`. -/ theorem convex.strict_anti_on_of_deriv_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : ∀ x ∈ interior D, deriv f x < 0) : strict_anti_on f D := λ x hx y, by simpa only [zero_mul, sub_lt_zero] using hD.image_sub_lt_mul_sub_of_deriv_lt hf (λ z hz, (differentiable_at_of_deriv_ne_zero (hf' z hz).ne).differentiable_within_at) hf' x y hx /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then `f` is a strictly antitone function. Note that we don't require differentiability explicitly as it already implied by the derivative being strictly negative. -/ theorem strict_anti_of_deriv_neg {f : ℝ → ℝ} (hf' : ∀ x, deriv f x < 0) : strict_anti f := strict_anti_on_univ.1 $ convex_univ.strict_anti_on_of_deriv_neg (λ z _, (differentiable_at_of_deriv_ne_zero (hf' z).ne).differentiable_within_at .continuous_within_at) (λ x _, hf' x) /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then `f` is an antitone function on `D`. -/ theorem convex.antitone_on_of_deriv_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) : antitone_on f D := λ x hx y hy hxy, by simpa only [zero_mul, sub_nonpos] using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos x y hx hy hxy /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then `f` is an antitone function. -/ theorem antitone_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) : antitone f := antitone_on_univ.1 $ convex_univ.antitone_on_of_deriv_nonpos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `D`. -/ theorem monotone_on.convex_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : monotone_on (deriv f) (interior D)) : convex_on ℝ D f := convex_on_of_slope_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb).le end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is antitone on the interior, then `f` is concave on `D`. -/ theorem antitone_on.concave_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (h_anti : antitone_on (deriv f) (interior D)) : concave_on ℝ D f := begin have : monotone_on (deriv (-f)) (interior D), { intros x hx y hy hxy, convert neg_le_neg (h_anti hx hy hxy); convert deriv.neg }, exact neg_convex_on_iff.mp (this.convex_on_of_deriv hD hf.neg hf'.neg), end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is strictly monotone on the interior, then `f` is strictly convex on `D`. -/ lemma strict_mono_on.strict_convex_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : strict_mono_on (deriv f) (interior D)) : strict_convex_on ℝ D f := strict_convex_on_of_slope_strict_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb) end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is strictly antitone on the interior, then `f` is strictly concave on `D`. -/ lemma strict_anti_on.strict_concave_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (h_anti : strict_anti_on (deriv f) (interior D)) : strict_concave_on ℝ D f := begin have : strict_mono_on (deriv (-f)) (interior D), { intros x hx y hy hxy, convert neg_lt_neg (h_anti hx hy hxy); convert deriv.neg }, exact neg_strict_convex_on_iff.mp (this.strict_convex_on_of_deriv hD hf.neg hf'.neg), end /-- If a function `f` is differentiable and `f'` is monotone on `ℝ` then `f` is convex. -/ theorem monotone.convex_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : monotone (deriv f)) : convex_on ℝ univ f := (hf'_mono.monotone_on _).convex_on_of_deriv convex_univ hf.continuous.continuous_on hf.differentiable_on /-- If a function `f` is differentiable and `f'` is antitone on `ℝ` then `f` is concave. -/ theorem antitone.concave_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_anti : antitone (deriv f)) : concave_on ℝ univ f := (hf'_anti.antitone_on _).concave_on_of_deriv convex_univ hf.continuous.continuous_on hf.differentiable_on /-- If a function `f` is differentiable and `f'` is strictly monotone on `ℝ` then `f` is strictly convex. -/ lemma strict_mono.strict_convex_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : strict_mono (deriv f)) : strict_convex_on ℝ univ f := (hf'_mono.strict_mono_on _).strict_convex_on_of_deriv convex_univ hf.continuous.continuous_on hf.differentiable_on /-- If a function `f` is differentiable and `f'` is strictly antitone on `ℝ` then `f` is strictly concave. -/ lemma strict_anti.strict_concave_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_anti : strict_anti (deriv f)) : strict_concave_on ℝ univ f := (hf'_anti.strict_anti_on _).strict_concave_on_of_deriv convex_univ hf.continuous.continuous_on hf.differentiable_on /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) : convex_on ℝ D f := (hD.interior.monotone_on_of_deriv_nonneg hf''.continuous_on (by rwa interior_interior) $ by rwa interior_interior).convex_on_of_deriv hD hf hf' /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonpositive on the interior, then `f` is concave on `D`. -/ theorem concave_on_of_deriv2_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonpos : ∀ x ∈ interior D, deriv^[2] f x ≤ 0) : concave_on ℝ D f := (hD.interior.antitone_on_of_deriv_nonpos hf''.continuous_on (by rwa interior_interior) $ by rwa interior_interior).concave_on_of_deriv hD hf hf' /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is strictly positive on the interior, then `f` is strictly convex on `D`. Note that we don't require twice differentiability explicitly as it already implied by the second derivative being strictly positive. -/ lemma strict_convex_on_of_deriv2_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : ∀ x ∈ interior D, 0 < (deriv^[2] f) x) : strict_convex_on ℝ D f := (hD.interior.strict_mono_on_of_deriv_pos (λ z hz, (differentiable_at_of_deriv_ne_zero (hf'' z hz).ne').differentiable_within_at .continuous_within_at) $ by rwa interior_interior).strict_convex_on_of_deriv hD hf hf' /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is strictly negative on the interior, then `f` is strictly concave on `D`. Note that we don't require twice differentiability explicitly as it already implied by the second derivative being strictly negative. -/ lemma strict_concave_on_of_deriv2_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : ∀ x ∈ interior D, deriv^[2] f x < 0) : strict_concave_on ℝ D f := (hD.interior.strict_anti_on_of_deriv_neg (λ z hz, (differentiable_at_of_deriv_ne_zero (hf'' z hz).ne).differentiable_within_at .continuous_within_at) $ by rwa interior_interior).strict_concave_on_of_deriv hD hf hf' /-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and `f''` is nonnegative on `D`, then `f` is convex on `D`. -/ theorem convex_on_open_of_deriv2_nonneg {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonneg : ∀ x ∈ D, 0 ≤ (deriv^[2] f) x) : convex_on ℝ D f := convex_on_of_deriv2_nonneg hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') (by simpa [hD₂.interior_eq] using hf'') (by simpa [hD₂.interior_eq] using hf''_nonneg) /-- If a function `f` is twice differentiable on an open convex set `D ⊆ ℝ` and `f''` is nonpositive on `D`, then `f` is concave on `D`. -/ theorem concave_on_open_of_deriv2_nonpos {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonpos : ∀ x ∈ D, deriv^[2] f x ≤ 0) : concave_on ℝ D f := concave_on_of_deriv2_nonpos hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') (by simpa [hD₂.interior_eq] using hf'') (by simpa [hD₂.interior_eq] using hf''_nonpos) /-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and `f''` is strictly positive on `D`, then `f` is strictly convex on `D`. Note that we don't require twice differentiability explicitly as it already implied by the second derivative being strictly positive. -/ lemma strict_convex_on_open_of_deriv2_pos {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : ∀ x ∈ D, 0 < (deriv^[2] f) x) : strict_convex_on ℝ D f := strict_convex_on_of_deriv2_pos hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') $ by simpa [hD₂.interior_eq] using hf'' /-- If a function `f` is twice differentiable on an open convex set `D ⊆ ℝ` and `f''` is strictly negative on `D`, then `f` is strictly concave on `D`. Note that we don't require twice differentiability explicitly as it already implied by the second derivative being strictly negative. -/ lemma strict_concave_on_open_of_deriv2_neg {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : ∀ x ∈ D, deriv^[2] f x < 0) : strict_concave_on ℝ D f := strict_concave_on_of_deriv2_neg hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') $ by simpa [hD₂.interior_eq] using hf'' /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f) x) : convex_on ℝ univ f := convex_on_open_of_deriv2_nonneg convex_univ is_open_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonneg x) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonpositive on `ℝ`, then `f` is concave on `ℝ`. -/ theorem concave_on_univ_of_deriv2_nonpos {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonpos : ∀ x, deriv^[2] f x ≤ 0) : concave_on ℝ univ f := concave_on_open_of_deriv2_nonpos convex_univ is_open_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonpos x) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is strictly positive on `ℝ`, then `f` is strictly convex on `ℝ`. Note that we don't require twice differentiability explicitly as it already implied by the second derivative being strictly positive. -/ lemma strict_convex_on_univ_of_deriv2_pos {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : ∀ x, 0 < (deriv^[2] f) x) : strict_convex_on ℝ univ f := strict_convex_on_open_of_deriv2_pos convex_univ is_open_univ hf'.differentiable_on $ λ x _, hf'' x /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is strictly negative on `ℝ`, then `f` is strictly concave on `ℝ`. Note that we don't require twice differentiability explicitly as it already implied by the second derivative being strictly negative. -/ lemma strict_concave_on_univ_of_deriv2_neg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : ∀ x, deriv^[2] f x < 0) : strict_concave_on ℝ univ f := strict_concave_on_open_of_deriv2_neg convex_univ is_open_univ hf'.differentiable_on $ λ x _, hf'' x /-! ### Functions `f : E → ℝ` -/ /-- Lagrange's Mean Value Theorem, applied to convex domains. -/ theorem domain_mvt {f : E → ℝ} {s : set E} {x y : E} {f' : E → (E →L[ℝ] ℝ)} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∃ z ∈ segment ℝ x y, f y - f x = f' z (y - x) := begin have hIccIoo := @Ioo_subset_Icc_self ℝ _ 0 1, -- parametrize segment set g : ℝ → E := λ t, x + t • (y - x), have hseg : ∀ t ∈ Icc (0:ℝ) 1, g t ∈ segment ℝ x y, { rw segment_eq_image', simp only [mem_image, and_imp, add_right_inj], intros t ht, exact ⟨t, ht, rfl⟩ }, have hseg' : Icc 0 1 ⊆ g ⁻¹' s, { rw ← image_subset_iff, unfold image, change ∀ _, _, intros z Hz, rw mem_set_of_eq at Hz, rcases Hz with ⟨t, Ht, hgt⟩, rw ← hgt, exact hs.segment_subset xs ys (hseg t Ht) }, -- derivative of pullback of f under parametrization have hfg: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) ((f' (g t) : E → ℝ) (y-x)) (Icc (0:ℝ) 1) t, { intros t Ht, have hg : has_deriv_at g (y-x) t, { have := ((has_deriv_at_id t).smul_const (y - x)).const_add x, rwa one_smul at this }, exact (hf (g t) $ hseg' Ht).comp_has_deriv_within_at _ hg.has_deriv_within_at hseg' }, -- apply 1-variable mean value theorem to pullback have hMVT : ∃ (t ∈ Ioo (0:ℝ) 1), ((f' (g t) : E → ℝ) (y-x)) = (f (g 1) - f (g 0)) / (1 - 0), { refine exists_has_deriv_at_eq_slope (f ∘ g) _ (by norm_num) _ _, { unfold continuous_on, exact λ t Ht, (hfg t Ht).continuous_within_at }, { refine λ t Ht, (hfg t $ hIccIoo Ht).has_deriv_at _, refine _root_.mem_nhds_iff.mpr _, use (Ioo (0:ℝ) 1), refine ⟨hIccIoo, _, Ht⟩, simp [real.Ioo_eq_ball, is_open_ball] } }, -- reinterpret on domain rcases hMVT with ⟨t, Ht, hMVT'⟩, use g t, refine ⟨hseg t $ hIccIoo Ht, _⟩, simp [g, hMVT'], end section is_R_or_C /-! ### Vector-valued functions `f : E → F`. Strict differentiability. A `C^1` function is strictly differentiable, when the field is `ℝ` or `ℂ`. This follows from the mean value inequality on balls, which is a particular case of the above results after restricting the scalars to `ℝ`. Note that it does not make sense to talk of a convex set over `ℂ`, but balls make sense and are enough. Many formulations of the mean value inequality could be generalized to balls over `ℝ` or `ℂ`. For now, we only include the ones that we need. -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] {G : Type*} [normed_group G] [normed_space 𝕜 G] {H : Type*} [normed_group H] [normed_space 𝕜 H] {f : G → H} {f' : G → G →L[𝕜] H} {x : G} /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_fderiv_at f (f' x) x := begin -- turn little-o definition of strict_fderiv into an epsilon-delta statement refine is_o_iff.mpr (λ c hc, metric.eventually_nhds_iff_ball.mpr _), -- the correct ε is the modulus of continuity of f' rcases metric.mem_nhds_iff.mp (inter_mem hder (hcont $ ball_mem_nhds _ hc)) with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, _⟩, -- simplify formulas involving the product E × E rintros ⟨a, b⟩ h, rw [← ball_prod_same, prod_mk_mem_set_prod_eq] at h, -- exploit the choice of ε as the modulus of continuity of f' have hf' : ∀ x' ∈ ball x ε, ∥f' x' - f' x∥ ≤ c, { intros x' H', rw ← dist_eq_norm, exact le_of_lt (hε H').2 }, -- apply mean value theorem letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, letI : is_scalar_tower ℝ 𝕜 G := restrict_scalars.is_scalar_tower _ _ _, refine (convex_ball _ _).norm_image_sub_le_of_norm_has_fderiv_within_le' _ hf' h.2 h.1, exact λ y hy, (hε hy).1.has_fderiv_within_at end /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_deriv_at_of_has_deriv_at_of_continuous_at {f f' : 𝕜 → G} {x : 𝕜} (hder : ∀ᶠ y in 𝓝 x, has_deriv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_deriv_at f (f' x) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder.mono (λ y hy, hy.has_fderiv_at)) $ (smul_rightL 𝕜 _ _ 1).continuous.continuous_at.comp hcont end is_R_or_C
719053b98b3adcafa492cf66eb9b72f76cf4495e
94e33a31faa76775069b071adea97e86e218a8ee
/src/number_theory/zsqrtd/basic.lean
f96fd17f37af300a30b517dee398130e33c9b4c7
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
33,352
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.associated import ring_theory.int.basic import tactic.ring /-! # ℤ[√d] The ring of integers adjoined with a square root of `d : ℤ`. After defining the norm, we show that it is a linearly ordered commutative ring, as well as an integral domain. We provide the universal property, that ring homomorphisms `ℤ√d →+* R` correspond to choices of square roots of `d` in `R`. -/ /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case. -/ structure zsqrtd (d : ℤ) := (re : ℤ) (im : ℤ) prefix `ℤ√`:100 := zsqrtd namespace zsqrtd section parameters {d : ℤ} instance : decidable_eq ℤ√d := by tactic.mk_dec_eq_instance theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, λ ⟨h₁, h₂⟩, by congr; assumption⟩ /-- Convert an integer to a `ℤ√d` -/ def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩ theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ instance : has_zero ℤ√d := ⟨of_int 0⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl instance : inhabited ℤ√d := ⟨0⟩ /-- The one of the ring -/ instance : has_one ℤ√d := ⟨of_int 1⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ instance : has_add ℤ√d := ⟨λ z w, ⟨z.1 + w.1, z.2 + w.2⟩⟩ @[simp] lemma add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] lemma add_re (z w : ℤ√d) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℤ√d) : (z + w).im = z.im + w.im := rfl @[simp] lemma bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := rfl @[simp] lemma bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := rfl @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := rfl @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ instance : has_neg ℤ√d := ⟨λ z, ⟨-z.1, -z.2⟩⟩ @[simp] lemma neg_re (z : ℤ√d) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℤ√d) : (-z).im = -z.im := rfl /-- Multiplication in `ℤ√d` -/ instance : has_mul ℤ√d := ⟨λ z w, ⟨z.1 * w.1 + d * z.2 * w.2, z.1 * w.2 + z.2 * w.1⟩⟩ @[simp] lemma mul_re (z w : ℤ√d) : (z * w).re = z.re * w.re + d * z.im * w.im := rfl @[simp] lemma mul_im (z w : ℤ√d) : (z * w).im = z.re * w.im + z.im * w.re := rfl instance : add_comm_group ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), sub := λ a b, a + -b, neg := has_neg.neg, zsmul := @zsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩, nsmul := @nsmul_rec (ℤ√d) ⟨0⟩ ⟨(+)⟩ }; intros; try { refl }; simp [ext, add_comm, add_left_comm] instance : add_group_with_one ℤ√d := { nat_cast := λ n, of_int n, int_cast := of_int, one := 1, .. zsqrtd.add_comm_group } instance : comm_ring ℤ√d := by refine_struct { add := (+), zero := (0 : ℤ√d), mul := (*), one := 1, npow := @npow_rec (ℤ√d) ⟨1⟩ ⟨(*)⟩, .. zsqrtd.add_group_with_one }; intros; try { refl }; simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] instance : add_monoid ℤ√d := by apply_instance instance : monoid ℤ√d := by apply_instance instance : comm_monoid ℤ√d := by apply_instance instance : comm_semigroup ℤ√d := by apply_instance instance : semigroup ℤ√d := by apply_instance instance : add_comm_semigroup ℤ√d := by apply_instance instance : add_semigroup ℤ√d := by apply_instance instance : comm_semiring ℤ√d := by apply_instance instance : semiring ℤ√d := by apply_instance instance : ring ℤ√d := by apply_instance instance : distrib ℤ√d := by apply_instance /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj (z : ℤ√d) : ℤ√d := ⟨z.1, -z.2⟩ @[simp] lemma conj_re (z : ℤ√d) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℤ√d) : (conj z).im = -z.im := rfl /-- `conj` as an `add_monoid_hom`. -/ def conj_hom : ℤ√d →+ ℤ√d := { to_fun := conj, map_add' := λ ⟨a, ai⟩ ⟨b, bi⟩, ext.mpr ⟨rfl, neg_add _ _⟩, map_zero' := ext.mpr ⟨rfl, neg_zero⟩ } @[simp] lemma conj_zero : conj (0 : ℤ√d) = 0 := conj_hom.map_zero @[simp] lemma conj_one : conj (1 : ℤ√d) = 1 := by simp only [zsqrtd.ext, zsqrtd.conj_re, zsqrtd.conj_im, zsqrtd.one_im, neg_zero, eq_self_iff_true, and_self] @[simp] lemma conj_neg (x : ℤ√d) : (-x).conj = -x.conj := rfl @[simp] lemma conj_add (x y : ℤ√d) : (x + y).conj = x.conj + y.conj := conj_hom.map_add x y @[simp] lemma conj_sub (x y : ℤ√d) : (x - y).conj = x.conj - y.conj := conj_hom.map_sub x y @[simp] lemma conj_conj {d : ℤ} (x : ℤ√d) : x.conj.conj = x := by simp only [ext, true_and, conj_re, eq_self_iff_true, neg_neg, conj_im] instance : nontrivial ℤ√d := ⟨⟨0, 1, dec_trivial⟩⟩ @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := rfl @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := rfl theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := rfl @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; refl @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; refl theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] instance : char_zero ℤ√d := { cast_injective := λ m n, by simp [ext] } @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext, of_int_re, of_int_im] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] theorem smul_re (a : ℤ) (b : ℤ√d) : (↑a * b).re = a * b.re := by simp theorem smul_im (a : ℤ) (b : ℤ√d) : (↑a * b).im = a * b.im := by simp @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem dmuld : sqrtd * sqrtd = d := by simp [ext] @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, sub_eq_add_neg, mul_comm] theorem conj_mul {a b : ℤ√d} : conj (a * b) = conj a * conj b := by { simp [ext], ring } protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := (int.cast_ring_hom _).map_add _ _ protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := (int.cast_ring_hom _).map_sub _ _ protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := (int.cast_ring_hom _).map_mul _ _ protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h lemma coe_int_dvd_iff (z : ℤ) (a : ℤ√d) : ↑z ∣ a ↔ z ∣ a.re ∧ z ∣ a.im := begin split, { rintro ⟨x, rfl⟩, simp only [add_zero, coe_int_re, zero_mul, mul_im, dvd_mul_right, and_self, mul_re, mul_zero, coe_int_im] }, { rintro ⟨⟨r, hr⟩, ⟨i, hi⟩⟩, use ⟨r, i⟩, rw [smul_val, ext], exact ⟨hr, hi⟩ }, end @[simp, norm_cast] lemma coe_int_dvd_coe_int (a b : ℤ) : (a : ℤ√d) ∣ b ↔ a ∣ b := begin rw coe_int_dvd_iff, split, { rintro ⟨hre, -⟩, rwa [coe_int_re] at hre }, { rw [coe_int_re, coe_int_im], exact λ hc, ⟨hc, dvd_zero a⟩ }, end protected lemma eq_of_smul_eq_smul_left {a : ℤ} {b c : ℤ√d} (ha : a ≠ 0) (h : ↑a * b = a * c) : b = c := begin rw ext at h ⊢, apply and.imp _ _ h; { simp only [smul_re, smul_im], exact int.eq_of_mul_eq_mul_left ha }, end section gcd lemma gcd_eq_zero_iff (a : ℤ√d) : int.gcd a.re a.im = 0 ↔ a = 0 := by simp only [int.gcd_eq_zero_iff, ext, eq_self_iff_true, zero_im, zero_re] lemma gcd_pos_iff (a : ℤ√d) : 0 < int.gcd a.re a.im ↔ a ≠ 0 := pos_iff_ne_zero.trans $ not_congr a.gcd_eq_zero_iff lemma coprime_of_dvd_coprime {a b : ℤ√d} (hcoprime : is_coprime a.re a.im) (hdvd : b ∣ a) : is_coprime b.re b.im := begin apply is_coprime_of_dvd, { rintro ⟨hre, him⟩, obtain rfl : b = 0, { simp only [ext, hre, eq_self_iff_true, zero_im, him, and_self, zero_re] }, rw zero_dvd_iff at hdvd, simpa only [hdvd, zero_im, zero_re, not_coprime_zero_zero] using hcoprime }, { intros z hz hznezero hzdvdu hzdvdv, apply hz, obtain ⟨ha, hb⟩ : z ∣ a.re ∧ z ∣ a.im, { rw ←coe_int_dvd_iff, apply dvd_trans _ hdvd, rw coe_int_dvd_iff, exact ⟨hzdvdu, hzdvdv⟩ }, exact hcoprime.is_unit_of_dvd' ha hb }, end lemma exists_coprime_of_gcd_pos {a : ℤ√d} (hgcd : 0 < int.gcd a.re a.im) : ∃ b : ℤ√d, a = ((int.gcd a.re a.im : ℤ) : ℤ√d) * b ∧ is_coprime b.re b.im := begin obtain ⟨re, im, H1, Hre, Him⟩ := int.exists_gcd_one hgcd, rw [mul_comm] at Hre Him, refine ⟨⟨re, im⟩, _, _⟩, { rw [smul_val, ext, ←Hre, ←Him], split; refl }, { rw [←int.gcd_eq_one_iff_coprime, H1] } end end gcd /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_assoc], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), convert this, simp only [one_mul, int.coe_nat_add, int.coe_nat_mul], ring } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ) (b : ℕ) := true | (a : ℕ) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : ℕ) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm /-- The norm of an element of `ℤ[√d]`. -/ def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im lemma norm_def (n : ℤ√d) : n.norm = n.re * n.re - d * n.im * n.im := rfl @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m := by { simp only [norm, mul_im, mul_re], ring } /-- `norm` as a `monoid_hom`. -/ def norm_monoid_hom : ℤ√d →* ℤ := { to_fun := norm, map_mul' := norm_mul, map_one' := norm_one } lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg] @[simp] lemma norm_neg (x : ℤ√d) : (-x).norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_neg, neg_mul, mul_neg, neg_neg] @[simp] lemma norm_conj (x : ℤ√d) : x.conj.norm = x.norm := coe_int_inj $ by simp only [norm_eq_mul_conj, conj_conj, mul_comm] lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (λ hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (λ hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ lemma is_unit_iff_norm_is_unit {d : ℤ} (z : ℤ√d) : is_unit z ↔ is_unit z.norm := by rw [int.is_unit_iff_nat_abs_eq, norm_eq_one_iff] lemma norm_eq_one_iff' {d : ℤ} (hd : d ≤ 0) (z : ℤ√d) : z.norm = 1 ↔ is_unit z := by rw [←norm_eq_one_iff, ←int.coe_nat_inj', int.nat_abs_of_nonneg (norm_nonneg hd z), int.coe_nat_one] lemma norm_eq_zero_iff {d : ℤ} (hd : d < 0) (z : ℤ√d) : z.norm = 0 ↔ z = 0 := begin split, { intro h, rw [ext, zero_re, zero_im], rw [norm_def, sub_eq_add_neg, mul_assoc] at h, have left := mul_self_nonneg z.re, have right := neg_nonneg.mpr (mul_nonpos_of_nonpos_of_nonneg hd.le (mul_self_nonneg z.im)), obtain ⟨ha, hb⟩ := (add_eq_zero_iff' left right).mp h, split; apply eq_zero_of_mul_self_eq_zero, { exact ha }, { rw [neg_eq_zero, mul_eq_zero] at hb, exact hb.resolve_left hd.ne } }, { rintro rfl, exact norm_zero } end lemma norm_eq_of_associated {d : ℤ} (hd : d ≤ 0) {x y : ℤ√d} (h : associated x y) : x.norm = y.norm := begin obtain ⟨u, rfl⟩ := h, rw [norm_mul, (norm_eq_one_iff' hd _).mpr u.is_unit, mul_one], end end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b instance : has_le ℤ√d := ⟨λ a b, nonneg (b - a)⟩ instance : has_lt ℤ√d := ⟨λ a b, ¬ b ≤ a⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le : @decidable_rel (ℤ√d) (≤) := λ _ _, decidable_nonneg _ theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩) (λm n xy zw, trivial) (λm n xy zw, sq_le_cancel zw xy)) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩) (λm n xy zw, sq_le_cancel xy zw) (λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) le_rfl xy) in have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this lemma nonneg.add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩, { trivial }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa [add_comm] using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (int.le.intro h)) }, { apply nat.le_add_right } }, { dsimp, rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa [add_comm] using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a) | ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a := begin have t := (b - a).nonneg_total, rwa neg_sub at t, end instance : preorder ℤ√d := { le := (≤), le_refl := λ a, show nonneg (a - a), by simp only [sub_self], le_trans := λ a b c hab hbc, by simpa [sub_add_sub_cancel'] using hab.add hbc, lt := (<), lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n := let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]⟩ end in begin refine ⟨x + d*y, h.trans _⟩, change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : ∀y, sq_le y d (d * y) 1 := λ y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b := λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) := by simp only [← int.cast_coe_nat] {single_pass := tt}; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact (nonneg_smul ha).add (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp [add_comm]]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp [add_comm]]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : 0 < c) : ¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) : Prop := (ns [] : ∀n : ℕ, x ≠ n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (λgpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos) (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_sq (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := λe, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_sq _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_sq _ _) theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : linear_order ℤ√d := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero_left h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero_left h2, have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ mul_right_cancel₀ w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ mul_right_cancel₀ z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : is_domain ℤ√d := { eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, .. zsqrtd.comm_ring, .. zsqrtd.nontrivial } protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (λe, ne_of_gt a0 e) (λe, ne_of_gt b0 e) instance : linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, mul_pos := @zsqrtd.mul_pos, zero_le_one := dec_trivial, .. zsqrtd.comm_ring, .. zsqrtd.linear_order, .. zsqrtd.nontrivial } instance : linear_ordered_ring ℤ√d := by apply_instance instance : ordered_ring ℤ√d := by apply_instance end lemma norm_eq_zero {d : ℤ} (h_nonsquare : ∀ n : ℤ, d ≠ n*n) (a : ℤ√d) : norm a = 0 ↔ a = 0 := begin refine ⟨λ ha, ext.mpr _, λ h, by rw [h, norm_zero]⟩, delta norm at ha, rw sub_eq_zero at ha, by_cases h : 0 ≤ d, { obtain ⟨d', rfl⟩ := int.eq_coe_of_zero_le h, haveI : nonsquare d' := ⟨λ n h, h_nonsquare n $ by exact_mod_cast h⟩, exact divides_sq_eq_zero_z ha, }, { push_neg at h, suffices : a.re * a.re = 0, { rw eq_zero_of_mul_self_eq_zero this at ha ⊢, simpa only [true_and, or_self_right, zero_re, zero_im, eq_self_iff_true, zero_eq_mul, mul_zero, mul_eq_zero, h.ne, false_or, or_self] using ha }, apply _root_.le_antisymm _ (mul_self_nonneg _), rw [ha, mul_assoc], exact mul_nonpos_of_nonpos_of_nonneg h.le (mul_self_nonneg _) } end variables {R : Type} @[ext] lemma hom_ext [ring R] {d : ℤ} (f g : ℤ√d →+* R) (h : f sqrtd = g sqrtd) : f = g := begin ext ⟨x_re, x_im⟩, simp [decompose, h], end variables [comm_ring R] /-- The unique `ring_hom` from `ℤ√d` to a ring `R`, constructed by replacing `√d` with the provided root. Conversely, this associates to every mapping `ℤ√d →+* R` a value of `√d` in `R`. -/ @[simps] def lift {d : ℤ} : {r : R // r * r = ↑d} ≃ (ℤ√d →+* R) := { to_fun := λ r, { to_fun := λ a, a.1 + a.2*(r : R), map_zero' := by simp, map_add' := λ a b, by { simp, ring, }, map_one' := by simp, map_mul' := λ a b, by { have : (a.re + a.im * r : R) * (b.re + b.im * r) = a.re * b.re + (a.re * b.im + a.im * b.re) * r + a.im * b.im * (r * r) := by ring, simp [this, r.prop], ring, } }, inv_fun := λ f, ⟨f sqrtd, by rw [←f.map_mul, dmuld, ring_hom.map_int_cast]⟩, left_inv := λ r, by { ext, simp }, right_inv := λ f, by { ext, simp } } /-- `lift r` is injective if `d` is non-square, and R has characteristic zero (that is, the map from `ℤ` into `R` is injective). -/ lemma lift_injective [char_zero R] {d : ℤ} (r : {r : R // r * r = ↑d}) (hd : ∀ n : ℤ, d ≠ n*n) : function.injective (lift r) := (injective_iff_map_eq_zero (lift r)).mpr $ λ a ha, begin have h_inj : function.injective (coe : ℤ → R) := int.cast_injective, suffices : lift r a.norm = 0, { simp only [coe_int_re, add_zero, lift_apply_apply, coe_int_im, int.cast_zero, zero_mul] at this, rwa [← int.cast_zero, h_inj.eq_iff, norm_eq_zero hd] at this }, rw [norm_eq_mul_conj, ring_hom.map_mul, ha, zero_mul] end end zsqrtd
1aaaf1a3538bd4574f65ce0a04b30be3665cf2a3
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/zify.lean
3c391f29cbd8b9d9afb2d93b2926e1690a942f5d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,406
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.int.cast -- used by clients import tactic.norm_cast /-! # A tactic to shift `ℕ` goals to `ℤ` It is often easier to work in `ℤ`, where subtraction is well behaved, than in `ℕ` where it isn't. `zify` is a tactic that casts goals and hypotheses about natural numbers to ones about integers. It makes use of `push_cast`, part of the `norm_cast` family, to simplify these goals. ## Implementation notes `zify` is extensible, using the attribute `@[zify]` to label lemmas used for moving propositions from `ℕ` to `ℤ`. `zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`. For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma. `zify` is very nearly just `simp only with zify push_cast`. There are a few minor differences: * `zify` lemmas are used in the opposite order of the standard simp form. E.g. we will rewrite with `int.coe_nat_le_coe_nat_iff` from right to left. * `zify` should fail if no `zify` lemma applies (i.e. it was unable to shift any proposition to ℤ). However, once this succeeds, it does not necessarily need to rewrite with any `push_cast` rules. -/ open tactic namespace zify /-- The `zify` attribute is used by the `zify` tactic. It applies to lemmas that shift propositions between `nat` and `int`. `zify` lemmas should have the form `∀ a₁ ... aₙ : ℕ, Pz (a₁ : ℤ) ... (aₙ : ℤ) ↔ Pn a₁ ... aₙ`. For example, `int.coe_nat_le_coe_nat_iff : ∀ (m n : ℕ), ↑m ≤ ↑n ↔ m ≤ n` is a `zify` lemma. -/ @[user_attribute] meta def zify_attr : user_attribute simp_lemmas unit := { name := `zify, descr := "Used to tag lemmas for use in the `zify` tactic", cache_cfg := { mk_cache := λ ns, mmap (λ n, do c ← mk_const n, return (c, tt)) ns >>= simp_lemmas.mk.append_with_symm, dependencies := [] } } /-- Given an expression `e`, `lift_to_z e` looks for subterms of `e` that are propositions "about" natural numbers and change them to propositions about integers. Returns an expression `e'` and a proof that `e = e'`. Includes `ge_iff_le` and `gt_iff_lt` in the simp set. These can't be tagged with `zify` as we want to use them in the "forward", not "backward", direction. -/ meta def lift_to_z (e : expr) : tactic (expr × expr) := do sl ← zify_attr.get_cache, sl ← sl.add_simp `ge_iff_le, sl ← sl.add_simp `gt_iff_lt, (e', prf, _) ← simplify sl [] e, return (e', prf) attribute [zify] int.coe_nat_le_coe_nat_iff int.coe_nat_lt_coe_nat_iff int.coe_nat_eq_coe_nat_iff end zify @[zify] lemma int.coe_nat_ne_coe_nat_iff (a b : ℕ) : (a : ℤ) ≠ b ↔ a ≠ b := by simp /-- `zify extra_lems e` is used to shift propositions in `e` from `ℕ` to `ℤ`. This is often useful since `ℤ` has well-behaved subtraction. The list of extra lemmas is used in the `push_cast` step. Returns an expression `e'` and a proof that `e = e'`.-/ meta def tactic.zify (extra_lems : list simp_arg_type) : expr → tactic (expr × expr) := λ z, do (z1, p1) ← zify.lift_to_z z <|> fail "failed to find an applicable zify lemma", (z2, p2) ← norm_cast.derive_push_cast extra_lems z1, prod.mk z2 <$> mk_eq_trans p1 p2 /-- A variant of `tactic.zify` that takes `h`, a proof of a proposition about natural numbers, and returns a proof of the zified version of that propositon. -/ meta def tactic.zify_proof (extra_lems : list simp_arg_type) (h : expr) : tactic expr := do (_, pf) ← infer_type h >>= tactic.zify extra_lems, mk_eq_mp pf h section setup_tactic_parser /-- The `zify` tactic is used to shift propositions from `ℕ` to `ℤ`. This is often useful since `ℤ` has well-behaved subtraction. ```lean example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) : c < a + 3*b := begin zify, zify at h, /- h : ¬↑x * ↑y * ↑z < 0 ⊢ ↑c < ↑a + 3 * ↑b -/ end ``` `zify` can be given extra lemmas to use in simplification. This is especially useful in the presence of nat subtraction: passing `≤` arguments will allow `push_cast` to do more work. ``` example (a b c : ℕ) (h : a - b < c) (hab : b ≤ a) : false := begin zify [hab] at h, /- h : ↑a - ↑b < ↑c -/ end ``` `zify` makes use of the `@[zify]` attribute to move propositions, and the `push_cast` tactic to simplify the `ℤ`-valued expressions. `zify` is in some sense dual to the `lift` tactic. `lift (z : ℤ) to ℕ` will change the type of an integer `z` (in the supertype) to `ℕ` (the subtype), given a proof that `z ≥ 0`; propositions concerning `z` will still be over `ℤ`. `zify` changes propositions about `ℕ` (the subtype) to propositions about `ℤ` (the supertype), without changing the type of any variable. -/ meta def tactic.interactive.zify (sl : parse simp_arg_list) (l : parse location) : tactic unit := do locs ← l.get_locals, replace_at (tactic.zify sl) locs l.include_goal >>= guardb end add_tactic_doc { name := "zify", category := doc_category.attr, decl_names := [`zify.zify_attr], tags := ["coercions", "transport"] } add_tactic_doc { name := "zify", category := doc_category.tactic, decl_names := [`tactic.interactive.zify], tags := ["coercions", "transport"] }
f37e56e9221614f85000869fbe48e85878805970
367134ba5a65885e863bdc4507601606690974c1
/test/monotonicity.lean
25cd7b00b2dc22511c2f088f0da749f720229fd9
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
8,580
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.monotonicity import tactic.norm_num import algebra.ordered_ring import measure_theory.lebesgue_measure import data.list.defs open list tactic tactic.interactive set example (h : 3 + 6 ≤ 4 + 5) : 1 + 3 + 2 + 6 ≤ 4 + 2 + 1 + 5 := begin ac_mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin ac_mono, mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin transitivity (1 + 3 + 2 - 5 : ℤ), { ac_mono }, { ac_mono }, end example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, norm_num end example (x y z a b : ℤ) (h : a ≤ (b : ℤ)) (h' : z ≤ y) : (1 + a + x) - y ≤ (1 + b + x) - z := begin transitivity (1 + a + x - z), { mono, }, { mono, mono, mono }, end example (x y z : ℤ) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin transitivity (1 + 3 + x - z), { mono }, { mono, mono, norm_num }, end example (x y z : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin ac_mono, mono* end @[simp] def list.le' {α : Type*} [has_le α] : list α → list α → Prop | (x::xs) (y::ys) := x ≤ y ∧ list.le' xs ys | [] [] := true | _ _ := false @[simp] instance list_has_le {α : Type*} [has_le α] : has_le (list α) := ⟨ list.le' ⟩ lemma list.le_refl {α : Type*} [preorder α] {xs : list α} : xs ≤ xs := begin induction xs with x xs, { trivial }, { simp [has_le.le,list.le], split, apply le_refl, apply xs_ih } end -- @[trans] lemma list.le_trans {α : Type*} [preorder α] {xs zs : list α} (ys : list α) (h : xs ≤ ys) (h' : ys ≤ zs) : xs ≤ zs := begin revert ys zs, induction xs with x xs ; intros ys zs h h' ; cases ys with y ys ; cases zs with z zs ; try { cases h ; cases h' ; done }, { apply list.le_refl }, { simp [has_le.le,list.le], split, apply le_trans h.left h'.left, apply xs_ih _ h.right h'.right, } end @[mono] lemma list_le_mono_left {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : xs ++ zs ≤ ys ++ zs := begin revert ys, induction xs with x xs ; intros ys h, { cases ys, apply list.le_refl, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, revert h, apply and.imp_right, apply xs_ih } end @[mono] lemma list_le_mono_right {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : zs ++ xs ≤ zs ++ ys := begin revert ys zs, induction xs with x xs ; intros ys zs h, { cases ys, { simp, apply list.le_refl }, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, suffices : list.le' ((zs ++ [x]) ++ xs) ((zs ++ [y]) ++ ys), { refine cast _ this, simp, }, apply list.le_trans (zs ++ [y] ++ xs), { apply list_le_mono_left, induction zs with z zs, { simp [has_le.le,list.le], apply h.left }, { simp [has_le.le,list.le], split, apply le_refl, apply zs_ih, } }, { apply xs_ih h.right, } } end lemma bar_bar' (h : [] ++ [3] ++ [2] ≤ [1] ++ [5] ++ [4]) : [] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end lemma bar_bar'' (h : [3] ++ [2] ++ [2] ≤ [5] ++ [4] ++ []) : [1] ++ ([3] ++ [2]) ++ [2] ≤ [1] ++ [5] ++ ([4] ++ []) := begin ac_mono, end lemma bar_bar (h : [3] ++ [2] ≤ [5] ++ [4]) : [1] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end def P (x : ℕ) := 7 ≤ x def Q (x : ℕ) := x ≤ 7 @[mono] lemma P_mono {x y : ℕ} (h : x ≤ y) : P x → P y := by { intro h', apply le_trans h' h } @[mono] lemma Q_mono {x y : ℕ} (h : y ≤ x) : Q x → Q y := by apply le_trans h example (x y z : ℕ) (h : x ≤ y) : P (x + z) → P (z + y) := begin ac_mono, ac_mono, end example (x y z : ℕ) (h : y ≤ x) : Q (x + z) → Q (z + y) := begin ac_mono, ac_mono, end example (x y z k m n : ℤ) (h₀ : z ≤ 0) (h₁ : y ≤ x) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : n + x + m ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono* : m + x + n ≤ y + n + m, transitivity ; [ skip , apply h₁ ], apply le_of_eq, ac_refl, end example (x y z k m n : ℤ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, success_if_fail { ac_mono }, admit }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono*, change 0 ≤ z, apply nat.zero_le, }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, change (m + x + n) * z ≤ z * (y + n + m), admit }, trivial, end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono^3, cc end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : z * (x + i + n + m) + k = z * (y + j + n + m) + k := begin congr, simp [h₁], end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono*, cc, end example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 1, end example {x y z : ℕ} : true := begin have : y + x ≤ y + z, { mono, guard_target' x ≤ z, admit }, trivial end example {x y z : ℕ} : true := begin suffices : x + y ≤ z + y, trivial, mono, guard_target' x ≤ z, admit, end example {x y z w : ℕ} : true := begin have : x + y ≤ z + w, { mono, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : ℕ} : true := begin have : x * y ≤ z * w, { mono with [0 ≤ z,0 ≤ y], { guard_target 0 ≤ z, admit }, { guard_target 0 ≤ y, admit }, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∧ y → z ∧ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∨ y → z ∨ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : ℤ} : true := begin suffices : x + y < w + z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, end example {x y z w : ℤ} : true := begin suffices : x * y < w * z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, { guard_target' 0 < y, admit }, { guard_target' 0 ≤ w, admit }, end open tactic example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 3 end example {α} [linear_order α] (a b c d e : α) : max a b ≤ e → b ≤ e := by { mono, apply le_max_right } example (a b c d e : Prop) (h : d → a) (h' : c → e) : (a ∧ b → c) ∨ d → (d ∧ b → e) ∨ a := begin mono, mono, mono, end example : ∫ x in Icc 0 1, real.exp x ≤ ∫ x in Icc 0 1, real.exp (x+1) := begin mono, { exact real.continuous_exp.integrable_on_compact compact_Icc }, { exact (real.continuous_exp.comp $ continuous_add_right 1).integrable_on_compact compact_Icc }, intro x, dsimp only, mono, linarith end
4e074ca3426e1b002a2a87cb673b6e71c16229e7
b29f946a2f0afd23ef86b9219116968babbb9f4f
/src/sandwich.lean
b811b8e62b45fce19084e1ede4fee99579dc514e
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M1P1-lean
58be7394fded719d95e45e6b10e1ecf2ed3c7c4c
3723468cc50f8bebd00a9811caf25224a578de17
refs/heads/master
1,587,063,867,779
1,572,727,164,000
1,572,727,164,000
165,845,802
14
4
Apache-2.0
1,549,730,698,000
1,547,554,675,000
Lean
UTF-8
Lean
false
false
2,208
lean
-- begin header import limits namespace M1P1 -- end header /- Section The sandwich theorem -/ /- Sub-section Introdiction -/ /- The sandwich theorem, or squeeze theorem, for sequences is the statement that if $(a_n)$, $(b_n)$, and $(c_n)$ are three real-valued sequences satisfying $a_n≤ b_n≤ c_n$ for all $n$, and if furthermore $a_n→ℓ$ and $c_n→ℓ$, then $b_n→ℓ$. The idea of the proof is straightforward -- if we want to ensure that $|b_n-ℓ|<ε$ then it suffices to show that $|a_n-ℓ|<ε$ and $|c_n-ℓ|<ε$. -/ /- Theorem If $(a_n)$, $(b_n)$, and $(c_n)$ are three real-valued sequences satisfying $a_n ≤ b_n ≤ c_n$ for all $n$, and if furthermore $a_n→ℓ$ and $c_n→ℓ$, then $b_n→ℓ$. -/ theorem sandwich (a b c : ℕ → ℝ) (l : ℝ) (ha : is_limit a l) (hc : is_limit c l) (hab : ∀ n, a n ≤ b n) (hbc : ∀ n, b n ≤ c n) : is_limit b l := begin -- We need to show that for all $ε>0$ there exists $N$ such that $n≥N$ implies $|b_n-ℓ|<ε$. So choose ε > 0. intros ε Hε, -- we now need an $N$. As usual it is the max of two other N's, one coming from $(a_n)$ and one from $(c_n)$. Choose $N_a$ and $N_c$ such that $|aₙ - l| < ε$ for $n ≥ Na$ and $|cₙ - l| < ε$ for $n ≥ Nc$. cases ha ε Hε with Na Ha, cases hc ε Hε with Nc Hc, -- Now let $N$ be the max of $N_a$ and $N_c$; we claim that this works. let N := max Na Nc, use N, -- Note that N ≥ Na and N ≥ Nc, have HNa : Na ≤ N := by obvious_ineq, have HNc : Nc ≤ N := by obvious_ineq, -- so for all n ≥ N, intros n Hn, -- we have $n≥ N_a$ and $n\geq N_c$, so $aₙ ≤ bₙ ≤ cₙ$, and $|aₙ - l|, |bₙ - l|$ are both less than $\epsilon$. have h1 : a n ≤ b n := hab n, have h2 : b n ≤ c n := hbc n, have h3 : |a n - l| < ε := Ha n (le_trans HNa Hn), have h4 : |c n - l| < ε := Hc n (le_trans HNc Hn), -- The result now follows easily from these inequalities (as $l-ε<a_n≤b_n≤c_n<l+ε$). revert h3,revert h4, unfold abs,unfold max, split_ifs;intros;linarith, end /- Note that Lean finds the last line of the proof automatically -- we do not need to explicitly tell it the inequality argument. -/ end M1P1
f5934762b8aaf59f5e5eac0d89166889b5c0ccc9
618003631150032a5676f229d13a079ac875ff77
/src/group_theory/eckmann_hilton.lean
65e0ef58c0af31b260d9e7e94ccd9d72eaa158ab
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,936
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau, Robert Y. Lewis -/ import tactic.basic import algebra.group.basic universe u namespace eckmann_hilton variables {X : Type u} local notation a `<`m`>` b := m a b class is_unital (m : X → X → X) (e : X) : Prop := (one_mul : ∀ x : X, (e <m> x) = x) (mul_one : ∀ x : X, (x <m> e) = x) lemma group.is_unital [G : group X] : is_unital (*) (1 : X) := { ..G } variables {m₁ m₂ : X → X → X} {e₁ e₂ : X} variables (h₁ : is_unital m₁ e₁) (h₂ : is_unital m₂ e₂) variables (distrib : ∀ a b c d, ((a <m₂> b) <m₁> (c <m₂> d)) = ((a <m₁> c) <m₂> (b <m₁> d))) include h₁ h₂ distrib lemma one : e₁ = e₂ := by simpa only [h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] using distrib e₂ e₁ e₁ e₂ lemma mul : (m₁ = m₂) := begin funext a b, calc m₁ a b = m₁ (m₂ a e₁) (m₂ e₁ b) : by simp only [one h₁ h₂ distrib, h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] ... = m₂ a b : by simp only [distrib, h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] end lemma mul_comm : is_commutative _ m₂ := ⟨λ a b, by simpa [mul h₁ h₂ distrib, h₂.one_mul, h₂.mul_one] using distrib e₂ a b e₂⟩ lemma mul_assoc : is_associative _ m₂ := ⟨λ a b c, by simpa [mul h₁ h₂ distrib, h₂.one_mul, h₂.mul_one] using distrib a b e₂ c⟩ def comm_monoid : comm_monoid X := { mul := m₂, one := e₂, mul_comm := (mul_comm h₁ h₂ distrib).comm, mul_assoc := (mul_assoc h₁ h₂ distrib).assoc, ..h₂ } def comm_group [G : group X] (distrib : ∀ a b c d, ((a * b) <m₁> (c * d)) = ((a <m₁> c) * (b <m₁> d))) : comm_group X := { mul_comm := (eckmann_hilton.comm_monoid h₁ group.is_unital distrib).mul_comm, ..G } end eckmann_hilton
20d48ea14c29f23b0313fefac34e79f80331ed5f
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/list/perm.lean
1e905f3ca040de47f8275e03f0ad90093b0fdd49
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
41,134
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro List permutations. -/ import data.list.basic logic.relation namespace list universe variables uu vv variables {α : Type uu} {β : Type vv} /-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations of each other. This is defined by induction using pairwise swaps. -/ inductive perm : list α → list α → Prop | nil : perm [] [] | skip : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ open perm infix ~ := perm @[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l | [] := perm.nil | (x::xs) := skip x (perm.refl xs) @[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p perm.nil (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁) theorem perm.swap' (x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ := trans (swap _ _ _) (skip _ $ skip _ p) attribute [trans] perm.trans theorem perm.eqv (α) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) instance is_setoid (α) : setoid (list α) := setoid.mk (@perm α) (perm.eqv α) theorem perm_subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ := λ a, perm.rec_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim i (λ ax, by simp [ax]) (λ al₁, or.inr (r₁ al₁))) (λ x y l ayxl, or.elim ayxl (λ ay, by simp [ay]) (λ axl, or.elim axl (λ ax, by simp [ax]) (λ al, or.inr (or.inr al)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem mem_of_perm {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ := iff.intro (λ m, perm_subset h m) (λ m, perm_subset h.symm m) theorem perm_app_left {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ := perm.rec_on p (perm.refl ([] ++ t₁)) (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_app_right {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂ | [] p := p | (x::xs) p := skip x (perm_app_right xs p) theorem perm_app {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ := trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂) theorem perm_app_cons (a : α) {h₁ h₂ t₁ t₂ : list α} (p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ := perm_app p₁ (skip a p₂) @[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂) | [] l₂ := perm.refl _ | (b::l₁) l₂ := (skip b (@perm_middle l₁ l₂)).trans (swap a b _) @[simp] theorem perm_cons_app (a : α) (l : list α) : l ++ [a] ~ a::l := by simpa using @perm_middle _ a l [] @[simp] theorem perm_app_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁) | [] l₂ := by simp | (a::t) l₂ := (skip a perm_app_comm).trans perm_middle.symm theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l := by simp theorem perm_length {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ := perm.rec_on p rfl (λ x l₁ l₂ p r, by simp[r]) (λ x y l, by simp) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem eq_nil_of_perm_nil {l₁ : list α} (p : [] ~ l₁) : l₁ = [] := eq_nil_of_length_eq_zero (perm_length p).symm theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] := ⟨λ p, eq_nil_of_perm_nil p.symm, λ e, e ▸ perm.refl _⟩ theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l | p := by injection eq_nil_of_perm_nil p theorem eq_singleton_of_perm {a b : α} (p : [a] ~ [b]) : a = b := by simpa using perm_subset p (by simp) theorem eq_singleton_of_perm_inv {a : α} {l : list α} (p : [a] ~ l) : l = [a] := match l, show 1 = _, from perm_length p, p with | [a'], rfl, p := by rw [eq_singleton_of_perm p] end @[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l | [] := perm.nil | (a::l) := by rw reverse_cons; exact (perm_cons_app _ _).trans (skip a $ reverse_perm l) theorem perm_cons_app_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) := trans (skip a p) perm_middle.symm @[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l := ⟨λ p, (eq_repeat.2 $ by exact ⟨by simpa using (perm_length p).symm, λ b m, eq_of_mem_repeat $ perm_subset p.symm m⟩).symm, λ h, h ▸ perm.refl _⟩ theorem perm_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : l ~ a :: l.erase a := let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in e₂.symm ▸ e₁.symm ▸ perm_middle @[elab_as_eliminator] theorem perm_induction_on {P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l, from assume l, list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ @[congr] theorem perm_filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : filter_map f l₁ ~ filter_map f l₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp [filter_map], cases f x with a; simp [filter_map, IH, skip] }, { simp [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] }, { exact IH₁.trans IH₂ } end @[congr] theorem perm_map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : map f l₁ ~ map f l₂ := by rw ← filter_map_eq_map; apply perm_filter_map _ p theorem perm_pmap {p : α → Prop} (f : Π a, p a → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp [IH, skip] }, { simp [swap] }, { refine IH₁.trans IH₂, exact λ a m, H₂ a (perm_subset p₂ m) } end theorem perm_filter (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ := by rw ← filter_map_eq_filter; apply perm_filter_map _ s theorem exists_perm_sublist {l₁ l₂ l₂' : list α} (s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s, { exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ }, { cases s with _ _ _ s l₁ _ _ s, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ }, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', skip x p', s'.cons2 _ _ _⟩ } }, { cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s, { exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ }, { exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ }, { exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ }, { exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } }, { exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in ⟨r₁, pr.trans pm, sr⟩ } end section rel open relator variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} local infixr ` ∘r ` : 80 := relation.comp lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm := begin funext a c, apply propext, split, { exact assume ⟨b, hab, hba⟩, perm.trans hab hba }, { exact assume h, ⟨a, perm.refl a, h⟩ } end lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v := begin induction hlu generalizing v, case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ }, case perm.skip : a l u hlu ih { cases huv with _ b _ v hab huv', rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩, exact ⟨b::l₂, forall₂.cons hab h₁₂, perm.skip _ h₂₃⟩ }, case perm.swap : a₁ a₂ l₁ l₂ h₂₃ { cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃, cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂, exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩ }, case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ { rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩, rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩, exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩ } end lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r := begin funext l₁ l₃, apply propext, split, { assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩, have : forall₂ (flip r) l₂ l₁, from h₁₂.flip , rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩, exact ⟨l', h₂.symm, h₁.flip⟩ }, { exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ } end lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm := assume a b h₁ c d h₂ h, have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩, have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d, by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this, let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in have b' = b, from right_unique_forall₂ @hr hcb hbc, this ▸ hbd lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm := assume a b hab c d hcd, iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp (assume a b c, left_unique_flip hr.1) hab.flip hcd.flip) end rel section subperm /-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects multiplicities of elements, and is used for the `≤` relation on multisets. -/ def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂ infix ` <+~ `:50 := subperm theorem nil_subperm {l : list α} : [] <+~ l := ⟨[], perm.nil, by simp⟩ theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ := suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂, from ⟨this p, this p.symm⟩, λ l₁ l₂ p ⟨u, pu, su⟩, let ⟨v, pv, sv⟩ := exists_perm_sublist su p in ⟨v, pv.trans pu, sv⟩ theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l := ⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩, λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩ theorem subperm_of_sublist {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ := ⟨l₁, perm.refl _, s⟩ theorem subperm_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ := ⟨l₂, p.symm, sublist.refl _⟩ theorem subperm.refl (l : list α) : l <+~ l := subperm_of_perm (perm.refl _) theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃ | s ⟨l₂', p₂, s₂⟩ := let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩ theorem length_le_of_subperm {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂ | ⟨l, p, s⟩ := perm_length p ▸ length_le_of_sublist s theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂ | ⟨l, p, s⟩ h := suffices l = l₂, from this ▸ p.symm, eq_of_sublist_of_length_le s $ perm_length p.symm ▸ h theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ := h₁.perm_of_length_le (length_le_of_subperm h₂) theorem subset_of_subperm {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂ | ⟨l, p, s⟩ := subset.trans (perm_subset p.symm) (subset_of_sublist s) end subperm theorem exists_perm_append_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l | ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩ | ._ ._ (sublist.cons l₁ l₂ a s) := let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨a::l, (skip a p).trans perm_middle.symm⟩ | ._ ._ (sublist.cons2 l₁ l₂ a s) := let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, skip a p⟩ theorem perm_countp (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ := by rw [countp_eq_length_filter, countp_eq_length_filter]; exact perm_length (perm_filter _ s) theorem countp_le_of_subperm (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂ | ⟨l, p', s⟩ := perm_countp p p' ▸ countp_le_of_sublist s theorem perm_count [decidable_eq α] {l₁ l₂ : list α} (p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ := perm_countp _ p theorem count_le_of_subperm [decidable_eq α] {l₁ l₂ : list α} (s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ := countp_le_of_subperm _ s theorem foldl_eq_of_perm {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) : ∀ b, foldl f b l₁ = foldl f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, r (f b x)) (λ x y t₁ t₂ p r b, by simp; rw rcomm; exact r (f (f b x) y)) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b)) theorem foldr_eq_of_perm {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) : ∀ b, foldr f b l₁ = foldr f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, by simp; rw [r b]) (λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b]) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) lemma rec_heq_of_perm {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α} (hl : perm l l') (f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b') (f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) : @list.rec α β b f l == @list.rec α β b f l' := begin induction hl, case list.perm.nil { refl }, case list.perm.skip : a l l' h ih { exact f_congr h ih }, case list.perm.swap : a a' l { exact f_swap }, case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ } end section variables {op : α → α → α} [is_associative α op] [is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l lemma fold_op_eq_of_perm {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a := foldl_eq_of_perm (right_comm _ (is_commutative.comm _) (is_associative.assoc _)) h _ end section comm_monoid open list variable [comm_monoid α] @[to_additive] lemma prod_eq_of_perm {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ := by induction h; simp [*, mul_left_comm] @[to_additive] lemma prod_reverse (l : list α) : prod l.reverse = prod l := prod_eq_of_perm $ reverse_perm l end comm_monoid theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ := begin generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂, intro p, revert l₁ l₂ r₁ r₂ e₁ e₂, refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _) (λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂, { apply (not_mem_nil a).elim, rw ← e₁, simp }, { cases l₁ with y l₁; cases l₂ with z l₂; dsimp at e₁ e₂; injections; subst x, { substs t₁ t₂, exact p }, { substs z t₁ t₂, exact p.trans perm_middle }, { substs y t₁ t₂, exact perm_middle.symm.trans p }, { substs z t₁ t₂, exact skip y (IH rfl rfl) } }, { rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩; dsimp at e₁ e₂; injections; substs x y, { substs r₁ r₂, exact skip a p }, { substs r₁ r₂, exact skip u p }, { substs r₁ v t₂, exact skip u (p.trans perm_middle) }, { substs r₁ r₂, exact skip y p }, { substs r₁ r₂ y u, exact skip a p }, { substs r₁ u v t₂, exact (skip y $ p.trans perm_middle).trans (swap _ _ _) }, { substs r₂ z t₁, exact skip y (perm_middle.symm.trans p) }, { substs r₂ y z t₁, exact (swap _ _ _).trans (skip u $ perm_middle.symm.trans p) }, { substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } }, { substs t₁ t₃, have : a ∈ t₂ := perm_subset p₁ (by simp), rcases mem_split this with ⟨l₂, r₂, e₂⟩, subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) } end theorem perm_cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := @perm_inv_core _ _ [] [] _ _ theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ := ⟨perm_cons_inv, skip a⟩ theorem perm_app_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂ | [] := iff.rfl | (a::l) := (perm_cons a).trans (perm_app_left_iff l) theorem perm_app_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ := ⟨λ p, (perm_app_left_iff _).1 $ trans perm_app_comm $ trans p perm_app_comm, perm_app_left _⟩ theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ := begin refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩, cases o₁ with a; cases o₂ with b, {refl}, { cases (perm_length p) }, { cases (perm_length p) }, { exact option.mem_to_list.1 ((mem_of_perm p).2 $ by simp) } end theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ := ⟨λ ⟨l, p, s⟩, begin cases s with _ _ _ s' u _ _ s', { exact (p.subperm_left.2 $ subperm_of_sublist $ sublist_cons _ _).trans (subperm_of_sublist s') }, { exact ⟨u, perm_cons_inv p, s'⟩ } end, λ ⟨l, p, s⟩, ⟨a::l, skip a p, s.cons2 _ _ _⟩⟩ theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂) (s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ := begin rcases s with ⟨l, p, s⟩, induction s generalizing l₁, case list.sublist.slnil { cases h₂ }, case list.sublist.cons : r₁ r₂ b s' ih { simp at h₂, cases h₂ with e m, { subst b, exact ⟨a::r₁, skip a p, s'.cons2 _ _ _⟩ }, { rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } }, case list.sublist.cons2 : r₁ r₂ b s' ih { have bm : b ∈ l₁ := (perm_subset p $ mem_cons_self _ _), have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm), rcases mem_split bm with ⟨t₁, t₂, rfl⟩, have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp, rcases ih am (nodup_of_sublist st d₁) (mt (λ x, subset_of_sublist st x) h₁) (perm_cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩, exact ⟨b::t, (skip b p').trans $ (swap _ _ _).trans (skip a perm_middle.symm), s'.cons2 _ _ _⟩ } end theorem subperm_app_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂ | [] := iff.rfl | (a::l) := (subperm_cons a).trans (subperm_app_left l) theorem subperm_app_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ := (perm_app_comm.subperm_left.trans perm_app_comm.subperm_right).trans (subperm_app_left l) theorem subperm.exists_of_length_lt {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂ | ⟨l, p, s⟩ h := suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from (this $ perm_length p.symm ▸ h).imp (λ a, (skip a p).subperm_right.1), begin clear subperm.exists_of_length_lt p h l₁, rename l₂ u, induction s with l₁ l₂ a s IH _ _ b s IH; intro h, { cases h }, { cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h, { exact (IH h).imp (λ a s, s.trans (subperm_of_sublist $ sublist_cons _ _)) }, { exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } }, { exact (IH $ nat.lt_of_succ_lt_succ h).imp (λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) } end theorem subperm_of_subset_nodup {l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ := begin induction d with a l₁' h d IH, { exact ⟨nil, perm.nil, nil_sublist _⟩ }, { cases forall_mem_cons.1 H with H₁ H₂, simp at h, exact cons_subperm_of_mem d h H₁ (IH H₂) } end theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) : l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ := ⟨λ p a, mem_of_perm p, λ H, subperm.antisymm (subperm_of_subset_nodup d₁ (λ a, (H a).1)) (subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩ theorem perm_ext_sublist_nodup {l₁ l₂ l : list α} (d : nodup l) (s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ := ⟨λ h, begin induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁, { exact eq_nil_of_perm_nil h.symm }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { exact IH d.2 s₁ h }, { apply d.1.elim, exact subset_of_subperm ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { apply d.1.elim, exact subset_of_subperm ⟨_, h, s₁⟩ (mem_cons_self _ _) }, { rw IH d.2 s₁ (perm_cons_inv h) } } end, λ h, by rw h⟩ section variable [decidable_eq α] -- attribute [congr] theorem erase_perm_erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁.erase a ~ l₂.erase a := if h₁ : a ∈ l₁ then have h₂ : a ∈ l₂, from perm_subset p h₁, perm_cons_inv $ trans (perm_erase h₁).symm $ trans p (perm_erase h₂) else have h₂ : a ∉ l₂, from mt (mem_of_perm p).2 h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l := ⟨l.erase a, perm.refl _, erase_sublist _ _⟩ theorem erase_subperm_erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a := let ⟨l, hp, hs⟩ := h in ⟨l.erase a, erase_perm_erase _ hp, erase_sublist_erase _ hs⟩ theorem perm_diff_left {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, erase_perm_erase] theorem perm_diff_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ := by induction h generalizing l; simp [*, erase_perm_erase, erase_comm] <|> exact (ih_1 _).trans (ih_2 _) theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂ | l₁ [] := ⟨a::l₁, by simp⟩ | l₁ (b::l₂) := begin repeat {rw diff_cons}, by_cases heq : a = b, { by_cases b ∈ l₁, { rw perm.subperm_right, apply subperm_cons_diff, simp [perm_diff_left, heq, perm_erase h] }, { simp [subperm_of_sublist, sublist.cons, h, heq] } }, { simp [heq, subperm_cons_diff] } end theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ := subset_of_subperm subperm_cons_diff theorem perm_bag_inter_left {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.bag_inter t ~ l₂.bag_inter t := begin induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp}, { by_cases x ∈ t; simp [*, skip] }, { by_cases x = y, {simp [h]}, by_cases xt : x ∈ t; by_cases yt : y ∈ t, { simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] }, { simp [xt, yt, mt mem_of_mem_erase, skip] }, { simp [xt, yt, mt mem_of_mem_erase, skip] }, { simp [xt, yt] } }, { exact (ih_1 _).trans (ih_2 _) } end theorem perm_bag_inter_right (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l.bag_inter t₁ = l.bag_inter t₂ := begin induction l with a l IH generalizing t₁ t₂ p, {simp}, by_cases a ∈ t₁, { simp [h, (mem_of_perm p).1 h, IH (erase_perm_erase _ p)] }, { simp [h, mt (mem_of_perm p).2 h, IH p] } end theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a := ⟨λ h, have a ∈ l₂, from perm_subset h (mem_cons_self a l₁), ⟨this, perm_cons_inv $ h.trans $ perm_erase this⟩, λ ⟨m, h⟩, trans (skip a h) (perm_erase m).symm⟩ theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ := ⟨perm_count, λ H, begin induction l₁ with a l₁ IH generalizing l₂, { cases l₂ with b l₂, {refl}, specialize H b, simp at H, contradiction }, { have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos), refine trans (skip a $ IH $ λ b, _) (perm_erase this).symm, specialize H b, rw perm_count (perm_erase this) at H, by_cases b = a; simp [h] at H ⊢; assumption } end⟩ instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) | [] [] := is_true $ perm.refl _ | [] (b::l₂) := is_false $ λ h, by have := eq_nil_of_perm_nil h; contradiction | (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a); exact decidable_of_iff' _ cons_perm_iff_perm_erase -- @[congr] theorem perm_erase_dup_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : erase_dup l₁ ~ erase_dup l₂ := perm_iff_count.2 $ λ a, if h : a ∈ l₁ then by simp [nodup_erase_dup, h, perm_subset p h] else by simp [h, mt (mem_of_perm p).2 h] -- attribute [congr] theorem perm_insert (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ := if h : a ∈ l₁ then by simpa [h, perm_subset p h] using p else by simpa [h, mt (mem_of_perm p).2 h] using skip a p theorem perm_insert_swap (x y : α) (l : list α) : insert x (insert y l) ~ insert y (insert x l) := begin by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl], by_cases xy : x = y, { simp [xy] }, simp [not_mem_cons_of_ne_of_not_mem xy xl, not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl], constructor end theorem perm_union_left {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ := begin induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp}, { exact perm_insert a ih }, { apply perm_insert_swap }, { exact ih_1.trans ih_2 } end theorem perm_union_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ := by induction l; simp [*, perm_insert] -- @[congr] theorem perm_union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ := trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂) theorem perm_inter_left {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ := perm_filter _ theorem perm_inter_right (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ := by dsimp [(∩), list.inter]; congr; funext a; rw [mem_of_perm p] -- @[congr] theorem perm_inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ := perm_inter_right l₂ p₂ ▸ perm_inter_left t₁ p₁ end theorem perm_pairwise {R : α → α → Prop} (S : symmetric R) : ∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ := suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩, λ l₁ l₂ p d, begin induction d with a l₁ h d IH generalizing l₂, { rw eq_nil_of_perm_nil p, constructor }, { have : a ∈ l₂ := perm_subset p (mem_cons_self _ _), rcases mem_split this with ⟨s₂, t₂, rfl⟩, have p' := perm_cons_inv (p.trans perm_middle), refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩), exact h _ (perm_subset p'.symm m) } end theorem perm_nodup {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) := perm_pairwise $ @ne.symm α theorem perm_bind_left {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) : l₁.bind f ~ l₂.bind f := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app_right _ IH }, { simp, rw [← append_assoc, ← append_assoc], exact perm_app_left _ perm_app_comm }, { exact trans IH₁ IH₂ } end theorem perm_bind_right (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) : l.bind f ~ l.bind g := by induction l with a l IH; simp; exact perm_app (h a) IH theorem perm_product_left {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) : product l₁ t₁ ~ product l₂ t₁ := perm_bind_left _ p theorem perm_product_right (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) : product l t₁ ~ product l t₂ := perm_bind_right _ $ λ a, perm_map _ p @[congr] theorem perm_product {l₁ l₂ : list α} {t₁ t₂ : list β} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ := trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂) theorem sublists_cons_perm_append (a : α) (l : list α) : sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) := begin simp [sublists, sublists_aux_cons_cons], refine skip _ ((skip _ _).trans perm_middle.symm), induction sublists_aux l cons with b l IH; simp, exact skip b ((skip _ IH).trans perm_middle.symm) end theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l | [] := perm.refl _ | (a::l) := let IH := sublists_perm_sublists' l in by rw sublists'_cons; exact (sublists_cons_perm_append _ _).trans (perm_app IH (perm_map _ IH)) theorem revzip_sublists (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l := begin rw revzip, apply list.reverse_rec_on l, { intros l₁ l₂ h, simp at h, simp [h] }, { intros l a IH l₁ l₂ h, rw [sublists_concat, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [simp at h, simp], rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { rw ← append_assoc, exact perm_app_left _ (IH _ _ h) }, { rw append_assoc, apply (perm_app_right _ perm_app_comm).trans, rw ← append_assoc, exact perm_app_left _ (IH _ _ h) } } end theorem revzip_sublists' (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l := begin rw revzip, induction l with a l IH; intros l₁ l₂ h, { simp at h, simp [h] }, { rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [simp at h, simp], rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { exact perm_middle.trans (skip _ (IH _ _ h)) }, { exact skip _ (IH _ _ h) } } end theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α} (H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁) (p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ := begin let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { cases h : f a, { simp [h], exact (IH (pairwise_cons.1 H).2).skip _ }, { simp [lookmap_cons_some _ _ h], exact p.skip _ } }, { cases h₁ : f a with c; cases h₂ : f b with d, { simp [h₁, h₂], apply swap }, { simp [h₁, lookmap_cons_some _ _ h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂], rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩, refl } }, { refine (IH₁ H).trans (IH₂ ((perm_pairwise _ p₁).1 H)), exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm } end theorem perm_erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α} (H : pairwise (λ a b, f a → f b → false) l₁) (p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ := begin let F := λ a b, f a → f b → false, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { by_cases h : f a, { simp [h, p] }, { simp [h], exact (IH (pairwise_cons.1 H).2).skip _ } }, { by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂], { cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ }, { apply swap } }, { refine (IH₁ H).trans (IH₂ ((perm_pairwise _ p₁).1 H)), exact λ a b h h₁ h₂, h h₂ h₁ } end /- enumerating permutations -/ section permutations theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β), (permutations_aux2 t ts r ys f).1 = ys ++ ts | [] f := rfl | (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with | ⟨_, zs⟩, rfl := rfl end @[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) : (permutations_aux2 t ts r [] f).2 = r := rfl @[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α) (f : list α → β) : (permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) :: (permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 := match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with | ⟨_, zs⟩, rfl := rfl end theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) : (permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 := by induction ys generalizing f; simp * theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} : l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts := begin induction ys with y ys ih generalizing l, { simp {contextual := tt} }, { rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]), by funext; simp, mem_cons_iff, ih], split; intro h, { rcases h with e | ⟨l₁, l₂, l0, ye, _⟩, { subst l', exact ⟨[], y::ys, by simp⟩ }, { substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } }, { rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩, { simp [ye] }, { simp at ye, rcases ye with ⟨rfl, rfl⟩, exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } } end theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} : l ∈ (permutations_aux2 t ts [] ys id).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts := by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2 theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) : length (permutations_aux2 t ts [] ys f).2 = length ys := by induction ys generalizing f; simp * theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : foldr (λy r, (permutations_aux2 t ts r y id).2) r L = L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r := by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}] theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} : l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts := have (∃ (a : list α), a ∈ L ∧ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts), from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩, λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩, by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this, or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc] theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r := by simp [foldr_permutations_aux2, (∘), length_permutations_aux2] theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α)) (n) (H : ∀ l ∈ L, length l = n) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r := begin rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)], induction L with l L ih, {simp}, have sum_map : sum (map length L) = n * length L := ih (λ l m, H l (mem_cons_of_mem _ m)), have length_l : length l = n := H _ (mem_cons_self _ _), simp [sum_map, length_l, mul_add, add_comm] end theorem perm_of_mem_permutations_aux : ∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2 m, rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m, rcases m with m | ⟨l₁, l₂, m, _, e⟩, { exact (IH1 m).trans perm_middle }, { subst e, have p : l₁ ++ l₂ ~ is, { simp [permutations] at m, cases m with e m, {simp [e]}, exact is.append_nil ▸ IH2 m }, exact (perm_app_left _ (perm_middle.trans (skip _ p))).trans (skip _ perm_app_comm) } end theorem perm_of_mem_permutations {l₁ l₂ : list α} (h : l₁ ∈ permutations l₂) : l₁ ~ l₂ := (eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _) (λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m) theorem length_permutations_aux : ∀ ts is : list α, length (permutations_aux ts is) + is.length.fact = (length ts + length is).fact := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2, have IH2 : length (permutations_aux is nil) + 1 = is.length.fact, { simpa using IH2 }, simp [-add_comm, nat.fact, nat.add_succ, mul_comm] at IH1, rw [permutations_aux_cons, length_foldr_permutations_aux2' _ _ _ _ _ (λ l m, perm_length (perm_of_mem_permutations m)), permutations, length, length, IH2, nat.succ_add, nat.fact_succ, mul_comm (nat.succ _), ← IH1, add_comm (_*_), add_assoc, nat.mul_succ, mul_comm] end theorem length_permutations (l : list α) : length (permutations l) = (length l).fact := length_permutations_aux l [] theorem mem_permutations_of_perm_lemma {is l : list α} (H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is []) : l ~ is → l ∈ permutations is := by simpa [permutations, perm_nil] using H theorem mem_permutations_aux_of_perm : ∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2 l p, rw [permutations_aux_cons, mem_foldr_permutations_aux2], rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m, { clear p, subst e, rcases mem_split (perm_subset p'.symm (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩, subst is', have p := perm_cons_inv (perm_middle.symm.trans p'), cases l₂ with a l₂', { exact or.inl ⟨l₁, by simpa using p⟩ }, { exact or.inr (or.inr ⟨l₁, a::l₂', mem_permutations_of_perm_lemma IH2 p, by simp⟩) } }, { exact or.inr (or.inl m) } end @[simp] theorem mem_permutations (s t : list α) : s ∈ permutations t ↔ s ~ t := ⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩ end permutations end list
d5619feb1d25888f7479d0cadc95554120636f73
7453f4f6074a6d5ce92b7bee2b29c409c061fbef
/src/NewtonMethod/uwyo_aux.lean
276462ceabc2a97044f2952e482079cd9fef5434
[ "Apache-2.0" ]
permissive
stanescuUW/numerical-analysis-with-Lean
b7b26755b8e925279f3afc1caa16b0666fc77ef8
98e6974f8b68cc5232ceff40535d776a33444c73
refs/heads/master
1,670,371,433,242
1,598,204,960,000
1,598,204,960,000
282,081,575
0
0
null
null
null
null
UTF-8
Lean
false
false
3,004
lean
import data.real.basic import .uwyo_sqrt2 import analysis.specific_limits open_locale topological_space open filter lemma aux_0 (X : ℚ) (hX: 0 < X): ( X * X + 2) / (2 * X) - X = (2 - X * X) / (2 * X) := begin set Y := X * X with hY, have h1 : 2 - Y = 2 + Y - 2 * Y, linarith, rw add_comm 2 Y at h1, rw h1, set V := 2 * X with hV, have h31 : V ≠ 0, linarith, have h2 := sub_div (Y+2) (2*Y) V, rw h2, have h32 : (2 * Y) / V = X, apply (div_eq_iff h31).mpr, rw [hY, hV], ring, rw h32, done end lemma aux_1 (X Y V : ℚ) (G : X ≠ 0) (hY : Y = X * X) (hV : V = 2 * X) (G1 : Y ≠ 0) : 4 * (Y + 2) / V * ((Y + 2) / (V)) = Y + 2 * 2 + (2*2/(X * X)) := begin -- this is a struggle rw hV, rw hY, norm_num, field_simp, have h211 : 2 * X * ( 2 * X ) = 4 * X * X, ring, rw h211, rw mul_assoc 4 X X, rw ← hY, field_simp, rw mul_assoc, have h212 : (Y+2) * (Y + 2) = Y * Y + 4 * Y +4, ring, rw h212, set T := 4 * (Y * Y + 4 * Y + 4) with hT, rw ← hT, have h214 : (4: ℚ) ≠ 0, linarith, have h213 : 4 * Y ≠ 0, exact mul_ne_zero h214 G1, apply (div_eq_iff h213).mpr, have h214 : (Y + 4 + (4/Y)) * (4 * Y) = (Y+4) * (4*Y) + (4/Y) * (4 * Y), ring, rw h214, have h215 : (4/Y) * (4 * Y) = 16, ring, rw mul_assoc, have h216 : Y * Y⁻¹ = 1, exact mul_inv_cancel G1, rw h216, linarith, rw h215, rw hT, ring, done end lemma aux_2 (X : ℚ) (G : X ≠ 0) : ( 2 / X - X ) * ( 2 / X - X ) = 4 / (X*X) - 4 + X * X := begin set V := (2/X) with hV, have h1 : V * V = 4 / (X * X), rw hV, ring, field_simp, have h11 : X ^ 2 = X * X, ring, rw h11, rw ← h1, have h2 : (V - X) * (V - X) = V * V - 2 * V * X + X * X, ring, rw h2, have h3 : V * X = 2, field_simp, ring, rw mul_assoc, rw mul_comm X⁻¹ _, rw mul_inv_cancel G, linarith, rw mul_assoc 2 V X, rw h3, linarith, done end -- This proof (considerably shorter than mine) is due to Reid Barton lemma aux_3 (s : ℕ → ℝ) (hs : ∀ n : ℕ, real.sqrt 2 < s n) : ¬ (tendsto s at_top (𝓝 0)) := begin rw metric.tendsto_at_top, push_neg, refine ⟨real.sqrt 2, by norm_num, λ N, ⟨N, le_refl _, _⟩⟩, change real.sqrt 2 ≤ abs (s N - 0), refine le_trans _ (le_abs_self _), specialize hs N, linarith, done end lemma no_rat_sq_eq_two (X : ℚ) (hX1 : X ≠ 0) : 0 ≠ ( 2 / X - X ) := begin by_contradiction H, push_neg at H, have h1 := congr_arg (λ (b : ℚ), X * b) H, simp only [] at h1, rw mul_zero at h1, have h2 : X * (2 / X - X) = 2 - X ^ 2, ring, have h21 : ( - X + 2 * X⁻¹) * X = - X * X + 2 * X⁻¹ * X, ring, rw h21, rw mul_assoc 2 (X⁻¹) X, rw mul_comm (X⁻¹) _, rw mul_inv_cancel hX1, ring, rw ← h1 at h2, have h2 : X ^ 2 = 2, linarith, have h3 : ∃ r : ℚ, r ^ 2 = 2, use X, exact h2, exact rational_not_sqrt_two h3, -- from uwyo_sqrt2 done end
286bfa10e25225c1858bdfabcf6bfe0b8084b097
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/hahn_series.lean
a622d351842cf686a7267b9e2cca515837907a09
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
61,427
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.well_founded_set import algebra.big_operators.finprod import ring_theory.valuation.basic import algebra.module.pi import ring_theory.power_series.basic import data.finsupp.pwo /-! # Hahn Series If `Γ` is ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered. With further structure on `R` and `Γ`, we can add further structure on `hahn_series Γ R`, with the most studied case being when `Γ` is a linearly ordered abelian group and `R` is a field, in which case `hahn_series Γ R` is a valued field, with value group `Γ`. These generalize Laurent series (with value group `ℤ`), and Laurent series are implemented that way in the file `ring_theory/laurent_series`. ## Main Definitions * If `Γ` is ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered. * If `R` is a (commutative) additive monoid or group, then so is `hahn_series Γ R`. * If `R` is a (comm_)(semi)ring, then so is `hahn_series Γ R`. * `hahn_series.add_val Γ R` defines an `add_valuation` on `hahn_series Γ R` when `Γ` is linearly ordered. * A `hahn_series.summable_family` is a family of Hahn series such that the union of their supports is well-founded and only finitely many are nonzero at any given coefficient. They have a formal sum, `hahn_series.summable_family.hsum`, which can be bundled as a `linear_map` as `hahn_series.summable_family.lsum`. Note that this is different from `summable` in the valuation topology, because there are topologically summable families that do not satisfy the axioms of `hahn_series.summable_family`, and formally summable families whose sums do not converge topologically. * Laurent series over `R` are implemented as `hahn_series ℤ R` in the file `ring_theory/laurent_series`. ## TODO * Build an API for the variable `X` (defined to be `single 1 1 : hahn_series Γ R`) in analogy to `X : R[X]` and `X : power_series R` ## References - [J. van der Hoeven, *Operators on Generalized Power Series*][van_der_hoeven] -/ open finset function open_locale big_operators classical pointwise polynomial noncomputable theory /-- If `Γ` is linearly ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are well-founded. -/ @[ext] structure hahn_series (Γ : Type*) (R : Type*) [partial_order Γ] [has_zero R] := (coeff : Γ → R) (is_pwo_support' : (support coeff).is_pwo) variables {Γ : Type*} {R : Type*} namespace hahn_series section zero variables [partial_order Γ] [has_zero R] lemma coeff_injective : injective (coeff : hahn_series Γ R → (Γ → R)) := ext @[simp] lemma coeff_inj {x y : hahn_series Γ R} : x.coeff = y.coeff ↔ x = y := coeff_injective.eq_iff /-- The support of a Hahn series is just the set of indices whose coefficients are nonzero. Notably, it is well-founded. -/ def support (x : hahn_series Γ R) : set Γ := support x.coeff @[simp] lemma is_pwo_support (x : hahn_series Γ R) : x.support.is_pwo := x.is_pwo_support' @[simp] lemma is_wf_support (x : hahn_series Γ R) : x.support.is_wf := x.is_pwo_support.is_wf @[simp] lemma mem_support (x : hahn_series Γ R) (a : Γ) : a ∈ x.support ↔ x.coeff a ≠ 0 := iff.refl _ instance : has_zero (hahn_series Γ R) := ⟨{ coeff := 0, is_pwo_support' := by simp }⟩ instance : inhabited (hahn_series Γ R) := ⟨0⟩ instance [subsingleton R] : subsingleton (hahn_series Γ R) := ⟨λ a b, a.ext b (subsingleton.elim _ _)⟩ @[simp] lemma zero_coeff {a : Γ} : (0 : hahn_series Γ R).coeff a = 0 := rfl @[simp] lemma coeff_fun_eq_zero_iff {x : hahn_series Γ R} : x.coeff = 0 ↔ x = 0 := coeff_injective.eq_iff' rfl lemma ne_zero_of_coeff_ne_zero {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : x ≠ 0 := mt (λ x0, (x0.symm ▸ zero_coeff : x.coeff g = 0)) h @[simp] lemma support_zero : support (0 : hahn_series Γ R) = ∅ := function.support_zero @[simp] lemma support_nonempty_iff {x : hahn_series Γ R} : x.support.nonempty ↔ x ≠ 0 := by rw [support, support_nonempty_iff, ne.def, coeff_fun_eq_zero_iff] @[simp] lemma support_eq_empty_iff {x : hahn_series Γ R} : x.support = ∅ ↔ x = 0 := support_eq_empty_iff.trans coeff_fun_eq_zero_iff /-- `single a r` is the Hahn series which has coefficient `r` at `a` and zero otherwise. -/ def single (a : Γ) : zero_hom R (hahn_series Γ R) := { to_fun := λ r, { coeff := pi.single a r, is_pwo_support' := (set.is_pwo_singleton a).mono pi.support_single_subset }, map_zero' := ext _ _ (pi.single_zero _) } variables {a b : Γ} {r : R} @[simp] theorem single_coeff_same (a : Γ) (r : R) : (single a r).coeff a = r := pi.single_eq_same a r @[simp] theorem single_coeff_of_ne (h : b ≠ a) : (single a r).coeff b = 0 := pi.single_eq_of_ne h r theorem single_coeff : (single a r).coeff b = if (b = a) then r else 0 := by { split_ifs with h; simp [h] } @[simp] lemma support_single_of_ne (h : r ≠ 0) : support (single a r) = {a} := pi.support_single_of_ne h lemma support_single_subset : support (single a r) ⊆ {a} := pi.support_single_subset lemma eq_of_mem_support_single {b : Γ} (h : b ∈ support (single a r)) : b = a := support_single_subset h @[simp] lemma single_eq_zero : (single a (0 : R)) = 0 := (single a).map_zero lemma single_injective (a : Γ) : function.injective (single a : R → hahn_series Γ R) := λ r s rs, by rw [← single_coeff_same a r, ← single_coeff_same a s, rs] lemma single_ne_zero (h : r ≠ 0) : single a r ≠ 0 := λ con, h (single_injective a (con.trans single_eq_zero.symm)) @[simp] lemma single_eq_zero_iff {a : Γ} {r : R} : single a r = 0 ↔ r = 0 := begin split, { contrapose!, exact single_ne_zero }, { simp {contextual := tt} } end instance [nonempty Γ] [nontrivial R] : nontrivial (hahn_series Γ R) := ⟨begin obtain ⟨r, s, rs⟩ := exists_pair_ne R, inhabit Γ, refine ⟨single (arbitrary Γ) r, single (arbitrary Γ) s, λ con, rs _⟩, rw [← single_coeff_same (arbitrary Γ) r, con, single_coeff_same], end⟩ section order variable [has_zero Γ] /-- The order of a nonzero Hahn series `x` is a minimal element of `Γ` where `x` has a nonzero coefficient, the order of 0 is 0. -/ def order (x : hahn_series Γ R) : Γ := if h : x = 0 then 0 else x.is_wf_support.min (support_nonempty_iff.2 h) @[simp] lemma order_zero : order (0 : hahn_series Γ R) = 0 := dif_pos rfl lemma order_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) : order x = x.is_wf_support.min (support_nonempty_iff.2 hx) := dif_neg hx lemma coeff_order_ne_zero {x : hahn_series Γ R} (hx : x ≠ 0) : x.coeff x.order ≠ 0 := begin rw order_of_ne hx, exact x.is_wf_support.min_mem (support_nonempty_iff.2 hx) end lemma order_le_of_coeff_ne_zero {Γ} [linear_ordered_cancel_add_comm_monoid Γ] {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : x.order ≤ g := le_trans (le_of_eq (order_of_ne (ne_zero_of_coeff_ne_zero h))) (set.is_wf.min_le _ _ ((mem_support _ _).2 h)) @[simp] lemma order_single (h : r ≠ 0) : (single a r).order = a := (order_of_ne (single_ne_zero h)).trans (support_single_subset ((single a r).is_wf_support.min_mem (support_nonempty_iff.2 (single_ne_zero h)))) lemma coeff_eq_zero_of_lt_order {x : hahn_series Γ R} {i : Γ} (hi : i < x.order) : x.coeff i = 0 := begin rcases eq_or_ne x 0 with rfl|hx, { simp }, contrapose! hi, rw [←ne.def, ←mem_support] at hi, rw [order_of_ne hx], exact set.is_wf.not_lt_min _ _ hi end end order section domain variables {Γ' : Type*} [partial_order Γ'] /-- Extends the domain of a `hahn_series` by an `order_embedding`. -/ def emb_domain (f : Γ ↪o Γ') : hahn_series Γ R → hahn_series Γ' R := λ x, { coeff := λ (b : Γ'), if h : b ∈ f '' x.support then x.coeff (classical.some h) else 0, is_pwo_support' := (x.is_pwo_support.image_of_monotone f.monotone).mono (λ b hb, begin contrapose! hb, rw [function.mem_support, dif_neg hb, not_not], end) } @[simp] lemma emb_domain_coeff {f : Γ ↪o Γ'} {x : hahn_series Γ R} {a : Γ} : (emb_domain f x).coeff (f a) = x.coeff a := begin rw emb_domain, dsimp only, by_cases ha : a ∈ x.support, { rw dif_pos (set.mem_image_of_mem f ha), exact congr rfl (f.injective (classical.some_spec (set.mem_image_of_mem f ha)).2) }, { rw [dif_neg, not_not.1 (λ c, ha ((mem_support _ _).2 c))], contrapose! ha, obtain ⟨b, hb1, hb2⟩ := (set.mem_image _ _ _).1 ha, rwa f.injective hb2 at hb1 } end @[simp] lemma emb_domain_mk_coeff {f : Γ → Γ'} (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') {x : hahn_series Γ R} {a : Γ} : (emb_domain ⟨⟨f, hfi⟩, hf⟩ x).coeff (f a) = x.coeff a := emb_domain_coeff lemma emb_domain_notin_image_support {f : Γ ↪o Γ'} {x : hahn_series Γ R} {b : Γ'} (hb : b ∉ f '' x.support) : (emb_domain f x).coeff b = 0 := dif_neg hb lemma support_emb_domain_subset {f : Γ ↪o Γ'} {x : hahn_series Γ R} : support (emb_domain f x) ⊆ f '' x.support := begin intros g hg, contrapose! hg, rw [mem_support, emb_domain_notin_image_support hg, not_not], end lemma emb_domain_notin_range {f : Γ ↪o Γ'} {x : hahn_series Γ R} {b : Γ'} (hb : b ∉ set.range f) : (emb_domain f x).coeff b = 0 := emb_domain_notin_image_support (λ con, hb (set.image_subset_range _ _ con)) @[simp] lemma emb_domain_zero {f : Γ ↪o Γ'} : emb_domain f (0 : hahn_series Γ R) = 0 := by { ext, simp [emb_domain_notin_image_support] } @[simp] lemma emb_domain_single {f : Γ ↪o Γ'} {g : Γ} {r : R} : emb_domain f (single g r) = single (f g) r := begin ext g', by_cases h : g' = f g, { simp [h] }, rw [emb_domain_notin_image_support, single_coeff_of_ne h], by_cases hr : r = 0, { simp [hr] }, rwa [support_single_of_ne hr, set.image_singleton, set.mem_singleton_iff], end lemma emb_domain_injective {f : Γ ↪o Γ'} : function.injective (emb_domain f : hahn_series Γ R → hahn_series Γ' R) := λ x y xy, begin ext g, rw [ext_iff, function.funext_iff] at xy, have xyg := xy (f g), rwa [emb_domain_coeff, emb_domain_coeff] at xyg, end end domain end zero section addition variable [partial_order Γ] section add_monoid variable [add_monoid R] instance : has_add (hahn_series Γ R) := { add := λ x y, { coeff := x.coeff + y.coeff, is_pwo_support' := (x.is_pwo_support.union y.is_pwo_support).mono (function.support_add _ _) } } instance : add_monoid (hahn_series Γ R) := { zero := 0, add := (+), add_assoc := λ x y z, by { ext, apply add_assoc }, zero_add := λ x, by { ext, apply zero_add }, add_zero := λ x, by { ext, apply add_zero } } @[simp] lemma add_coeff' {x y : hahn_series Γ R} : (x + y).coeff = x.coeff + y.coeff := rfl lemma add_coeff {x y : hahn_series Γ R} {a : Γ} : (x + y).coeff a = x.coeff a + y.coeff a := rfl lemma support_add_subset {x y : hahn_series Γ R} : support (x + y) ⊆ support x ∪ support y := λ a ha, begin rw [mem_support, add_coeff] at ha, rw [set.mem_union, mem_support, mem_support], contrapose! ha, rw [ha.1, ha.2, add_zero], end lemma min_order_le_order_add {Γ} [linear_ordered_cancel_add_comm_monoid Γ] {x y : hahn_series Γ R} (hxy : x + y ≠ 0) : min x.order y.order ≤ (x + y).order := begin by_cases hx : x = 0, { simp [hx], }, by_cases hy : y = 0, { simp [hy], }, rw [order_of_ne hx, order_of_ne hy, order_of_ne hxy], refine le_trans _ (set.is_wf.min_le_min_of_subset support_add_subset), { exact x.is_wf_support.union y.is_wf_support }, { exact set.nonempty.mono (set.subset_union_left _ _) (support_nonempty_iff.2 hx) }, rw set.is_wf.min_union, end /-- `single` as an additive monoid/group homomorphism -/ @[simps] def single.add_monoid_hom (a : Γ) : R →+ (hahn_series Γ R) := { map_add' := λ x y, by { ext b, by_cases h : b = a; simp [h] }, ..single a } /-- `coeff g` as an additive monoid/group homomorphism -/ @[simps] def coeff.add_monoid_hom (g : Γ) : (hahn_series Γ R) →+ R := { to_fun := λ f, f.coeff g, map_zero' := zero_coeff, map_add' := λ x y, add_coeff } section domain variables {Γ' : Type*} [partial_order Γ'] lemma emb_domain_add (f : Γ ↪o Γ') (x y : hahn_series Γ R) : emb_domain f (x + y) = emb_domain f x + emb_domain f y := begin ext g, by_cases hg : g ∈ set.range f, { obtain ⟨a, rfl⟩ := hg, simp }, { simp [emb_domain_notin_range, hg] } end end domain end add_monoid instance [add_comm_monoid R] : add_comm_monoid (hahn_series Γ R) := { add_comm := λ x y, by { ext, apply add_comm } .. hahn_series.add_monoid } section add_group variable [add_group R] instance : add_group (hahn_series Γ R) := { neg := λ x, { coeff := λ a, - x.coeff a, is_pwo_support' := by { rw function.support_neg, exact x.is_pwo_support }, }, add_left_neg := λ x, by { ext, apply add_left_neg }, .. hahn_series.add_monoid } @[simp] lemma neg_coeff' {x : hahn_series Γ R} : (- x).coeff = - x.coeff := rfl lemma neg_coeff {x : hahn_series Γ R} {a : Γ} : (- x).coeff a = - x.coeff a := rfl @[simp] lemma support_neg {x : hahn_series Γ R} : (- x).support = x.support := by { ext, simp } @[simp] lemma sub_coeff' {x y : hahn_series Γ R} : (x - y).coeff = x.coeff - y.coeff := by { ext, simp [sub_eq_add_neg] } lemma sub_coeff {x y : hahn_series Γ R} {a : Γ} : (x - y).coeff a = x.coeff a - y.coeff a := by simp end add_group instance [add_comm_group R] : add_comm_group (hahn_series Γ R) := { .. hahn_series.add_comm_monoid, .. hahn_series.add_group } end addition section distrib_mul_action variables [partial_order Γ] {V : Type*} [monoid R] [add_monoid V] [distrib_mul_action R V] instance : has_smul R (hahn_series Γ V) := ⟨λ r x, { coeff := r • x.coeff, is_pwo_support' := x.is_pwo_support.mono (function.support_smul_subset_right r x.coeff) }⟩ @[simp] lemma smul_coeff {r : R} {x : hahn_series Γ V} {a : Γ} : (r • x).coeff a = r • (x.coeff a) := rfl instance : distrib_mul_action R (hahn_series Γ V) := { smul := (•), one_smul := λ _, by { ext, simp }, smul_zero := λ _, by { ext, simp }, smul_add := λ _ _ _, by { ext, simp [smul_add] }, mul_smul := λ _ _ _, by { ext, simp [mul_smul] } } variables {S : Type*} [monoid S] [distrib_mul_action S V] instance [has_smul R S] [is_scalar_tower R S V] : is_scalar_tower R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp }⟩ instance [smul_comm_class R S V] : smul_comm_class R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp [smul_comm] }⟩ end distrib_mul_action section module variables [partial_order Γ] [semiring R] {V : Type*} [add_comm_monoid V] [module R V] instance : module R (hahn_series Γ V) := { zero_smul := λ _, by { ext, simp }, add_smul := λ _ _ _, by { ext, simp [add_smul] }, .. hahn_series.distrib_mul_action } /-- `single` as a linear map -/ @[simps] def single.linear_map (a : Γ) : R →ₗ[R] (hahn_series Γ R) := { map_smul' := λ r s, by { ext b, by_cases h : b = a; simp [h] }, ..single.add_monoid_hom a } /-- `coeff g` as a linear map -/ @[simps] def coeff.linear_map (g : Γ) : (hahn_series Γ R) →ₗ[R] R := { map_smul' := λ r s, rfl, ..coeff.add_monoid_hom g } section domain variables {Γ' : Type*} [partial_order Γ'] lemma emb_domain_smul (f : Γ ↪o Γ') (r : R) (x : hahn_series Γ R) : emb_domain f (r • x) = r • emb_domain f x := begin ext g, by_cases hg : g ∈ set.range f, { obtain ⟨a, rfl⟩ := hg, simp }, { simp [emb_domain_notin_range, hg] } end /-- Extending the domain of Hahn series is a linear map. -/ @[simps] def emb_domain_linear_map (f : Γ ↪o Γ') : hahn_series Γ R →ₗ[R] hahn_series Γ' R := { to_fun := emb_domain f, map_add' := emb_domain_add f, map_smul' := emb_domain_smul f } end domain end module section multiplication variable [ordered_cancel_add_comm_monoid Γ] instance [has_zero R] [has_one R] : has_one (hahn_series Γ R) := ⟨single 0 1⟩ @[simp] lemma one_coeff [has_zero R] [has_one R] {a : Γ} : (1 : hahn_series Γ R).coeff a = if a = 0 then 1 else 0 := single_coeff @[simp] lemma single_zero_one [has_zero R] [has_one R] : (single 0 (1 : R)) = 1 := rfl @[simp] lemma support_one [mul_zero_one_class R] [nontrivial R] : support (1 : hahn_series Γ R) = {0} := support_single_of_ne one_ne_zero @[simp] lemma order_one [mul_zero_one_class R] : order (1 : hahn_series Γ R) = 0 := begin cases subsingleton_or_nontrivial R with h h; haveI := h, { rw [subsingleton.elim (1 : hahn_series Γ R) 0, order_zero] }, { exact order_single one_ne_zero } end instance [non_unital_non_assoc_semiring R] : has_mul (hahn_series Γ R) := { mul := λ x y, { coeff := λ a, ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd, is_pwo_support' := begin have h : {a : Γ | ∑ (ij : Γ × Γ) in add_antidiagonal x.is_pwo_support y.is_pwo_support a, x.coeff ij.fst * y.coeff ij.snd ≠ 0} ⊆ {a : Γ | (add_antidiagonal x.is_pwo_support y.is_pwo_support a).nonempty}, { intros a ha, contrapose! ha, simp [not_nonempty_iff_eq_empty.1 ha] }, exact is_pwo_support_add_antidiagonal.mono h, end, }, } @[simp] lemma mul_coeff [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} : (x * y).coeff a = ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd := rfl lemma mul_coeff_right' [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_pwo) (hys : y.support ⊆ s) : (x * y).coeff a = ∑ ij in (add_antidiagonal x.is_pwo_support hs a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_right hys) _ (λ _ _, rfl), intros b hb, simp only [not_and, mem_sdiff, mem_add_antidiagonal, mem_support, not_imp_not] at hb, rw [hb.2 hb.1.1 hb.1.2.2, mul_zero], end lemma mul_coeff_left' [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_pwo) (hxs : x.support ⊆ s) : (x * y).coeff a = ∑ ij in (add_antidiagonal hs y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_left hxs) _ (λ _ _, rfl), intros b hb, simp only [not_and', mem_sdiff, mem_add_antidiagonal, mem_support, not_ne_iff] at hb, rw [hb.2 ⟨hb.1.2.1, hb.1.2.2⟩, zero_mul], end instance [non_unital_non_assoc_semiring R] : distrib (hahn_series Γ R) := { left_distrib := λ x y z, begin ext a, have hwf := (y.is_pwo_support.union z.is_pwo_support), rw [mul_coeff_right' hwf, add_coeff, mul_coeff_right' hwf (set.subset_union_right _ _), mul_coeff_right' hwf (set.subset_union_left _ _)], { simp only [add_coeff, mul_add, sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], } end, right_distrib := λ x y z, begin ext a, have hwf := (x.is_pwo_support.union y.is_pwo_support), rw [mul_coeff_left' hwf, add_coeff, mul_coeff_left' hwf (set.subset_union_right _ _), mul_coeff_left' hwf (set.subset_union_left _ _)], { simp only [add_coeff, add_mul, sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], }, end, .. hahn_series.has_mul, .. hahn_series.has_add } lemma single_mul_coeff_add [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : ((single b r) * x).coeff (a + b) = r * x.coeff a := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, mul_zero], rw [sum_congr _ (λ _ _, rfl), sum_empty], ext ⟨a1, a2⟩, simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not, mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro rfl h2 h1, rw add_comm at h1, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(b, a)}, (single b r).coeff ij.fst * x.coeff ij.snd, { apply sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal, mem_singleton, set.mem_set_of_eq], split, { rintro ⟨rfl, h2, h1⟩, rw add_comm at h1, refine ⟨rfl, add_right_cancel h1⟩ }, { rintro ⟨rfl, rfl⟩, exact ⟨rfl, by simp [hx], add_comm _ _⟩ } }, { simp } end lemma mul_single_coeff_add [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : (x * (single b r)).coeff (a + b) = x.coeff a * r := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, zero_mul], rw [sum_congr _ (λ _ _, rfl), sum_empty], ext ⟨a1, a2⟩, simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not, mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro h2 rfl h1, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(a,b)}, x.coeff ij.fst * (single b r).coeff ij.snd, { apply sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal, mem_singleton, set.mem_set_of_eq], split, { rintro ⟨h2, rfl, h1⟩, refine ⟨add_right_cancel h1, rfl⟩ }, { rintro ⟨rfl, rfl⟩, simp [hx] } }, { simp } end @[simp] lemma mul_single_zero_coeff [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : (x * (single 0 r)).coeff a = x.coeff a * r := by rw [← add_zero a, mul_single_coeff_add, add_zero] lemma single_zero_mul_coeff [non_unital_non_assoc_semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : ((single 0 r) * x).coeff a = r * x.coeff a := by rw [← add_zero a, single_mul_coeff_add, add_zero] @[simp] lemma single_zero_mul_eq_smul [semiring R] {r : R} {x : hahn_series Γ R} : (single 0 r) * x = r • x := by { ext, exact single_zero_mul_coeff } theorem support_mul_subset_add_support [non_unital_non_assoc_semiring R] {x y : hahn_series Γ R} : support (x * y) ⊆ support x + support y := begin apply set.subset.trans (λ x hx, _) support_add_antidiagonal_subset_add, { exact x.is_pwo_support }, { exact y.is_pwo_support }, contrapose! hx, simp only [not_nonempty_iff_eq_empty, ne.def, set.mem_set_of_eq] at hx, simp [hx], end lemma mul_coeff_order_add_order {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [non_unital_non_assoc_semiring R] (x y : hahn_series Γ R) : (x * y).coeff (x.order + y.order) = x.coeff x.order * y.coeff y.order := begin by_cases hx : x = 0, { simp [hx], }, by_cases hy : y = 0, { simp [hy], }, rw [order_of_ne hx, order_of_ne hy, mul_coeff, finset.add_antidiagonal_min_add_min, finset.sum_singleton], end private lemma mul_assoc' [non_unital_semiring R] (x y z : hahn_series Γ R) : x * y * z = x * (y * z) := begin ext b, rw [mul_coeff_left' (x.is_pwo_support.add y.is_pwo_support) support_mul_subset_add_support, mul_coeff_right' (y.is_pwo_support.add z.is_pwo_support) support_mul_subset_add_support], simp only [mul_coeff, add_coeff, sum_mul, mul_sum, sum_sigma'], refine sum_bij_ne_zero (λ a has ha0, ⟨⟨a.2.1, a.2.2 + a.1.2⟩, ⟨a.2.2, a.1.2⟩⟩) _ _ _ _, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [and_true, set.image2_add, eq_self_iff_true, mem_add_antidiagonal, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq] at H1 H2 ⊢, obtain ⟨⟨H3, nz, rfl⟩, nx, ny, rfl⟩ := H1, exact ⟨⟨nx, set.add_mem_add ny nz, (add_assoc _ _ _).symm⟩, ny, nz⟩ }, { rintros ⟨⟨i1,j1⟩, k1,l1⟩ ⟨⟨i2,j2⟩, k2,l2⟩ H1 H2 H3 H4 H5, simp only [set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq] at H1 H3 H5, obtain ⟨⟨rfl, H⟩, rfl, rfl⟩ := H5, simp only [and_true, prod.mk.inj_iff, eq_self_iff_true, heq_iff_eq, ←H1.2.2.2, ←H3.2.2.2] }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [exists_prop, set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, sigma.exists, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq, prod.exists] at H1 H2 ⊢, obtain ⟨⟨nx, H, rfl⟩, ny, nz, rfl⟩ := H1, exact ⟨i + k, l, i, k, ⟨⟨set.add_mem_add nx ny, nz, add_assoc _ _ _⟩, nx, ny, rfl⟩, λ con, H2 ((mul_assoc _ _ _).symm.trans con), ⟨rfl, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp [mul_assoc], } end instance [non_unital_non_assoc_semiring R] : non_unital_non_assoc_semiring (hahn_series Γ R) := { zero := 0, add := (+), mul := (*), zero_mul := λ _, by { ext, simp }, mul_zero := λ _, by { ext, simp }, .. hahn_series.add_comm_monoid, .. hahn_series.distrib } instance [non_unital_semiring R] : non_unital_semiring (hahn_series Γ R) := { zero := 0, add := (+), mul := (*), mul_assoc := mul_assoc', .. hahn_series.non_unital_non_assoc_semiring } instance [non_assoc_semiring R] : non_assoc_semiring (hahn_series Γ R) := { zero := 0, one := 1, add := (+), mul := (*), one_mul := λ x, by { ext, exact single_zero_mul_coeff.trans (one_mul _) }, mul_one := λ x, by { ext, exact mul_single_zero_coeff.trans (mul_one _) }, .. add_monoid_with_one.unary, .. hahn_series.non_unital_non_assoc_semiring } instance [semiring R] : semiring (hahn_series Γ R) := { zero := 0, one := 1, add := (+), mul := (*), .. hahn_series.non_assoc_semiring, .. hahn_series.non_unital_semiring } instance [non_unital_comm_semiring R] : non_unital_comm_semiring (hahn_series Γ R) := { mul_comm := λ x y, begin ext, simp_rw [mul_coeff, mul_comm], refine sum_bij (λ a ha, a.swap) (λ a ha, _) (λ a ha, rfl) (λ _ _ _ _, prod.swap_inj.1) (λ a ha, ⟨a.swap, _, a.swap_swap.symm⟩); rwa swap_mem_add_antidiagonal, end, .. hahn_series.non_unital_semiring } instance [comm_semiring R] : comm_semiring (hahn_series Γ R) := { .. hahn_series.non_unital_comm_semiring, .. hahn_series.semiring } instance [non_unital_non_assoc_ring R] : non_unital_non_assoc_ring (hahn_series Γ R) := { .. hahn_series.non_unital_non_assoc_semiring, .. hahn_series.add_group } instance [non_unital_ring R] : non_unital_ring (hahn_series Γ R) := { .. hahn_series.non_unital_non_assoc_ring, .. hahn_series.non_unital_semiring } instance [non_assoc_ring R] : non_assoc_ring (hahn_series Γ R) := { .. hahn_series.non_unital_non_assoc_ring, .. hahn_series.non_assoc_semiring } instance [ring R] : ring (hahn_series Γ R) := { .. hahn_series.semiring, .. hahn_series.add_comm_group } instance [non_unital_comm_ring R] : non_unital_comm_ring (hahn_series Γ R) := { .. hahn_series.non_unital_comm_semiring, .. hahn_series.non_unital_ring } instance [comm_ring R] : comm_ring (hahn_series Γ R) := { .. hahn_series.comm_semiring, .. hahn_series.ring } instance {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [non_unital_non_assoc_semiring R] [no_zero_divisors R] : no_zero_divisors (hahn_series Γ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y xy, begin by_cases hx : x = 0, { left, exact hx }, right, contrapose! xy, rw [hahn_series.ext_iff, function.funext_iff, not_forall], refine ⟨x.order + y.order, _⟩, rw [mul_coeff_order_add_order x y, zero_coeff, mul_eq_zero], simp [coeff_order_ne_zero, hx, xy], end } instance {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [ring R] [is_domain R] : is_domain (hahn_series Γ R) := { .. hahn_series.no_zero_divisors, .. hahn_series.nontrivial, .. hahn_series.ring } @[simp] lemma order_mul {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [non_unital_non_assoc_semiring R] [no_zero_divisors R] {x y : hahn_series Γ R} (hx : x ≠ 0) (hy : y ≠ 0) : (x * y).order = x.order + y.order := begin apply le_antisymm, { apply order_le_of_coeff_ne_zero, rw [mul_coeff_order_add_order x y], exact mul_ne_zero (coeff_order_ne_zero hx) (coeff_order_ne_zero hy) }, { rw [order_of_ne hx, order_of_ne hy, order_of_ne (mul_ne_zero hx hy), ← set.is_wf.min_add], exact set.is_wf.min_le_min_of_subset (support_mul_subset_add_support) }, end @[simp] lemma order_pow {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [semiring R] [no_zero_divisors R] (x : hahn_series Γ R) (n : ℕ) : (x ^ n).order = n • x.order := begin induction n with h IH, { simp }, rcases eq_or_ne x 0 with rfl|hx, { simp }, rw [pow_succ', order_mul (pow_ne_zero _ hx) hx, succ_nsmul', IH] end section non_unital_non_assoc_semiring variables [non_unital_non_assoc_semiring R] @[simp] lemma single_mul_single {a b : Γ} {r s : R} : single a r * single b s = single (a + b) (r * s) := begin ext x, by_cases h : x = a + b, { rw [h, mul_single_coeff_add], simp }, { rw [single_coeff_of_ne h, mul_coeff, sum_eq_zero], simp_rw mem_add_antidiagonal, rintro ⟨y, z⟩ ⟨hy, hz, rfl⟩, rw [eq_of_mem_support_single hy, eq_of_mem_support_single hz] at h, exact (h rfl).elim } end end non_unital_non_assoc_semiring section non_assoc_semiring variables [non_assoc_semiring R] /-- `C a` is the constant Hahn Series `a`. `C` is provided as a ring homomorphism. -/ @[simps] def C : R →+* (hahn_series Γ R) := { to_fun := single 0, map_zero' := single_eq_zero, map_one' := rfl, map_add' := λ x y, by { ext a, by_cases h : a = 0; simp [h] }, map_mul' := λ x y, by rw [single_mul_single, zero_add] } @[simp] lemma C_zero : C (0 : R) = (0 : hahn_series Γ R) := C.map_zero @[simp] lemma C_one : C (1 : R) = (1 : hahn_series Γ R) := C.map_one lemma C_injective : function.injective (C : R → hahn_series Γ R) := begin intros r s rs, rw [ext_iff, function.funext_iff] at rs, have h := rs 0, rwa [C_apply, single_coeff_same, C_apply, single_coeff_same] at h, end lemma C_ne_zero {r : R} (h : r ≠ 0) : (C r : hahn_series Γ R) ≠ 0 := begin contrapose! h, rw ← C_zero at h, exact C_injective h, end lemma order_C {r : R} : order (C r : hahn_series Γ R) = 0 := begin by_cases h : r = 0, { rw [h, C_zero, order_zero] }, { exact order_single h } end end non_assoc_semiring section semiring variables [semiring R] lemma C_mul_eq_smul {r : R} {x : hahn_series Γ R} : C r * x = r • x := single_zero_mul_eq_smul end semiring section domain variables {Γ' : Type*} [ordered_cancel_add_comm_monoid Γ'] lemma emb_domain_mul [non_unital_non_assoc_semiring R] (f : Γ ↪o Γ') (hf : ∀ x y, f (x + y) = f x + f y) (x y : hahn_series Γ R) : emb_domain f (x * y) = emb_domain f x * emb_domain f y := begin ext g, by_cases hg : g ∈ set.range f, { obtain ⟨g, rfl⟩ := hg, simp only [mul_coeff, emb_domain_coeff], transitivity ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support g).map (function.embedding.prod_map f.to_embedding f.to_embedding), (emb_domain f x).coeff (ij.1) * (emb_domain f y).coeff (ij.2), { simp }, apply sum_subset, { rintro ⟨i, j⟩ hij, simp only [exists_prop, mem_map, prod.mk.inj_iff, mem_add_antidiagonal, function.embedding.coe_prod_map, mem_support, prod.exists] at hij, obtain ⟨i, j, ⟨hx, hy, rfl⟩, rfl, rfl⟩ := hij, simp [hx, hy, hf], }, { rintro ⟨_, _⟩ h1 h2, contrapose! h2, obtain ⟨i, hi, rfl⟩ := support_emb_domain_subset (ne_zero_and_ne_zero_of_mul h2).1, obtain ⟨j, hj, rfl⟩ := support_emb_domain_subset (ne_zero_and_ne_zero_of_mul h2).2, simp only [exists_prop, mem_map, prod.mk.inj_iff, mem_add_antidiagonal, function.embedding.coe_prod_map, mem_support, prod.exists], simp only [mem_add_antidiagonal, emb_domain_coeff, mem_support, ←hf, order_embedding.eq_iff_eq] at h1, exact ⟨i, j, h1, rfl⟩ } }, { rw [emb_domain_notin_range hg, eq_comm], contrapose! hg, obtain ⟨_, _, hi, hj, rfl⟩ := support_mul_subset_add_support ((mem_support _ _).2 hg), obtain ⟨i, hi, rfl⟩ := support_emb_domain_subset hi, obtain ⟨j, hj, rfl⟩ := support_emb_domain_subset hj, refine ⟨i + j, hf i j⟩, } end lemma emb_domain_one [non_assoc_semiring R] (f : Γ ↪o Γ') (hf : f 0 = 0): emb_domain f (1 : hahn_series Γ R) = (1 : hahn_series Γ' R) := emb_domain_single.trans $ hf.symm ▸ rfl /-- Extending the domain of Hahn series is a ring homomorphism. -/ @[simps] def emb_domain_ring_hom [non_assoc_semiring R] (f : Γ →+ Γ') (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') : hahn_series Γ R →+* hahn_series Γ' R := { to_fun := emb_domain ⟨⟨f, hfi⟩, hf⟩, map_one' := emb_domain_one _ f.map_zero, map_mul' := emb_domain_mul _ f.map_add, map_zero' := emb_domain_zero, map_add' := emb_domain_add _} lemma emb_domain_ring_hom_C [non_assoc_semiring R] {f : Γ →+ Γ'} {hfi : function.injective f} {hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g'} {r : R} : emb_domain_ring_hom f hfi hf (C r) = C r := emb_domain_single.trans (by simp) end domain section algebra variables [comm_semiring R] {A : Type*} [semiring A] [algebra R A] instance : algebra R (hahn_series Γ A) := { to_ring_hom := C.comp (algebra_map R A), smul_def' := λ r x, by { ext, simp }, commutes' := λ r x, by { ext, simp only [smul_coeff, single_zero_mul_eq_smul, ring_hom.coe_comp, ring_hom.to_fun_eq_coe, C_apply, function.comp_app, algebra_map_smul, mul_single_zero_coeff], rw [← algebra.commutes, algebra.smul_def], }, } theorem C_eq_algebra_map : C = (algebra_map R (hahn_series Γ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (hahn_series Γ A) r = C (algebra_map R A r) := rfl instance [nontrivial Γ] [nontrivial R] : nontrivial (subalgebra R (hahn_series Γ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], obtain ⟨a, ha⟩ := exists_ne (0 : Γ), refine ⟨single a 1, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, function.funext_iff, not_forall], refine ⟨a, _⟩, rw [single_coeff_same, algebra_map_apply, C_apply, single_coeff_of_ne ha], exact zero_ne_one end⟩⟩ section domain variables {Γ' : Type*} [ordered_cancel_add_comm_monoid Γ'] /-- Extending the domain of Hahn series is an algebra homomorphism. -/ @[simps] def emb_domain_alg_hom (f : Γ →+ Γ') (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') : hahn_series Γ A →ₐ[R] hahn_series Γ' A := { commutes' := λ r, emb_domain_ring_hom_C, .. emb_domain_ring_hom f hfi hf } end domain end algebra end multiplication section semiring variables [semiring R] /-- The ring `hahn_series ℕ R` is isomorphic to `power_series R`. -/ @[simps] def to_power_series : hahn_series ℕ R ≃+* power_series R := { to_fun := λ f, power_series.mk f.coeff, inv_fun := λ f, ⟨λ n, power_series.coeff R n f, (nat.lt_wf.is_wf _).is_pwo⟩, left_inv := λ f, by { ext, simp }, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, simp }, map_mul' := λ f g, begin ext n, simp only [power_series.coeff_mul, power_series.coeff_mk, mul_coeff, is_pwo_support], classical, refine sum_filter_ne_zero.symm.trans ((sum_congr _ $ λ _ _, rfl).trans sum_filter_ne_zero), ext m, simp only [nat.mem_antidiagonal, mem_add_antidiagonal, and.congr_left_iff, mem_filter, mem_support], rintro h, rw [and_iff_right (left_ne_zero_of_mul h), and_iff_right (right_ne_zero_of_mul h)], end } lemma coeff_to_power_series {f : hahn_series ℕ R} {n : ℕ} : power_series.coeff R n f.to_power_series = f.coeff n := power_series.coeff_mk _ _ lemma coeff_to_power_series_symm {f : power_series R} {n : ℕ} : (hahn_series.to_power_series.symm f).coeff n = power_series.coeff R n f := rfl variables (Γ) (R) [ordered_semiring Γ] [nontrivial Γ] /-- Casts a power series as a Hahn series with coefficients from an `ordered_semiring`. -/ def of_power_series : (power_series R) →+* hahn_series Γ R := (hahn_series.emb_domain_ring_hom (nat.cast_add_monoid_hom Γ) nat.strict_mono_cast.injective (λ _ _, nat.cast_le)).comp (ring_equiv.to_ring_hom to_power_series.symm) variables {Γ} {R} lemma of_power_series_injective : function.injective (of_power_series Γ R) := emb_domain_injective.comp to_power_series.symm.injective @[simp] lemma of_power_series_apply (x : power_series R) : of_power_series Γ R x = hahn_series.emb_domain ⟨⟨(coe : ℕ → Γ), nat.strict_mono_cast.injective⟩, λ a b, begin simp only [function.embedding.coe_fn_mk], exact nat.cast_le, end⟩ (to_power_series.symm x) := rfl lemma of_power_series_apply_coeff (x : power_series R) (n : ℕ) : (of_power_series Γ R x).coeff n = power_series.coeff R n x := by simp @[simp] lemma of_power_series_C (r : R) : of_power_series Γ R (power_series.C R r) = hahn_series.C r := begin ext n, simp only [C, single_coeff, of_power_series_apply, ring_hom.coe_mk], split_ifs with hn hn, { subst hn, convert @emb_domain_coeff _ _ _ _ _ _ _ _ 0; simp }, { rw emb_domain_notin_image_support, simp only [not_exists, set.mem_image, to_power_series_symm_apply_coeff, mem_support, power_series.coeff_C], intro, simp [ne.symm hn] {contextual := tt} } end @[simp] lemma of_power_series_X : of_power_series Γ R power_series.X = single 1 1 := begin ext n, simp only [single_coeff, of_power_series_apply, ring_hom.coe_mk], split_ifs with hn hn, { rw hn, convert @emb_domain_coeff _ _ _ _ _ _ _ _ 1; simp }, { rw emb_domain_notin_image_support, simp only [not_exists, set.mem_image, to_power_series_symm_apply_coeff, mem_support, power_series.coeff_X], intro, simp [ne.symm hn] {contextual := tt} } end @[simp] lemma of_power_series_X_pow {R} [comm_semiring R] (n : ℕ) : of_power_series Γ R (power_series.X ^ n) = single (n : Γ) 1 := begin rw ring_hom.map_pow, induction n with n ih, { simp, refl }, rw [pow_succ, ih, of_power_series_X, mul_comm, single_mul_single, one_mul, nat.cast_succ] end -- Lemmas about converting hahn_series over fintype to and from mv_power_series /-- The ring `hahn_series (σ →₀ ℕ) R` is isomorphic to `mv_power_series σ R` for a `fintype` `σ`. We take the index set of the hahn series to be `finsupp` rather than `pi`, even though we assume `fintype σ` as this is more natural for alignment with `mv_power_series`. After importing `algebra.order.pi` the ring `hahn_series (σ → ℕ) R` could be constructed instead. -/ @[simps] def to_mv_power_series {σ : Type*} [fintype σ] : hahn_series (σ →₀ ℕ) R ≃+* mv_power_series σ R := { to_fun := λ f, f.coeff, inv_fun := λ f, ⟨(f : (σ →₀ ℕ) → R), finsupp.is_pwo _⟩, left_inv := λ f, by { ext, simp }, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, simp }, map_mul' := λ f g, begin ext n, simp only [mv_power_series.coeff_mul], classical, change (f * g).coeff n = _, simp_rw [mul_coeff], refine sum_filter_ne_zero.symm.trans ((sum_congr _ (λ _ _, rfl)).trans sum_filter_ne_zero), ext m, simp only [and.congr_left_iff, mem_add_antidiagonal, mem_filter, mem_support, finsupp.mem_antidiagonal], rintro h, rw [and_iff_right (left_ne_zero_of_mul h), and_iff_right (right_ne_zero_of_mul h)], end } variables {σ : Type*} [fintype σ] lemma coeff_to_mv_power_series {f : hahn_series (σ →₀ ℕ) R} {n : σ →₀ ℕ} : mv_power_series.coeff R n f.to_mv_power_series = f.coeff n := rfl lemma coeff_to_mv_power_series_symm {f : mv_power_series σ R} {n : σ →₀ ℕ} : (hahn_series.to_mv_power_series.symm f).coeff n = mv_power_series.coeff R n f := rfl end semiring section algebra variables (R) [comm_semiring R] {A : Type*} [semiring A] [algebra R A] /-- The `R`-algebra `hahn_series ℕ A` is isomorphic to `power_series A`. -/ @[simps] def to_power_series_alg : (hahn_series ℕ A) ≃ₐ[R] power_series A := { commutes' := λ r, begin ext n, simp only [algebra_map_apply, power_series.algebra_map_apply, ring_equiv.to_fun_eq_coe, C_apply, coeff_to_power_series], cases n, { simp only [power_series.coeff_zero_eq_constant_coeff, single_coeff_same], refl }, { simp only [n.succ_ne_zero, ne.def, not_false_iff, single_coeff_of_ne], rw [power_series.coeff_C, if_neg n.succ_ne_zero] } end, .. to_power_series } variables (Γ) (R) [ordered_semiring Γ] [nontrivial Γ] /-- Casting a power series as a Hahn series with coefficients from an `ordered_semiring` is an algebra homomorphism. -/ @[simps] def of_power_series_alg : (power_series A) →ₐ[R] hahn_series Γ A := (hahn_series.emb_domain_alg_hom (nat.cast_add_monoid_hom Γ) nat.strict_mono_cast.injective (λ _ _, nat.cast_le)).comp (alg_equiv.to_alg_hom (to_power_series_alg R).symm) instance power_series_algebra {S : Type*} [comm_semiring S] [algebra S (power_series R)] : algebra S (hahn_series Γ R) := ring_hom.to_algebra $ (of_power_series Γ R).comp (algebra_map S (power_series R)) variables {R} {S : Type*} [comm_semiring S] [algebra S (power_series R)] lemma algebra_map_apply' (x : S) : algebra_map S (hahn_series Γ R) x = of_power_series Γ R (algebra_map S (power_series R) x) := rfl @[simp] lemma _root_.polynomial.algebra_map_hahn_series_apply (f : R[X]) : algebra_map R[X] (hahn_series Γ R) f = of_power_series Γ R f := rfl lemma _root_.polynomial.algebra_map_hahn_series_injective : function.injective (algebra_map R[X] (hahn_series Γ R)) := of_power_series_injective.comp (polynomial.coe_injective R) end algebra section valuation variables (Γ R) [linear_ordered_add_comm_group Γ] [ring R] [is_domain R] /-- The additive valuation on `hahn_series Γ R`, returning the smallest index at which a Hahn Series has a nonzero coefficient, or `⊤` for the 0 series. -/ def add_val : add_valuation (hahn_series Γ R) (with_top Γ) := add_valuation.of (λ x, if x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.order) (if_pos rfl) ((if_neg one_ne_zero).trans (by simp [order_of_ne])) (λ x y, begin by_cases hx : x = 0, { by_cases hy : y = 0; { simp [hx, hy] } }, { by_cases hy : y = 0, { simp [hx, hy] }, { simp only [hx, hy, support_nonempty_iff, if_neg, not_false_iff, is_wf_support], by_cases hxy : x + y = 0, { simp [hxy] }, rw [if_neg hxy, ← with_top.coe_min, with_top.coe_le_coe], exact min_order_le_order_add hxy } }, end) (λ x y, begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_top.coe_add, with_top.coe_eq_coe, order_mul hx hy], end) variables {Γ} {R} lemma add_val_apply {x : hahn_series Γ R} : add_val Γ R x = if x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.order := add_valuation.of_apply _ @[simp] lemma add_val_apply_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) : add_val Γ R x = x.order := if_neg hx lemma add_val_le_of_coeff_ne_zero {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : add_val Γ R x ≤ g := begin rw [add_val_apply_of_ne (ne_zero_of_coeff_ne_zero h), with_top.coe_le_coe], exact order_le_of_coeff_ne_zero h end end valuation lemma is_pwo_Union_support_powers [linear_ordered_add_comm_group Γ] [ring R] [is_domain R] {x : hahn_series Γ R} (hx : 0 < add_val Γ R x) : (⋃ n : ℕ, (x ^ n).support).is_pwo := begin apply (x.is_wf_support.is_pwo.add_submonoid_closure (λ g hg, _)).mono _, { exact with_top.coe_le_coe.1 (le_trans (le_of_lt hx) (add_val_le_of_coeff_ne_zero hg)) }, refine set.Union_subset (λ n, _), induction n with n ih; intros g hn, { simp only [exists_prop, and_true, set.mem_singleton_iff, set.set_of_eq_eq_singleton, mem_support, ite_eq_right_iff, ne.def, not_false_iff, one_ne_zero, pow_zero, not_forall, one_coeff] at hn, rw [hn, set_like.mem_coe], exact add_submonoid.zero_mem _ }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support hn, exact set_like.mem_coe.2 (add_submonoid.add_mem _ (add_submonoid.subset_closure hi) (ih hj)) } end section variables (Γ) (R) [partial_order Γ] [add_comm_monoid R] /-- An infinite family of Hahn series which has a formal coefficient-wise sum. The requirements for this are that the union of the supports of the series is well-founded, and that only finitely many series are nonzero at any given coefficient. -/ structure summable_family (α : Type*) := (to_fun : α → hahn_series Γ R) (is_pwo_Union_support' : set.is_pwo (⋃ (a : α), (to_fun a).support)) (finite_co_support' : ∀ (g : Γ), ({a | (to_fun a).coeff g ≠ 0}).finite) end namespace summable_family section add_comm_monoid variables [partial_order Γ] [add_comm_monoid R] {α : Type*} instance : has_coe_to_fun (summable_family Γ R α) (λ _, α → hahn_series Γ R):= ⟨to_fun⟩ lemma is_pwo_Union_support (s : summable_family Γ R α) : set.is_pwo (⋃ (a : α), (s a).support) := s.is_pwo_Union_support' lemma finite_co_support (s : summable_family Γ R α) (g : Γ) : (function.support (λ a, (s a).coeff g)).finite := s.finite_co_support' g lemma coe_injective : @function.injective (summable_family Γ R α) (α → hahn_series Γ R) coe_fn | ⟨f1, hU1, hf1⟩ ⟨f2, hU2, hf2⟩ h := begin change f1 = f2 at h, subst h, end @[ext] lemma ext {s t : summable_family Γ R α} (h : ∀ (a : α), s a = t a) : s = t := coe_injective $ funext h instance : has_add (summable_family Γ R α) := ⟨λ x y, { to_fun := x + y, is_pwo_Union_support' := (x.is_pwo_Union_support.union y.is_pwo_Union_support).mono (begin rw ← set.Union_union_distrib, exact set.Union_mono (λ a, support_add_subset) end), finite_co_support' := λ g, ((x.finite_co_support g).union (y.finite_co_support g)).subset begin intros a ha, change (x a).coeff g + (y a).coeff g ≠ 0 at ha, rw [set.mem_union, function.mem_support, function.mem_support], contrapose! ha, rw [ha.1, ha.2, add_zero] end }⟩ instance : has_zero (summable_family Γ R α) := ⟨⟨0, by simp, by simp⟩⟩ instance : inhabited (summable_family Γ R α) := ⟨0⟩ @[simp] lemma coe_add {s t : summable_family Γ R α} : ⇑(s + t) = s + t := rfl lemma add_apply {s t : summable_family Γ R α} {a : α} : (s + t) a = s a + t a := rfl @[simp] lemma coe_zero : ((0 : summable_family Γ R α) : α → hahn_series Γ R) = 0 := rfl lemma zero_apply {a : α} : (0 : summable_family Γ R α) a = 0 := rfl instance : add_comm_monoid (summable_family Γ R α) := { add := (+), zero := 0, zero_add := λ s, by { ext, apply zero_add }, add_zero := λ s, by { ext, apply add_zero }, add_comm := λ s t, by { ext, apply add_comm }, add_assoc := λ r s t, by { ext, apply add_assoc } } /-- The infinite sum of a `summable_family` of Hahn series. -/ def hsum (s : summable_family Γ R α) : hahn_series Γ R := { coeff := λ g, ∑ᶠ i, (s i).coeff g, is_pwo_support' := s.is_pwo_Union_support.mono (λ g, begin contrapose, rw [set.mem_Union, not_exists, function.mem_support, not_not], simp_rw [mem_support, not_not], intro h, rw [finsum_congr h, finsum_zero], end) } @[simp] lemma hsum_coeff {s : summable_family Γ R α} {g : Γ} : s.hsum.coeff g = ∑ᶠ i, (s i).coeff g := rfl lemma support_hsum_subset {s : summable_family Γ R α} : s.hsum.support ⊆ ⋃ (a : α), (s a).support := λ g hg, begin rw [mem_support, hsum_coeff, finsum_eq_sum _ (s.finite_co_support _)] at hg, obtain ⟨a, h1, h2⟩ := exists_ne_zero_of_sum_ne_zero hg, rw [set.mem_Union], exact ⟨a, h2⟩, end @[simp] lemma hsum_add {s t : summable_family Γ R α} : (s + t).hsum = s.hsum + t.hsum := begin ext g, simp only [hsum_coeff, add_coeff, add_apply], exact finsum_add_distrib (s.finite_co_support _) (t.finite_co_support _) end end add_comm_monoid section add_comm_group variables [partial_order Γ] [add_comm_group R] {α : Type*} {s t : summable_family Γ R α} {a : α} instance : add_comm_group (summable_family Γ R α) := { neg := λ s, { to_fun := λ a, - s a, is_pwo_Union_support' := by { simp_rw [support_neg], exact s.is_pwo_Union_support' }, finite_co_support' := λ g, by { simp only [neg_coeff', pi.neg_apply, ne.def, neg_eq_zero], exact s.finite_co_support g } }, add_left_neg := λ a, by { ext, apply add_left_neg }, .. summable_family.add_comm_monoid } @[simp] lemma coe_neg : ⇑(-s) = - s := rfl lemma neg_apply : (-s) a = - (s a) := rfl @[simp] lemma coe_sub : ⇑(s - t) = s - t := rfl lemma sub_apply : (s - t) a = s a - t a := rfl end add_comm_group section semiring variables [ordered_cancel_add_comm_monoid Γ] [semiring R] {α : Type*} instance : has_smul (hahn_series Γ R) (summable_family Γ R α) := { smul := λ x s, { to_fun := λ a, x * (s a), is_pwo_Union_support' := begin apply (x.is_pwo_support.add s.is_pwo_Union_support).mono, refine set.subset.trans (set.Union_mono (λ a, support_mul_subset_add_support)) _, intro g, simp only [set.mem_Union, exists_imp_distrib], exact λ a ha, (set.add_subset_add (set.subset.refl _) (set.subset_Union _ a)) ha, end, finite_co_support' := λ g, begin refine ((add_antidiagonal x.is_pwo_support s.is_pwo_Union_support g).finite_to_set.bUnion' (λ ij hij, _)).subset (λ a ha, _), { exact λ ij hij, function.support (λ a, (s a).coeff ij.2) }, { apply s.finite_co_support }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support ha, simp only [exists_prop, set.mem_Union, mem_add_antidiagonal, mul_coeff, mem_support, is_pwo_support, prod.exists], exact ⟨i, j, mem_coe.2 (mem_add_antidiagonal.2 ⟨hi, set.mem_Union.2 ⟨a, hj⟩, rfl⟩), hj⟩ } end } } @[simp] lemma smul_apply {x : hahn_series Γ R} {s : summable_family Γ R α} {a : α} : (x • s) a = x * (s a) := rfl instance : module (hahn_series Γ R) (summable_family Γ R α) := { smul := (•), smul_zero := λ x, ext (λ a, mul_zero _), zero_smul := λ x, ext (λ a, zero_mul _), one_smul := λ x, ext (λ a, one_mul _), add_smul := λ x y s, ext (λ a, add_mul _ _ _), smul_add := λ x s t, ext (λ a, mul_add _ _ _), mul_smul := λ x y s, ext (λ a, mul_assoc _ _ _) } @[simp] lemma hsum_smul {x : hahn_series Γ R} {s : summable_family Γ R α} : (x • s).hsum = x * s.hsum := begin ext g, simp only [mul_coeff, hsum_coeff, smul_apply], have h : ∀ i, (s i).support ⊆ ⋃ j, (s j).support := set.subset_Union _, refine (eq.trans (finsum_congr (λ a, _)) (finsum_sum_comm (add_antidiagonal x.is_pwo_support s.is_pwo_Union_support g) (λ i ij, x.coeff (prod.fst ij) * (s i).coeff ij.snd) _)).trans _, { refine sum_subset (add_antidiagonal_mono_right (set.subset_Union _ a)) _, rintro ⟨i, j⟩ hU ha, rw mem_add_antidiagonal at *, rw [not_not.1 (λ con, ha ⟨hU.1, con, hU.2.2⟩), mul_zero] }, { rintro ⟨i, j⟩ hij, refine (s.finite_co_support j).subset _, simp_rw [function.support_subset_iff', function.mem_support, not_not], intros a ha, rw [ha, mul_zero] }, { refine (sum_congr rfl _).trans (sum_subset (add_antidiagonal_mono_right _) _).symm, { rintro ⟨i, j⟩ hij, rw mul_finsum, apply s.finite_co_support, }, { intros x hx, simp only [set.mem_Union, ne.def, mem_support], contrapose! hx, simp [hx] }, { rintro ⟨i, j⟩ hU ha, rw mem_add_antidiagonal at *, rw [← hsum_coeff, not_not.1 (λ con, ha ⟨hU.1, con, hU.2.2⟩), mul_zero] } } end /-- The summation of a `summable_family` as a `linear_map`. -/ @[simps] def lsum : (summable_family Γ R α) →ₗ[hahn_series Γ R] (hahn_series Γ R) := { to_fun := hsum, map_add' := λ _ _, hsum_add, map_smul' := λ _ _, hsum_smul } @[simp] lemma hsum_sub {R : Type*} [ring R] {s t : summable_family Γ R α} : (s - t).hsum = s.hsum - t.hsum := by rw [← lsum_apply, linear_map.map_sub, lsum_apply, lsum_apply] end semiring section of_finsupp variables [partial_order Γ] [add_comm_monoid R] {α : Type*} /-- A family with only finitely many nonzero elements is summable. -/ def of_finsupp (f : α →₀ (hahn_series Γ R)) : summable_family Γ R α := { to_fun := f, is_pwo_Union_support' := begin apply (f.support.is_pwo_bUnion.2 $ λ a ha, (f a).is_pwo_support).mono, refine set.Union_subset_iff.2 (λ a g hg, _), have haf : a ∈ f.support, { rw [finsupp.mem_support_iff, ← support_nonempty_iff], exact ⟨g, hg⟩ }, exact set.mem_bUnion haf hg end, finite_co_support' := λ g, begin refine f.support.finite_to_set.subset (λ a ha, _), simp only [coeff.add_monoid_hom_apply, mem_coe, finsupp.mem_support_iff, ne.def, function.mem_support], contrapose! ha, simp [ha] end } @[simp] lemma coe_of_finsupp {f : α →₀ (hahn_series Γ R)} : ⇑(summable_family.of_finsupp f) = f := rfl @[simp] lemma hsum_of_finsupp {f : α →₀ (hahn_series Γ R)} : (of_finsupp f).hsum = f.sum (λ a, id) := begin ext g, simp only [hsum_coeff, coe_of_finsupp, finsupp.sum, ne.def], simp_rw [← coeff.add_monoid_hom_apply, id.def], rw [add_monoid_hom.map_sum, finsum_eq_sum_of_support_subset], intros x h, simp only [coeff.add_monoid_hom_apply, mem_coe, finsupp.mem_support_iff, ne.def], contrapose! h, simp [h] end end of_finsupp section emb_domain variables [partial_order Γ] [add_comm_monoid R] {α β : Type*} /-- A summable family can be reindexed by an embedding without changing its sum. -/ def emb_domain (s : summable_family Γ R α) (f : α ↪ β) : summable_family Γ R β := { to_fun := λ b, if h : b ∈ set.range f then s (classical.some h) else 0, is_pwo_Union_support' := begin refine s.is_pwo_Union_support.mono (set.Union_subset (λ b g h, _)), by_cases hb : b ∈ set.range f, { rw dif_pos hb at h, exact set.mem_Union.2 ⟨classical.some hb, h⟩ }, { contrapose! h, simp [hb] } end, finite_co_support' := λ g, ((s.finite_co_support g).image f).subset begin intros b h, by_cases hb : b ∈ set.range f, { simp only [ne.def, set.mem_set_of_eq, dif_pos hb] at h, exact ⟨classical.some hb, h, classical.some_spec hb⟩ }, { contrapose! h, simp only [ne.def, set.mem_set_of_eq, dif_neg hb, not_not, zero_coeff] } end } variables (s : summable_family Γ R α) (f : α ↪ β) {a : α} {b : β} lemma emb_domain_apply : s.emb_domain f b = if h : b ∈ set.range f then s (classical.some h) else 0 := rfl @[simp] lemma emb_domain_image : s.emb_domain f (f a) = s a := begin rw [emb_domain_apply, dif_pos (set.mem_range_self a)], exact congr rfl (f.injective (classical.some_spec (set.mem_range_self a))) end @[simp] lemma emb_domain_notin_range (h : b ∉ set.range f) : s.emb_domain f b = 0 := by rw [emb_domain_apply, dif_neg h] @[simp] lemma hsum_emb_domain : (s.emb_domain f).hsum = s.hsum := begin ext g, simp only [hsum_coeff, emb_domain_apply, apply_dite hahn_series.coeff, dite_apply, zero_coeff], exact finsum_emb_domain f (λ a, (s a).coeff g) end end emb_domain section powers variables [linear_ordered_add_comm_group Γ] [comm_ring R] [is_domain R] /-- The powers of an element of positive valuation form a summable family. -/ def powers (x : hahn_series Γ R) (hx : 0 < add_val Γ R x) : summable_family Γ R ℕ := { to_fun := λ n, x ^ n, is_pwo_Union_support' := is_pwo_Union_support_powers hx, finite_co_support' := λ g, begin have hpwo := (is_pwo_Union_support_powers hx), by_cases hg : g ∈ ⋃ n : ℕ, {g | (x ^ n).coeff g ≠ 0 }, swap, { exact set.finite_empty.subset (λ n hn, hg (set.mem_Union.2 ⟨n, hn⟩)) }, apply hpwo.is_wf.induction hg, intros y ys hy, refine ((((add_antidiagonal x.is_pwo_support hpwo y).finite_to_set.bUnion (λ ij hij, hy ij.snd _ _)).image nat.succ).union (set.finite_singleton 0)).subset _, { exact (mem_add_antidiagonal.1 (mem_coe.1 hij)).2.1 }, { obtain ⟨hi, hj, rfl⟩ := mem_add_antidiagonal.1 (mem_coe.1 hij), rw [← zero_add ij.snd, ← add_assoc, add_zero], exact add_lt_add_right (with_top.coe_lt_coe.1 (lt_of_lt_of_le hx (add_val_le_of_coeff_ne_zero hi))) _, }, { rintro (_ | n) hn, { exact set.mem_union_right _ (set.mem_singleton 0) }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support hn, refine set.mem_union_left _ ⟨n, set.mem_Union.2 ⟨⟨i, j⟩, set.mem_Union.2 ⟨_, hj⟩⟩, rfl⟩, simp only [and_true, set.mem_Union, mem_add_antidiagonal, mem_coe, eq_self_iff_true, ne.def, mem_support, set.mem_set_of_eq], exact ⟨hi, n, hj⟩ } } end } variables {x : hahn_series Γ R} (hx : 0 < add_val Γ R x) @[simp] lemma coe_powers : ⇑(powers x hx) = pow x := rfl lemma emb_domain_succ_smul_powers : (x • powers x hx).emb_domain ⟨nat.succ, nat.succ_injective⟩ = powers x hx - of_finsupp (finsupp.single 0 1) := begin apply summable_family.ext (λ n, _), cases n, { rw [emb_domain_notin_range, sub_apply, coe_powers, pow_zero, coe_of_finsupp, finsupp.single_eq_same, sub_self], rw [set.mem_range, not_exists], exact nat.succ_ne_zero }, { refine eq.trans (emb_domain_image _ ⟨nat.succ, nat.succ_injective⟩) _, simp only [pow_succ, coe_powers, coe_sub, smul_apply, coe_of_finsupp, pi.sub_apply], rw [finsupp.single_eq_of_ne (n.succ_ne_zero).symm, sub_zero] } end lemma one_sub_self_mul_hsum_powers : (1 - x) * (powers x hx).hsum = 1 := begin rw [← hsum_smul, sub_smul, one_smul, hsum_sub, ← hsum_emb_domain (x • powers x hx) ⟨nat.succ, nat.succ_injective⟩, emb_domain_succ_smul_powers], simp, end end powers end summable_family section inversion variables [linear_ordered_add_comm_group Γ] section is_domain variables [comm_ring R] [is_domain R] lemma unit_aux (x : hahn_series Γ R) {r : R} (hr : r * x.coeff x.order = 1) : 0 < add_val Γ R (1 - C r * (single (- x.order) 1) * x) := begin have h10 : (1 : R) ≠ 0 := one_ne_zero, have x0 : x ≠ 0 := ne_zero_of_coeff_ne_zero (right_ne_zero_of_mul_eq_one hr), refine lt_of_le_of_ne ((add_val Γ R).map_le_sub (ge_of_eq (add_val Γ R).map_one) _) _, { simp only [add_valuation.map_mul], rw [add_val_apply_of_ne x0, add_val_apply_of_ne (single_ne_zero h10), add_val_apply_of_ne _, order_C, order_single h10, with_top.coe_zero, zero_add, ← with_top.coe_add, neg_add_self, with_top.coe_zero], { exact le_refl 0 }, { exact C_ne_zero (left_ne_zero_of_mul_eq_one hr) } }, { rw [add_val_apply, ← with_top.coe_zero], split_ifs, { apply with_top.coe_ne_top }, rw [ne.def, with_top.coe_eq_coe], intro con, apply coeff_order_ne_zero h, rw [← con, mul_assoc, sub_coeff, one_coeff, if_pos rfl, C_mul_eq_smul, smul_coeff, smul_eq_mul, ← add_neg_self x.order, single_mul_coeff_add, one_mul, hr, sub_self] } end lemma is_unit_iff {x : hahn_series Γ R} : is_unit x ↔ is_unit (x.coeff x.order) := begin split, { rintro ⟨⟨u, i, ui, iu⟩, rfl⟩, refine is_unit_of_mul_eq_one (u.coeff u.order) (i.coeff i.order) ((mul_coeff_order_add_order u i).symm.trans _), rw [ui, one_coeff, if_pos], rw [← order_mul (left_ne_zero_of_mul_eq_one ui) (right_ne_zero_of_mul_eq_one ui), ui, order_one] }, { rintro ⟨⟨u, i, ui, iu⟩, h⟩, rw [units.coe_mk] at h, rw h at iu, have h := summable_family.one_sub_self_mul_hsum_powers (unit_aux x iu), rw [sub_sub_cancel] at h, exact is_unit_of_mul_is_unit_right (is_unit_of_mul_eq_one _ _ h) }, end end is_domain instance [field R] : field (hahn_series Γ R) := { inv := λ x, if x0 : x = 0 then 0 else (C (x.coeff x.order)⁻¹ * (single (-x.order)) 1 * (summable_family.powers _ (unit_aux x (inv_mul_cancel (coeff_order_ne_zero x0)))).hsum), inv_zero := dif_pos rfl, mul_inv_cancel := λ x x0, begin refine (congr rfl (dif_neg x0)).trans _, have h := summable_family.one_sub_self_mul_hsum_powers (unit_aux x (inv_mul_cancel (coeff_order_ne_zero x0))), rw [sub_sub_cancel] at h, rw [← mul_assoc, mul_comm x, h], end, .. hahn_series.is_domain, .. hahn_series.comm_ring } end inversion end hahn_series
c9d4f3d48762379bc00c6ba059c6c58c22f5a4d2
43390109ab88557e6090f3245c47479c123ee500
/src/xenalib/Keji_permutation_group.lean
6a0d9717da347ce916262a4882c256c73e68ae68
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,327
lean
import xenalib.Group_actions data.fintype data.set.finite data.equiv.basic xenalib.Ellen_Arlt_matrix_rings algebra.big_operators data.set.finite group_theory.coset algebra.group import group_theory.perm local attribute [instance] classical.prop_decidable open fintype set_option pp.proofs true -- noncomputable instance {n : ℕ} : fintype {f : fin n→ fin n // function.bijective f} := -- set_fintype _ def S (n: ℕ ) := equiv.perm (fin n) instance (n : ℕ) : has_coe_to_fun (S n) := by unfold S; apply_instance -- def e {n:ℕ} {R:Type} [comm_ring R] (σ : fin n → fin n) : R:= sorry -- theorem Sig_eq_inv {n:ℕ} {R:Type} [comm_ring R] (π: S n) : @e n R _ π.1 = e (π.symm).1 := sorry -- theorem sig_mul {n:ℕ} {R:Type} [comm_ring R] (σ π : fin n → fin n) : @e n R _ (σ ∘ π )= (@e n R _ σ ) * @e n R _ π := sorry -- theorem sig_swap {n:ℕ} {R:Type} [comm_ring R] (i j : fin n): e (equiv.swap i j).1 = (-1 :R) := sorry -- noncomputable instance Sn_finite {n:ℕ}: fintype (S n):= -- fintype.of_surjective -- (λ (f : {f : fin n → fin n // function.bijective f}), equiv.of_bijective f.2) -- begin -- unfold function.surjective, -- simp, -- intro b, -- let f:{f : fin n → fin n // function.bijective f}:= ⟨ b.1,b.bijective⟩, -- existsi f.1, -- existsi f.2, -- apply equiv.ext, -- intro x, -- rw equiv.of_bijective_to_fun, -- refl, -- end instance g (n : ℕ) : is_group_action (equiv.to_fun : S n → fin n → fin n) := { one := λ _, rfl, mul := λ _ _ _, rfl } open is_group_action theorem Sn_transitive {n:ℕ}(i:fin n): ∀ (j:fin n), j ∈ is_group_action.orbit equiv.to_fun i:= begin intro j, unfold is_group_action.orbit, unfold set.range, simp, let f := λx, if x=i then j else if x=j then i else x, refine exists.intro ⟨ f,f, λ _, begin simp [f]; split_ifs; simp*, end, λ _, begin simp [f]; split_ifs; simp*, end⟩ _, simp, simp[f], split_ifs, refl, refl, end variables (n :ℕ) (σ : S n) open function def compose: ℕ → (fin n → fin n) → (fin n → fin n) | 0 σ := σ | (i + 1) σ := comp σ (compose i σ ) def cyclic_subtype :Type := {x : S n // ∃ (j: ℕ), (compose j σ.1) = x.1} def Cyclic_Group_generated_by (σ : S n ): group {x : S n // ∃ (j: ℕ), (compose j σ.1) = x.1} := def Cycle (σ : S n): Prop:= ∃! (i:fin n), card (is_group_action.orbit equiv.to_fun i) > 1, def f' {n:ℕ }(f:is_group_action.stabilizer (equiv.to_fun: S (n+1) → fin (n+1) → fin (n+1)) ⟨n, nat.lt_succ_self _⟩): fin n → fin n := λ x, ⟨(f.1.1 (fin.raise x)).1, begin have : ((f.val).to_fun ⟨n, nat.lt_succ_self n⟩).val = n := fin.veq_of_eq f.2, refine lt_of_le_of_ne _ _, exact (nat.le_of_lt_succ (f.1.1 (fin.raise x)).2), assume h, conv at h {to_rhs, rw ← this}, have h : x.val = n := fin.veq_of_eq (f.1.bijective.1 (fin.eq_of_veq h)), have : x.val < n := x.2, simpa[lt_irrefl, h] using this, end⟩ @[simp] lemma fin_thing {n : ℕ} (a : fin n) : (⟨a.1, a.2⟩ : fin n) = a := by cases a;refl #print is_group_action.mul theorem f'_bijective {n:ℕ }(f:is_group_action.stabilizer (equiv.to_fun: S (n+1) → fin (n+1) → fin (n+1)) ⟨n, nat.lt_succ_self _⟩): function.bijective(f' f):= begin unfold function.bijective, split, unfold function.injective, intros, rw[f'] at a, have H1: ((f.val).to_fun (fin.raise a₁)).val = ((f.val).to_fun (fin.raise a₂)).val, rw[ fin.veq_of_eq a], have H2 : (fin.raise a₁).val = (fin.raise a₂).val, exact fin.veq_of_eq (f.1.bijective.1 (fin.eq_of_veq H1)), exact fin.eq_of_veq H2, unfold function.surjective, intros, unfold f', existsi (⟨ (f.val⁻¹ .to_fun (fin.raise b)).val, begin have H1: f.val⁻¹ ∈ stabilizer (equiv.to_fun: S (n+1) → fin (n+1) → fin (n+1)) ⟨n, nat.lt_succ_self _⟩, rw[is_subgroup.inv_mem_iff], exact f.2, have : ((f.val⁻¹).to_fun ⟨n, nat.lt_succ_self n⟩).val = n := fin.veq_of_eq H1, refine lt_of_le_of_ne _ _, exact (nat.le_of_lt_succ (f.1.2 (fin.raise b)).2), assume h, conv at h {to_rhs, rw ← this}, have h : b.val = n := fin.veq_of_eq ((f.val⁻¹).bijective.1 (fin.eq_of_veq h)), have : b.val < n := b.2, simpa[lt_irrefl, h] using this, end⟩ : fin n), simp [fin.raise], apply fin.eq_of_veq, simp, -- (is_group_action.mul (equiv.to_fun : S (n+1) → fin (n+1) → fin (n+1)) _ _ _).symm._, -- rw mul_inv_self, -- exact b.2, rw ← is_group_action.mul (equiv.to_fun : S (n+1) → fin (n+1) → fin (n+1)), rw mul_inv_self, refl, end open function noncomputable def F : is_group_action.stabilizer (equiv.to_fun: S (n+1) → fin (n+1) → fin (n+1)) ⟨n, nat.lt_succ_self _⟩ → S n:= λ f, ⟨ (f' f),surj_inv (f'_bijective f).2 , left_inverse_surj_inv (f'_bijective f), right_inverse_surj_inv(f'_bijective f).2⟩ theorem bijection_form_stab_to_Sn: bijective (F n):= begin unfold function.bijective, split, unfold injective, intros, simp[F] at a, refine subtype.eq (equiv.ext _ _ _), have : f' a₁ = f' a₂, by injection a, simp [f'] at this, have:= congr_fun this, dsimp at this, intro a, by_cases a.1 < n, have := (fin.veq_of_eq (this_1 ⟨a.1, h⟩)), simp [fin.raise] at this, exact fin.eq_of_veq this, have H1 : n≤ a.1, exact le_of_not_lt h, have H2: a.1 ≤ n, exact nat.le_of_lt_succ a.2, have H3: a.1= n, exact le_antisymm H2 H1, have H4: a= ⟨n, nat.lt_succ_self _⟩, exact fin.eq_of_veq H3, rw[H4], have H5: (a₁.val) ⟨n, _⟩ =⟨n, _⟩, exact a₁.2, have H6: (a₂.val) ⟨n, _⟩ =⟨n, _⟩, exact a₂.2, exact eq.trans H5 H6.symm, unfold surjective, intro, simp[F], let k:= λ(x:fin(n+1)),if hxn : x.1<n then (⟨b.1 ⟨x.1, hxn⟩, begin have H1: (b.1 ⟨x.1, hxn⟩).1 < n, exact (b.1 ⟨x.1, hxn⟩).2, exact lt_trans H1 (nat.lt_succ_self n), end ⟩ : fin(n+1)) else n, existsi( ⟨k ,λ(x:fin(n+1)),if hxn : x.1<n then ⟨b.2 ⟨x.1, hxn⟩, begin have H1: (b.2 ⟨x.1, hxn⟩).1 < n, exact (b.2 ⟨x.1, hxn⟩).2, exact lt_trans H1 (nat.lt_succ_self n), end ⟩ else n, begin unfold left_inverse, intro, by_cases x.val < n, simp [h, dif_pos h], --have H1: end, sorry⟩ :fin (n + 1) ≃ fin (n + 1)) end #check eq.trans #check le_antisymm #check le_of_not_lt theorem mag_S {n:ℕ}: fintype.card (S n) = nat.fact n := sorry #check nat.le_of_lt_succ #check nat.add_one #check lt_trans
8e84b142e81db7c5fe81dd5bc35009146a4b9399
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/match1.lean
7563af7515c954394a953fbb207d4aecd347c067
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
3,856
lean
-- #print "---- h1" def h1 (b : Bool) : Nat := match b with | true => 0 | false => 10 #eval h1 false #print "---- h2" def h2 (x : List Nat) : Nat := match x with | [x1, x2] => x1 + x2 | x::xs => x | _ => 0 #eval h2 [1, 2] #eval h2 [10, 4, 5] #eval h2 [] #print "---- h3" def h3 (x : Array Nat) : Nat := match x with | #[x] => x | #[x, y] => x + y | xs => xs.size #eval h3 #[10] #eval h3 #[10, 20] #eval h3 #[10, 20, 30, 40] #print "---- inv" inductive Image {α β : Type} (f : α → β) : β → Type | mk (a : α) : Image f (f a) def mkImage {α β : Type} (f : α → β) (a : α) : Image f (f a) := Image.mk a def inv {α β : Type} {f : α → β} {b : β} (t : Image f b) : α := match b, t with | _, Image.mk a => a #eval inv (mkImage Nat.succ 10) theorem foo {p q} (h : p ∨ q) : q ∨ p := match h with | Or.inl h => Or.inr h | Or.inr h => Or.inl h def f (x : Nat × Nat) : Bool × Bool × Bool → Nat := match x with | (a, b) => fun _ => a structure S := (x y z : Nat := 0) def f1 : S → S := fun { x := x, ..} => { y := x } theorem ex2 : f1 { x := 10 } = { y := 10 } := rfl universes u inductive Vec (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) inductive VecPred {α : Type u} (P : α → Prop) : {n : Nat} → Vec α n → Prop | nil : VecPred P Vec.nil | cons {n : Nat} {head : α} {tail : Vec α n} : P head → VecPred P tail → VecPred P (Vec.cons head tail) theorem ex3 {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head _, VecPred.cons h _ => ⟨head, h⟩ theorem ex4 {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ -- ERROR axiom someNat : Nat noncomputable def f2 (x : Nat) := -- must mark as noncomputable since it uses axiom `someNat` x + someNat inductive Parity : Nat -> Type | even (n) : Parity (n + n) | odd (n) : Parity (Nat.succ (n + n)) axiom nDiv2 (n : Nat) : n % 2 = 0 → n = n/2 + n/2 axiom nDiv2Succ (n : Nat) : n % 2 ≠ 0 → n = Nat.succ (n/2 + n/2) def parity (n : Nat) : Parity n := if h : n % 2 = 0 then Eq.ndrec (Parity.even (n/2)) (nDiv2 n h).symm else Eq.ndrec (Parity.odd (n/2)) (nDiv2Succ n h).symm partial def natToBin : (n : Nat) → List Bool | 0 => [] | n => match n, parity n with | _, Parity.even j => false :: natToBin j | _, Parity.odd j => true :: natToBin j #eval natToBin 6 partial def natToBin' : (n : Nat) → List Bool | 0 => [] | n => match parity n with | Parity.even j => false :: natToBin j | Parity.odd j => true :: natToBin j partial def natToBinBad (n : Nat) : List Bool := match n, parity n with | 0, _ => [] | _, Parity.even j => false :: natToBin j | _, Parity.odd j => true :: natToBin j partial def natToBin2 (n : Nat) : List Bool := match n, parity n with | _, Parity.even 0 => [] | _, Parity.even j => false :: natToBin j | _, Parity.odd j => true :: natToBin j #eval natToBin2 6 partial def natToBin2' (n : Nat) : List Bool := match parity n with | Parity.even 0 => [] | Parity.even j => false :: natToBin j | Parity.odd j => true :: natToBin j #check fun (a, b) => a -- Error type of pattern variable contains metavariables #check fun (a, b) => (a:Nat) + b #check fun (a, b) => a && b #check fun ((a : Nat), (b : Nat)) => a + b #check fun | some a, some b => some (a + b : Nat) | _, _ => none -- overapplied matcher #check fun x => (match x with | 0 => id | x+1 => id) x #check fun | #[1, 2] => 2 | #[] => 0 | #[3, 4, 5] => 3 | _ => 4 -- underapplied matcher def g {α} : List α → Nat | [a] => 1 | _ => 0 #check g.match_1 #check fun (e : Empty) => (nomatch e : False)
6c037a4b3fd062c519f84297793dc11cb87253e7
e151e9053bfd6d71740066474fc500a087837323
/src/hott/cubical/cube.lean
c207bad5f736e28aea9bfbd543badd2a0853092b
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
21,902
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn, Jakob von Raumer Cubes -/ import .square universes u v w hott_theory namespace hott open hott.equiv hott.is_equiv sigma namespace eq inductive cube {A : Type u} {a₀₀₀ : A} : Π{a₂₀₀ a₀₂₀ a₂₂₀ a₀₀₂ a₂₀₂ a₀₂₂ a₂₂₂ : A} {p₁₀₀ : a₀₀₀ = a₂₀₀} {p₀₁₀ : a₀₀₀ = a₀₂₀} {p₀₀₁ : a₀₀₀ = a₀₀₂} {p₁₂₀ : a₀₂₀ = a₂₂₀} {p₂₁₀ : a₂₀₀ = a₂₂₀} {p₂₀₁ : a₂₀₀ = a₂₀₂} {p₁₀₂ : a₀₀₂ = a₂₀₂} {p₀₁₂ : a₀₀₂ = a₀₂₂} {p₀₂₁ : a₀₂₀ = a₀₂₂} {p₁₂₂ : a₀₂₂ = a₂₂₂} {p₂₁₂ : a₂₀₂ = a₂₂₂} {p₂₂₁ : a₂₂₀ = a₂₂₂} (s₀₁₁ : square p₀₁₀ p₀₁₂ p₀₀₁ p₀₂₁) (s₂₁₁ : square p₂₁₀ p₂₁₂ p₂₀₁ p₂₂₁) (s₁₀₁ : square p₁₀₀ p₁₀₂ p₀₀₁ p₂₀₁) (s₁₂₁ : square p₁₂₀ p₁₂₂ p₀₂₁ p₂₂₁) (s₁₁₀ : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀) (s₁₁₂ : square p₀₁₂ p₂₁₂ p₁₀₂ p₁₂₂), Type u | idc : cube ids ids ids ids ids ids variables {A : Type _} {B : Type _} {a₀₀₀ a₂₀₀ a₀₂₀ a₂₂₀ a₀₀₂ a₂₀₂ a₀₂₂ a₂₂₂ a a' : A} {p₁₀₀ : a₀₀₀ = a₂₀₀} {p₀₁₀ : a₀₀₀ = a₀₂₀} {p₀₀₁ : a₀₀₀ = a₀₀₂} {p₁₂₀ : a₀₂₀ = a₂₂₀} {p₂₁₀ : a₂₀₀ = a₂₂₀} {p₂₀₁ : a₂₀₀ = a₂₀₂} {p₁₀₂ : a₀₀₂ = a₂₀₂} {p₀₁₂ : a₀₀₂ = a₀₂₂} {p₀₂₁ : a₀₂₀ = a₀₂₂} {p₁₂₂ : a₀₂₂ = a₂₂₂} {p₂₁₂ : a₂₀₂ = a₂₂₂} {p₂₂₁ : a₂₂₀ = a₂₂₂} {s₀₁₁ : square p₀₁₀ p₀₁₂ p₀₀₁ p₀₂₁} {s₂₁₁ : square p₂₁₀ p₂₁₂ p₂₀₁ p₂₂₁} {s₁₀₁ : square p₁₀₀ p₁₀₂ p₀₀₁ p₂₀₁} {s₁₂₁ : square p₁₂₀ p₁₂₂ p₀₂₁ p₂₂₁} {s₁₁₀ : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} {s₁₁₂ : square p₀₁₂ p₂₁₂ p₁₀₂ p₁₂₂} {b₁ b₂ b₃ b₄ : B} (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) @[hott,reducible] def idc := @cube.idc @[hott,reducible] def idcube (a : A) := @cube.idc A a variables (s₁₁₀ s₁₀₁ s₀₁₁) @[hott] def refl1 : cube s₀₁₁ s₀₁₁ hrfl hrfl vrfl vrfl := by induction s₀₁₁; exact idc @[hott] def refl2 : cube hrfl hrfl s₁₀₁ s₁₀₁ hrfl hrfl := by induction s₁₀₁; exact idc @[hott] def refl3 : cube vrfl vrfl vrfl vrfl s₁₁₀ s₁₁₀ := by induction s₁₁₀; exact idc variables {s₁₁₀ s₁₀₁ s₀₁₁} @[hott] def rfl1 : cube s₀₁₁ s₀₁₁ hrfl hrfl vrfl vrfl := refl1 _ @[hott] def rfl2 : cube hrfl hrfl s₁₀₁ s₁₀₁ hrfl hrfl := refl2 _ @[hott] def rfl3 : cube vrfl vrfl vrfl vrfl s₁₁₀ s₁₁₀ := refl3 _ -- Variables for composition variables {a₄₀₀ a₄₀₂ a₄₂₀ a₄₂₂ a₀₄₀ a₀₄₂ a₂₄₀ a₂₄₂ a₀₀₄ a₀₂₄ a₂₀₄ a₂₂₄ : A} {p₃₀₀ : a₂₀₀ = a₄₀₀} {p₃₀₂ : a₂₀₂ = a₄₀₂} {p₃₂₀ : a₂₂₀ = a₄₂₀} {p₃₂₂ : a₂₂₂ = a₄₂₂} {p₄₀₁ : a₄₀₀ = a₄₀₂} {p₄₁₀ : a₄₀₀ = a₄₂₀} {p₄₁₂ : a₄₀₂ = a₄₂₂} {p₄₂₁ : a₄₂₀ = a₄₂₂} {p₀₃₀ : a₀₂₀ = a₀₄₀} {p₀₃₂ : a₀₂₂ = a₀₄₂} {p₂₃₀ : a₂₂₀ = a₂₄₀} {p₂₃₂ : a₂₂₂ = a₂₄₂} {p₀₄₁ : a₀₄₀ = a₀₄₂} {p₁₄₀ : a₀₄₀ = a₂₄₀} {p₁₄₂ : a₀₄₂ = a₂₄₂} {p₂₄₁ : a₂₄₀ = a₂₄₂} {p₀₀₃ : a₀₀₂ = a₀₀₄} {p₀₂₃ : a₀₂₂ = a₀₂₄} {p₂₀₃ : a₂₀₂ = a₂₀₄} {p₂₂₃ : a₂₂₂ = a₂₂₄} {p₀₁₄ : a₀₀₄ = a₀₂₄} {p₁₀₄ : a₀₀₄ = a₂₀₄} {p₁₂₄ : a₀₂₄ = a₂₂₄} {p₂₁₄ : a₂₀₄ = a₂₂₄} {s₃₀₁ : square p₃₀₀ p₃₀₂ p₂₀₁ p₄₀₁} {s₃₁₀ : square p₂₁₀ p₄₁₀ p₃₀₀ p₃₂₀} {s₃₁₂ : square p₂₁₂ p₄₁₂ p₃₀₂ p₃₂₂} {s₃₂₁ : square p₃₂₀ p₃₂₂ p₂₂₁ p₄₂₁} {s₄₁₁ : square p₄₁₀ p₄₁₂ p₄₀₁ p₄₂₁} {s₀₃₁ : square p₀₃₀ p₀₃₂ p₀₂₁ p₀₄₁} {s₁₃₀ : square p₀₃₀ p₂₃₀ p₁₂₀ p₁₄₀} {s₁₃₂ : square p₀₃₂ p₂₃₂ p₁₂₂ p₁₄₂} {s₂₃₁ : square p₂₃₀ p₂₃₂ p₂₂₁ p₂₄₁} {s₁₄₁ : square p₁₄₀ p₁₄₂ p₀₄₁ p₂₄₁} {s₀₁₃ : square p₀₁₂ p₀₁₄ p₀₀₃ p₀₂₃} {s₁₀₃ : square p₁₀₂ p₁₀₄ p₀₀₃ p₂₀₃} {s₁₂₃ : square p₁₂₂ p₁₂₄ p₀₂₃ p₂₂₃} {s₂₁₃ : square p₂₁₂ p₂₁₄ p₂₀₃ p₂₂₃} {s₁₁₄ : square p₀₁₄ p₂₁₄ p₁₀₄ p₁₂₄} (d : cube s₂₁₁ s₄₁₁ s₃₀₁ s₃₂₁ s₃₁₀ s₃₁₂) (e : cube s₀₃₁ s₂₃₁ s₁₂₁ s₁₄₁ s₁₃₀ s₁₃₂) (f : cube s₀₁₃ s₂₁₃ s₁₀₃ s₁₂₃ s₁₁₂ s₁₁₄) /- Composition of Cubes -/ include c d @[hott] def cube_concat1 : cube s₀₁₁ s₄₁₁ (s₁₀₁ ⬝h s₃₀₁) (s₁₂₁ ⬝h s₃₂₁) (s₁₁₀ ⬝v s₃₁₀) (s₁₁₂ ⬝v s₃₁₂) := by induction d; exact c omit d include e @[hott] def cube_concat2 : cube (s₀₁₁ ⬝h s₀₃₁) (s₂₁₁ ⬝h s₂₃₁) s₁₀₁ s₁₄₁ (s₁₁₀ ⬝h s₁₃₀) (s₁₁₂ ⬝h s₁₃₂) := by induction e; exact c omit e include f @[hott] def cube_concat3 : cube (s₀₁₁ ⬝v s₀₁₃) (s₂₁₁ ⬝v s₂₁₃) (s₁₀₁ ⬝v s₁₀₃) (s₁₂₁ ⬝v s₁₂₃) s₁₁₀ s₁₁₄ := by induction f; exact c omit f c @[hott] def eq_of_cube (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : transpose s₁₀₁⁻¹ᵛ ⬝h s₁₁₀ ⬝h transpose s₁₂₁ = whisker_square (eq_bot_of_square s₀₁₁) (eq_bot_of_square s₂₁₁) idp idp s₁₁₂ := by induction c; reflexivity @[hott] def eq_of_deg12_cube {s s' : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} (c : cube vrfl vrfl vrfl vrfl s s') : s = s' := by induction s; exact eq_of_cube c @[hott] def square_pathover {A B : Type _} {a a' : A} {b₁ b₂ b₃ b₄ : A → B} {f₁ : b₁ ~ b₂} {f₂ : b₃ ~ b₄} {f₃ : b₁ ~ b₃} {f₄ : b₂ ~ b₄} {p : a = a'} {q : square (f₁ a) (f₂ a) (f₃ a) (f₄ a)} {r : square (f₁ a') (f₂ a') (f₃ a') (f₄ a')} (s : cube (natural_square f₁ p) (natural_square f₂ p) (natural_square f₃ p) (natural_square f₄ p) q r) : q =[p; λ a, square (f₁ a) (f₂ a) (f₃ a) (f₄ a)] r := by induction p; apply pathover_idp_of_eq; exact eq_of_deg12_cube s -- a special case where the endpoints do not depend on `p` @[hott] def square_pathover' {f₁ : A → b₁ = b₂} {f₂ : A → b₃ = b₄} {f₃ : A → b₁ = b₃} {f₄ : A → b₂ = b₄} {p : a = a'} {q : square (f₁ a) (f₂ a) (f₃ a) (f₄ a)} {r : square (f₁ a') (f₂ a') (f₃ a') (f₄ a')} (s : cube (vdeg_square (ap f₁ p)) (vdeg_square (ap f₂ p)) (vdeg_square (ap f₃ p)) (vdeg_square (ap f₄ p)) q r) : q =[p;λ a,square (f₁ a) (f₂ a) (f₃ a) (f₄ a)] r := begin induction p, apply pathover_idp_of_eq;exact eq_of_deg12_cube s end /- Transporting along a square -/ -- TODO: remove: they are defined again below @[hott] def cube_transport110 {s₁₁₀' : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} (p : s₁₁₀ = s₁₁₀') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀' s₁₁₂ := by induction p; exact c @[hott] def cube_transport112 {s₁₁₂' : square p₀₁₂ p₂₁₂ p₁₀₂ p₁₂₂} (p : s₁₁₂ = s₁₁₂') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂':= by induction p; exact c @[hott] def cube_transport011 {s₀₁₁' : square p₀₁₀ p₀₁₂ p₀₀₁ p₀₂₁} (p : s₀₁₁ = s₀₁₁') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁' s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂ := by induction p; exact c @[hott] def cube_transport211 {s₂₁₁' : square p₂₁₀ p₂₁₂ p₂₀₁ p₂₂₁} (p : s₂₁₁ = s₂₁₁') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁' s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂ := by induction p; exact c @[hott] def cube_transport101 {s₁₀₁' : square p₁₀₀ p₁₀₂ p₀₀₁ p₂₀₁} (p : s₁₀₁ = s₁₀₁') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁ s₁₀₁' s₁₂₁ s₁₁₀ s₁₁₂ := by induction p; exact c @[hott] def cube_transport121 {s₁₂₁' : square p₁₂₀ p₁₂₂ p₀₂₁ p₂₂₁} (p : s₁₂₁ = s₁₂₁') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁' s₁₁₀ s₁₁₂ := by induction p; exact c /- Each equality between squares leads to a cube which is degenerate in one dimension. -/ @[hott] def deg1_cube {s₁₁₀' : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} (p : s₁₁₀ = s₁₁₀') : cube s₁₁₀ s₁₁₀' hrfl hrfl vrfl vrfl := by induction p; exact rfl1 @[hott] def deg2_cube {s₁₁₀' : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} (p : s₁₁₀ = s₁₁₀') : cube hrfl hrfl s₁₁₀ s₁₁₀' hrfl hrfl := by induction p; exact rfl2 @[hott] def deg3_cube {s₁₁₀' : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} (p : s₁₁₀ = s₁₁₀') : cube vrfl vrfl vrfl vrfl s₁₁₀ s₁₁₀' := by induction p; exact rfl3 /- For each square of parralel equations, there are cubes where the square's sides appear in a degenerated way and two opposite sides are ids's -/ section variables {a₀ a₁ : A} {p₀₀ p₀₂ p₂₀ p₂₂ : a₀ = a₁} {s₁₀ : p₀₀ = p₂₀} {s₁₂ : p₀₂ = p₂₂} {s₀₁ : p₀₀ = p₀₂} {s₂₁ : p₂₀ = p₂₂} (sq : square s₁₀ s₁₂ s₀₁ s₂₁) include sq @[hott] def ids3_cube_of_square : cube (hdeg_square s₀₁) (hdeg_square s₂₁) (hdeg_square s₁₀) (hdeg_square s₁₂) ids ids := by induction p₀₀; induction sq; apply idc @[hott] def ids1_cube_of_square : cube ids ids (vdeg_square s₁₀) (vdeg_square s₁₂) (hdeg_square s₀₁) (hdeg_square s₂₁) := by induction p₀₀; induction sq; apply idc @[hott] def ids2_cube_of_square : cube (vdeg_square s₁₀) (vdeg_square s₁₂) ids ids (vdeg_square s₀₁) (vdeg_square s₂₁) := by induction p₀₀; induction sq; apply idc end /- Cube fillers -/ section cube_fillers variables (s₁₁₀ s₁₁₂ s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁) @[hott] def cube_fill110 : Σ lid, cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ lid s₁₁₂ := begin induction s₀₁₁, induction s₂₁₁, let fillsq := square_fill_l (eq_of_vdeg_square s₁₀₁) (eq_of_hdeg_square s₁₁₂) (eq_of_vdeg_square s₁₂₁), apply sigma.mk, apply cube_transport101 (to_left_inv (vdeg_square_equiv _ _) s₁₀₁), apply cube_transport112 (to_left_inv (hdeg_square_equiv _ _) s₁₁₂), apply cube_transport121 (to_left_inv (vdeg_square_equiv _ _) s₁₂₁), apply ids1_cube_of_square, exact fillsq.2 end @[hott] def cube_fill112 : Σ lid, cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ lid := begin induction s₀₁₁, induction s₂₁₁, let fillsq := square_fill_r (eq_of_vdeg_square s₁₀₁) (eq_of_hdeg_square s₁₁₀) (eq_of_vdeg_square s₁₂₁), apply sigma.mk, apply cube_transport101 (to_left_inv (vdeg_square_equiv _ _) s₁₀₁), apply cube_transport110 (to_left_inv (hdeg_square_equiv _ _) s₁₁₀), apply cube_transport121 (to_left_inv (vdeg_square_equiv _ _) s₁₂₁), apply ids1_cube_of_square, exact fillsq.2, end @[hott] def cube_fill011 : Σ lid, cube lid s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂ := begin induction s₁₀₁, induction s₁₂₁, let fillsq := square_fill_t (eq_of_vdeg_square s₁₁₀) (eq_of_vdeg_square s₁₁₂) (eq_of_vdeg_square s₂₁₁), apply sigma.mk, apply cube_transport110 (to_left_inv (vdeg_square_equiv _ _) s₁₁₀), apply cube_transport211 (to_left_inv (vdeg_square_equiv _ _) s₂₁₁), apply cube_transport112 (to_left_inv (vdeg_square_equiv _ _) s₁₁₂), apply ids2_cube_of_square, exact fillsq.2, end @[hott] def cube_fill211 : Σ lid, cube s₀₁₁ lid s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂ := begin induction s₁₀₁, induction s₁₂₁, let fillsq := square_fill_b (eq_of_vdeg_square s₀₁₁) (eq_of_vdeg_square s₁₁₀) (eq_of_vdeg_square s₁₁₂), apply sigma.mk, apply cube_transport011 (to_left_inv (vdeg_square_equiv _ _) s₀₁₁), apply cube_transport110 (to_left_inv (vdeg_square_equiv _ _) s₁₁₀), apply cube_transport112 (to_left_inv (vdeg_square_equiv _ _) s₁₁₂), apply ids2_cube_of_square, exact fillsq.2, end @[hott] def cube_fill101 : Σ lid, cube s₀₁₁ s₂₁₁ lid s₁₂₁ s₁₁₀ s₁₁₂ := begin induction s₁₁₀, induction s₁₁₂, let fillsq := square_fill_t (eq_of_hdeg_square s₀₁₁) (eq_of_hdeg_square s₂₁₁) (eq_of_hdeg_square s₁₂₁), apply sigma.mk, apply cube_transport011 (to_left_inv (hdeg_square_equiv _ _) s₀₁₁), apply cube_transport211 (to_left_inv (hdeg_square_equiv _ _) s₂₁₁), apply cube_transport121 (to_left_inv (hdeg_square_equiv _ _) s₁₂₁), apply ids3_cube_of_square, exact fillsq.2, end @[hott] def cube_fill121 : Σ lid, cube s₀₁₁ s₂₁₁ s₁₀₁ lid s₁₁₀ s₁₁₂ := begin induction s₁₁₀, induction s₁₁₂, let fillsq := square_fill_b (eq_of_hdeg_square s₁₀₁) (eq_of_hdeg_square s₀₁₁) (eq_of_hdeg_square s₂₁₁), apply sigma.mk, apply cube_transport101 (to_left_inv (hdeg_square_equiv _ _) s₁₀₁), apply cube_transport011 (to_left_inv (hdeg_square_equiv _ _) s₀₁₁), apply cube_transport211 (to_left_inv (hdeg_square_equiv _ _) s₂₁₁), apply ids3_cube_of_square, exact fillsq.2, end end cube_fillers /- Apply a non-dependent function to an entire cube -/ include c @[hott] def apc (f : A → B) : cube (aps f s₀₁₁) (aps f s₂₁₁) (aps f s₁₀₁) (aps f s₁₂₁) (aps f s₁₁₀) (aps f s₁₁₂) := by induction c; exact idc omit c /- Transpose a cube (swap dimensions) -/ include c @[hott] def transpose12 : cube s₁₀₁ s₁₂₁ s₀₁₁ s₂₁₁ (transpose s₁₁₀) (transpose s₁₁₂) := by induction c; exact idc @[hott] def transpose13 : cube s₁₁₀ s₁₁₂ (transpose s₁₀₁) (transpose s₁₂₁) s₀₁₁ s₂₁₁ := by induction c; exact idc @[hott] def transpose23 : cube (transpose s₀₁₁) (transpose s₂₁₁) (transpose s₁₁₀) (transpose s₁₁₂) (transpose s₁₀₁) (transpose s₁₂₁) := by induction c; exact idc omit c /- Inverting a cube along one dimension -/ include c @[hott] def cube_inverse1 : cube s₂₁₁ s₀₁₁ s₁₀₁⁻¹ʰ s₁₂₁⁻¹ʰ s₁₁₀⁻¹ᵛ s₁₁₂⁻¹ᵛ := by induction c; exact idc @[hott] def cube_inverse2 : cube s₀₁₁⁻¹ʰ s₂₁₁⁻¹ʰ s₁₂₁ s₁₀₁ s₁₁₀⁻¹ʰ s₁₁₂⁻¹ʰ := by induction c; exact idc @[hott] def cube_inverse3 : cube s₀₁₁⁻¹ᵛ s₂₁₁⁻¹ᵛ s₁₀₁⁻¹ᵛ s₁₂₁⁻¹ᵛ s₁₁₂ s₁₁₀ := by induction c; exact idc omit c @[hott] def eq_concat1 {s₀₁₁' : square p₀₁₀ p₀₁₂ p₀₀₁ p₀₂₁} (r : s₀₁₁' = s₀₁₁) (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁' s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂ := by induction r; exact c @[hott] def concat1_eq {s₂₁₁' : square p₂₁₀ p₂₁₂ p₂₀₁ p₂₂₁} (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) (r : s₂₁₁ = s₂₁₁') : cube s₀₁₁ s₂₁₁' s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂ := by induction r; exact c @[hott] def eq_concat2 {s₁₀₁' : square p₁₀₀ p₁₀₂ p₀₀₁ p₂₀₁} (r : s₁₀₁' = s₁₀₁) (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁ s₁₀₁' s₁₂₁ s₁₁₀ s₁₁₂ := by induction r; exact c @[hott] def concat2_eq {s₁₂₁' : square p₁₂₀ p₁₂₂ p₀₂₁ p₂₂₁} (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) (r : s₁₂₁ = s₁₂₁') : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁' s₁₁₀ s₁₁₂ := by induction r; exact c @[hott] def eq_concat3 {s₁₁₀' : square p₀₁₀ p₂₁₀ p₁₀₀ p₁₂₀} (r : s₁₁₀' = s₁₁₀) (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀' s₁₁₂ := by induction r; exact c @[hott] def concat3_eq {s₁₁₂' : square p₀₁₂ p₂₁₂ p₁₀₂ p₁₂₂} (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) (r : s₁₁₂ = s₁₁₂') : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂' := by induction r; exact c infix ` ⬝1 `:75 := cube_concat1 infix ` ⬝2 `:75 := cube_concat2 infix ` ⬝3 `:75 := cube_concat3 infixr ` ⬝p1 `:75 := eq_concat1 infixl ` ⬝1p `:75 := concat1_eq infixr ` ⬝p2 `:75 := eq_concat2 infixl ` ⬝2p `:75 := concat2_eq infixr ` ⬝p3 `:75 := eq_concat3 infixl ` ⬝3p `:75 := concat3_eq @[hott] def whisker001 {p₀₀₁' : a₀₀₀ = a₀₀₂} (q : p₀₀₁' = p₀₀₁) (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube (q ⬝ph s₀₁₁) s₂₁₁ (q ⬝ph s₁₀₁) s₁₂₁ s₁₁₀ s₁₁₂ := by induction q; exact c @[hott] def whisker021 {p₀₂₁' : a₀₂₀ = a₀₂₂} (q : p₀₂₁' = p₀₂₁) (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube (s₀₁₁ ⬝hp q⁻¹) s₂₁₁ s₁₀₁ (q ⬝ph s₁₂₁) s₁₁₀ s₁₁₂ := by induction q; exact c @[hott] def whisker021' {p₀₂₁' : a₀₂₀ = a₀₂₂} (q : p₀₂₁ = p₀₂₁') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube (s₀₁₁ ⬝hp q) s₂₁₁ s₁₀₁ (q⁻¹ ⬝ph s₁₂₁) s₁₁₀ s₁₁₂ := by induction q; exact c @[hott] def whisker201 {p₂₀₁' : a₂₀₀ = a₂₀₂} (q : p₂₀₁' = p₂₀₁) (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ (q ⬝ph s₂₁₁) (s₁₀₁ ⬝hp q⁻¹) s₁₂₁ s₁₁₀ s₁₁₂ := by induction q; exact c @[hott] def whisker201' {p₂₀₁' : a₂₀₀ = a₂₀₂} (q : p₂₀₁ = p₂₀₁') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ (q⁻¹ ⬝ph s₂₁₁) (s₁₀₁ ⬝hp q) s₁₂₁ s₁₁₀ s₁₁₂ := by induction q; exact c @[hott] def whisker221 {p₂₂₁' : a₂₂₀ = a₂₂₂} (q : p₂₂₁ = p₂₂₁') (c : cube s₀₁₁ s₂₁₁ s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ (s₂₁₁ ⬝hp q) s₁₀₁ (s₁₂₁ ⬝hp q) s₁₁₀ s₁₁₂ := by induction q; exact c @[hott] def move221 {p₂₂₁' : a₂₂₀ = a₂₂₂} {s₁₂₁ : square p₁₂₀ p₁₂₂ p₀₂₁ p₂₂₁'} (q : p₂₂₁ = p₂₂₁') (c : cube s₀₁₁ (s₂₁₁ ⬝hp q) s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁ s₁₀₁ (s₁₂₁ ⬝hp q⁻¹) s₁₁₀ s₁₁₂ := by induction q; exact c @[hott] def move201 {p₂₀₁' : a₂₀₀ = a₂₀₂} {s₁₀₁ : square p₁₀₀ p₁₀₂ p₀₀₁ p₂₀₁'} (q : p₂₀₁' = p₂₀₁) (c : cube s₀₁₁ (q ⬝ph s₂₁₁) s₁₀₁ s₁₂₁ s₁₁₀ s₁₁₂) : cube s₀₁₁ s₂₁₁ (s₁₀₁ ⬝hp q) s₁₂₁ s₁₁₀ s₁₁₂ := by induction q; exact c end eq end hott
4b190cd3a682619d73f283121610adb5bf86329a
d8820d2c92be8052d13f9c8f8c483a6e15c5f566
/src/M40001/M40001_C1.lean
e213ede6c7d096c50dc2011e0ae5efea94f5f647
[]
no_license
JasonKYi/M4000x_LEAN_formalisation
4a19b84f6d0fe2e214485b8532e21cd34996c4b1
6e99793f2fcbe88596e27644f430e46aa2a464df
refs/heads/master
1,599,755,414,708
1,589,494,604,000
1,589,494,604,000
221,759,483
8
1
null
1,589,494,605,000
1,573,755,201,000
Lean
UTF-8
Lean
false
false
12,702
lean
-- begin header import tactic.ring namespace M40001 -- end header /- Section Sets and Logic -/ /- Sub-section 1.3 Relations -/ /- Sub-section 1.3.1 The Law of the Excluded Middle -/ /- The Law of the Excluded Middle states that for any proposition $P$, either $P$, or its negation $¬ P$ is true. -/ /- Theorem If $P$ is a proposition, then $ ¬ (¬ P) ⇔ P$. -/ theorem not_not_P_is_P (P : Prop) : ¬ (¬ P) ↔ P := begin -- We need to show that $¬ (¬ P)$ is true 'if and only if' $P$ is true. So we consider both directions of the implication. split, -- Let's first consider the forward implication, i.e. $¬ (¬ P)$ is true implies that $P$ is also true. intro hp, -- We will prove this by contradiction so given $¬ (¬ P)$ is true let's make a dubious assumption that $¬ P$ is true. apply classical.by_contradiction, intro hnp, -- But $¬ P$ is true implies that $¬ (¬ P)$ is false which is a contradiction to our premis that $¬ (¬ P)$ is true. Thus, $¬ P$ must be false which by the Law of the excluded middle implies $P$ is true, resulting in the first part of the proof! contradiction, -- Now we need to proof that the backwards implication is also correct, i.e. $P$ is true implies $¬ (¬ P)$ is also true. -- To show that $¬ (¬ P)$ is true when $P$ is true, we can simply show that $P$ is true implies $¬ P$ is false. intros hp hnp, -- But this is true by definition, so we have nothing left to prove! contradiction, end /- Remark. Note that for many simple propositions alike the one above, LEAN is able to use automation to complete our proof. Indeed, by using the tactic $\tt{finish}$, the above proof becomes a one-liner! -/ /- Theorem If $P$ is a proposition, then $ ¬ (¬ P) ⇔ P$. (This time proven using $\tt{finish}$) -/ theorem not_not_P_is_P_tauto (P : Prop) : ¬ (¬ P) ↔ P := begin -- As we can see, $\tt{finish}$ finished the proof! finish end /- Sub-section 1.3.2 De Morgan's Laws -/ /- Theorem (1) Let $P$ and $Q$ be propositions, then $¬ (P ∨ Q) ⇔ (¬ P) ∧ (¬ Q)$ -/ theorem demorgan_a (P Q : Prop) : ¬ (P ∨ Q) ↔ (¬ P) ∧ (¬ Q) := begin -- Again we have an 'if and only if' statement so we need to consider both directions of the argument. split, -- We first show that $¬ (P ∨ Q) ⇒ ¬ P ∧ ¬ Q$ through contradiction. Suppose $¬ (P ∨ Q)$ is true, and we make a dubious assumption that $P$ is true. intro h, split, intro hp, -- But then $¬ (P ∨ Q)$ is false! A contradiction! Therefore $P$ must be false. apply h, left, exact hp, -- Similarly, supposing $Q$ is true also results in a contradiction! Therefore $Q$ is also false. intro hq, apply h, right, exact hq, -- With that, we now focus our attention on the backwards implication, i.e. $(¬ P) ∧ (¬ Q) ⇒ ¬ (P ∨ Q)$. -- Again, let's approach this by contradiction. Given $¬ P ∧ ¬ Q$ suppose we have $P$ or $Q$. intros h hpq, -- But $P$ can't be true, as we have $¬ P$, cases h with hnp hnq, cases hpq with hp hq, contradiction, -- Therefore, $Q$ must be true. -- But $Q$ also can't be true as we have $¬ Q$! Contradiction! Therefore, given $(¬ P) ∧ (¬ Q)$, $(P ∨ Q)$ must not be true, i.e. $¬ (P ∨ Q)$ is true, which is exactly what we need! contradiction, end /- Theorem (2) Let $P$ and $Q$ be propositions, then $¬ (P ∧ Q) ⇔ (¬ P) ∨ (¬ Q)$ -/ theorem demorgan_b (P Q : Prop) : ¬ (P ∧ Q) ↔ (¬ P) ∨ (¬ Q) := begin -- Once again, we have an 'if and only' if statement, therefore, we need to consider both directions. split, -- We first show that $¬ (P ∧ Q) ⇒ ¬ P ∨ ¬ Q$. Suppose $¬ (P ∧ Q)$. intro h, -- By the law of the excluded middle, we have either $P$ or $¬ P$. cases (classical.em P) with hp hnp, -- Suppose first that we have $P$. Then, we must have $¬ Q$ as having $Q$ implies $P ∧ Q$ which contradicts with $¬ (P ∧ Q)$, have hnq : ¬ Q, intro hq, have hpq : P ∧ Q, split, exact hp, exact hq, contradiction, -- hence, we have $¬ P ∨ ¬ Q$. right, exact hnq, -- Now let's suppose $¬ P$. But as $¬ P$ implies $¬ P ∨ ¬ Q$, we have nothing left to prove. left, exact hnp, -- With the forward implication dealt with, let's consider the reverse, i.e. $¬ P ∨ ¬ Q ⇒ ¬ (P ∧ Q)$. -- Given $¬ P ∨ ¬ Q$ let's suppose that $P ∧ Q$. intros h hpq, -- But this is a contradiction as $P ∧ Q$ implies that neither $P$ nor $Q$ is false! cases h with hnp hnq, cases hpq with hp hq, contradiction, cases hpq with hp hq, -- Therefore, $P ∧ Q$ must be false by contradiction which results in the second part of our proof! contradiction, end /- Excercise. As you can see, writing LEAN proofs is so much more fun than drawing truth tables! Why don't you try it out by proving $\lnot P \iff (P \implies \tt{false})$ <a href="https://leanprover-community.github.io/lean-web-editor/#url=https%3A%2F%2Fraw.githubusercontent.com%2FJasonKYi%2FM4000x_LEAN_formalisation%2Fmaster%2Fsrc%2FExercises%2FExercies1.lean">here</a>? -/ /- Sub-section 1.3.3 Transitivity of Implications, and the Contrapositive -/ /- Theorem $⇒$ is transitive, i.e. if $P$, $Q$, and $R$ are propositions, then $P ⇒ Q$ and $Q ⇒ R$ means $P ⇒ R$. -/ theorem imp_trans (P Q R : Prop) : (P → Q) ∧ (Q → R) → (P → R) := begin -- Suppose $P ⇒ Q$ and $Q ⇒ R$ are both true, we then would like to prove that $P ⇒ R$ is true. intro h, cases h with hpq hqr, -- Say that $P$ is true, intro hp, -- then by $P ⇒ Q$, $Q$ must be true. But we also have $Q ⇒ R$, therefore $R$ is also true, which is exactly what we wish to prove! exact hqr (hpq hp), end /- Theorem If $P$ and $Q$ are propositions, then $(P ⇒ Q) ⇔ (¬ Q ⇒ ¬ P)$. -/ theorem contra (P Q : Prop) : (P → Q) ↔ (¬ Q → ¬ P) := begin -- Let's first consider the implication from left to right, i.e. $(P ⇒ Q) ⇒ (¬ Q ⇒ ¬ P)$. split, -- We will prove this by contradiction, so suppose we have $P ⇒ Q$, $¬ Q$ and not $¬ P$. intros h hnq hp, -- But not $¬ P$ is simply $P$, and $P$ implies $Q$, a contradiction to $¬ Q$! Therefore, $P ⇒ Q$ must imply $¬ Q ⇒ ¬ P$ as required. exact hnq (h hp), -- Now lets consider reverse, $(¬ Q ⇒ ¬ P) ⇒ (P ⇒ Q)$. Suppose we have $¬ Q ⇒ ¬ P$ and $P$. intros h hp, -- If $Q$ is true then we have nothing left to prove, so suppose $¬ Q$ is true. cases (classical.em Q) with hq hnq, exact hq, exfalso, -- But $¬ Q$ implies $¬ P$ which contradicts with $P$, therefore, $¬ Q$ must be false as requied. exact h hnq hp, end /- Excercise. What can we deduce if we apply the contrapositive to $\lnot Q \implies \lnot P$? Try it out <a href="https://leanprover-community.github.io/lean-web-editor/#url=https%3A%2F%2Fraw.githubusercontent.com%2FJasonKYi%2FM4000x_LEAN_formalisation%2Fmaster%2Fsrc%2FExercises%2FExercies2.lean">here</a>? -/ /- Sub-section 1.3.4 Distributivity -/ /- Theorem (1) If $P$, $Q$, and $R$ are propositions. Then, $P ∧ (Q ∨ R) ⇔ (P ∧ Q) ∨ (P ∧ R)$; -/ theorem dis_and_or (P Q R : Prop) : P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := begin -- Let's first consider the foward implication, $P ∧ (Q ∨ R) ⇒ (P ∧ Q) ∨ (P ∧ R)$ split, -- Suppose $P$ is true and either $Q$ or $R$ is true. rintro ⟨hp, hqr⟩, -- But this means either $P$ and $Q$ is true or $P$ and $R$ is true which is exactly what we need. cases hqr with hq hr, left, split, repeat {assumption}, right, split, repeat {assumption}, -- With that, we now need to prove the backwards implication. Suppose $(P ∧ Q) ∨ (P ∧ R)$. intro h, -- Let's consider both cases. cases h with hpq hpr, -- If $P ∧ Q$ is true, then $P$ is true and $Q ∨ R$ is also true. cases hpq with hp hq, split, assumption, left, assumption, -- Similarly, is $P ∧ R$ is true, then $P$ is true and $Q ∨ R$ is also true. cases hpr with hp hr, -- Therefore, by considering bothe cases, we see that either $P ∧ Q$ or $P ∧ R$ implies $P ∧ (Q ∨ R)$. split, assumption, right, assumption, end /- Theorem (2) $P ∨ (Q ∧ R) ⇔ (P ∨ Q) ∧ (P ∨ R)$. -/ theorem dis_or_and (P Q R : Prop) : P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) := begin -- We first consider the forward implication $P ∨ (Q ∧ R) ⇒ (P ∨ Q) ∧ (P ∨ R)$. split, -- Suppose we have $P ∨ (Q ∧ R)$, then either $P$ is true or $Q$ and $R$ is true$. intro h, -- Let's consider both cases. If $P$ is true, then both $P ∨ Q$ and $P ∨ R$ are true. cases h with hp hqr, split, repeat {left, assumption}, -- Similarly, if $P$ and $Q$ are true, then both $P ∨ Q$ and $P ∨ R$ are true. cases hqr with hq hr, split, repeat {right, assumption}, -- Now let's consider the backwards implication. Suppose that $(P ∨ Q)$ and $(P ∨ R)$ is true and lets consider all the cases. intro h, cases h with hpq hpr, -- If $P$ is true the $P ∨ (Q ∧ R)$ is also true. cases hpq with hp hq, cases hpr with hp hr, repeat {left, assumption}, -- If $¬ P$ is true then from $(P ∨ Q)$ and $(P ∨ R)$, $Q$ and $R$ must be true, and therefore, $P ∨ (Q ∧ R)$ is also true. cases hpr with hp hr, left, assumption, right, split, repeat {assumption}, end /- Sub-section 1.7 Sets and Propositions -/ universe u variable {Ω : Type*} -- Let $Ω$ be a fixed set with subsets $X$ and $Y$, then /- Theorem (1) $\bar{X ∪ Y} = \bar{X} ∩ \bar{Y}$. -/ theorem de_morg_set_a (X Y : set Ω) : - (X ∪ Y) = - X ∩ - Y := begin -- What exactly does $\bar{(X ∪ Y)}$ and $\bar{X} ∩ \bar{Y}$ mean? Well, lets find out! ext, -- As we can see, to show that $\bar{X ∪ Y} = \bar{X} ∩ \bar{Y}$, we in fact need to prove $x ∈ \bar{(X ∪ Y)} ↔ x ∈ \bar{X} ∩ \bar{Y}$. split, -- So let's first prove that $x ∈ \bar{X ∪ Y} → x ∈ \bar{X} ∩ \bar{Y}$. Suppose $x ∈ \bar{X ∪ Y}$, then $x$ is not in $X$ and $x$ is not in $Y$. dsimp, intro h, push_neg at h, -- But this is exactly what we need! assumption, -- Now, let's consider the backwards implication. Similarly, $x ∈ \bar{X} ∩ \bar{Y}$ means $x$ is not in $X$ and $x$ is not in $Y$. dsimp, intro h, -- But this is what $x ∈ \bar{X ∪ Y}$ means, so we're done! push_neg, assumption end /- Theorem (2) $\bar{X ∩ Y} = \bar{X} ∪ \bar{Y}$. -/ theorem de_morg_set_b (X Y : set Ω) : - (X ∩ Y) = - X ∪ - Y := begin -- Rather than proving this manually, why not try some automation this time. ext, finish end /- Remark. Would you look at that! Proving the de Morgan's law with one single line. Now thats a nice proof if I ever seen one! -/ /- Sub-section 1.7.1 "For All" and "There Exists" -/ /- Theorem Given a propositon $P$ whose truth value is dependent on $x ∈ X$, then $∀ x ∈ X, ¬ P(x) ⇔ ¬ (∃ x ∈ X, P(x))$, and -/ theorem neg_exist_is_all (X : Type) (P : X → Prop) : (∀ x : X, ¬ P x) ↔ ¬ (∃ x : X, P x) := begin -- (⇒) Let's first prove the forward implication, i.e. suppose that $∀ x ∈ X, ¬ P(x)$, we need to show that $¬ ∃ x ∈ X, P(x)$. split, -- Let's prove this by contradiction! Let's suppose that $¬ ∃ x ∈ X, P(x)$ is in fact $\tt{false}$ and there is actually a $x$ out there where $P(x)$ is true! rintro h ⟨x, hx⟩, -- But, by our assumption $∀ x ∈ X$, $P(x)$ is false, thus a contradiction! from (h x) hx, -- (⇐) Now let's consider the other direction. Suppose that there does not exist a $x$ such that $P(x)$ is true, i.e. $¬ ∃ x ∈ X, P(x)$. intro ha, -- Similarly, let's suppose that $∀ x ∈ X, ¬P x$ is not true. intros x hx, -- But then, there must be a $x$ such that $P(x)$ is true, again, a contradiction! have : ∃ (x : X), P x, existsi x, assumption, contradiction, end /- Theorem $¬ (∀ x ∈ X, ¬ P(x)) ⇔ ∃ x ∈ X, P(x)$. -/ theorem neg_all_is_exist (X : Type) (P : X → Prop) : ¬ (∀ x : X, ¬ P x) ↔ ∃ x : X, P x := begin -- Now that we have gone through quite a lot of LEAN proofs, try to understand this one yourself! split, {intro h, apply classical.by_contradiction, push_neg, contradiction }, {rintro ⟨x, hx⟩ h, from (h x) hx } end end M40001
f191d8e7c187f5c590f80c8238e3a6bdd868ee4e
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/indicator_function.lean
e3da1ab95fb80ca86ff4b48013cf62075faaf6e4
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
8,534
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.pi_instances import data.set.disjointed import data.support /-! # Indicator function `indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `0` otherwise. ## Implementation note In mathematics, an indicator function or a characteristic function is a function used to indicate membership of an element in a set `s`, having the value `1` for all elements of `s` and the value `0` otherwise. But since it is usually used to restrict a function to a certain set `s`, we let the indicator function take the value `f x` for some function `f`, instead of `1`. If the usual indicator function is needed, just set `f` to be the constant function `λx, 1`. ## Tags indicator, characteristic -/ noncomputable theory open_locale classical big_operators namespace set universes u v variables {α : Type u} {β : Type v} section has_zero variables [has_zero β] {s t : set α} {f g : α → β} {a : α} /-- `indicator s f a` is `f a` if `a ∈ s`, `0` otherwise. -/ @[reducible] def indicator (s : set α) (f : α → β) : α → β := λ x, if x ∈ s then f x else 0 lemma indicator_apply (s : set α) (f : α → β) (a : α) : indicator s f a = if a ∈ s then f a else 0 := rfl @[simp] lemma indicator_of_mem (h : a ∈ s) (f : α → β) : indicator s f a = f a := if_pos h @[simp] lemma indicator_of_not_mem (h : a ∉ s) (f : α → β) : indicator s f a = 0 := if_neg h lemma eq_on_indicator : eq_on (indicator s f) f s := λ x hx, indicator_of_mem hx f lemma support_indicator : function.support (s.indicator f) ⊆ s := λ x hx, hx.imp_symm (λ h, indicator_of_not_mem h f) @[simp] lemma indicator_range_comp {ι : Sort*} (f : ι → α) (g : α → β) : indicator (range f) g ∘ f = g ∘ f := piecewise_range_comp _ _ _ lemma indicator_congr (h : ∀ a ∈ s, f a = g a) : indicator s f = indicator s g := funext $ λx, by { simp only [indicator], split_ifs, { exact h _ h_1 }, refl } @[simp] lemma indicator_univ (f : α → β) : indicator (univ : set α) f = f := funext $ λx, indicator_of_mem (mem_univ _) f @[simp] lemma indicator_empty (f : α → β) : indicator (∅ : set α) f = λa, 0 := funext $ λx, indicator_of_not_mem (not_mem_empty _) f variable (β) @[simp] lemma indicator_zero (s : set α) : indicator s (λx, (0:β)) = λx, (0:β) := funext $ λx, by { simp only [indicator], split_ifs, refl, refl } variable {β} lemma indicator_indicator (s t : set α) (f : α → β) : indicator s (indicator t f) = indicator (s ∩ t) f := funext $ λx, by { simp only [indicator], split_ifs, repeat {simp * at * {contextual := tt}} } lemma indicator_comp_of_zero {γ} [has_zero γ] {g : β → γ} (hg : g 0 = 0) : indicator s (g ∘ f) = λ a, indicator (f '' s) g (indicator s f a) := begin funext, simp only [indicator], split_ifs with h h', { refl }, { have := mem_image_of_mem _ h, contradiction }, { rwa eq_comm }, refl end lemma indicator_preimage (s : set α) (f : α → β) (B : set β) : (indicator s f)⁻¹' B = s ∩ f ⁻¹' B ∪ sᶜ ∩ (λa:α, (0:β)) ⁻¹' B := by { rw [indicator, if_preimage] } lemma indicator_preimage_of_not_mem (s : set α) (f : α → β) {t : set β} (ht : (0:β) ∉ t) : (indicator s f)⁻¹' t = s ∩ f ⁻¹' t := by simp [indicator_preimage, set.preimage_const_of_not_mem ht] lemma mem_range_indicator {r : β} {s : set α} {f : α → β} : r ∈ range (indicator s f) ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by simp [indicator, ite_eq_iff, exists_or_distrib, eq_univ_iff_forall, and_comm, or_comm, @eq_comm _ r 0] end has_zero section add_monoid variables [add_monoid β] {s t : set α} {f g : α → β} {a : α} lemma indicator_union_of_not_mem_inter (h : a ∉ s ∩ t) (f : α → β) : indicator (s ∪ t) f a = indicator s f a + indicator t f a := by { simp only [indicator], split_ifs, repeat {simp * at * {contextual := tt}} } lemma indicator_union_of_disjoint (h : disjoint s t) (f : α → β) : indicator (s ∪ t) f = λa, indicator s f a + indicator t f a := funext $ λa, indicator_union_of_not_mem_inter (by { convert not_mem_empty a, have := disjoint.eq_bot h, assumption }) _ lemma indicator_add (s : set α) (f g : α → β) : indicator s (λa, f a + g a) = λa, indicator s f a + indicator s g a := by { funext, simp only [indicator], split_ifs, { refl }, rw add_zero } variables (β) instance is_add_monoid_hom.indicator (s : set α) : is_add_monoid_hom (λf:α → β, indicator s f) := { map_add := λ _ _, indicator_add _ _ _, map_zero := indicator_zero _ _ } variables {β} {𝕜 : Type*} [monoid 𝕜] [distrib_mul_action 𝕜 β] lemma indicator_smul (s : set α) (r : 𝕜) (f : α → β) : indicator s (λ (x : α), r • f x) = λ (x : α), r • indicator s f x := by { simp only [indicator], funext, split_ifs, refl, exact (smul_zero r).symm } end add_monoid section add_group variables [add_group β] {s t : set α} {f g : α → β} {a : α} variables (β) instance is_add_group_hom.indicator (s : set α) : is_add_group_hom (λf:α → β, indicator s f) := { .. is_add_monoid_hom.indicator β s } variables {β} lemma indicator_neg (s : set α) (f : α → β) : indicator s (λa, - f a) = λa, - indicator s f a := show indicator s (- f) = - indicator s f, from is_add_group_hom.map_neg _ _ lemma indicator_sub (s : set α) (f g : α → β) : indicator s (λa, f a - g a) = λa, indicator s f a - indicator s g a := show indicator s (f - g) = indicator s f - indicator s g, from is_add_group_hom.map_sub _ _ _ lemma indicator_compl (s : set α) (f : α → β) : indicator sᶜ f = λ a, f a - indicator s f a := begin funext, simp only [indicator], split_ifs with h₁ h₂, { rw sub_zero }, { rw sub_self }, { rw ← mem_compl_iff at h₂, contradiction } end lemma indicator_finset_sum {β} [add_comm_monoid β] {ι : Type*} (I : finset ι) (s : set α) (f : ι → α → β) : indicator s (∑ i in I, f i) = ∑ i in I, indicator s (f i) := begin convert (finset.sum_hom _ _).symm, split, exact indicator_zero _ _ end lemma indicator_finset_bUnion {β} [add_comm_monoid β] {ι} (I : finset ι) (s : ι → set α) {f : α → β} : (∀ (i ∈ I) (j ∈ I), i ≠ j → s i ∩ s j = ∅) → indicator (⋃ i ∈ I, s i) f = λ a, ∑ i in I, indicator (s i) f a := begin refine finset.induction_on I _ _, assume h, { funext, simp }, assume a I haI ih hI, funext, simp only [haI, finset.sum_insert, not_false_iff], rw [finset.bUnion_insert, indicator_union_of_not_mem_inter, ih _], { assume i hi j hj hij, exact hI i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj) hij }, simp only [not_exists, exists_prop, mem_Union, mem_inter_eq, not_and], assume hx a' ha', have := hI a (finset.mem_insert_self _ _) a' (finset.mem_insert_of_mem ha') _, { assume h, have h := mem_inter hx h, rw this at h, exact not_mem_empty _ h }, { assume h, rw h at haI, contradiction } end end add_group section mul_zero_class variables [mul_zero_class β] {s t : set α} {f g : α → β} {a : α} lemma indicator_mul (s : set α) (f g : α → β) : indicator s (λa, f a * g a) = λa, indicator s f a * indicator s g a := by { funext, simp only [indicator], split_ifs, { refl }, rw mul_zero } end mul_zero_class section order variables [has_zero β] [preorder β] {s t : set α} {f g : α → β} {a : α} lemma indicator_nonneg' (h : a ∈ s → 0 ≤ f a) : 0 ≤ indicator s f a := by { rw indicator_apply, split_ifs with as, { exact h as }, refl } lemma indicator_nonneg (h : ∀ a ∈ s, 0 ≤ f a) : ∀ a, 0 ≤ indicator s f a := λ a, indicator_nonneg' (h a) lemma indicator_nonpos' (h : a ∈ s → f a ≤ 0) : indicator s f a ≤ 0 := by { rw indicator_apply, split_ifs with as, { exact h as }, refl } lemma indicator_nonpos (h : ∀ a ∈ s, f a ≤ 0) : ∀ a, indicator s f a ≤ 0 := λ a, indicator_nonpos' (h a) @[mono] lemma indicator_le_indicator (h : f a ≤ g a) : indicator s f a ≤ indicator s g a := by { simp only [indicator], split_ifs with ha, { exact h }, refl } lemma indicator_le_indicator_of_subset (h : s ⊆ t) (hf : ∀a, 0 ≤ f a) (a : α) : indicator s f a ≤ indicator t f a := begin simp only [indicator], split_ifs with h₁, { refl }, { have := h h₁, contradiction }, { exact hf a }, { refl } end end order end set
eb8eb22dad7809d9b266f972b007aea4f4a10a07
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/ring_theory/finiteness.lean
e92ccb25f6b935f011e40c84ac5fa3359afb777e
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
39,774
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import group_theory.finiteness import ring_theory.algebra_tower import ring_theory.ideal.quotient import ring_theory.noetherian /-! # Finiteness conditions in commutative algebra In this file we define several notions of finiteness that are common in commutative algebra. ## Main declarations - `module.finite`, `algebra.finite`, `ring_hom.finite`, `alg_hom.finite` all of these express that some object is finitely generated *as module* over some base ring. - `algebra.finite_type`, `ring_hom.finite_type`, `alg_hom.finite_type` all of these express that some object is finitely generated *as algebra* over some base ring. - `algebra.finite_presentation`, `ring_hom.finite_presentation`, `alg_hom.finite_presentation` all of these express that some object is finitely presented *as algebra* over some base ring. -/ open function (surjective) open_locale big_operators polynomial section module_and_algebra variables (R A B M N : Type*) /-- A module over a semiring is `finite` if it is finitely generated as a module. -/ class module.finite [semiring R] [add_comm_monoid M] [module R M] : Prop := (out : (⊤ : submodule R M).fg) /-- An algebra over a commutative semiring is of `finite_type` if it is finitely generated over the base ring as algebra. -/ class algebra.finite_type [comm_semiring R] [semiring A] [algebra R A] : Prop := (out : (⊤ : subalgebra R A).fg) /-- An algebra over a commutative semiring is `finite_presentation` if it is the quotient of a polynomial ring in `n` variables by a finitely generated ideal. -/ def algebra.finite_presentation [comm_semiring R] [semiring A] [algebra R A] : Prop := ∃ (n : ℕ) (f : mv_polynomial (fin n) R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg namespace module variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] lemma finite_def {R M} [semiring R] [add_comm_monoid M] [module R M] : finite R M ↔ (⊤ : submodule R M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ @[priority 100] -- see Note [lower instance priority] instance is_noetherian.finite [is_noetherian R M] : finite R M := ⟨is_noetherian.noetherian ⊤⟩ namespace finite open _root_.submodule set lemma iff_add_monoid_fg {M : Type*} [add_comm_monoid M] : module.finite ℕ M ↔ add_monoid.fg M := ⟨λ h, add_monoid.fg_def.2 $ (fg_iff_add_submonoid_fg ⊤).1 (finite_def.1 h), λ h, finite_def.2 $ (fg_iff_add_submonoid_fg ⊤).2 (add_monoid.fg_def.1 h)⟩ lemma iff_add_group_fg {G : Type*} [add_comm_group G] : module.finite ℤ G ↔ add_group.fg G := ⟨λ h, add_group.fg_def.2 $ (fg_iff_add_subgroup_fg ⊤).1 (finite_def.1 h), λ h, finite_def.2 $ (fg_iff_add_subgroup_fg ⊤).2 (add_group.fg_def.1 h)⟩ variables {R M N} lemma exists_fin [finite R M] : ∃ (n : ℕ) (s : fin n → M), span R (range s) = ⊤ := submodule.fg_iff_exists_fin_generating_family.mp out lemma of_surjective [hM : finite R M] (f : M →ₗ[R] N) (hf : surjective f) : finite R N := ⟨begin rw [← linear_map.range_eq_top.2 hf, ← submodule.map_top], exact hM.1.map f end⟩ lemma of_injective [is_noetherian R N] (f : M →ₗ[R] N) (hf : function.injective f) : finite R M := ⟨fg_of_injective f hf⟩ variables (R) instance self : finite R R := ⟨⟨{1}, by simpa only [finset.coe_singleton] using ideal.span_singleton_one⟩⟩ variable (M) lemma of_restrict_scalars_finite (R A M : Type*) [comm_semiring R] [semiring A] [add_comm_monoid M] [module R M] [module A M] [algebra R A] [is_scalar_tower R A M] [hM : finite R M] : finite A M := begin rw [finite_def, fg_def] at hM ⊢, obtain ⟨S, hSfin, hSgen⟩ := hM, refine ⟨S, hSfin, eq_top_iff.2 _⟩, have := submodule.span_le_restrict_scalars R A S, rw hSgen at this, exact this end variables {R M} instance prod [hM : finite R M] [hN : finite R N] : finite R (M × N) := ⟨begin rw ← submodule.prod_top, exact hM.1.prod hN.1 end⟩ instance pi {ι : Type*} {M : ι → Type*} [fintype ι] [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] [h : ∀ i, finite R (M i)] : finite R (Π i, M i) := ⟨begin rw ← submodule.pi_top, exact submodule.fg_pi (λ i, (h i).1), end⟩ lemma equiv [hM : finite R M] (e : M ≃ₗ[R] N) : finite R N := of_surjective (e : M →ₗ[R] N) e.surjective section algebra lemma trans {R : Type*} (A B : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] [semiring B] [algebra R B] [algebra A B] [is_scalar_tower R A B] : ∀ [finite R A] [finite A B], finite R B | ⟨⟨s, hs⟩⟩ ⟨⟨t, ht⟩⟩ := ⟨submodule.fg_def.2 ⟨set.image2 (•) (↑s : set A) (↑t : set B), set.finite.image2 _ s.finite_to_set t.finite_to_set, by rw [set.image2_smul, submodule.span_smul hs (↑t : set B), ht, submodule.restrict_scalars_top]⟩⟩ @[priority 100] -- see Note [lower instance priority] instance finite_type {R : Type*} (A : Type*) [comm_semiring R] [semiring A] [algebra R A] [hRA : finite R A] : algebra.finite_type R A := ⟨subalgebra.fg_of_submodule_fg hRA.1⟩ end algebra end finite end module instance module.finite.base_change [comm_semiring R] [semiring A] [algebra R A] [add_comm_monoid M] [module R M] [h : module.finite R M] : module.finite A (tensor_product R A M) := begin classical, obtain ⟨s, hs⟩ := h.out, refine ⟨⟨s.image (tensor_product.mk R A M 1), eq_top_iff.mpr $ λ x _, _⟩⟩, apply tensor_product.induction_on x, { exact zero_mem _ }, { intros x y, rw [finset.coe_image, ← submodule.span_span_of_tower R, submodule.span_image, hs, submodule.map_top, linear_map.range_coe], change _ ∈ submodule.span A (set.range $ tensor_product.mk R A M 1), rw [← mul_one x, ← smul_eq_mul, ← tensor_product.smul_tmul'], exact submodule.smul_mem _ x (submodule.subset_span $ set.mem_range_self y) }, { exact λ _ _, submodule.add_mem _ } end instance module.finite.tensor_product [comm_semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid N] [module R N] [hM : module.finite R M] [hN : module.finite R N] : module.finite R (tensor_product R M N) := { out := (tensor_product.map₂_mk_top_top_eq_top R M N).subst (hM.out.map₂ _ hN.out) } namespace algebra variables [comm_ring R] [comm_ring A] [algebra R A] [comm_ring B] [algebra R B] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] namespace finite_type lemma self : finite_type R R := ⟨⟨{1}, subsingleton.elim _ _⟩⟩ section open_locale classical protected lemma mv_polynomial (ι : Type*) [fintype ι] : finite_type R (mv_polynomial ι R) := ⟨⟨finset.univ.image mv_polynomial.X, begin rw eq_top_iff, refine λ p, mv_polynomial.induction_on' p (λ u x, finsupp.induction u (subalgebra.algebra_map_mem _ x) (λ i n f hif hn ih, _)) (λ p q ihp ihq, subalgebra.add_mem _ ihp ihq), rw [add_comm, mv_polynomial.monomial_add_single], exact subalgebra.mul_mem _ ih (subalgebra.pow_mem _ (subset_adjoin $ finset.mem_image_of_mem _ $ finset.mem_univ _) _) end⟩⟩ end lemma of_restrict_scalars_finite_type [algebra A B] [is_scalar_tower R A B] [hB : finite_type R B] : finite_type A B := begin obtain ⟨S, hS⟩ := hB.out, refine ⟨⟨S, eq_top_iff.2 (λ b, _)⟩⟩, have le : adjoin R (S : set B) ≤ subalgebra.restrict_scalars R (adjoin A S), { apply (algebra.adjoin_le _ : _ ≤ (subalgebra.restrict_scalars R (adjoin A ↑S))), simp only [subalgebra.coe_restrict_scalars], exact algebra.subset_adjoin, }, exact le (eq_top_iff.1 hS b), end variables {R A B} lemma of_surjective (hRA : finite_type R A) (f : A →ₐ[R] B) (hf : surjective f) : finite_type R B := ⟨begin convert hRA.1.map f, simpa only [map_top f, @eq_comm _ ⊤, eq_top_iff, alg_hom.mem_range] using hf end⟩ lemma equiv (hRA : finite_type R A) (e : A ≃ₐ[R] B) : finite_type R B := hRA.of_surjective e e.surjective lemma trans [algebra A B] [is_scalar_tower R A B] (hRA : finite_type R A) (hAB : finite_type A B) : finite_type R B := ⟨fg_trans' hRA.1 hAB.1⟩ /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a finset. -/ lemma iff_quotient_mv_polynomial : (finite_type R A) ↔ ∃ (s : finset A) (f : (mv_polynomial {x // x ∈ s} R) →ₐ[R] A), (surjective f) := begin split, { rintro ⟨s, hs⟩, use [s, mv_polynomial.aeval coe], intro x, have hrw : (↑s : set A) = (λ (x : A), x ∈ s.val) := rfl, rw [← set.mem_range, ← alg_hom.coe_range, ← adjoin_eq_range, ← hrw, hs], exact set.mem_univ x }, { rintro ⟨s, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R {x // x ∈ s}) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype. -/ lemma iff_quotient_mv_polynomial' : (finite_type R A) ↔ ∃ (ι : Type u_2) (_ : fintype ι) (f : (mv_polynomial ι R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial, rintro ⟨s, ⟨f, hsur⟩⟩, use [{x // x ∈ s}, by apply_instance, f, hsur] }, { rintro ⟨ι, ⟨hfintype, ⟨f, hsur⟩⟩⟩, letI : fintype ι := hfintype, exact finite_type.of_surjective (finite_type.mv_polynomial R ι) f hsur } end /-- An algebra is finitely generated if and only if it is a quotient of a polynomial ring in `n` variables. -/ lemma iff_quotient_mv_polynomial'' : (finite_type R A) ↔ ∃ (n : ℕ) (f : (mv_polynomial (fin n) R) →ₐ[R] A), (surjective f) := begin split, { rw iff_quotient_mv_polynomial', rintro ⟨ι, hfintype, ⟨f, hsur⟩⟩, resetI, have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι), exact ⟨fintype.card ι, alg_hom.comp f equiv.symm, function.surjective.comp hsur (alg_equiv.symm equiv).surjective⟩ }, { rintro ⟨n, ⟨f, hsur⟩⟩, exact finite_type.of_surjective (finite_type.mv_polynomial R (fin n)) f hsur } end /-- A finitely presented algebra is of finite type. -/ lemma of_finite_presentation : finite_presentation R A → finite_type R A := begin rintro ⟨n, f, hf⟩, apply (finite_type.iff_quotient_mv_polynomial'').2, exact ⟨n, f, hf.1⟩ end instance prod [hA : finite_type R A] [hB : finite_type R B] : finite_type R (A × B) := ⟨begin rw ← subalgebra.prod_top, exact hA.1.prod hB.1 end⟩ lemma is_noetherian_ring (R S : Type*) [comm_ring R] [comm_ring S] [algebra R S] [h : algebra.finite_type R S] [is_noetherian_ring R] : is_noetherian_ring S := begin obtain ⟨s, hs⟩ := h.1, apply is_noetherian_ring_of_surjective (mv_polynomial s R) S (mv_polynomial.aeval coe : mv_polynomial s R →ₐ[R] S), rw [← set.range_iff_surjective, alg_hom.coe_to_ring_hom, ← alg_hom.coe_range, ← algebra.adjoin_range_eq_range_aeval, subtype.range_coe_subtype, finset.set_of_mem, hs], refl end lemma _root_.subalgebra.fg_iff_finite_type {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : S.fg ↔ algebra.finite_type R S := S.fg_top.symm.trans ⟨λ h, ⟨h⟩, λ h, h.out⟩ end finite_type namespace finite_presentation variables {R A B} /-- An algebra over a Noetherian ring is finitely generated if and only if it is finitely presented. -/ lemma of_finite_type [is_noetherian_ring R] : finite_type R A ↔ finite_presentation R A := begin refine ⟨λ h, _, algebra.finite_type.of_finite_presentation⟩, obtain ⟨n, f, hf⟩ := algebra.finite_type.iff_quotient_mv_polynomial''.1 h, refine ⟨n, f, hf, _⟩, have hnoet : is_noetherian_ring (mv_polynomial (fin n) R) := by apply_instance, replace hnoet := (is_noetherian_ring_iff.1 hnoet).noetherian, exact hnoet f.to_ring_hom.ker, end /-- If `e : A ≃ₐ[R] B` and `A` is finitely presented, then so is `B`. -/ lemma equiv (hfp : finite_presentation R A) (e : A ≃ₐ[R] B) : finite_presentation R B := begin obtain ⟨n, f, hf⟩ := hfp, use [n, alg_hom.comp ↑e f], split, { exact function.surjective.comp e.surjective hf.1 }, suffices hker : (alg_hom.comp ↑e f).to_ring_hom.ker = f.to_ring_hom.ker, { rw hker, exact hf.2 }, { have hco : (alg_hom.comp ↑e f).to_ring_hom = ring_hom.comp ↑e.to_ring_equiv f.to_ring_hom, { have h : (alg_hom.comp ↑e f).to_ring_hom = e.to_alg_hom.to_ring_hom.comp f.to_ring_hom := rfl, have h1 : ↑(e.to_ring_equiv) = (e.to_alg_hom).to_ring_hom := rfl, rw [h, h1] }, rw [ring_hom.ker_eq_comap_bot, hco, ← ideal.comap_comap, ← ring_hom.ker_eq_comap_bot, ring_hom.ker_coe_equiv (alg_equiv.to_ring_equiv e), ring_hom.ker_eq_comap_bot] } end variable (R) /-- The ring of polynomials in finitely many variables is finitely presented. -/ protected lemma mv_polynomial (ι : Type u_2) [fintype ι] : finite_presentation R (mv_polynomial ι R) := begin have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι), refine ⟨_, alg_equiv.to_alg_hom equiv.symm, _⟩, split, { exact (alg_equiv.symm equiv).surjective }, suffices hinj : function.injective equiv.symm.to_alg_hom.to_ring_hom, { rw [(ring_hom.injective_iff_ker_eq_bot _).1 hinj], exact submodule.fg_bot }, exact (alg_equiv.symm equiv).injective end /-- `R` is finitely presented as `R`-algebra. -/ lemma self : finite_presentation R R := equiv (finite_presentation.mv_polynomial R pempty) (mv_polynomial.is_empty_alg_equiv R pempty) variable {R} /-- The quotient of a finitely presented algebra by a finitely generated ideal is finitely presented. -/ protected lemma quotient {I : ideal A} (h : I.fg) (hfp : finite_presentation R A) : finite_presentation R (A ⧸ I) := begin obtain ⟨n, f, hf⟩ := hfp, refine ⟨n, (ideal.quotient.mkₐ R I).comp f, _, _⟩, { exact (ideal.quotient.mkₐ_surjective R I).comp hf.1 }, { refine ideal.fg_ker_comp _ _ hf.2 _ hf.1, simp [h] } end /-- If `f : A →ₐ[R] B` is surjective with finitely generated kernel and `A` is finitely presented, then so is `B`. -/ lemma of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) (hker : f.to_ring_hom.ker.fg) (hfp : finite_presentation R A) : finite_presentation R B := equiv (hfp.quotient hker) (ideal.quotient_ker_alg_equiv_of_surjective hf) lemma iff : finite_presentation R A ↔ ∃ n (I : ideal (mv_polynomial (fin n) R)) (e : (_ ⧸ I) ≃ₐ[R] A), I.fg := begin split, { rintros ⟨n, f, hf⟩, exact ⟨n, f.to_ring_hom.ker, ideal.quotient_ker_alg_equiv_of_surjective hf.1, hf.2⟩ }, { rintros ⟨n, I, e, hfg⟩, exact equiv ((finite_presentation.mv_polynomial R _).quotient hfg) e } end /-- An algebra is finitely presented if and only if it is a quotient of a polynomial ring whose variables are indexed by a fintype by a finitely generated ideal. -/ lemma iff_quotient_mv_polynomial' : finite_presentation R A ↔ ∃ (ι : Type u_2) (_ : fintype ι) (f : mv_polynomial ι R →ₐ[R] A), surjective f ∧ f.to_ring_hom.ker.fg := begin split, { rintro ⟨n, f, hfs, hfk⟩, set ulift_var := mv_polynomial.rename_equiv R equiv.ulift, refine ⟨ulift (fin n), infer_instance, f.comp ulift_var.to_alg_hom, hfs.comp ulift_var.surjective, ideal.fg_ker_comp _ _ _ hfk ulift_var.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv ulift_var.to_ring_equiv, }, { rintro ⟨ι, hfintype, f, hf⟩, resetI, have equiv := mv_polynomial.rename_equiv R (fintype.equiv_fin ι), refine ⟨fintype.card ι, f.comp equiv.symm, hf.1.comp (alg_equiv.symm equiv).surjective, ideal.fg_ker_comp _ f _ hf.2 equiv.symm.surjective⟩, convert submodule.fg_bot, exact ring_hom.ker_coe_equiv (equiv.symm.to_ring_equiv), } end /-- If `A` is a finitely presented `R`-algebra, then `mv_polynomial (fin n) A` is finitely presented as `R`-algebra. -/ lemma mv_polynomial_of_finite_presentation (hfp : finite_presentation R A) (ι : Type*) [fintype ι] : finite_presentation R (mv_polynomial ι A) := begin rw iff_quotient_mv_polynomial' at hfp ⊢, classical, obtain ⟨ι', _, f, hf_surj, hf_ker⟩ := hfp, resetI, let g := (mv_polynomial.map_alg_hom f).comp (mv_polynomial.sum_alg_equiv R ι ι').to_alg_hom, refine ⟨ι ⊕ ι', by apply_instance, g, (mv_polynomial.map_surjective f.to_ring_hom hf_surj).comp (alg_equiv.surjective _), ideal.fg_ker_comp _ _ _ _ (alg_equiv.surjective _)⟩, { convert submodule.fg_bot, exact ring_hom.ker_coe_equiv (mv_polynomial.sum_alg_equiv R ι ι').to_ring_equiv }, { rw [alg_hom.to_ring_hom_eq_coe, mv_polynomial.map_alg_hom_coe_ring_hom, mv_polynomial.ker_map], exact hf_ker.map mv_polynomial.C, } end /-- If `A` is an `R`-algebra and `S` is an `A`-algebra, both finitely presented, then `S` is finitely presented as `R`-algebra. -/ lemma trans [algebra A B] [is_scalar_tower R A B] (hfpA : finite_presentation R A) (hfpB : finite_presentation A B) : finite_presentation R B := begin obtain ⟨n, I, e, hfg⟩ := iff.1 hfpB, exact equiv ((mv_polynomial_of_finite_presentation hfpA _).quotient hfg) (e.restrict_scalars R) end end finite_presentation end algebra end module_and_algebra namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] /-- A ring morphism `A →+* B` is `finite` if `B` is finitely generated as `A`-module. -/ def finite (f : A →+* B) : Prop := by letI : algebra A B := f.to_algebra; exact module.finite A B /-- A ring morphism `A →+* B` is of `finite_type` if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →+* B) : Prop := @algebra.finite_type A B _ _ f.to_algebra /-- A ring morphism `A →+* B` is of `finite_presentation` if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →+* B) : Prop := @algebra.finite_presentation A B _ _ f.to_algebra namespace finite variables (A) lemma id : finite (ring_hom.id A) := module.finite.self A variables {A} lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite := begin letI := f.to_algebra, exact module.finite.of_surjective (algebra.of_id A B).to_linear_map hf end lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := @module.finite.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma finite_type {f : A →+* B} (hf : f.finite) : finite_type f := @module.finite.finite_type _ _ _ _ f.to_algebra hf lemma of_comp_finite {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite) : g.finite := begin letI := f.to_algebra, letI := g.to_algebra, letI := (g.comp f).to_algebra, letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C, letI : module.finite A C := h, exact module.finite.of_restrict_scalars_finite A B C end end finite namespace finite_type variables (A) lemma id : finite_type (ring_hom.id A) := algebra.finite_type.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := @algebra.finite_type.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra hf { to_fun := g, commutes' := λ a, rfl, .. g } hg lemma of_surjective (f : A →+* B) (hf : surjective f) : f.finite_type := by { rw ← f.comp_id, exact (id A).comp_surjective hf } lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := @algebra.finite_type.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra begin fconstructor, intros a b c, simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end hf hg lemma of_finite {f : A →+* B} (hf : f.finite) : f.finite_type := @module.finite.finite_type _ _ _ _ f.to_algebra hf alias of_finite ← _root_.ring_hom.finite.to_finite_type lemma of_finite_presentation {f : A →+* B} (hf : f.finite_presentation) : f.finite_type := @algebra.finite_type.of_finite_presentation A B _ _ f.to_algebra hf lemma of_comp_finite_type {f : A →+* B} {g : B →+* C} (h : (g.comp f).finite_type) : g.finite_type := begin letI := f.to_algebra, letI := g.to_algebra, letI := (g.comp f).to_algebra, letI : is_scalar_tower A B C := restrict_scalars.is_scalar_tower A B C, letI : algebra.finite_type A C := h, exact algebra.finite_type.of_restrict_scalars_finite_type A B C end end finite_type namespace finite_presentation variables (A) lemma id : finite_presentation (ring_hom.id A) := algebra.finite_presentation.self A variables {A} lemma comp_surjective {f : A →+* B} {g : B →+* C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.ker.fg) : (g.comp f).finite_presentation := @algebra.finite_presentation.of_surjective A B C _ _ f.to_algebra _ (g.comp f).to_algebra { to_fun := g, commutes' := λ a, rfl, .. g } hg hker hf lemma of_surjective (f : A →+* B) (hf : surjective f) (hker : f.ker.fg) : f.finite_presentation := by { rw ← f.comp_id, exact (id A).comp_surjective hf hker} lemma of_finite_type [is_noetherian_ring A] {f : A →+* B} : f.finite_type ↔ f.finite_presentation := @algebra.finite_presentation.of_finite_type A B _ _ f.to_algebra _ lemma comp {g : B →+* C} {f : A →+* B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := @algebra.finite_presentation.trans A B C _ _ f.to_algebra _ (g.comp f).to_algebra g.to_algebra { smul_assoc := λ a b c, begin simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl end } hf hg end finite_presentation end ring_hom namespace alg_hom variables {R A B C : Type*} [comm_ring R] variables [comm_ring A] [comm_ring B] [comm_ring C] variables [algebra R A] [algebra R B] [algebra R C] /-- An algebra morphism `A →ₐ[R] B` is finite if it is finite as ring morphism. In other words, if `B` is finitely generated as `A`-module. -/ def finite (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite /-- An algebra morphism `A →ₐ[R] B` is of `finite_type` if it is of finite type as ring morphism. In other words, if `B` is finitely generated as `A`-algebra. -/ def finite_type (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_type /-- An algebra morphism `A →ₐ[R] B` is of `finite_presentation` if it is of finite presentation as ring morphism. In other words, if `B` is finitely presented as `A`-algebra. -/ def finite_presentation (f : A →ₐ[R] B) : Prop := f.to_ring_hom.finite_presentation namespace finite variables (R A) lemma id : finite (alg_hom.id R A) := ring_hom.finite.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite) (hf : f.finite) : (g.comp f).finite := ring_hom.finite.comp hg hf lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite := ring_hom.finite.of_surjective f hf lemma finite_type {f : A →ₐ[R] B} (hf : f.finite) : finite_type f := ring_hom.finite.finite_type hf lemma of_comp_finite {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite) : g.finite := ring_hom.finite.of_comp_finite h end finite namespace finite_type variables (R A) lemma id : finite_type (alg_hom.id R A) := ring_hom.finite_type.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_type) (hf : f.finite_type) : (g.comp f).finite_type := ring_hom.finite_type.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_type) (hg : surjective g) : (g.comp f).finite_type := ring_hom.finite_type.comp_surjective hf hg lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) : f.finite_type := ring_hom.finite_type.of_surjective f hf lemma of_finite_presentation {f : A →ₐ[R] B} (hf : f.finite_presentation) : f.finite_type := ring_hom.finite_type.of_finite_presentation hf lemma of_comp_finite_type {f : A →ₐ[R] B} {g : B →ₐ[R] C} (h : (g.comp f).finite_type) : g.finite_type := ring_hom.finite_type.of_comp_finite_type h end finite_type namespace finite_presentation variables (R A) lemma id : finite_presentation (alg_hom.id R A) := ring_hom.finite_presentation.id A variables {R A} lemma comp {g : B →ₐ[R] C} {f : A →ₐ[R] B} (hg : g.finite_presentation) (hf : f.finite_presentation) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp hg hf lemma comp_surjective {f : A →ₐ[R] B} {g : B →ₐ[R] C} (hf : f.finite_presentation) (hg : surjective g) (hker : g.to_ring_hom.ker.fg) : (g.comp f).finite_presentation := ring_hom.finite_presentation.comp_surjective hf hg hker lemma of_surjective (f : A →ₐ[R] B) (hf : surjective f) (hker : f.to_ring_hom.ker.fg) : f.finite_presentation := ring_hom.finite_presentation.of_surjective f hf hker lemma of_finite_type [is_noetherian_ring A] {f : A →ₐ[R] B} : f.finite_type ↔ f.finite_presentation := ring_hom.finite_presentation.of_finite_type end finite_presentation end alg_hom section monoid_algebra variables {R : Type*} {M : Type*} namespace add_monoid_algebra open algebra add_submonoid submodule section span section semiring variables [comm_semiring R] [add_monoid M] /-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_adjoin_support (f : add_monoid_algebra R M) : f ∈ adjoin R (of' R M '' f.support) := begin suffices : span R (of' R M '' f.support) ≤ (adjoin R (of' R M '' f.support)).to_submodule, { exact this (mem_span_support f) }, rw submodule.span_le, exact subset_adjoin end /-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the set of supports of elements of `S` generates `add_monoid_algebra R M`. -/ lemma support_gen_of_gen {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (⋃ f ∈ S, (of' R M '' (f.support : set M))) = ⊤ := begin refine le_antisymm le_top _, rw [← hS, adjoin_le_iff], intros f hf, have hincl : of' R M '' f.support ⊆ ⋃ (g : add_monoid_algebra R M) (H : g ∈ S), of' R M '' g.support, { intros s hs, exact set.mem_Union₂.2 ⟨f, ⟨hf, hs⟩⟩ }, exact adjoin_mono hincl (mem_adjoin_support f) end /-- If a set `S` generates, as algebra, `add_monoid_algebra R M`, then the image of the union of the supports of elements of `S` generates `add_monoid_algebra R M`. -/ lemma support_gen_of_gen' {S : set (add_monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (of' R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ := begin suffices : of' R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of' R M '' (f.support : set M)), { rw this, exact support_gen_of_gen hS }, simp only [set.image_Union] end end semiring section ring variables [comm_ring R] [add_comm_monoid M] /-- If `add_monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image generates, as algera, `add_monoid_algebra R M`. -/ lemma exists_finset_adjoin_eq_top [h : finite_type R (add_monoid_algebra R M)] : ∃ G : finset M, algebra.adjoin R (of' R M '' G) = ⊤ := begin unfreezingI { obtain ⟨S, hS⟩ := h }, letI : decidable_eq M := classical.dec_eq M, use finset.bUnion S (λ f, f.support), have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M), { simp only [finset.set_bUnion_coe, finset.coe_bUnion] }, rw [this], exact support_gen_of_gen' hS end /-- The image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by `S : set M` if and only if `m ∈ S`. -/ lemma of'_mem_span [nontrivial R] {m : M} {S : set M} : of' R M m ∈ span R (of' R M '' S) ↔ m ∈ S := begin refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩, rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported, finsupp.support_single_ne_zero _ (@one_ne_zero R _ (by apply_instance))] at h, simpa using h end /--If the image of an element `m : M` in `add_monoid_algebra R M` belongs the submodule generated by the closure of some `S : set M` then `m ∈ closure S`. -/ lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M} (h : of' R M m ∈ span R (submonoid.closure (of' R M '' S) : set (add_monoid_algebra R M))) : m ∈ closure S := begin suffices : multiplicative.of_add m ∈ submonoid.closure (multiplicative.to_add ⁻¹' S), { simpa [← to_submonoid_closure] }, let S' := @submonoid.closure M multiplicative.mul_one_class S, have h' : submonoid.map (of R M) S' = submonoid.closure ((λ (x : M), (of R M) x) '' S) := monoid_hom.map_mclosure _ _, rw [set.image_congr' (show ∀ x, of' R M x = of R M x, from λ x, of'_eq_of x), ← h'] at h, simpa using of'_mem_span.1 h end end ring end span variables [add_comm_monoid M] /-- If a set `S` generates an additive monoid `M`, then the image of `M` generates, as algebra, `add_monoid_algebra R M`. -/ lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M} (hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval (λ (s : S), of' R M ↑s) : mv_polynomial S R → add_monoid_algebra R M) := begin refine λ f, induction_on f (λ m, _) _ _, { have : m ∈ closure S := hS.symm ▸ mem_top _, refine closure_induction this (λ m hm, _) _ _, { exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ }, { exact ⟨1, alg_hom.map_one _⟩ }, { rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩, exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply, single_mul_single, one_mul]; refl⟩ } }, { rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩, exact ⟨P + Q, alg_hom.map_add _ _ _⟩ }, { rintro r f ⟨P, rfl⟩, exact ⟨r • P, alg_hom.map_smul _ _ _⟩ } end variables (R M) /-- If an additive monoid `M` is finitely generated then `add_monoid_algebra R M` is of finite type. -/ instance finite_type_of_fg [comm_ring R] [h : add_monoid.fg M] : finite_type R (add_monoid_algebra R M) := begin obtain ⟨S, hS⟩ := h.out, exact (finite_type.mv_polynomial R (S : set M)).of_surjective (mv_polynomial.aeval (λ (s : (S : set M)), of' R M ↑s)) (mv_polynomial_aeval_of_surjective_of_closure hS) end variables {R M} /-- An additive monoid `M` is finitely generated if and only if `add_monoid_algebra R M` is of finite type. -/ lemma finite_type_iff_fg [comm_ring R] [nontrivial R] : finite_type R (add_monoid_algebra R M) ↔ add_monoid.fg M := begin refine ⟨λ h, _, λ h, @add_monoid_algebra.finite_type_of_fg _ _ _ _ h⟩, obtain ⟨S, hS⟩ := @exists_finset_adjoin_eq_top R M _ _ h, refine add_monoid.fg_def.2 ⟨S, (eq_top_iff' _).2 (λ m, _)⟩, have hm : of' R M m ∈ (adjoin R (of' R M '' ↑S)).to_submodule, { simp only [hS, top_to_submodule, submodule.mem_top], }, rw [adjoin_eq_span] at hm, exact mem_closure_of_mem_span_closure hm end /-- If `add_monoid_algebra R M` is of finite type then `M` is finitely generated. -/ lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (add_monoid_algebra R M)] : add_monoid.fg M := finite_type_iff_fg.1 h /-- An additive group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/ lemma finite_type_iff_group_fg {G : Type*} [add_comm_group G] [comm_ring R] [nontrivial R] : finite_type R (add_monoid_algebra R G) ↔ add_group.fg G := by simpa [add_group.fg_iff_add_monoid.fg] using finite_type_iff_fg end add_monoid_algebra namespace monoid_algebra open algebra submonoid submodule section span section semiring variables [comm_semiring R] [monoid M] /-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_adjoint_support (f : monoid_algebra R M) : f ∈ adjoin R (of R M '' f.support) := begin suffices : span R (of R M '' f.support) ≤ (adjoin R (of R M '' f.support)).to_submodule, { exact this (mem_span_support f) }, rw submodule.span_le, exact subset_adjoin end /-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the set of supports of elements of `S` generates `monoid_algebra R M`. -/ lemma support_gen_of_gen {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (⋃ f ∈ S, (of R M '' (f.support : set M))) = ⊤ := begin refine le_antisymm le_top _, rw [← hS, adjoin_le_iff], intros f hf, have hincl : (of R M) '' f.support ⊆ ⋃ (g : monoid_algebra R M) (H : g ∈ S), of R M '' g.support, { intros s hs, exact set.mem_Union₂.2 ⟨f, ⟨hf, hs⟩⟩ }, exact adjoin_mono hincl (mem_adjoint_support f) end /-- If a set `S` generates, as algebra, `monoid_algebra R M`, then the image of the union of the supports of elements of `S` generates `monoid_algebra R M`. -/ lemma support_gen_of_gen' {S : set (monoid_algebra R M)} (hS : algebra.adjoin R S = ⊤) : algebra.adjoin R (of R M '' (⋃ f ∈ S, (f.support : set M))) = ⊤ := begin suffices : of R M '' (⋃ f ∈ S, (f.support : set M)) = ⋃ f ∈ S, (of R M '' (f.support : set M)), { rw this, exact support_gen_of_gen hS }, simp only [set.image_Union] end end semiring section ring variables [comm_ring R] [comm_monoid M] /-- If `monoid_algebra R M` is of finite type, there there is a `G : finset M` such that its image generates, as algera, `monoid_algebra R M`. -/ lemma exists_finset_adjoin_eq_top [h :finite_type R (monoid_algebra R M)] : ∃ G : finset M, algebra.adjoin R (of R M '' G) = ⊤ := begin unfreezingI { obtain ⟨S, hS⟩ := h }, letI : decidable_eq M := classical.dec_eq M, use finset.bUnion S (λ f, f.support), have : (finset.bUnion S (λ f, f.support) : set M) = ⋃ f ∈ S, (f.support : set M), { simp only [finset.set_bUnion_coe, finset.coe_bUnion] }, rw [this], exact support_gen_of_gen' hS end /-- The image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by `S : set M` if and only if `m ∈ S`. -/ lemma of_mem_span_of_iff [nontrivial R] {m : M} {S : set M} : of R M m ∈ span R (of R M '' S) ↔ m ∈ S := begin refine ⟨λ h, _, λ h, submodule.subset_span $ set.mem_image_of_mem (of R M) h⟩, rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported, finsupp.support_single_ne_zero _ (@one_ne_zero R _ (by apply_instance))] at h, simpa using h end /--If the image of an element `m : M` in `monoid_algebra R M` belongs the submodule generated by the closure of some `S : set M` then `m ∈ closure S`. -/ lemma mem_closure_of_mem_span_closure [nontrivial R] {m : M} {S : set M} (h : of R M m ∈ span R (submonoid.closure (of R M '' S) : set (monoid_algebra R M))) : m ∈ closure S := begin rw ← monoid_hom.map_mclosure at h, simpa using of_mem_span_of_iff.1 h end end ring end span variables [comm_monoid M] /-- If a set `S` generates a monoid `M`, then the image of `M` generates, as algebra, `monoid_algebra R M`. -/ lemma mv_polynomial_aeval_of_surjective_of_closure [comm_semiring R] {S : set M} (hS : closure S = ⊤) : function.surjective (mv_polynomial.aeval (λ (s : S), of R M ↑s) : mv_polynomial S R → monoid_algebra R M) := begin refine λ f, induction_on f (λ m, _) _ _, { have : m ∈ closure S := hS.symm ▸ mem_top _, refine closure_induction this (λ m hm, _) _ _, { exact ⟨mv_polynomial.X ⟨m, hm⟩, mv_polynomial.aeval_X _ _⟩ }, { exact ⟨1, alg_hom.map_one _⟩ }, { rintro m₁ m₂ ⟨P₁, hP₁⟩ ⟨P₂, hP₂⟩, exact ⟨P₁ * P₂, by rw [alg_hom.map_mul, hP₁, hP₂, of_apply, of_apply, of_apply, single_mul_single, one_mul]⟩ } }, { rintro f g ⟨P, rfl⟩ ⟨Q, rfl⟩, exact ⟨P + Q, alg_hom.map_add _ _ _⟩ }, { rintro r f ⟨P, rfl⟩, exact ⟨r • P, alg_hom.map_smul _ _ _⟩ } end /-- If a monoid `M` is finitely generated then `monoid_algebra R M` is of finite type. -/ instance finite_type_of_fg [comm_ring R] [monoid.fg M] : finite_type R (monoid_algebra R M) := (add_monoid_algebra.finite_type_of_fg R (additive M)).equiv (to_additive_alg_equiv R M).symm /-- A monoid `M` is finitely generated if and only if `monoid_algebra R M` is of finite type. -/ lemma finite_type_iff_fg [comm_ring R] [nontrivial R] : finite_type R (monoid_algebra R M) ↔ monoid.fg M := ⟨λ h, monoid.fg_iff_add_fg.2 $ add_monoid_algebra.finite_type_iff_fg.1 $ h.equiv $ to_additive_alg_equiv R M, λ h, @monoid_algebra.finite_type_of_fg _ _ _ _ h⟩ /-- If `monoid_algebra R M` is of finite type then `M` is finitely generated. -/ lemma fg_of_finite_type [comm_ring R] [nontrivial R] [h : finite_type R (monoid_algebra R M)] : monoid.fg M := finite_type_iff_fg.1 h /-- A group `G` is finitely generated if and only if `add_monoid_algebra R G` is of finite type. -/ lemma finite_type_iff_group_fg {G : Type*} [comm_group G] [comm_ring R] [nontrivial R] : finite_type R (monoid_algebra R G) ↔ group.fg G := by simpa [group.fg_iff_monoid.fg] using finite_type_iff_fg end monoid_algebra end monoid_algebra section vasconcelos variables {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (f : M →ₗ[R] M) noncomputable theory /-- The structure of a module `M` over a ring `R` as a module over `polynomial R` when given a choice of how `X` acts by choosing a linear map `f : M →ₗ[R] M` -/ def module_polynomial_of_endo : module R[X] M := module.comp_hom M (polynomial.aeval f).to_ring_hom lemma module_polynomial_of_endo_smul_def (n : R[X]) (a : M) : @@has_smul.smul (module_polynomial_of_endo f).to_has_smul n a = polynomial.aeval f n a := rfl local attribute [simp] module_polynomial_of_endo_smul_def include f lemma module_polynomial_of_endo.is_scalar_tower : @is_scalar_tower R R[X] M _ (by { letI := module_polynomial_of_endo f, apply_instance }) _ := begin letI := module_polynomial_of_endo f, constructor, intros x y z, simp, end open polynomial module /-- A theorem/proof by Vasconcelos, given a finite module `M` over a commutative ring, any surjective endomorphism of `M` is also injective. Based on, https://math.stackexchange.com/a/239419/31917, https://www.ams.org/journals/tran/1969-138-00/S0002-9947-1969-0238839-5/. This is similar to `is_noetherian.injective_of_surjective_endomorphism` but only applies in the commutative case, but does not use a Noetherian hypothesis. -/ theorem module.finite.injective_of_surjective_endomorphism [hfg : finite R M] (f_surj : function.surjective f) : function.injective f := begin letI := module_polynomial_of_endo f, haveI : is_scalar_tower R R[X] M := module_polynomial_of_endo.is_scalar_tower f, have hfgpoly : finite R[X] M, from finite.of_restrict_scalars_finite R _ _, have X_mul : ∀ o, (X : R[X]) • o = f o, { intro, simp, }, have : (⊤ : submodule R[X] M) ≤ ideal.span {X} • ⊤, { intros a ha, obtain ⟨y, rfl⟩ := f_surj a, rw [← X_mul y], exact submodule.smul_mem_smul (ideal.mem_span_singleton.mpr (dvd_refl _)) trivial, }, obtain ⟨F, hFa, hFb⟩ := submodule.exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul _ (⊤ : submodule R[X] M) (finite_def.mp hfgpoly) this, rw [← linear_map.ker_eq_bot, linear_map.ker_eq_bot'], intros m hm, rw ideal.mem_span_singleton' at hFa, obtain ⟨G, hG⟩ := hFa, suffices : (F - 1) • m = 0, { have Fmzero := hFb m (by simp), rwa [← sub_add_cancel F 1, add_smul, one_smul, this, zero_add] at Fmzero, }, rw [← hG, mul_smul, X_mul m, hm, smul_zero], end end vasconcelos
b0bea13ab80014ef60ae25bef4216942d25ede59
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast18.lean
53311c07b3dcb0c69e97fcea803fde6988c644a3
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
591
lean
-- Backward chaining with tagged rules set_option blast.strategy "backward" constants {P Q R S T U : Prop} (Hpq : P → Q) (Hqr : Q → R) (Hrs : R → S) (Hst : S → T) constants (Huq : U → Q) (Hur : U → R) (Hus : U → S) (Hut : U → T) attribute Hpq [intro] attribute Hqr [intro] attribute Hrs [intro] attribute Hst [intro] attribute Huq [intro] attribute Hur [intro] attribute Hus [intro] attribute Hut [intro] definition lemma1 (p : P) : Q := by blast definition lemma2 (p : P) : R := by blast definition lemma3 (p : P) : S := by blast definition lemma4 (p : P) : T := by blast
f85b79f768cc30c03e2ed6f9fc0be594145bc933
649957717d58c43b5d8d200da34bf374293fe739
/src/data/multiset.lean
0413d439c9286b3ab516cdc82f5efb859cfd7186
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
132,004
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.equiv.basic data.list.basic data.list.perm data.list.sort data.quot data.string algebra.order_functions algebra.group_power algebra.ordered_group category.traversable.lemmas tactic.interactive category.traversable.instances category.basic open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} local infix ` • ` := add_monoid.smul /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append lemma card_smul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by induction n; simp [succ_smul, *, nat.succ_mul] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, bot := 0, bot_le := multiset.zero_le, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl @[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ instance (f : α → β) : is_add_monoid_hom (map f) := { map_add := map_add _, map_zero := map_zero _ } @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ @[simp] theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive multiset.sum_singleton] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive multiset.sum_add] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) := { map_add := sum_add, map_zero := sum_zero } lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) : ∀n, (add_monoid.smul n m).prod = m.prod ^ n | 0 := rfl | (n + 1) := by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.pow_one, prod_add, prod_smul n] @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive multiset.sum_repeat] prod_repeat @[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := multiset.induction_on m (by simp) (by simp) @[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := multiset.induction_on m (by simp) (by simp) attribute [to_additive multiset.sum_map_zero] prod_map_one @[simp, to_additive multiset.sum_map_add] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive multiset.sum_map_sum_map] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) lemma prod_hom [comm_monoid α] [comm_monoid β] (f : α → β) [is_monoid_hom f] (s : multiset α) : (s.map f).prod = f s.prod := multiset.induction_on s (by simp [is_monoid_hom.map_one f]) (by simp [is_monoid_hom.map_mul f] {contextual := tt}) lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod := quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a lemma sum_hom [add_comm_monoid α] [add_comm_monoid β] (f : α → β) [is_add_monoid_hom f] (s : multiset α) : (s.map f).sum = f s.sum := multiset.induction_on s (by simp [is_add_monoid_hom.map_zero f]) (by simp [is_add_monoid_hom.map_add f] {contextual := tt}) attribute [to_additive multiset.sum_hom] multiset.prod_hom lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) : f s.sum ≤ (s.map f).sum := multiset.induction_on s (le_of_eq h_zero) $ assume a s ih, by rw [sum_cons, map_cons, sum_cons]; from le_trans (h_add a s.sum) (add_le_add_left' ih) lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} : abs s.sum ≤ (s.map abs).sum := le_sum_of_subadditive _ abs_zero abs_add s /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, -map_const, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive multiset.sum_bind] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _ @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] @[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) @[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- diagonal -/ theorem revzip_powerset_aux {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux l)) : s + t = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux' l)) : s + t = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃s t⦄, (s, t) ∈ revzip l' → s + t = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact perm_map _ powerset_aux_perm_powerset_aux', end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact perm_map _ (powerset_aux_perm p) end def diagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem diagonal_coe (l : list α) : @diagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem diagonal_coe' (l : list α) : @diagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' @[simp] theorem mem_diagonal {s₁ s₂ t : multiset α} : (s₁, s₂) ∈ diagonal t ↔ s₁ + s₂ = t := quotient.induction_on t $ λ l, begin simp [diagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], exact ⟨_, le_add_right _ _, rfl, add_sub_cancel_left _ _⟩ end @[simp] theorem diagonal_map_fst (s : multiset α) : (diagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_map_snd (s : multiset α) : (diagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_zero : @diagonal α 0 = (0, 0)::0 := rfl @[simp] theorem diagonal_cons (a : α) (s) : diagonal (a::s) = map (prod.map id (cons a)) (diagonal s) + map (prod.map (cons a) id) (diagonal s) := quotient.induction_on s $ λ l, begin simp [revzip, reverse_append], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_diagonal (s : multiset α) : card (diagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← diagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((diagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] }, end /- powerset_len -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, (perm_length p.symm).trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, (perm_length p).trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact perm_app IH (perm_map _ (IHn p)) }, { simp, apply perm_app_right, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = 0::0 := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a::s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_sublists' _ _)) theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_of_sublist _ h)) /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) := { map_add := countp_add, map_zero := countp_zero _ } theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) := countp.is_add_monoid_hom @[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[extensionality] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp [max_min_distrib_left], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero {} : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono (assume a b, h) lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem injective_map {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α} (hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) := let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ theorem nodup_powerset_len {n : ℕ} {s : multiset α} (h : nodup s) : nodup (powerset_len n s) := nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h) @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 := ⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _, λ h, h.symm ▸ erase_dup_zero⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sup variables [semilattice_sup_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a :: s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup := fold_erase_dup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 (le_refl _) _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) end sup section inf variables [semilattice_inf_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a :: s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf := fold_erase_dup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 (le_refl _) _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) end inf section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] @[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card := quot.induction_on s $ length_merge_sort _ end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp, split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset namespace multiset instance : functor multiset := { map := @map } instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F] variables {α' β' : Type u_1} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.skip { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end instance : monad multiset := { pure := λ α x, x::0, bind := @bind, .. multiset.functor } instance : is_lawful_monad multiset := { bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih, by rw [bind_cons, map_cons, bind_zero, add_zero], pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero], bind_assoc := @bind_assoc } open functor open traversable is_lawful_traversable @[simp] lemma lift_beta {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_beta _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x (by { intro, rw [traverse,quotient.lift_beta,function.comp], simp, congr }) lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [comp_map,map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose /- Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := congr_arg coe $ list.Ico.map_sub _ _ _ h theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 := congr_arg coe $ list.Ico.bag_inter_consecutive n m l @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h @[simp] theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := congr_arg coe $ list.Ico.filter_ge_of_le_bot hln lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = ∅ := congr_arg coe $ list.Ico.filter_ge_of_top_le hml lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := congr_arg coe $ list.Ico.filter_ge_of_ge hnl @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_ge n m l end Ico variable (α) def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le (perm_length h) $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } end multiset
22a954b9bf897bdd3e223a9409e21e414556528a
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/direct_sum/ring.lean
e4097dcbdf8eb917da291a5c348aec2daf9677dd
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,244
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.algebra.basic import algebra.algebra.operations import algebra.direct_sum.basic import group_theory.subgroup /-! # Additively-graded multiplicative structures on `⨁ i, A i` This module provides a set of heterogeneous typeclasses for defining a multiplicative structure over `⨁ i, A i` such that `(*) : A i → A j → A (i + j)`; that is to say, `A` forms an additively-graded ring. The typeclasses are: * `direct_sum.ghas_one A` * `direct_sum.ghas_mul A` * `direct_sum.gmonoid A` * `direct_sum.gcomm_monoid A` Respectively, these imbue the direct sum `⨁ i, A i` with: * `direct_sum.has_one` * `direct_sum.non_unital_non_assoc_semiring` * `direct_sum.semiring`, `direct_sum.ring` * `direct_sum.comm_semiring`, `direct_sum.comm_ring` the base ring `A 0` with: * `direct_sum.grade_zero.has_one` * `direct_sum.grade_zero.non_unital_non_assoc_semiring` * `direct_sum.grade_zero.semiring`, `direct_sum.grade_zero.ring` * `direct_sum.grade_zero.comm_semiring`, `direct_sum.grade_zero.comm_ring` and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication: * (nothing) * `direct_sum.grade_zero.has_scalar (A 0)`, `direct_sum.grade_zero.smul_with_zero (A 0)` * `direct_sum.grade_zero.module (A 0)` * (nothing) Note that in the presence of these instances, `⨁ i, A i` itself inherits an `A 0`-action. `direct_sum.of_zero_ring_hom : A 0 →+* ⨁ i, A i` provides `direct_sum.of A 0` as a ring homomorphism. `direct_sum.to_semiring` extends `direct_sum.to_add_monoid` to produce a `ring_hom`. ## Direct sums of subobjects Additionally, this module provides helper functions to construct `gmonoid` and `gcomm_monoid` instances for: * `A : ι → submonoid S`: `direct_sum.ghas_one.of_add_submonoids`, `direct_sum.ghas_mul.of_add_submonoids`, `direct_sum.gmonoid.of_add_submonoids`, `direct_sum.gcomm_monoid.of_add_submonoids`. * `A : ι → subgroup S`: `direct_sum.ghas_one.of_add_subgroups`, `direct_sum.ghas_mul.of_add_subgroups`, `direct_sum.gmonoid.of_add_subgroups`, `direct_sum.gcomm_monoid.of_add_subgroups`. * `A : ι → submodule S`: `direct_sum.ghas_one.of_submodules`, `direct_sum.ghas_mul.of_submodules`, `direct_sum.gmonoid.of_submodules`, `direct_sum.gcomm_monoid.of_submodules`. If `complete_lattice.independent (set.range A)`, these provide a gradation of `⨆ i, A i`, and the mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as `direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`. ## tags graded ring, filtered ring, direct sum, add_submonoid -/ variables {ι : Type*} [decidable_eq ι] namespace direct_sum open_locale direct_sum /-! ### Typeclasses -/ section defs variables (A : ι → Type*) /-- A graded version of `has_one`, which must be of grade 0. -/ class ghas_one [has_zero ι] := (one : A 0) /-- A graded version of `has_mul` that also subsumes `non_unital_non_assoc_semiring` by requiring the multiplication be an `add_monoid_hom`. Multiplication combines grades additively, like `add_monoid_algebra`. -/ class ghas_mul [has_add ι] [Π i, add_comm_monoid (A i)] := (mul {i j} : A i →+ A j →+ A (i + j)) variables {A} /-- `direct_sum.ghas_one` implies a `has_one (Σ i, A i)`, although this is only used as an instance locally to define notation in `direct_sum.gmonoid` and similar typeclasses. -/ def ghas_one.to_sigma_has_one [has_zero ι] [ghas_one A] : has_one (Σ i, A i) := ⟨⟨_, ghas_one.one⟩⟩ /-- `direct_sum.ghas_mul` implies a `has_mul (Σ i, A i)`, although this is only used as an instance locally to define notation in `direct_sum.gmonoid` and similar typeclasses. -/ def ghas_mul.to_sigma_has_mul [has_add ι] [Π i, add_comm_monoid (A i)] [ghas_mul A] : has_mul (Σ i, A i) := ⟨λ (x y : Σ i, A i), ⟨_, ghas_mul.mul x.snd y.snd⟩⟩ end defs section defs variables (A : ι → Type*) local attribute [instance] ghas_one.to_sigma_has_one local attribute [instance] ghas_mul.to_sigma_has_mul /-- A graded version of `monoid`. -/ class gmonoid [add_monoid ι] [Π i, add_comm_monoid (A i)] extends ghas_mul A, ghas_one A := (one_mul (a : Σ i, A i) : 1 * a = a) (mul_one (a : Σ i, A i) : a * 1 = a) (mul_assoc (a : Σ i, A i) (b : Σ i, A i) (c : Σ i, A i) : a * b * c = a * (b * c)) /-- A graded version of `comm_monoid`. -/ class gcomm_monoid [add_comm_monoid ι] [Π i, add_comm_monoid (A i)] extends gmonoid A := (mul_comm (a : Σ i, A i) (b : Σ i, A i) : a * b = b * a) end defs /-! ### Shorthands for creating the above typeclasses -/ section shorthands variables {R : Type*} /-! #### From `add_submonoid`s -/ /-- Build a `ghas_one` instance for a collection of `add_submonoid`s. -/ @[simps one] def ghas_one.of_add_submonoids [semiring R] [has_zero ι] (carriers : ι → add_submonoid R) (one_mem : (1 : R) ∈ carriers 0) : ghas_one (λ i, carriers i) := { one := ⟨1, one_mem⟩ } -- `@[simps]` doesn't generate a useful lemma, so we state one manually below. /-- Build a `ghas_mul` instance for a collection of `add_submonoids`. -/ def ghas_mul.of_add_submonoids [semiring R] [has_add ι] (carriers : ι → add_submonoid R) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : ghas_mul (λ i, carriers i) := { mul := λ i j, { to_fun := λ a, { to_fun := λ b, ⟨(a * b : R), mul_mem a b⟩, map_add' := λ _ _, subtype.ext (mul_add _ _ _), map_zero' := subtype.ext (mul_zero _), }, map_add' := λ _ _, add_monoid_hom.ext $ λ _, subtype.ext (add_mul _ _ _), map_zero' := add_monoid_hom.ext $ λ _, subtype.ext (zero_mul _) }, } -- `@[simps]` doesn't generate this well @[simp] lemma ghas_mul.of_add_submonoids_mul [semiring R] [has_add ι] (carriers : ι → add_submonoid R) (mul_mem) {i j} (a : carriers i) (b : carriers j) : @ghas_mul.mul _ _ _ _ _ (ghas_mul.of_add_submonoids carriers mul_mem) i j a b = ⟨a * b, mul_mem a b⟩ := rfl /-- Build a `gmonoid` instance for a collection of `add_submonoid`s. -/ @[simps to_ghas_one to_ghas_mul] def gmonoid.of_add_submonoids [semiring R] [add_monoid ι] (carriers : ι → add_submonoid R) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gmonoid (λ i, carriers i) := { one_mul := λ ⟨i, a, h⟩, sigma.subtype_ext (zero_add _) (one_mul _), mul_one := λ ⟨i, a, h⟩, sigma.subtype_ext (add_zero _) (mul_one _), mul_assoc := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩ ⟨k, c, hc⟩, sigma.subtype_ext (add_assoc _ _ _) (mul_assoc _ _ _), ..ghas_one.of_add_submonoids carriers one_mem, ..ghas_mul.of_add_submonoids carriers mul_mem } /-- Build a `gcomm_monoid` instance for a collection of `add_submonoid`s. -/ @[simps to_gmonoid] def gcomm_monoid.of_add_submonoids [comm_semiring R] [add_comm_monoid ι] (carriers : ι → add_submonoid R) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gcomm_monoid (λ i, carriers i) := { mul_comm := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩, sigma.subtype_ext (add_comm _ _) (mul_comm _ _), ..gmonoid.of_add_submonoids carriers one_mem mul_mem} /-! #### From `add_subgroup`s -/ /-- Build a `ghas_one` instance for a collection of `add_subgroup`s. -/ @[simps one] def ghas_one.of_add_subgroups [ring R] [has_zero ι] (carriers : ι → add_subgroup R) (one_mem : (1 : R) ∈ carriers 0) : ghas_one (λ i, carriers i) := ghas_one.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem -- `@[simps]` doesn't generate a useful lemma, so we state one manually below. /-- Build a `ghas_mul` instance for a collection of `add_subgroup`s. -/ def ghas_mul.of_add_subgroups [ring R] [has_add ι] (carriers : ι → add_subgroup R) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : ghas_mul (λ i, carriers i) := ghas_mul.of_add_submonoids (λ i, (carriers i).to_add_submonoid) mul_mem -- `@[simps]` doesn't generate this well @[simp] lemma ghas_mul.of_add_subgroups_mul [ring R] [has_add ι] (carriers : ι → add_subgroup R) (mul_mem) {i j} (a : carriers i) (b : carriers j) : @ghas_mul.mul _ _ _ _ _ (ghas_mul.of_add_subgroups carriers mul_mem) i j a b = ⟨a * b, mul_mem a b⟩ := rfl /-- Build a `gmonoid` instance for a collection of `add_subgroup`s. -/ @[simps to_ghas_one to_ghas_mul] def gmonoid.of_add_subgroups [ring R] [add_monoid ι] (carriers : ι → add_subgroup R) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gmonoid (λ i, carriers i) := gmonoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem /-- Build a `gcomm_monoid` instance for a collection of `add_subgroup`s. -/ @[simps to_gmonoid] def gcomm_monoid.of_add_subgroups [comm_ring R] [add_comm_monoid ι] (carriers : ι → add_subgroup R) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gcomm_monoid (λ i, carriers i) := gcomm_monoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem /-! #### From `submodules`s -/ variables {A : Type*} /-- Build a `ghas_one` instance for a collection of `submodule`s. -/ @[simps one] def ghas_one.of_submodules [comm_semiring R] [semiring A] [algebra R A] [has_zero ι] (carriers : ι → submodule R A) (one_mem : (1 : A) ∈ carriers 0) : ghas_one (λ i, carriers i) := ghas_one.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem -- `@[simps]` doesn't generate a useful lemma, so we state one manually below. /-- Build a `ghas_mul` instance for a collection of `submodule`s. -/ def ghas_mul.of_submodules [comm_semiring R] [semiring A] [algebra R A] [has_add ι] (carriers : ι → submodule R A) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) : ghas_mul (λ i, carriers i) := ghas_mul.of_add_submonoids (λ i, (carriers i).to_add_submonoid) mul_mem -- `@[simps]` doesn't generate this well @[simp] lemma ghas_mul.of_submodules_mul [comm_semiring R] [semiring A] [algebra R A] [has_add ι] (carriers : ι → submodule R A) (mul_mem) {i j} (a : carriers i) (b : carriers j) : @ghas_mul.mul _ _ _ _ _ (ghas_mul.of_submodules carriers mul_mem) i j a b = ⟨a * b, mul_mem a b⟩ := rfl /-- Build a `gmonoid` instance for a collection of `submodules`s. -/ @[simps to_ghas_one to_ghas_mul] def gmonoid.of_submodules [comm_semiring R] [semiring A] [algebra R A] [add_monoid ι] (carriers : ι → submodule R A) (one_mem : (1 : A) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) : gmonoid (λ i, carriers i) := gmonoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem /-- Build a `gcomm_monoid` instance for a collection of `submodules`s. -/ @[simps to_gmonoid] def gcomm_monoid.of_submodules [comm_semiring R] [comm_semiring A] [algebra R A] [add_comm_monoid ι] (carriers : ι → submodule R A) (one_mem : (1 : A) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) : gcomm_monoid (λ i, carriers i) := gcomm_monoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem end shorthands variables (A : ι → Type*) /-! ### Instances for `⨁ i, A i` -/ section one variables [has_zero ι] [ghas_one A] [Π i, add_comm_monoid (A i)] instance : has_one (⨁ i, A i) := { one := direct_sum.of (λ i, A i) 0 ghas_one.one} end one section mul variables [has_add ι] [Π i, add_comm_monoid (A i)] [ghas_mul A] open add_monoid_hom (map_zero map_add flip_apply coe_comp comp_hom_apply_apply) /-- The multiplication from the `has_mul` instance, as a bundled homomorphism. -/ def mul_hom : (⨁ i, A i) →+ (⨁ i, A i) →+ ⨁ i, A i := direct_sum.to_add_monoid $ λ i, add_monoid_hom.flip $ direct_sum.to_add_monoid $ λ j, add_monoid_hom.flip $ (direct_sum.of A _).comp_hom.comp ghas_mul.mul instance : non_unital_non_assoc_semiring (⨁ i, A i) := { mul := λ a b, mul_hom A a b, zero := 0, add := (+), zero_mul := λ a, by simp only [map_zero, add_monoid_hom.zero_apply], mul_zero := λ a, by simp only [map_zero], left_distrib := λ a b c, by simp only [map_add], right_distrib := λ a b c, by simp only [map_add, add_monoid_hom.add_apply], .. direct_sum.add_comm_monoid _ _} variables {A} lemma mul_hom_of_of {i j} (a : A i) (b : A j) : mul_hom A (of _ i a) (of _ j b) = of _ (i + j) (ghas_mul.mul a b) := begin unfold mul_hom, rw [to_add_monoid_of, flip_apply, to_add_monoid_of, flip_apply, coe_comp, function.comp_app, comp_hom_apply_apply, coe_comp, function.comp_app], end lemma of_mul_of {i j} (a : A i) (b : A j) : of _ i a * of _ j b = of _ (i + j) (ghas_mul.mul a b) := mul_hom_of_of a b end mul section semiring variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A] open add_monoid_hom (flip_hom coe_comp comp_hom_apply_apply flip_apply flip_hom_apply) private lemma one_mul (x : ⨁ i, A i) : 1 * x = x := suffices mul_hom A 1 = add_monoid_hom.id (⨁ i, A i), from add_monoid_hom.congr_fun this x, begin apply add_hom_ext, intros i xi, unfold has_one.one, rw mul_hom_of_of, exact dfinsupp.single_eq_of_sigma_eq (gmonoid.one_mul ⟨i, xi⟩), end private lemma mul_one (x : ⨁ i, A i) : x * 1 = x := suffices (mul_hom A).flip 1 = add_monoid_hom.id (⨁ i, A i), from add_monoid_hom.congr_fun this x, begin apply add_hom_ext, intros i xi, unfold has_one.one, rw [flip_apply, mul_hom_of_of], exact dfinsupp.single_eq_of_sigma_eq (gmonoid.mul_one ⟨i, xi⟩), end private lemma mul_assoc (a b c : ⨁ i, A i) : a * b * c = a * (b * c) := suffices (mul_hom A).comp_hom.comp (mul_hom A) -- `λ a b c, a * b * c` as a bundled hom = (add_monoid_hom.comp_hom flip_hom $ -- `λ a b c, a * (b * c)` as a bundled hom (mul_hom A).flip.comp_hom.comp (mul_hom A)).flip, from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b) c, begin ext ai ax bi bx ci cx : 6, dsimp only [coe_comp, function.comp_app, comp_hom_apply_apply, flip_apply, flip_hom_apply], rw [mul_hom_of_of, mul_hom_of_of, mul_hom_of_of, mul_hom_of_of], exact dfinsupp.single_eq_of_sigma_eq (gmonoid.mul_assoc ⟨ai, ax⟩ ⟨bi, bx⟩ ⟨ci, cx⟩), end /-- The `semiring` structure derived from `gmonoid A`. -/ instance semiring : semiring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := one_mul A, mul_one := mul_one A, mul_assoc := mul_assoc A, ..direct_sum.non_unital_non_assoc_semiring _, } end semiring section comm_semiring variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_monoid A] private lemma mul_comm (a b : ⨁ i, A i) : a * b = b * a := suffices mul_hom A = (mul_hom A).flip, from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b, begin apply add_hom_ext, intros ai ax, apply add_hom_ext, intros bi bx, rw [add_monoid_hom.flip_apply, mul_hom_of_of, mul_hom_of_of], exact dfinsupp.single_eq_of_sigma_eq (gcomm_monoid.mul_comm ⟨ai, ax⟩ ⟨bi, bx⟩), end /-- The `comm_semiring` structure derived from `gcomm_monoid A`. -/ instance comm_semiring : comm_semiring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), mul_comm := mul_comm A, ..direct_sum.semiring _, } end comm_semiring section ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gmonoid A] /-- The `ring` derived from `gmonoid A`. -/ instance ring : ring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), neg := has_neg.neg, ..(direct_sum.semiring _), ..(direct_sum.add_comm_group _), } end ring section comm_ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_monoid A] /-- The `comm_ring` derived from `gcomm_monoid A`. -/ instance comm_ring : comm_ring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), neg := has_neg.neg, ..(direct_sum.ring _), ..(direct_sum.comm_semiring _), } end comm_ring /-! ### Instances for `A 0` The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various types of multiplicative structure. -/ section grade_zero section one variables [has_zero ι] [ghas_one A] [Π i, add_comm_monoid (A i)] /-- `1 : A 0` is the value provided in `direct_sum.ghas_one.one`. -/ @[nolint unused_arguments] instance grade_zero.has_one : has_one (A 0) := ⟨ghas_one.one⟩ @[simp] lemma of_zero_one : of _ 0 (1 : A 0) = 1 := rfl end one section mul variables [add_monoid ι] [Π i, add_comm_monoid (A i)] [ghas_mul A] /-- `(•) : A 0 → A i → A i` is the value provided in `direct_sum.ghas_mul.mul`, composed with an `eq.rec` to turn `A (0 + i)` into `A i`. -/ instance grade_zero.has_scalar (i : ι) : has_scalar (A 0) (A i) := { smul := λ x y, (zero_add i).rec (ghas_mul.mul x y) } /-- `(*) : A 0 → A 0 → A 0` is the value provided in `direct_sum.ghas_mul.mul`, composed with an `eq.rec` to turn `A (0 + 0)` into `A 0`. -/ instance grade_zero.has_mul : has_mul (A 0) := { mul := (•) } @[simp]lemma grade_zero.smul_eq_mul (a b : A 0) : a • b = a * b := rfl @[simp] lemma of_zero_smul {i} (a : A 0) (b : A i) : of _ _ (a • b) = of _ _ a * of _ _ b := begin rw of_mul_of, dsimp [has_mul.mul, direct_sum.of, dfinsupp.single_add_hom_apply], congr' 1, rw zero_add, apply eq_rec_heq, end @[simp] lemma of_zero_mul (a b : A 0) : of _ 0 (a * b) = of _ 0 a * of _ 0 b:= of_zero_smul A a b instance grade_zero.non_unital_non_assoc_semiring : non_unital_non_assoc_semiring (A 0) := function.injective.non_unital_non_assoc_semiring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of A 0).map_add (of_zero_mul A) instance grade_zero.smul_with_zero (i : ι) : smul_with_zero (A 0) (A i) := begin letI := smul_with_zero.comp_hom (⨁ i, A i) (of A 0).to_zero_hom, refine dfinsupp.single_injective.smul_with_zero (of A i).to_zero_hom (of_zero_smul A), end end mul section semiring variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A] /-- The `semiring` structure derived from `gmonoid A`. -/ instance grade_zero.semiring : semiring (A 0) := function.injective.semiring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) /-- `of A 0` is a `ring_hom`, using the `direct_sum.grade_zero.semiring` structure. -/ def of_zero_ring_hom : A 0 →+* (⨁ i, A i) := { map_one' := of_zero_one A, map_mul' := of_zero_mul A, ..(of _ 0) } /-- Each grade `A i` derives a `A 0`-module structure from `gmonoid A`. Note that this results in an overall `module (A 0) (⨁ i, A i)` structure via `direct_sum.module`. -/ instance grade_zero.module {i} : module (A 0) (A i) := begin letI := module.comp_hom (⨁ i, A i) (of_zero_ring_hom A), exact dfinsupp.single_injective.module (A 0) (of A i) (λ a, of_zero_smul A a), end end semiring section comm_semiring variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_monoid A] /-- The `comm_semiring` structure derived from `gcomm_monoid A`. -/ instance grade_zero.comm_semiring : comm_semiring (A 0) := function.injective.comm_semiring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) end comm_semiring section ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gmonoid A] /-- The `ring` derived from `gmonoid A`. -/ instance grade_zero.ring : ring (A 0) := function.injective.ring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) (of A 0).map_neg (of A 0).map_sub end ring section comm_ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_monoid A] /-- The `comm_ring` derived from `gcomm_monoid A`. -/ instance grade_zero.comm_ring : comm_ring (A 0) := function.injective.comm_ring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) (of A 0).map_neg (of A 0).map_sub end comm_ring end grade_zero section to_semiring variables {R : Type*} [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A] [semiring R] variables {A} /-- If two ring homomorphisms from `⨁ i, A i` are equal on each `of A i y`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' (F G : (⨁ i, A i) →+* R) (h : ∀ i, (F : (⨁ i, A i) →+ R).comp (of _ i) = (G : (⨁ i, A i) →+ R).comp (of _ i)) : F = G := ring_hom.coe_add_monoid_hom_injective $ direct_sum.add_hom_ext' h /-- A family of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul` describes a `ring_hom`s on `⨁ i, A i`. This is a stronger version of `direct_sum.to_monoid`. Of particular interest is the case when `A i` are bundled subojects, `f` is the family of coercions such as `add_submonoid.subtype (A i)`, and the `[gmonoid A]` structure originates from `direct_sum.gmonoid.of_add_submonoids`, in which case the proofs about `ghas_one` and `ghas_mul` can be discharged by `rfl`. -/ @[simps] def to_semiring (f : Π i, A i →+ R) (hone : f _ (ghas_one.one) = 1) (hmul : ∀ {i j} (ai : A i) (aj : A j), f _ (ghas_mul.mul ai aj) = f _ ai * f _ aj) : (⨁ i, A i) →+* R := { to_fun := to_add_monoid f, map_one' := begin change (to_add_monoid f) (of _ 0 _) = 1, rw to_add_monoid_of, exact hone end, map_mul' := begin rw (to_add_monoid f).map_mul_iff, ext xi xv yi yv : 4, show to_add_monoid f (of A xi xv * of A yi yv) = to_add_monoid f (of A xi xv) * to_add_monoid f (of A yi yv), rw [of_mul_of, to_add_monoid_of, to_add_monoid_of, to_add_monoid_of], exact hmul _ _, end, .. to_add_monoid f} @[simp] lemma to_semiring_of (f : Π i, A i →+ R) (hone hmul) (i : ι) (x : A i) : to_semiring f hone hmul (of _ i x) = f _ x := to_add_monoid_of f i x @[simp] lemma to_semiring_coe_add_monoid_hom (f : Π i, A i →+ R) (hone hmul): (to_semiring f hone hmul : (⨁ i, A i) →+ R) = to_add_monoid f := rfl /-- Families of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul` are isomorphic to `ring_hom`s on `⨁ i, A i`. This is a stronger version of `dfinsupp.lift_add_hom`. -/ @[simps] def lift_ring_hom : {f : Π {i}, A i →+ R // f (ghas_one.one) = 1 ∧ ∀ {i j} (ai : A i) (aj : A j), f (ghas_mul.mul ai aj) = f ai * f aj} ≃ ((⨁ i, A i) →+* R) := { to_fun := λ f, to_semiring f.1 f.2.1 f.2.2, inv_fun := λ F, ⟨λ i, (F : (⨁ i, A i) →+ R).comp (of _ i), begin simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom], rw ←F.map_one, refl end, λ i j ai aj, begin simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom], rw [←F.map_mul, of_mul_of], end⟩, left_inv := λ f, begin ext xi xv, exact to_add_monoid_of f.1 xi xv, end, right_inv := λ F, begin apply ring_hom.coe_add_monoid_hom_injective, ext xi xv, simp only [ring_hom.coe_add_monoid_hom_mk, direct_sum.to_add_monoid_of, add_monoid_hom.mk_coe, add_monoid_hom.comp_apply, to_semiring_coe_add_monoid_hom], end} /-- Two `ring_hom`s out of a direct sum are equal if they agree on the generators. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext ⦃f g : (⨁ i, A i) →+* R⦄ (h : ∀ i, (↑f : (⨁ i, A i) →+ R).comp (of A i) = (↑g : (⨁ i, A i) →+ R).comp (of A i)) : f = g := direct_sum.lift_ring_hom.symm.injective $ subtype.ext $ funext h end to_semiring end direct_sum /-! ### Concrete instances -/ /-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/ instance semiring.direct_sum_gmonoid {R : Type*} [add_monoid ι] [semiring R] : direct_sum.gmonoid (λ i : ι, R) := { mul := λ i j, add_monoid_hom.mul, one_mul := λ a, sigma.ext (zero_add _) (heq_of_eq (one_mul _)), mul_one := λ a, sigma.ext (add_zero _) (heq_of_eq (mul_one _)), mul_assoc := λ a b c, sigma.ext (add_assoc _ _ _) (heq_of_eq (mul_assoc _ _ _)), one := 1 } @[simp] lemma semiring.direct_sum_mul {R : Type*} [add_monoid ι] [semiring R] {i j} (x y : R) : @direct_sum.ghas_mul.mul _ _ (λ _ : ι, R) _ _ _ i j x y = x * y := rfl open_locale direct_sum -- To check the lemma above does match example {R : Type*} [add_monoid ι] [semiring R] (i j : ι) (a b : R) : (direct_sum.of _ i a * direct_sum.of _ j b : ⨁ i, R) = direct_sum.of _ (i + j) (by exact a * b) := by rw [direct_sum.of_mul_of, semiring.direct_sum_mul] /-- A direct sum of copies of a `comm_semiring` inherits the commutative multiplication structure. -/ instance comm_semiring.direct_sum_gcomm_monoid {R : Type*} [add_comm_monoid ι] [comm_semiring R] : direct_sum.gcomm_monoid (λ i : ι, R) := { mul_comm := λ a b, sigma.ext (add_comm _ _) (heq_of_eq (mul_comm _ _)), .. semiring.direct_sum_gmonoid } namespace submodule variables {R A : Type*} [comm_semiring R] /-- A direct sum of powers of a submodule of an algebra has a multiplicative structure. -/ instance nat_power_direct_sum_gmonoid [semiring A] [algebra R A] (S : submodule R A) : direct_sum.gmonoid (λ i : ℕ, ↥(S ^ i)) := direct_sum.gmonoid.of_submodules _ (by { rw [←one_le, pow_zero], exact le_rfl }) (λ i j p q, by { rw pow_add, exact submodule.mul_mem_mul p.prop q.prop }) /-- A direct sum of powers of a submodule of a commutative algebra has a commutative multiplicative structure. -/ instance nat_power_direct_sum_gcomm_monoid [comm_semiring A] [algebra R A] (S : submodule R A) : direct_sum.gcomm_monoid (λ i : ℕ, ↥(S ^ i)) := direct_sum.gcomm_monoid.of_submodules _ (by { rw [←one_le, pow_zero], exact le_rfl }) (λ i j p q, by { rw pow_add, exact submodule.mul_mem_mul p.prop q.prop }) end submodule
8ea2f9e254513b17885976be7f4fab1c0cd2906a
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_get_point_from_x_soundness.lean
ab13b27d171e0633007415ccc9035a2c38da5a0c
[]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
26,289
lean
/- File: signature_recover_public_key_get_point_from_x_soundness.lean Autogenerated file. -/ import starkware.cairo.lean.semantics.soundness.hoare import .signature_recover_public_key_code import ..signature_recover_public_key_spec import .signature_recover_public_key_validate_reduced_field_element_soundness import .signature_recover_public_key_reduce_soundness import .signature_recover_public_key_unreduced_sqr_soundness import .signature_recover_public_key_unreduced_mul_soundness open tactic open starkware.cairo.common.cairo_secp.signature open starkware.cairo.common.cairo_secp.constants open starkware.cairo.common.math open starkware.cairo.common.cairo_secp.field open starkware.cairo.common.cairo_secp.ec open starkware.cairo.common.cairo_secp.bigint variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F] variable mem : F → F variable σ : register_state F /- starkware.cairo.common.cairo_secp.signature.get_point_from_x autogenerated soundness theorem -/ theorem auto_sound_get_point_from_x -- arguments (range_check_ptr : F) (x : BigInt3 F) (v : F) -- code is in memory at σ.pc (h_mem : mem_at mem code_get_point_from_x σ.pc) -- all dependencies are in memory (h_mem_0 : mem_at mem code_assert_nn (σ.pc - 751)) (h_mem_1 : mem_at mem code_assert_le (σ.pc - 747)) (h_mem_2 : mem_at mem code_assert_nn_le (σ.pc - 742)) (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 719)) (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 707)) (h_mem_6 : mem_at mem code_unreduced_sqr (σ.pc - 687)) (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 671)) (h_mem_9 : mem_at mem code_reduce (σ.pc - 612)) (h_mem_10 : mem_at mem code_validate_reduced_field_element (σ.pc - 599)) -- input arguments on the stack (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 7)) (hin_x : x = cast_BigInt3 mem (σ.fp - 6)) (hin_v : v = mem (σ.fp - 3)) -- conclusion : ensures_ret mem σ (λ κ τ, ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 7)) (mem $ τ.ap - 7) (spec_get_point_from_x mem κ range_check_ptr x v (mem (τ.ap - 7)) (cast_EcPoint mem (τ.ap - 6)))) := begin apply ensures_of_ensuresb, intro νbound, have h_mem_rec := h_mem, unpack_memory code_get_point_from_x at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64, hpc65⟩, -- ap += 6 step_advance_ap hpc0 hpc1, -- function call step_assert_eq hpc2 with arg0, step_assert_eq hpc3 with arg1, step_sub hpc4 (auto_sound_assert_nn mem _ range_check_ptr v _ _ _), { rw hpc5, norm_num2, exact h_mem_0 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v] }, try { dsimp [cast_BigInt3] }, try { arith_simps }, try { simp only [arg0, arg1] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v] }, try { dsimp [cast_BigInt3] }, try { arith_simps }, try { simp only [arg0, arg1] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, intros κ_call6 ap6 h_call6, rcases h_call6 with ⟨h_call6_ap_offset, h_call6⟩, rcases h_call6 with ⟨rc_m6, rc_mle6, hl_range_check_ptr₁, h_call6⟩, generalize' hr_rev_range_check_ptr₁: mem (ap6 - 1) = range_check_ptr₁, have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁, try { simp only [arg0 ,arg1] at hl_range_check_ptr₁ }, rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁, try { simp only [arg0 ,arg1] at h_call6 }, rw [hin_range_check_ptr] at h_call6, clear arg0 arg1, -- function call step_assert_eq hpc6 with arg0, step_assert_eq hpc7 with arg1, step_assert_eq hpc8 with arg2, step_sub hpc9 (auto_sound_unreduced_sqr mem _ x _ _), { rw hpc10, norm_num2, exact h_mem_6 }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁] }, try { dsimp [cast_BigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2] }, try { simp only [h_call6_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call11 ap11 h_call11, rcases h_call11 with ⟨h_call11_ap_offset, h_call11⟩, generalize' hr_rev_x_square: cast_UnreducedBigInt3 mem (ap11 - 3) = x_square, simp only [hr_rev_x_square] at h_call11, have htv_x_square := hr_rev_x_square.symm, clear hr_rev_x_square, clear arg0 arg1 arg2, -- function call step_assert_eq hpc11 with arg0, step_assert_eq hpc12 with arg1, step_assert_eq hpc13 with arg2, step_assert_eq hpc14 with arg3, step_sub hpc15 (auto_sound_reduce mem _ range_check_ptr₁ x_square _ _ _ _ _), { rw hpc16, norm_num2, exact h_mem_9 }, { rw hpc16, norm_num2, exact h_mem_4 }, { rw hpc16, norm_num2, exact h_mem_7 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call17 ap17 h_call17, rcases h_call17 with ⟨h_call17_ap_offset, h_call17⟩, rcases h_call17 with ⟨rc_m17, rc_mle17, hl_range_check_ptr₂, h_call17⟩, generalize' hr_rev_range_check_ptr₂: mem (ap17 - 4) = range_check_ptr₂, have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂, generalize' hr_rev_x_square_reduced: cast_BigInt3 mem (ap17 - 3) = x_square_reduced, simp only [hr_rev_x_square_reduced] at h_call17, have htv_x_square_reduced := hr_rev_x_square_reduced.symm, clear hr_rev_x_square_reduced, try { simp only [arg0 ,arg1 ,arg2 ,arg3] at hl_range_check_ptr₂ }, try { rw [h_call11_ap_offset] at hl_range_check_ptr₂ }, try { arith_simps at hl_range_check_ptr₂ }, rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂, try { simp only [arg0 ,arg1 ,arg2 ,arg3] at h_call17 }, try { rw [h_call11_ap_offset] at h_call17 }, try { arith_simps at h_call17 }, rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call17, clear arg0 arg1 arg2 arg3, -- function call step_assert_eq hpc17 with arg0, step_assert_eq hpc18 with arg1, step_assert_eq hpc19 with arg2, step_assert_eq hpc20 with arg3, step_assert_eq hpc21 with arg4, step_assert_eq hpc22 with arg5, step_sub hpc23 (auto_sound_unreduced_mul mem _ x x_square_reduced _ _ _), { rw hpc24, norm_num2, exact h_mem_5 }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call25 ap25 h_call25, rcases h_call25 with ⟨h_call25_ap_offset, h_call25⟩, generalize' hr_rev_x_cube: cast_UnreducedBigInt3 mem (ap25 - 3) = x_cube, simp only [hr_rev_x_cube] at h_call25, have htv_x_cube := hr_rev_x_cube.symm, clear hr_rev_x_cube, clear arg0 arg1 arg2 arg3 arg4 arg5, -- local var step_assert_eq hpc25 with temp0, step_assert_eq hpc26 with temp1, step_assert_eq hpc27 with temp2, have lc_x_cube: x_cube = cast_UnreducedBigInt3 mem σ.fp, { try { ext } ; { try { simp only [htv_x_cube] }, try { dsimp [cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [temp0, temp1, temp2] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, clear temp0 temp1 temp2, -- function call step_assert_eq hpc28 with arg0, step_sub hpc29 (auto_sound_nondet_bigint3 mem _ range_check_ptr₂ _ _), { rw hpc30, norm_num2, exact h_mem_4 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, intros κ_call31 ap31 h_call31, rcases h_call31 with ⟨h_call31_ap_offset, h_call31⟩, rcases h_call31 with ⟨rc_m31, rc_mle31, hl_range_check_ptr₃, h_call31⟩, generalize' hr_rev_range_check_ptr₃: mem (ap31 - 4) = range_check_ptr₃, have htv_range_check_ptr₃ := hr_rev_range_check_ptr₃.symm, clear hr_rev_range_check_ptr₃, generalize' hr_rev_y: cast_BigInt3 mem (ap31 - 3) = y, simp only [hr_rev_y] at h_call31, have htv_y := hr_rev_y.symm, clear hr_rev_y, try { simp only [arg0] at hl_range_check_ptr₃ }, try { rw [h_call25_ap_offset] at hl_range_check_ptr₃ }, try { arith_simps at hl_range_check_ptr₃ }, rw [←htv_range_check_ptr₃, ←htv_range_check_ptr₂] at hl_range_check_ptr₃, try { simp only [arg0] at h_call31 }, try { rw [h_call25_ap_offset] at h_call31 }, try { arith_simps at h_call31 }, rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call31, clear arg0, -- local var step_assert_eq hpc31 with temp0, step_assert_eq hpc32 with temp1, step_assert_eq hpc33 with temp2, have lc_y: y = cast_BigInt3 mem (σ.fp + 3), { try { ext } ; { try { simp only [htv_y] }, try { dsimp [cast_BigInt3] }, try { arith_simps }, try { simp only [temp0, temp1, temp2] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, clear temp0 temp1 temp2, -- function call step_assert_eq hpc34 with arg0, step_assert_eq hpc35 with arg1, step_assert_eq hpc36 with arg2, step_assert_eq hpc37 with arg3, step_sub hpc38 (auto_sound_validate_reduced_field_element mem _ range_check_ptr₃ y _ _ _ _ _ _), { rw hpc39, norm_num2, exact h_mem_10 }, { rw hpc39, norm_num2, exact h_mem_0 }, { rw hpc39, norm_num2, exact h_mem_1 }, { rw hpc39, norm_num2, exact h_mem_2 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube, htv_range_check_ptr₃, htv_y, lc_y] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube, htv_range_check_ptr₃, htv_y, lc_y] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call40 ap40 h_call40, rcases h_call40 with ⟨rc_m40, rc_mle40, hl_range_check_ptr₄, h_call40⟩, generalize' hr_rev_range_check_ptr₄: mem (ap40 - 1) = range_check_ptr₄, have htv_range_check_ptr₄ := hr_rev_range_check_ptr₄.symm, clear hr_rev_range_check_ptr₄, try { simp only [arg0 ,arg1 ,arg2 ,arg3] at hl_range_check_ptr₄ }, rw [←htv_range_check_ptr₄, ←htv_range_check_ptr₃] at hl_range_check_ptr₄, try { simp only [arg0 ,arg1 ,arg2 ,arg3] at h_call40 }, rw [←htv_range_check_ptr₃, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call40, clear arg0 arg1 arg2 arg3, -- function call step_assert_eq hpc40 with arg0, step_assert_eq hpc41 with arg1, step_assert_eq hpc42 hpc43 with arg2, have h_δ40_c0 : ∀ x : F, x / (2 : ℤ) = x * (-1809251394333065606848661391547535052811553607665798349986546028067936010240 : ℤ), { intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 }, have h_δ40_c0_fz : ∀ x : F, x / 2 = x / (2 : ℤ), { intro x, norm_cast }, step_sub hpc44 (auto_sound_assert_nn mem _ range_check_ptr₄ ((y.d0 + v) / (2 : ℤ)) _ _ _), { rw hpc45, norm_num2, exact h_mem_0 }, { try { simp only [h_δ40_c0_fz, h_δ40_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube, htv_range_check_ptr₃, htv_y, lc_y, htv_range_check_ptr₄] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { simp only [h_δ40_c0_fz, h_δ40_c0] }, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube, htv_range_check_ptr₃, htv_y, lc_y, htv_range_check_ptr₄] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, intros κ_call46 ap46 h_call46, rcases h_call46 with ⟨h_call46_ap_offset, h_call46⟩, rcases h_call46 with ⟨rc_m46, rc_mle46, hl_range_check_ptr₅, h_call46⟩, generalize' hr_rev_range_check_ptr₅: mem (ap46 - 1) = range_check_ptr₅, have htv_range_check_ptr₅ := hr_rev_range_check_ptr₅.symm, clear hr_rev_range_check_ptr₅, try { simp only [arg0 ,arg1 ,arg2] at hl_range_check_ptr₅ }, rw [←htv_range_check_ptr₅, ←htv_range_check_ptr₄] at hl_range_check_ptr₅, try { simp only [arg0 ,arg1 ,arg2] at h_call46 }, rw [←htv_range_check_ptr₄, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call46, clear arg0 arg1 arg2, -- function call step_assert_eq hpc46 with arg0, step_assert_eq hpc47 with arg1, step_assert_eq hpc48 with arg2, step_sub hpc49 (auto_sound_unreduced_sqr mem _ y _ _), { rw hpc50, norm_num2, exact h_mem_6 }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube, htv_range_check_ptr₃, htv_y, lc_y, htv_range_check_ptr₄, htv_range_check_ptr₅] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, arg2] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset, h_call46_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call51 ap51 h_call51, rcases h_call51 with ⟨h_call51_ap_offset, h_call51⟩, generalize' hr_rev_y_square: cast_UnreducedBigInt3 mem (ap51 - 3) = y_square, simp only [hr_rev_y_square] at h_call51, have htv_y_square := hr_rev_y_square.symm, clear hr_rev_y_square, clear arg0 arg1 arg2, -- function call step_assert_eq hpc51 hpc52 with arg0, step_assert_eq hpc53 with arg1, step_assert_eq hpc54 with arg2, step_assert_eq hpc55 with arg3, step_assert_eq hpc56 with arg4, step_sub hpc57 (auto_sound_verify_zero mem _ range_check_ptr₅ { d0 := x_cube.d0 + BETA - y_square.d0, d1 := x_cube.d1 - y_square.d1, d2 := x_cube.d2 - y_square.d2 } _ _ _), { rw hpc58, norm_num2, exact h_mem_7 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube, htv_range_check_ptr₃, htv_y, lc_y, htv_range_check_ptr₄, htv_range_check_ptr₅, htv_y_square] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, (eq_sub_of_eq_add arg2), (eq_sub_of_eq_add arg3), (eq_sub_of_eq_add arg4)] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset, h_call46_ap_offset, h_call51_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube, htv_range_check_ptr₃, htv_y, lc_y, htv_range_check_ptr₄, htv_range_check_ptr₅, htv_y_square] }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [arg0, arg1, (eq_sub_of_eq_add arg2), (eq_sub_of_eq_add arg3), (eq_sub_of_eq_add arg4)] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset, h_call46_ap_offset, h_call51_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call59 ap59 h_call59, rcases h_call59 with ⟨h_call59_ap_offset, h_call59⟩, rcases h_call59 with ⟨rc_m59, rc_mle59, hl_range_check_ptr₆, h_call59⟩, generalize' hr_rev_range_check_ptr₆: mem (ap59 - 1) = range_check_ptr₆, have htv_range_check_ptr₆ := hr_rev_range_check_ptr₆.symm, clear hr_rev_range_check_ptr₆, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4] at hl_range_check_ptr₆ }, try { rw [h_call51_ap_offset] at hl_range_check_ptr₆ }, try { arith_simps at hl_range_check_ptr₆ }, rw [←htv_range_check_ptr₆, ←htv_range_check_ptr₅] at hl_range_check_ptr₆, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4] at h_call59 }, try { rw [h_call51_ap_offset] at h_call59 }, try { arith_simps at h_call59 }, rw [←htv_range_check_ptr₅, hl_range_check_ptr₅, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr] at h_call59, clear arg0 arg1 arg2 arg3 arg4, -- return step_assert_eq hpc59 with hret0, step_assert_eq hpc60 with hret1, step_assert_eq hpc61 with hret2, step_assert_eq hpc62 with hret3, step_assert_eq hpc63 with hret4, step_assert_eq hpc64 with hret5, step_ret hpc65, -- finish step_done, use_only [rfl, rfl], -- range check condition use_only (rc_m6+rc_m17+rc_m31+rc_m40+rc_m46+rc_m59+0+0), split, linarith [rc_mle6, rc_mle17, rc_mle31, rc_mle40, rc_mle46, rc_mle59], split, { arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3 ,hret4 ,hret5] }, rw [←htv_range_check_ptr₆, hl_range_check_ptr₆, hl_range_check_ptr₅, hl_range_check_ptr₄, hl_range_check_ptr₃, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof -- user-provided reduction suffices auto_spec: auto_spec_get_point_from_x mem _ range_check_ptr x v _ _, { apply sound_get_point_from_x, apply auto_spec }, -- prove the auto generated assertion dsimp [auto_spec_get_point_from_x], try { norm_num1 }, try { arith_simps }, use_only [κ_call6], use_only [range_check_ptr₁], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have spec6 := h_call6 rc_h_range_check_ptr', rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec6, try { dsimp at spec6, arith_simps at spec6 }, use_only [spec6], use_only [κ_call11], use_only [x_square], try { dsimp at h_call11, arith_simps at h_call11 }, try { use_only [h_call11] }, use_only [κ_call17], use_only [range_check_ptr₂], use_only [x_square_reduced], have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁, have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' }, have spec17 := h_call17 rc_h_range_check_ptr₁', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec17, try { dsimp at spec17, arith_simps at spec17 }, use_only [spec17], use_only [κ_call25], use_only [x_cube], try { dsimp at h_call25, arith_simps at h_call25 }, try { use_only [h_call25] }, use_only [κ_call31], use_only [range_check_ptr₃], use_only [y], have rc_h_range_check_ptr₃ := range_checked_offset' rc_h_range_check_ptr₂, have rc_h_range_check_ptr₃' := range_checked_add_right rc_h_range_check_ptr₃, try { norm_cast at rc_h_range_check_ptr₃' }, have spec31 := h_call31 rc_h_range_check_ptr₂', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←htv_range_check_ptr₃] at spec31, try { dsimp at spec31, arith_simps at spec31 }, use_only [spec31], use_only [κ_call40], use_only [range_check_ptr₄], have rc_h_range_check_ptr₄ := range_checked_offset' rc_h_range_check_ptr₃, have rc_h_range_check_ptr₄' := range_checked_add_right rc_h_range_check_ptr₄, try { norm_cast at rc_h_range_check_ptr₄' }, have spec40 := h_call40 rc_h_range_check_ptr₃', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←htv_range_check_ptr₄] at spec40, try { dsimp at spec40, arith_simps at spec40 }, use_only [spec40], use_only [κ_call46], use_only [range_check_ptr₅], have rc_h_range_check_ptr₅ := range_checked_offset' rc_h_range_check_ptr₄, have rc_h_range_check_ptr₅' := range_checked_add_right rc_h_range_check_ptr₅, try { norm_cast at rc_h_range_check_ptr₅' }, have spec46 := h_call46 rc_h_range_check_ptr₄', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←hl_range_check_ptr₄, ←htv_range_check_ptr₅] at spec46, try { dsimp at spec46, arith_simps at spec46 }, use_only [spec46], use_only [κ_call51], use_only [y_square], try { dsimp at h_call51, arith_simps at h_call51 }, try { use_only [h_call51] }, use_only [κ_call59], use_only [range_check_ptr₆], have rc_h_range_check_ptr₆ := range_checked_offset' rc_h_range_check_ptr₅, have rc_h_range_check_ptr₆' := range_checked_add_right rc_h_range_check_ptr₆, try { norm_cast at rc_h_range_check_ptr₆' }, have spec59 := h_call59 rc_h_range_check_ptr₅', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←hl_range_check_ptr₂, ←hl_range_check_ptr₃, ←hl_range_check_ptr₄, ←hl_range_check_ptr₅, ←htv_range_check_ptr₆] at spec59, try { dsimp at spec59, arith_simps at spec59 }, use_only [spec59], try { split, linarith }, try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_x, hin_v, htv_range_check_ptr₁, htv_x_square, htv_range_check_ptr₂, htv_x_square_reduced, htv_x_cube, lc_x_cube, htv_range_check_ptr₃, htv_y, lc_y, htv_range_check_ptr₄, htv_range_check_ptr₅, htv_y_square, htv_range_check_ptr₆] }, }, try { dsimp [cast_BigInt3, cast_UnreducedBigInt3, cast_EcPoint] }, try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3, hret4, hret5] }, try { simp only [h_call6_ap_offset, h_call11_ap_offset, h_call17_ap_offset, h_call25_ap_offset, h_call31_ap_offset, h_call46_ap_offset, h_call51_ap_offset, h_call59_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, end
a5f248bc800f4b208748416a317f0d8220d74854
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/tests/lean/zipper.lean
9c2410cfb18a6ceefb4f64790e0ffcfa48d5b0d1
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,409
lean
structure ListZipper (α : Type) := (xs : List α) (bs : List α) -- set_option trace.compiler.ir.rc true variables {α : Type} namespace ListZipper def goForward : ListZipper α → ListZipper α | ⟨[], bs⟩ => ⟨[], bs⟩ | ⟨x::xs, bs⟩ => ⟨xs, x::bs⟩ def goBackward : ListZipper α → ListZipper α | ⟨xs, []⟩ => ⟨xs, []⟩ | ⟨xs, b::bs⟩ => ⟨b::xs, bs⟩ def insert : ListZipper α → α → ListZipper α | ⟨xs, bs⟩, x => ⟨xs, x::bs⟩ def erase : ListZipper α → ListZipper α | ⟨[], bs⟩ => ⟨[], bs⟩ | ⟨x::xs, bs⟩ => ⟨xs, bs⟩ def curr [Inhabited α] : ListZipper α → α | ⟨[], bs⟩ => arbitrary _ | ⟨x::xs, bs⟩ => x def currOpt : ListZipper α → Option α | ⟨[], bs⟩ => none | ⟨x::xs, bs⟩ => some x def toList : ListZipper α → List α | ⟨xs, bs⟩ => bs.reverse ++ xs def atEnd (z : ListZipper α) : Bool := z.xs.isEmpty end ListZipper def List.toListZipper (xs : List α) : ListZipper α := ⟨xs, []⟩ partial def testAux : ListZipper Nat → ListZipper Nat | z => if z.atEnd then z else if z.curr % 2 == 0 then testAux (z.goForward.insert 0) else if z.curr > 20 then testAux z.erase else testAux z.goForward -- testAux z.goForward def test (xs : List Nat) : List Nat := (testAux xs.toListZipper).toList #eval (IO.println (test [10, 11, 13, 20, 22, 40, 41, 11]) : IO Unit)
5e5c98d2b1d25d04950b9ad272488a016b2b41e3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/apply.lean
4200c49f2fdbadcd3b387c3fd535344b51b346a1
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,296
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort universes u_1 namespace Mathlib /-! This file provides an alternative implementation for `apply` to fix the so-called "apply bug". The issue arises when the goals is a Π-type -- whether it is visible or hidden behind a definition. For instance, consider the following proof: ``` example {α β} (x y z : α → β) (h₀ : x ≤ y) (h₁ : y ≤ z) : x ≤ z := begin apply le_trans, end ``` Because `x ≤ z` is definitionally equal to `∀ i, x i ≤ z i`, `apply` will fail. The alternative definition, `apply'` fixes this. When `apply` would work, `apply` is used and otherwise, a different strategy is deployed -/ namespace tactic /-- With `gs` a list of proof goals, `reorder_goals gs new_g` will use the `new_goals` policy `new_g` to rearrange the dependent goals to either drop them, push them to the end of the list or leave them in place. The `bool` values in `gs` indicates whether the goal is dependent or not. -/ def reorder_goals {α : Type u_1} (gs : List (Bool × α)) : new_goals → List α := sorry
bdec1b485b292a719efaa0093a1eca0959bbc918
5ca7b1b12d14c4742e29366312ba2c2ef8201b21
/experiments/bool_le_induction_example.lean
a4d4333055ca6a7d92de9eef16c57e9bc39b4041
[ "Apache-2.0" ]
permissive
MatthiasHu/natural_number_game
2e464482ef3001863430b0336133b6697b275ba3
2d764f72669ae30861f6a1057fce0257f3e466c4
refs/heads/master
1,609,719,110,419
1,576,345,737,000
1,576,345,737,000
240,296,314
0
0
Apache-2.0
1,581,608,357,000
1,581,608,356,000
null
UTF-8
Lean
false
false
2,099
lean
-- random experiments that predate [nat_num_game] approach import tactic.linarith -- any import is fine @[derive decidable_eq] inductive mybool | ff : mybool | tt : mybool namespace mybool inductive le : mybool → mybool → Prop | f_le_f : le ff ff | f_le_t : le ff tt | t_le_t : le tt tt -- notation instance : has_le mybool := ⟨mybool.le⟩ -- I now never want to see `le` ever ever again. open le -- Could I have generated this automatically? instance decidable_le : ∀ a b : mybool, decidable (a ≤ b) := λ a b, mybool.rec_on a (mybool.rec_on b (is_true f_le_f) $ is_true f_le_t) $ mybool.rec_on b (is_false $ λ h, by cases h) $ is_true t_le_t instance decidable_le' : ∀ a b : mybool, decidable (a ≤ b) := λ a b, begin cases a; cases b; -- just work it out Lean try {exact is_true t_le_t}; try {exact is_true f_le_t}; try {exact is_true f_le_f}; try {exact (is_false $ λ h, by cases h)} end theorem induction (a b : mybool) (h : a ≤ b) (P : Π (c d : mybool), Prop) : P ff ff → P ff tt → P tt tt → P a b := λ h_ff_ff h_ff_tt h_tt_tt, begin cases a;cases b, exact h_ff_ff, exact h_ff_tt, cases h, exact h_tt_tt, end example (a b : mybool) (h : a ≤ b) (P : Π (a b : mybool), Prop) -- possible other hypotheses here : P a b := begin cases a; cases b; cases h, -- is there a tactic of the form `thing h` which does the same thing? sorry, sorry, sorry end -- These presumably could have been auto-generated but I didn't want -- to clog up the code with weird @isms theorem le_refl (a : mybool) : a ≤ a := begin cases a; exact dec_trivial, -- Is there just one tactic which will do this? end theorem le_trans {a b c : mybool} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := begin cases a;cases b;cases c; cases hab; cases hbc; exact dec_trivial, -- Is there just one tactic which will do this? end theorem le_antisymm {a b : mybool} (hab : a ≤ b) (hba : b ≤ a) : a = b := begin cases a; cases b; cases hab; cases hba; exact dec_trivial, -- Is there just one tactic which will do this? end end mybool
57c036fcef1810e111b210c3456aa7f9bddfd99e
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/group_theory/group_action/defs.lean
08f816db11bbda9c47513fe51c5f2b673692b07a
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,287
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yury Kudryashov -/ import algebra.group.defs import algebra.group.hom import algebra.group.type_tags import logic.embedding /-! # Definitions of group actions This file defines a hierarchy of group action type-classes: * `has_scalar M α` and its additive version `has_vadd G P` are notation typeclasses for `•` and `+ᵥ`, respectively; * `mul_action M α` and its additive version `add_action G P` are typeclasses used for actions of multiplicative and additive monoids and groups; * `distrib_mul_action M A` is a typeclass for an action of a multiplicative monoid on an additive monoid such that `a • (b + c) = a • b + a • c` and `a • 0 = 0`. The hierarchy is extended further by `module`, defined elsewhere. Also provided are type-classes regarding the interaction of different group actions, * `smul_comm_class M N α` and its additive version `vadd_comm_class M N α`; * `is_scalar_tower M N α` (no additive version). ## Notation - `a • b` is used as notation for `has_scalar.smul a b`. - `a +ᵥ b` is used as notation for `has_vadd.vadd a b`. ## Implementation details This file should avoid depending on other parts of `group_theory`, to avoid import cycles. More sophisticated lemmas belong in `group_theory.group_action`. ## Tags group action -/ variables {M N G A B α β γ : Type*} open function /-- Type class for the `+ᵥ` notation. -/ class has_vadd (G : Type*) (P : Type*) := (vadd : G → P → P) /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ @[to_additive has_vadd] class has_scalar (M : Type*) (α : Type*) := (smul : M → α → α) infix ` +ᵥ `:65 := has_vadd.vadd infixr ` • `:73 := has_scalar.smul /-- Typeclass for faithful actions. -/ class has_faithful_vadd (G : Type*) (P : Type*) [has_vadd G P] : Prop := (eq_of_vadd_eq_vadd : ∀ {g₁ g₂ : G}, (∀ p : P, g₁ +ᵥ p = g₂ +ᵥ p) → g₁ = g₂) /-- Typeclass for faithful actions. -/ @[to_additive has_faithful_vadd] class has_faithful_scalar (M : Type*) (α : Type*) [has_scalar M α] : Prop := (eq_of_smul_eq_smul : ∀ {m₁ m₂ : M}, (∀ a : α, m₁ • a = m₂ • a) → m₁ = m₂) export has_faithful_scalar (eq_of_smul_eq_smul) has_faithful_vadd (eq_of_vadd_eq_vadd) @[to_additive] lemma smul_left_injective' [has_scalar M α] [has_faithful_scalar M α] : function.injective ((•) : M → α → α) := λ m₁ m₂ h, has_faithful_scalar.eq_of_smul_eq_smul (congr_fun h) /-- See also `monoid.to_mul_action` and `mul_zero_class.to_smul_with_zero`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance has_mul.to_has_scalar (α : Type*) [has_mul α] : has_scalar α α := ⟨(*)⟩ @[simp, to_additive] lemma smul_eq_mul (α : Type*) [has_mul α] {a a' : α} : a • a' = a * a' := rfl /-- Type class for additive monoid actions. -/ @[protect_proj] class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P := (zero_vadd : ∀ p : P, (0 : G) +ᵥ p = p) (add_vadd : ∀ (g₁ g₂ : G) (p : P), (g₁ + g₂) +ᵥ p = g₁ +ᵥ (g₂ +ᵥ p)) /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[protect_proj, to_additive] class mul_action (α : Type*) (β : Type*) [monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) /-- A typeclass mixin saying that two additive actions on the same space commute. -/ class vadd_comm_class (M N α : Type*) [has_vadd M α] [has_vadd N α] : Prop := (vadd_comm : ∀ (m : M) (n : N) (a : α), m +ᵥ (n +ᵥ a) = n +ᵥ (m +ᵥ a)) /-- A typeclass mixin saying that two multiplicative actions on the same space commute. -/ @[to_additive] class smul_comm_class (M N α : Type*) [has_scalar M α] [has_scalar N α] : Prop := (smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a) export mul_action (mul_smul) add_action (add_vadd) smul_comm_class (smul_comm) vadd_comm_class (vadd_comm) attribute [to_additive_reorder 1] has_pow attribute [to_additive_reorder 1 4] has_pow.pow attribute [to_additive has_scalar] has_pow attribute [to_additive has_scalar.smul] has_pow.pow /-- Frequently, we find ourselves wanting to express a bilinear map `M →ₗ[R] N →ₗ[R] P` or an equivalence between maps `(M →ₗ[R] N) ≃ₗ[R] (M' →ₗ[R] N')` where the maps have an associated ring `R`. Unfortunately, using definitions like these requires that `R` satisfy `comm_semiring R`, and not just `semiring R`. Using `M →ₗ[R] N →+ P` and `(M →ₗ[R] N) ≃+ (M' →ₗ[R] N')` avoids this problem, but throws away structure that is useful for when we _do_ have a commutative (semi)ring. To avoid making this compromise, we instead state these definitions as `M →ₗ[R] N →ₗ[S] P` or `(M →ₗ[R] N) ≃ₗ[S] (M' →ₗ[R] N')` and require `smul_comm_class S R` on the appropriate modules. When the caller has `comm_semiring R`, they can set `S = R` and `smul_comm_class_self` will populate the instance. If the caller only has `semiring R` they can still set either `R = ℕ` or `S = ℕ`, and `add_comm_monoid.nat_smul_comm_class` or `add_comm_monoid.nat_smul_comm_class'` will populate the typeclass, which is still sufficient to recover a `≃+` or `→+` structure. An example of where this is used is `linear_map.prod_equiv`. -/ library_note "bundled maps over different rings" /-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ @[to_additive] lemma smul_comm_class.symm (M N α : Type*) [has_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class N M α := ⟨λ a' a b, (smul_comm a a' b).symm⟩ /-- Commutativity of additive actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ add_decl_doc vadd_comm_class.symm @[to_additive] instance smul_comm_class_self (M α : Type*) [comm_monoid M] [mul_action M α] : smul_comm_class M M α := ⟨λ a a' b, by rw [← mul_smul, mul_comm, mul_smul]⟩ /-- An instance of `is_scalar_tower M N α` states that the multiplicative action of `M` on `α` is determined by the multiplicative actions of `M` on `N` and `N` on `α`. -/ class is_scalar_tower (M N α : Type*) [has_scalar M N] [has_scalar N α] [has_scalar M α] : Prop := (smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • (y • z)) @[simp] lemma smul_assoc {M N} [has_scalar M N] [has_scalar N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z instance semigroup.is_scalar_tower [semigroup α] : is_scalar_tower α α α := ⟨mul_assoc⟩ namespace has_scalar variables [has_scalar M α] /-- Auxiliary definition for `has_scalar.comp`, `mul_action.comp_hom`, `distrib_mul_action.comp_hom`, `module.comp_hom`, etc. -/ @[simp, to_additive /-" Auxiliary definition for `has_vadd.comp`, `add_action.comp_hom`, etc. "-/] def comp.smul (g : N → M) (n : N) (a : α) : α := g n • a variables (α) /-- An action of `M` on `α` and a funcion `N → M` induces an action of `N` on `α`. See note [reducible non-instances]. Since this is reducible, we make sure to go via `has_scalar.comp.smul` to prevent typeclass inference unfolding too far. -/ @[reducible, to_additive /-" An additive action of `M` on `α` and a funcion `N → M` induces an additive action of `N` on `α` "-/] def comp (g : N → M) : has_scalar N α := { smul := has_scalar.comp.smul g } variables {α} /-- If an action forms a scalar tower then so does the action formed by `has_scalar.comp`. -/ @[priority 100] instance comp.is_scalar_tower [has_scalar M β] [has_scalar α β] [is_scalar_tower M α β] (g : N → M) : (by haveI := comp α g; haveI := comp β g; exact is_scalar_tower N α β) := by exact {smul_assoc := λ n, @smul_assoc _ _ _ _ _ _ _ (g n) } @[priority 100] instance comp.smul_comm_class [has_scalar β α] [smul_comm_class M β α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class N β α) := by exact {smul_comm := λ n, @smul_comm _ _ _ _ _ _ (g n) } @[priority 100] instance comp.smul_comm_class' [has_scalar β α] [smul_comm_class β M α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class β N α) := by exact {smul_comm := λ _ n, @smul_comm _ _ _ _ _ _ _ (g n) } end has_scalar section variables [monoid M] [mul_action M α] @[to_additive] lemma smul_smul (a₁ a₂ : M) (b : α) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm variable (M) @[simp, to_additive] theorem one_smul (b : α) : (1 : M) • b = b := mul_action.one_smul _ variables {M} /-- Pullback a multiplicative action along an injective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pullback an additive action along an injective map respecting `+ᵥ`."] protected def function.injective.mul_action [has_scalar M β] (f : β → α) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pushforward an additive action along a surjective map respecting `+ᵥ`."] protected def function.surjective.mul_action [has_scalar M β] (f : α → β) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } section ite variables (p : Prop) [decidable p] @[to_additive] lemma ite_smul (a₁ a₂ : M) (b : α) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl @[to_additive] lemma smul_ite (a : M) (b₁ b₂ : α) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end ite section variables (M) /-- The regular action of a monoid on itself by left multiplication. This is promoted to a module by `semiring.to_module`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance monoid.to_mul_action : mul_action M M := { smul := (*), one_smul := one_mul, mul_smul := mul_assoc } /-- The regular action of a monoid on itself by left addition. This is promoted to an `add_torsor` by `add_group_is_add_torsor`. -/ add_decl_doc add_monoid.to_add_action instance is_scalar_tower.left : is_scalar_tower M M α := ⟨λ x y z, mul_smul x y z⟩ variables {M} /-- Note that the `smul_comm_class M α α` typeclass argument is usually satisfied by `algebra M α`. -/ @[to_additive] lemma mul_smul_comm [has_mul α] (s : M) (x y : α) [smul_comm_class M α α] : x * (s • y) = s • (x * y) := (smul_comm s x y).symm /-- Note that the `is_scalar_tower M α α` typeclass argument is usually satisfied by `algebra M α`. -/ lemma smul_mul_assoc [has_mul α] (r : M) (x y : α) [is_scalar_tower M α α] : (r • x) * y = r • (x * y) := smul_assoc r x y /-- Note that the `is_scalar_tower M α α` and `smul_comm_class M α α` typeclass arguments are usually satisfied by `algebra M α`. -/ lemma smul_mul_smul [has_mul α] (r s : M) (x y : α) [is_scalar_tower M α α] [smul_comm_class M α α] : (r • x) * (s • y) = (r * s) • (x * y) := by rw [smul_mul_assoc, mul_smul_comm, ← smul_assoc, smul_eq_mul] end namespace mul_action variables (M α) /-- Embedding of `α` into functions `M → α` induced by a multiplicative action of `M` on `α`. -/ @[to_additive] def to_fun : α ↪ (M → α) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul M y₁ ▸ one_smul M y₂ ▸ by convert congr_fun H 1⟩ /-- Embedding of `α` into functions `M → α` induced by an additive action of `M` on `α`. -/ add_decl_doc add_action.to_fun variables {M α} @[simp, to_additive] lemma to_fun_apply (x : M) (y : α) : mul_action.to_fun M α y x = x • y := rfl variable (α) /-- A multiplicative action of `M` on `α` and a monoid homomorphism `N → M` induce a multiplicative action of `N` on `α`. See note [reducible non-instances]. -/ @[reducible, to_additive] def comp_hom [monoid N] (g : N →* M) : mul_action N α := { smul := has_scalar.comp.smul g, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } /-- An additive action of `M` on `α` and an additive monoid homomorphism `N → M` induce an additive action of `N` on `α`. See note [reducible non-instances]. -/ add_decl_doc add_action.comp_hom end mul_action end section compatible_scalar @[simp] lemma smul_one_smul {M} (N) [monoid N] [has_scalar M N] [mul_action N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • (1 : N)) • y = x • y := by rw [smul_assoc, one_smul] end compatible_scalar /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ class distrib_mul_action (M : Type*) (A : Type*) [monoid M] [add_monoid A] extends mul_action M A := (smul_add : ∀(r : M) (x y : A), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : M), r • (0 : A) = 0) section variables [monoid M] [add_monoid A] [distrib_mul_action M A] theorem smul_add (a : M) (b₁ b₂ : A) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : M) : a • (0 : A) = 0 := distrib_mul_action.smul_zero _ /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_mul_action [add_monoid B] [has_scalar M B] (f : B →+ A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add], smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero], .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib_mul_action [add_monoid B] [has_scalar M B] (f : A →+ B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← f.map_add] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero], .. hf.mul_action f smul } variable (A) /-- Compose a `distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def distrib_mul_action.comp_hom [monoid N] (f : N →* M) : distrib_mul_action N A := { smul := has_scalar.comp.smul f, smul_zero := λ x, smul_zero (f x), smul_add := λ x, smul_add (f x), .. mul_action.comp_hom A f } /-- Scalar multiplication by `r` as an `add_monoid_hom`. -/ def const_smul_hom (r : M) : A →+ A := { to_fun := (•) r, map_zero' := smul_zero r, map_add' := smul_add r } variable {A} @[simp] lemma const_smul_hom_apply (r : M) (x : A) : const_smul_hom A r x = r • x := rfl @[simp] lemma const_smul_hom_one : const_smul_hom A (1:M) = add_monoid_hom.id _ := by { ext, rw [const_smul_hom_apply, one_smul, add_monoid_hom.id_apply] } end section variables [monoid M] [add_group A] [distrib_mul_action M A] @[simp] theorem smul_neg (r : M) (x : A) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : M) (x y : A) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end variable (α) /-- The monoid of endomorphisms. Note that this is generalized by `category_theory.End` to categories other than `Type u`. -/ protected def function.End := α → α instance : monoid (function.End α) := { one := id, mul := (∘), mul_assoc := λ f g h, rfl, mul_one := λ f, rfl, one_mul := λ f, rfl, } instance : inhabited (function.End α) := ⟨1⟩ variable {α} /-- The tautological action by `function.End α` on `α`. -/ instance mul_action.function_End : mul_action (function.End α) α := { smul := ($), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma function.End.smul_def (f : function.End α) (a : α) : f • a = f a := rfl /-- The monoid hom representing a monoid action. When `M` is a group, see `mul_action.to_perm_hom`. -/ def mul_action.to_End_hom [monoid M] [mul_action M α] : M →* function.End α := { to_fun := (•), map_one' := funext (one_smul M), map_mul' := λ x y, funext (mul_smul x y) } /-- The monoid action induced by a monoid hom to `function.End α` See note [reducible non-instances]. -/ @[reducible] def mul_action.of_End_hom [monoid M] (f : M →* function.End α) : mul_action M α := mul_action.comp_hom α f /-- The tautological additive action by `additive (function.End α)` on `α`. -/ instance add_action.function_End : add_action (additive (function.End α)) α := { vadd := ($), zero_vadd := λ _, rfl, add_vadd := λ _ _ _, rfl } /-- The additive monoid hom representing an additive monoid action. When `M` is a group, see `add_action.to_perm_hom`. -/ def add_action.to_End_hom [add_monoid M] [add_action M α] : M →+ additive (function.End α) := { to_fun := (+ᵥ), map_zero' := funext (zero_vadd M), map_add' := λ x y, funext (add_vadd x y) } /-- The additive action induced by a hom to `additive (function.End α)` See note [reducible non-instances]. -/ @[reducible] def add_action.of_End_hom [add_monoid M] (f : M →+ additive (function.End α)) : add_action M α := add_action.comp_hom α f
292fe4129bf865bacb1d55ff36b4b4cbd4cfedaf
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/data/cpi/process/default.lean
ddcb6bcf4a13fb0ee893f1c401a41055722763e8
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
59
lean
import data.cpi.process.basic data.cpi.process.equivalence
ae1c7a2c324ee0e6a9dbdd9bc1c5a9df195f653b
26ac254ecb57ffcb886ff709cf018390161a9225
/src/tactic/core.lean
364a5d28a87063384ec1d0c99743ad2d1d085cc9
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
84,233
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic import control.basic import meta.expr import meta.rb_map import data.bool import tactic.lean_core_docs import tactic.interactive_expr import tactic.fix_by_cases universe variable u instance : has_lt pos := { lt := λ x y, (x.line, x.column) < (y.line, y.column) } namespace expr open tactic /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) /-- `kreplace e old new` replaces all occurrences of the expression `old` in `e` with `new`. The occurrences of `old` in `e` are determined using keyed matching with transparency `md`; see `kabstract` for details. If `unify` is true, we may assign metavariables in `e` as we match subterms of `e` against `old`. -/ meta def kreplace (e old new : expr) (md := semireducible) (unify := tt) : tactic expr := do e ← kabstract e old md unify, pure $ e.instantiate_var new end expr namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] : list α → format | [] := to_fmt "[]" | xs := to_fmt "[" ++ group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) ++ to_fmt "]" end format namespace tactic open function /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup /-- `mk_local_pisn e n` instantiates the first `n` variables of a pi expression `e`, and returns the new local constants along with the instantiated expression. Fails if `e` does not begin with at least `n` pi binders. -/ meta def mk_local_pisn : expr → nat → tactic (list expr × expr) | (expr.pi n bi d b) (c + 1) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pisn (b.instantiate_var p) c, return ((p :: ps), r) | e 0 := return ([], e) | _ _ := failed -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file' e d.to_name then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro1) <|> note n none e /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `revert_deps e` reverts all the hypotheses that depend on one of the local constants `e`, including the local definitions that have `e` in their definition. This fixes a bug in `revert_kdeps` that does not revert local definitions for which `e` only appears in the definition. -/ /- We cannot implement it as `revert e >> intro1`, because that would change the local constant in the context. -/ meta def revert_deps (e : expr) : tactic ℕ := do n ← revert_kdeps e, l ← local_context, [pos] ← return $ l.indexes_of e, let l := l.drop pos.succ, -- local hypotheses after `e` ls ← l.mfilter $ λ e', try_core (local_def_value e') >>= λ o, return $ o.elim ff $ λ e'', e''.has_local_constant e, n' ← revert_lst ls, return $ n + n' /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip /-- `clear_value e` clears the body of the local definition `e`, changing it into a regular hypothesis. A hypothesis `e : α := t` is changed to `e : α`. This tactic is called `clearbody` in Coq. -/ meta def clear_value (e : expr) : tactic unit := do n ← revert_after e, is_local_def e <|> pp e >>= λ s, fail format!"Cannot clear the body of {s}. It is not a local definition.", let nm := e.local_pp_name, (generalize' e nm >> clear e) <|> fail format!"Cannot clear the body of {nm}. The resulting goal is not type correct.", intron n /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of the given (Pi-)type. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of the given function. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity /-- Auxilliary defintion for `get_pi_binders`. -/ meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr) | es (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, let new_b := expr.instantiate_var b l, get_pi_binders_aux (⟨n, bi, d⟩::es) new_b | es e := return (es, e) /-- Get the binders and target of a pi-type. Instantiates bound variables by local constants. Cf. `pi_binders` in `meta.expr` (which produces open terms). See also `mk_local_pis` in `init.core.tactic` which does almost the same. -/ meta def get_pi_binders : expr → tactic (list binder × expr) | e := do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e) /-- Auxilliary definition for `get_pi_binders_dep`. -/ meta def get_pi_binders_dep_aux : ℕ → expr → tactic (list (ℕ × binder) × expr) | n (expr.pi nm bi d b) := do l ← mk_local' nm bi d, (ls, r) ← get_pi_binders_dep_aux (n+1) (expr.instantiate_var b l), return (if b.has_var then ls else (n, ⟨nm, bi, d⟩)::ls, r) | n e := return ([], e) /-- A variant of `get_pi_binders` that only returns the binders that do not occur in later arguments or in the target. Also returns the argument position of each returned binder. -/ meta def get_pi_binders_dep : expr → tactic (list (ℕ × binder) × expr) := get_pi_binders_dep_aux 0 /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, [c] ← pure $ env.constructors_of struct_n | fail "too many constructors", vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= mk_local_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply the lemmas generated by the tactics in `l` on the first goal, and fail if none succeeds. -/ meta def apply_list_expr : list (tactic expr) → tactic unit | [] := fail "no matching rule" | (h::t) := (do e ← h, interactive.concat_tags (apply e)) <|> apply_list_expr t /-- Constructs a list of `tactic expr` given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list. We need to return a list of `tactic expr`, rather than just `expr`, because these expressions will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck. -/ meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr)) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n), build_list_expr_for_apply (m ++ t)) <|> return ((i_to_expr_for_apply h) :: tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit := do l ← lock_tactic_state $ build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt := (use_symmetry : bool := tt) (use_exfalso : bool := tt) (apply : expr → tactic (list (name × expr)) := tactic.apply) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) (on_success : expr → tactic unit := (λ _, skip)) (on_failure : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= (λ e, do opt.apply e, on_success e, tac))) <|> (on_failure >> fail "apply_any tactic failed; no lemma could be applied") /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), when (repl_tp ≠ tp) $ change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- `sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`, and fail otherwise. -/ meta def sorry_if_contains_sorry : tactic unit := do g ← target, guard g.contains_sorry <|> fail "goal does not contain `sorrry`", tactic.admit /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), t ← target, new_goal ← mk_meta_var (t.pis lc), old::other_goals ← get_goals, set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Like `mk_local_pis` but translating into weak head normal form before checking if it is a `Π`. -/ meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do (expr.pi n bi d b) ← whnf e | return ([], e), p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) /-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g`. -/ meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do t ← infer_type h, (ctxt, t) ← mk_local_pis_whnf t, `(@Exists %%α %%p) ← whnf t transparency.all | fail "expected a term of the shape ∀xs, ∃a, p xs a", α_t ← infer_type α, expr.sort u ← whnf α_t transparency.all, value ← mk_local_def data (α.pis ctxt), t' ← head_beta (p.app (value.mk_app ctxt)), spec ← mk_local_def spec (t'.pis ctxt), dependent_pose_core [ (value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt), (spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)], try (tactic.clear h), intro1, intro1 /-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`, and a final hypothesis on `p as`. -/ meta def choose : expr → list name → tactic unit | h [] := fail "expect list of variables" | h [n] := do cnt ← revert h, intro n, intron (cnt - 1), return () | h (n::ns) := do v ← get_unused_name >>= choose1 h n, choose v ns /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- Similar to `mk_local_pis` but make meta variables instead of local constants. -/ meta def mk_meta_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_meta_var d, (ps, r) ← mk_meta_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here : string → lean.parser unit | str := do left ← emit_command_here str, if left.length = 0 then return () else emit_code_here left /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← mk_local_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. -/ meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end precedence `setup_tactic_parser`:0 /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open lean open lean.parser open interactive interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `refine ...` or `exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s reserve prefix `pformat! `:100 /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) reserve prefix `fail! `:100 /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) reserve prefix `trace! `:100 /-- The combination of `pformat` and `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := do e ← get_env, s ← e.decl_olean `tactic.reset_instance_cache, return $ s.popn_back 17 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← types.with_ident_list <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
c457a843e31cdc2a4a7c6033e7267cb5266bf85e
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/notes/10.1.19.Polymorphism/boxed.lean
492692073bbc5f043980c6a1cc41960843c92ff1
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
219
lean
namespace boxed_adt inductive boxed (T : Type) : Type --defining the type boxed | box : T → boxed open boxed def unbox {T : Type} : boxed T → T --{} tell lean to infer an argument | (box a) := a end boxed_adt
3a9467b9a068fba3d8e4b7886d45473f302537ba
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/System.lean
8c0766bc230792c22b8894f04d775735893ad769
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
297
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.System.IO import Init.System.Platform import Init.System.Uri import Init.System.Mutex import Init.System.Promise
91375d9d5c120e9e340a0e5c7c7061291e5d44dc
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0503.lean
65c6ca89b2e2e1d80010f5c2a9ba81e51450ab85
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
75
lean
example (p q : Prop) (hp : p) (hq : q) : p ∧ q := by split; assumption
8a358f51fc6d9e24f39c0b28aafa17b9f2d0c838
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/ind3.lean
2850b28f250f63698340f0e01f3000e5ce414b9d
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
446
lean
#exit inductive tree (A : Type) : Type := | node : A → forest A → tree A with forest : Type := | nil : forest A | cons : tree A → forest A → forest A #check tree.{1} #check forest.{1} #check tree.rec.{1 1} #check forest.rec.{1 1} #print "===============" inductive group : Type := mk_group : Π (carrier : Type) (mul : carrier → carrier → carrier) (one : carrier), group #check group.{1} #check group.{2} #check group.rec.{1 1}
244626ddc82df7c0da95dd71225b233a00314c87
263b858cfdc89a2f9d3a4b5f400694bf81ab855d
/mm0-lean/x86/x86.lean
d61154ca515179ef432045a609feacebc6d2cb9e
[ "CC0-1.0" ]
permissive
jcommelin/mm0
97d89e6935cdf21523a6f29904bd0a2a042335cc
7482b84b3518cae5c730ba07d91e23ae978dafd9
refs/heads/master
1,617,826,105,860
1,583,734,867,000
1,583,735,028,000
248,705,227
0
0
CC0-1.0
1,584,693,150,000
1,584,693,150,000
null
UTF-8
Lean
false
false
30,171
lean
import x86.bits logic.relation namespace x86 local notation `S` := bitvec.singleton @[reducible] def regnum := bitvec 4 def RAX : regnum := 0 def RCX : regnum := 1 def RDX : regnum := 2 def RSP : regnum := 4 def RBP : regnum := 5 def RSI : regnum := 6 def RDI : regnum := 7 def REX := option (bitvec 4) def REX.to_nat : REX → ℕ | none := 0 | (some r) := r.to_nat def REX.W (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 3) def REX.R (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 2) def REX.X (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 1) def REX.B (r : REX) : bool := option.cases_on r ff (λ r, vector.nth r 0) def rex_reg (b : bool) (r : bitvec 3) : regnum := (bitvec.append r (S b) : _) structure scale_index := (scale : bitvec 2) (index : regnum) inductive base | none | rip | reg (reg : regnum) inductive RM : Type | reg : regnum → RM | mem : option scale_index → base → qword → RM def RM.is_mem : RM → Prop | (RM.mem _ _ _) := true | _ := false @[reducible] def Mod := bitvec 2 inductive read_displacement : Mod → qword → list byte → Prop | disp0 : read_displacement 0 0 [] | disp8 (b : byte) : read_displacement 1 (EXTS b) [b] | disp32 (w : word) (l) : w.to_list_byte l → read_displacement 2 (EXTS w) l def read_sib_displacement (mod : Mod) (bbase : regnum) (w : qword) (Base : base) (l : list byte) : Prop := if bbase = RBP ∧ mod = 0 then ∃ b, w = EXTS b ∧ Base = base.none ∧ l = [b] else read_displacement mod w l ∧ Base = base.reg bbase inductive read_SIB (rex : REX) (mod : Mod) : RM → list byte → Prop | mk (b : byte) (bs ix SS) (disp bbase' l) : split_bits b.to_nat [⟨3, bs⟩, ⟨3, ix⟩, ⟨2, SS⟩] → let bbase := rex_reg rex.B bs, index := rex_reg rex.X ix, scaled_index : option scale_index := if index = RSP then none else some ⟨SS, index⟩ in read_sib_displacement mod bbase disp bbase' l → read_SIB (RM.mem scaled_index bbase' disp) (b :: l) inductive read_ModRM (rex : REX) : regnum → RM → list byte → Prop | imm32 (b : byte) (reg_opc : bitvec 3) (i : word) (disp) : split_bits b.to_nat [⟨3, 0b101⟩, ⟨3, reg_opc⟩, ⟨2, 0b00⟩] → i.to_list_byte disp → read_ModRM (rex_reg rex.R reg_opc) (RM.mem none base.rip (EXTS i)) (b :: disp) | reg (b : byte) (rm reg_opc : bitvec 3) : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, 0b11⟩] → read_ModRM (rex_reg rex.R reg_opc) (RM.reg (rex_reg rex.B rm)) [b] | sib (b : byte) (reg_opc : bitvec 3) (mod : Mod) (sib) (l) : split_bits b.to_nat [⟨3, 0b100⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] → read_SIB rex mod sib l → read_ModRM (rex_reg rex.R reg_opc) sib (b :: l) | mem (b : byte) (rm reg_opc : bitvec 3) (mod : Mod) (disp l) : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] → rm ≠ 0b100 → ¬ (rm = 0b101 ∧ mod = 0b00) → read_displacement mod disp l → read_ModRM (rex_reg rex.R reg_opc) (RM.mem none (base.reg (rex_reg rex.B rm)) disp) (b :: l) inductive read_opcode_ModRM (rex : REX) : bitvec 3 → RM → list byte → Prop | mk (rn : regnum) (rm l v b) : read_ModRM rex rn rm l → split_bits rn.to_nat [⟨3, v⟩, ⟨1, b⟩] → read_opcode_ModRM v rm l -- obsolete group 1-4 prefixes omitted inductive read_prefixes : REX → list byte → Prop | nil : read_prefixes none [] | rex (b : byte) (rex) : split_bits b.to_nat [⟨4, rex⟩, ⟨4, 0b0100⟩] → read_prefixes (some rex) [b] @[derive decidable_eq] inductive wsize | Sz8 (have_rex : bool) | Sz16 | Sz32 | Sz64 open wsize def wsize.to_nat : wsize → ℕ | (Sz8 _) := 8 | Sz16 := 16 | Sz32 := 32 | Sz64 := 64 inductive read_imm8 : qword → list byte → Prop | mk (b : byte) : read_imm8 (EXTS b) [b] inductive read_imm16 : qword → list byte → Prop | mk (w : bitvec 16) (l) : bits_to_byte 2 w l → read_imm16 (EXTS w) l inductive read_imm32 : qword → list byte → Prop | mk (w : word) (l) : w.to_list_byte l → read_imm32 (EXTS w) l def read_imm : wsize → qword → list byte → Prop | (Sz8 _) := read_imm8 | Sz16 := read_imm16 | Sz32 := read_imm32 | Sz64 := read_imm32 def read_full_imm : wsize → qword → list byte → Prop | (Sz8 _) := read_imm8 | Sz16 := read_imm16 | Sz32 := read_imm32 | Sz64 := λ w l, w.to_list_byte l def op_size (have_rex w v : bool) : wsize := if ¬ v then Sz8 have_rex else if w then Sz64 else -- if override then Sz16 else Sz32 def op_size_W (rex : REX) : bool → wsize := op_size rex.is_some rex.W inductive dest_src | Rm_i : RM → qword → dest_src | Rm_r : RM → regnum → dest_src | R_rm : regnum → RM → dest_src open dest_src inductive imm_rm | rm : RM → imm_rm | imm : qword → imm_rm inductive unop | dec | inc | not | neg inductive binop | add | or | adc | sbb | and | sub | xor | cmp | rol | ror | rcl | rcr | shl | shr | tst | sar inductive binop.bits : binop → bitvec 4 → Prop | add : binop.bits binop.add 0x0 | or : binop.bits binop.or 0x1 | adc : binop.bits binop.adc 0x2 | sbb : binop.bits binop.sbb 0x3 | and : binop.bits binop.and 0x4 | sub : binop.bits binop.sub 0x5 | xor : binop.bits binop.xor 0x6 | cmp : binop.bits binop.cmp 0x7 | rol : binop.bits binop.rol 0x8 | ror : binop.bits binop.ror 0x9 | rcl : binop.bits binop.rcl 0xa | rcr : binop.bits binop.rcr 0xb | shl : binop.bits binop.shl 0xc | shr : binop.bits binop.shr 0xd | tst : binop.bits binop.tst 0xe | sar : binop.bits binop.sar 0xf inductive basic_cond | o | b | e | na | s | l | ng inductive basic_cond.bits : basic_cond → bitvec 3 → Prop | o : basic_cond.bits basic_cond.o 0x0 | b : basic_cond.bits basic_cond.b 0x1 | e : basic_cond.bits basic_cond.e 0x2 | na : basic_cond.bits basic_cond.na 0x3 | s : basic_cond.bits basic_cond.s 0x4 | l : basic_cond.bits basic_cond.l 0x6 | ng : basic_cond.bits basic_cond.ng 0x7 inductive cond_code | always | pos : basic_cond → cond_code | neg : basic_cond → cond_code def cond_code.mk : bool → basic_cond → cond_code | ff := cond_code.pos | tt := cond_code.neg inductive cond_code.bits : cond_code → bitvec 4 → Prop | mk (v : bitvec 4) (b c code) : split_bits v.to_nat [⟨1, S b⟩, ⟨3, c⟩] → basic_cond.bits code c → cond_code.bits (cond_code.mk b code) v inductive ast | unop : unop → wsize → RM → ast | binop : binop → wsize → dest_src → ast | mul : wsize → RM → ast | div : wsize → RM → ast | lea : wsize → dest_src → ast | movsx : wsize → dest_src → wsize → ast | movzx : wsize → dest_src → wsize → ast | xchg : wsize → RM → regnum → ast | cmpxchg : wsize → RM → regnum → ast | xadd : wsize → RM → regnum → ast | cmov : cond_code → wsize → dest_src → ast | setcc : cond_code → bool → RM → ast | jump : RM → ast | jcc : cond_code → qword → ast | call : imm_rm → ast | ret : qword → ast | push : imm_rm → ast | pop : RM → ast | leave : ast | cmc | clc | stc -- | int : byte → ast | syscall def ast.mov := ast.cmov cond_code.always inductive decode_hi (v : bool) (sz : wsize) (r : RM) : bool → bitvec 3 → ast → list byte → Prop | test (imm l) : read_imm sz imm l → decode_hi ff 0b000 (ast.binop binop.tst sz (Rm_i r imm)) l | not : decode_hi ff 0b010 (ast.unop unop.not sz r) [] | neg : decode_hi ff 0b011 (ast.unop unop.neg sz r) [] | mul : decode_hi ff 0b100 (ast.mul sz r) [] | div : decode_hi ff 0b110 (ast.div sz r) [] | inc : decode_hi tt 0b000 (ast.unop unop.inc sz r) [] | dec : decode_hi tt 0b001 (ast.unop unop.dec sz r) [] | call : v → decode_hi tt 0b010 (ast.call (imm_rm.rm r)) [] | jump : v → decode_hi tt 0b100 (ast.jump r) [] | push : v → decode_hi tt 0b110 (ast.push (imm_rm.rm r)) [] inductive decode_two (rex : REX) : ast → list byte → Prop | cmov (b : byte) (c reg r l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x4⟩] → let sz := op_size tt rex.W tt in read_ModRM rex reg r l → cond_code.bits code c → decode_two (ast.cmov code sz (R_rm reg r)) (b :: l) | jcc (b : byte) (c imm l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x8⟩] → read_imm32 imm l → cond_code.bits code c → decode_two (ast.jcc code imm) (b :: l) | setcc (b : byte) (c reg r l code) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0x9⟩] → read_ModRM rex reg r l → cond_code.bits code c → decode_two (ast.setcc code rex.is_some r) (b :: l) | cmpxchg (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1011000⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_two (ast.cmpxchg sz r reg) (b :: l) | movsx (b : byte) (v s reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b11⟩, ⟨1, S s⟩, ⟨4, 0xb⟩] → let sz2 := op_size_W rex tt, sz := if v then Sz16 else Sz8 rex.is_some in read_ModRM rex reg r l → decode_two ((if s then ast.movsx else ast.movzx) sz (R_rm reg r) sz2) (b :: l) | xadd (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100000⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_two (ast.xadd sz r reg) (b :: l) | syscall : decode_two ast.syscall [0x05] inductive decode_aux (rex : REX) : ast → list byte → Prop | binop1 (b : byte) (v d opc reg r l op) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S d⟩, ⟨1, 0b0⟩, ⟨3, opc⟩, ⟨2, 0b00⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → let src_dst := if d then R_rm reg r else Rm_r r reg in binop.bits op (EXTZ opc) → decode_aux (ast.binop op sz src_dst) (b :: l) | binop_imm_rax (b : byte) (v opc imm l op) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b10⟩, ⟨3, opc⟩, ⟨2, 0b00⟩] → let sz := op_size_W rex v in binop.bits op (EXTZ opc) → read_imm sz imm l → decode_aux (ast.binop op sz (Rm_i (RM.reg RAX) imm)) (b :: l) | binop_imm (b : byte) (v opc r l1 imm l2 op) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000000⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → read_imm sz imm l2 → binop.bits op (EXTZ opc) → decode_aux (ast.binop op sz (Rm_i r imm)) (b :: l1 ++ l2) | binop_imm8 (opc r l1 imm l2 op) : let sz := op_size_W rex tt in read_opcode_ModRM rex opc r l1 → binop.bits op (EXTZ opc) → read_imm8 imm l2 → decode_aux (ast.binop op sz (Rm_i r imm)) (0x83 :: l1 ++ l2) | binop_hi (b : byte) (v opc r imm op l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100000⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → opc ≠ 6 → binop.bits op (rex_reg tt opc) → read_imm8 imm l2 → decode_aux (ast.binop op sz (Rm_i r imm)) (b :: l1 ++ l2) | binop_hi_reg (b : byte) (v x opc r op l) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S x⟩, ⟨6, 0b110100⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l → opc ≠ 6 → binop.bits op (rex_reg tt opc) → decode_aux (ast.binop op sz (if x then Rm_r r RCX else Rm_i r 1)) (b :: l) | two (a l) : decode_two rex a l → decode_aux a (0x0f :: l) | movsx (reg r l) : read_ModRM rex reg r l → decode_aux (ast.movsx Sz32 (R_rm reg r) Sz64) (0x63 :: l) | mov (b : byte) (v d reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨1, S d⟩, ⟨6, 0b100010⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → let src_dst := if d then R_rm reg r else Rm_r r reg in decode_aux (ast.mov sz src_dst) (b :: l) | mov64 (b : byte) (r v imm l) : split_bits b.to_nat [⟨3, r⟩, ⟨1, S v⟩, ⟨4, 0xb⟩] → let sz := op_size_W rex v in read_full_imm sz imm l → decode_aux (ast.mov sz (Rm_i (RM.reg (rex_reg rex.B r)) imm)) (b :: l) | mov_imm (b : byte) (v opc r imm l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100011⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → read_imm sz imm l2 → decode_aux (ast.mov sz (Rm_i r imm)) (b :: l1 ++ l2) | xchg (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000011⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_aux (ast.xchg sz r reg) (b :: l) | xchg_rax (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b10010⟩] → let sz := op_size tt rex.W tt in decode_aux (ast.xchg sz (RM.reg RAX) (rex_reg rex.B r)) [b] | push_imm (b : byte) (x imm l) : split_bits b.to_nat [⟨1, 0b0⟩, ⟨1, S x⟩, ⟨6, 0b011010⟩] → read_imm (if x then Sz8 ff else Sz32) imm l → decode_aux (ast.push (imm_rm.imm imm)) (b :: l) | push_rm (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b01010⟩] → decode_aux (ast.push (imm_rm.rm (RM.reg (rex_reg rex.B r)))) [b] | pop (b : byte) (r) : split_bits b.to_nat [⟨3, r⟩, ⟨5, 0b01011⟩] → decode_aux (ast.pop (RM.reg (rex_reg rex.B r))) [b] | pop_rm (r l) : read_opcode_ModRM rex 0 r l → decode_aux (ast.pop r) (0x8f :: l) | jump (b : byte) (x imm l) : split_bits b.to_nat [⟨1, 0b1⟩, ⟨1, S x⟩, ⟨6, 0b111010⟩] → (if x then read_imm8 imm l else read_imm32 imm l) → decode_aux (ast.jcc cond_code.always imm) (b :: l) | jcc8 (b : byte) (c code imm l) : split_bits b.to_nat [⟨4, c⟩, ⟨4, 0b0111⟩] → cond_code.bits code c → read_imm8 imm l → decode_aux (ast.jcc code imm) (b :: l) | call (imm l) : read_imm32 imm l → decode_aux (ast.call (imm_rm.imm imm)) (0xe8 :: l) | ret (b : byte) (v imm l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1100001⟩] → (if v then imm = 0 ∧ l = [] else read_imm16 imm l) → decode_aux (ast.ret imm) (b :: l) | leave : decode_aux ast.leave [0xc9] | lea (reg r l) : let sz := op_size tt rex.W tt in read_ModRM rex reg r l → RM.is_mem r → decode_aux (ast.lea sz (R_rm reg r)) (0x8d :: l) | test (b : byte) (v reg r l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1000010⟩] → let sz := op_size_W rex v in read_ModRM rex reg r l → decode_aux (ast.binop binop.tst sz (Rm_r r reg)) (b :: l) | test_rax (b : byte) (v imm l) : split_bits b.to_nat [⟨1, S v⟩, ⟨7, 0b1010100⟩] → let sz := op_size tt rex.W v in read_imm sz imm l → decode_aux (ast.binop binop.tst sz (Rm_i (RM.reg RAX) imm)) (b :: l) | cmc : decode_aux ast.cmc [0xf5] | clc : decode_aux ast.clc [0xf8] | stc : decode_aux ast.stc [0xf9] -- | int (imm) : decode_aux (ast.int imm) [0xcd, imm] | hi (b : byte) (v x opc r a l1 l2) : split_bits b.to_nat [⟨1, S v⟩, ⟨2, 0b11⟩, ⟨1, S x⟩, ⟨4, 0xf⟩] → let sz := op_size_W rex v in read_opcode_ModRM rex opc r l1 → decode_hi v sz r x opc a l2 → decode_aux a (b :: l1 ++ l2) inductive decode : ast → list byte → Prop | mk {rex l1 a l2} : read_prefixes rex l1 → decode_aux rex a l2 → decode a (l1 ++ l2) ---------------------------------------- -- Dynamic semantics ---------------------------------------- structure flags := (CF ZF SF OF : bool) def basic_cond.read : basic_cond → flags → bool | basic_cond.o f := f.OF | basic_cond.b f := f.CF | basic_cond.e f := f.ZF | basic_cond.na f := f.CF || f.ZF | basic_cond.s f := f.SF | basic_cond.l f := f.SF ≠ f.OF | basic_cond.ng f := f.ZF || (f.SF ≠ f.OF) def cond_code.read : cond_code → flags → bool | cond_code.always f := tt | (cond_code.pos c) f := c.read f | (cond_code.neg c) f := bnot $ c.read f structure perm := (isR isW isX : bool) def perm.R : perm := ⟨tt, ff, ff⟩ def perm.W : perm := ⟨ff, tt, ff⟩ def perm.X : perm := ⟨ff, ff, tt⟩ instance perm.has_add : has_add perm := ⟨λ p1 p2, ⟨p1.isR || p2.isR, p1.isW || p2.isW, p1.isX || p2.isX⟩⟩ instance perm.has_le : has_le perm := ⟨λ p1 p2, p1 + p2 = p2⟩ structure mem := (valid : qword → Prop) (mem : ∀ w, valid w → byte) (perm : ∀ w, valid w → perm) structure config := (rip : qword) (regs : regnum → qword) (flags : flags) (mem : mem) def mem.read1 (p : perm) (m : mem) (w : qword) (b : byte) : Prop := ∃ h, b = m.mem w h ∧ p ≤ m.perm w h inductive mem.read' (p : perm) (m : mem) : qword → list byte → Prop | nil (w) : mem.read' w [] | cons {w b l} : m.read1 p w b → mem.read' (w + 1) l → mem.read' w (b :: l) def mem.read (m : mem) : qword → list byte → Prop := m.read' perm.R def mem.readX (m : mem) : qword → list byte → Prop := m.read' (perm.R + perm.X) def mem.set (m : mem) (w : qword) (b : byte) : mem := {mem := λ w' h', if w = w' then b else m.mem w' h', ..m} inductive mem.write1 (m : mem) (w : qword) (b : byte) : mem → Prop | mk (h : m.valid w) : perm.R + perm.W ≤ m.perm w h → mem.write1 (m.set w b) inductive mem.write : mem → qword → list byte → mem → Prop | nil (m w) : mem.write m w [] m | cons {m1 m2 m3 : mem} {w b l} : m1.write1 w b m2 → mem.write m2 (w + 1) l m3 → mem.write m1 w (b :: l) m3 inductive EA | i : qword → EA | r : regnum → EA | m : qword → EA def EA.addr : EA → qword | (EA.m a) := a | _ := 0 def index_ea (k : config) : option scale_index → qword | none := 0 | (some ⟨sc, ix⟩) := (bitvec.shl 1 sc.to_nat) * (k.regs ix) def base.ea (k : config) : base → qword | base.none := 0 | base.rip := k.rip | (base.reg r) := k.regs r def RM.ea (k : config) : RM → EA | (RM.reg r) := EA.r r | (RM.mem ix b d) := EA.m (index_ea k ix + b.ea k + d) def ea_dest (k : config) : dest_src → EA | (Rm_i v _) := v.ea k | (Rm_r v _) := v.ea k | (R_rm r _) := EA.r r def ea_src (k : config) : dest_src → EA | (Rm_i _ v) := EA.i v | (Rm_r _ v) := EA.r v | (R_rm _ v) := v.ea k def imm_rm.ea (k : config) : imm_rm → EA | (imm_rm.rm rm) := rm.ea k | (imm_rm.imm q) := EA.i q def EA.read (k : config) : EA → ∀ sz : wsize, bitvec sz.to_nat → Prop | (EA.i i) sz b := b = EXTZ i | (EA.r r) (Sz8 ff) b := b = EXTZ (if r.nth 2 then (k.regs (r - 4)).ushr 8 else k.regs r) | (EA.r r) sz b := b = EXTZ (k.regs r) | (EA.m a) sz b := ∃ l, k.mem.read a l ∧ bits_to_byte (sz.to_nat / 8) b l def EA.readq (k : config) (ea : EA) (sz : wsize) (q : qword) : Prop := ∃ w, ea.read k sz w ∧ q = EXTZ w def EA.read' (ea : EA) (sz : wsize) : pstate config qword := pstate.assert $ λ k, ea.readq k sz def config.set_reg (k : config) (r : regnum) (v : qword) : config := {regs := λ i, if i = r then v else k.regs i, ..k} def config.write_reg (k : config) (r : regnum) : ∀ sz : wsize, bitvec sz.to_nat → config | (Sz8 have_rex) v := if ¬ have_rex ∧ r.nth 2 then let r' := r - 4 in config.set_reg k r' ((k.regs r').update 8 v) else config.set_reg k r ((k.regs r).update 0 v) | Sz16 v := config.set_reg k r ((k.regs r).update 0 v) | Sz32 v := config.set_reg k r (EXTZ v) | Sz64 v := config.set_reg k r v inductive config.write_mem (k : config) : qword → list byte → config → Prop | mk {a l m'} : k.mem.write a l m' → config.write_mem a l {mem := m', ..k} inductive EA.write (k : config) : EA → ∀ sz : wsize, bitvec sz.to_nat → config → Prop | r (r sz v) : EA.write (EA.r r) sz v (config.write_reg k r sz v) | m {a} {sz : wsize} {v l k'} : let n := sz.to_nat / 8 in bits_to_byte n v l → k.write_mem a l k' → EA.write (EA.m a) sz v k' def EA.writeq (k : config) (ea : EA) (sz : wsize) (q : qword) (k' : config) : Prop := ea.write k sz (EXTZ q) k' def EA.write' (ea : EA) (sz : wsize) (q : qword) : pstate config unit := pstate.lift $ λ k _, EA.writeq k ea sz q def write_rip (q : qword) : pstate config unit := pstate.modify $ λ k, {rip := q, ..k} inductive dest_src.read (k : config) (sz : wsize) (ds : dest_src) : EA → qword → qword → Prop | mk (d s) : let ea := ea_dest k ds in ea.readq k sz d → (ea_src k ds).readq k sz s → dest_src.read ea d s def dest_src.read' (sz : wsize) (ds : dest_src) : pstate config (EA × qword × qword) := pstate.assert $ λ k ⟨ea, d, s⟩, dest_src.read k sz ds ea d s def EA.call_dest (k : config) : EA → qword → Prop | (EA.i i) q := q = k.rip + i | (EA.r r) q := q = k.regs r | (EA.m a) q := (EA.m a).read k Sz64 q inductive EA.jump (k : config) : EA → config → Prop | mk (ea : EA) (q) : ea.call_dest k q → EA.jump ea {rip := q, ..k} def write_flags (f : config → flags → flags) : pstate config unit := pstate.lift $ λ k _ k', k' = {flags := f k k.flags, ..k} def MSB (sz : wsize) (w : qword) : bool := w.nth (fin.of_nat (sz.to_nat - 1)) def write_SF_ZF (sz : wsize) (w : qword) : pstate config unit := write_flags $ λ k f, { SF := MSB sz w, ZF := (EXTZ w : bitvec sz.to_nat) = 0, ..f } def write_result_flags (sz : wsize) (w : qword) (c o : bool) : pstate config unit := write_flags (λ k f, {CF := c, OF := o, ..f}) >> write_SF_ZF sz w def erase_flags : pstate config unit := do f ← pstate.any, pstate.modify $ λ s, {flags := f, ..s} def sadd_OV (sz : wsize) (a b : qword) : bool := MSB sz a = MSB sz b ∧ MSB sz (a + b) ≠ MSB sz a def ssub_OV (sz : wsize) (a b : qword) : bool := MSB sz a ≠ MSB sz b ∧ MSB sz (a - b) ≠ MSB sz a def add_carry (sz : wsize) (a b : qword) : qword × bool × bool := (a + b, 2 ^ sz.to_nat ≤ a.to_nat + b.to_nat, sadd_OV sz a b) def sub_borrow (sz : wsize) (a b : qword) : qword × bool × bool := (a - b, a.to_nat < b.to_nat, ssub_OV sz a b) def write_CF_OF_result (sz : wsize) (w : qword) (c o : bool) (ea : EA) : pstate config unit := write_result_flags sz w c o >> ea.write' sz w def write_SF_ZF_result (sz : wsize) (w : qword) (ea : EA) : pstate config unit := write_SF_ZF sz w >> ea.write' sz w def mask_shift : wsize → qword → ℕ | Sz64 w := (EXTZ w : bitvec 6).to_nat | _ w := (EXTZ w : bitvec 5).to_nat def write_binop (sz : wsize) (ea : EA) (a b : qword) : binop → pstate config unit | binop.add := let (w, c, o) := add_carry sz a b in write_CF_OF_result sz w c o ea | binop.sub := let (w, c, o) := sub_borrow sz a b in write_CF_OF_result sz w c o ea | binop.cmp := let (w, c, o) := sub_borrow sz a b in write_result_flags sz w c o | binop.tst := write_result_flags sz (a.and b) ff ff | binop.and := write_CF_OF_result sz (a.and b) ff ff ea | binop.xor := write_CF_OF_result sz (a.xor b) ff ff ea | binop.or := write_CF_OF_result sz (a.or b) ff ff ea | binop.rol := pstate.fail | binop.ror := pstate.fail | binop.rcl := pstate.fail | binop.rcr := pstate.fail | binop.shl := ea.write' sz (a.shl (mask_shift sz b)) >> erase_flags | binop.shr := ea.write' sz (a.ushr (mask_shift sz b)) >> erase_flags | binop.sar := ea.write' sz (a.fill_shr (mask_shift sz b) (MSB sz a)) >> erase_flags | binop.adc := do k ← pstate.get, let result := a + b + EXTZ (S k.flags.CF), let CF := 2 ^ sz.to_nat ≤ a.to_nat + b.to_nat, OF ← pstate.any, write_CF_OF_result sz result CF OF ea | binop.sbb := do k ← pstate.get, let carry : qword := EXTZ (S k.flags.CF), let result := a - (b + carry), let CF := a.to_nat < b.to_nat + carry.to_nat, OF ← pstate.any, write_CF_OF_result sz result CF OF ea def write_unop (sz : wsize) (a : qword) (ea : EA) : unop → pstate config unit | unop.inc := do let (w, _, o) := add_carry sz a 1, write_flags (λ k f, {OF := o, ..f}), write_SF_ZF_result sz w ea | unop.dec := do let (w, _, o) := sub_borrow sz a 1, write_flags (λ k f, {OF := o, ..f}), write_SF_ZF_result sz w ea | unop.not := ea.write' sz a.not | unop.neg := do CF ← pstate.any, write_flags (λ k f, {CF := CF, ..f}), write_SF_ZF_result sz (-a) ea def pop_aux : pstate config qword := do k ← pstate.get, let sp := k.regs RSP, (EA.r RSP).write' Sz64 (sp + 8), (EA.m sp).read' Sz64 def pop (rm : RM) : pstate config unit := do k ← pstate.get, pop_aux >>= (rm.ea k).write' Sz64 def pop_rip : pstate config unit := pop_aux >>= write_rip def push_aux (w : qword) : pstate config unit := do k ← pstate.get, let sp := k.regs RSP - 8, (EA.r RSP).write' Sz64 sp, (EA.m sp).write' Sz64 w def push (i : imm_rm) : pstate config unit := do k ← pstate.get, (i.ea k).read' Sz64 >>= push_aux def push_rip : pstate config unit := do k ← pstate.get, push_aux k.rip def execute : ast → pstate config unit | (ast.unop op sz rm) := do k ← pstate.get, let ea := rm.ea k, w ← ea.read' sz, write_unop sz w ea op | (ast.binop op sz ds) := do (ea, d, s) ← dest_src.read' sz ds, write_binop sz ea d s op | (ast.mul sz r) := do eax ← (EA.r RAX).read' sz, k ← pstate.get, src ← (r.ea k).read' sz, match sz with | (Sz8 _) := (EA.r RAX).write' Sz16 (eax * src) | _ := do let hi := bitvec.of_nat sz.to_nat ((eax.to_nat * src.to_nat).shiftl sz.to_nat), (EA.r RAX).write' sz (eax * src), (EA.r RDX).write' sz (EXTZ hi) end, erase_flags | (ast.div sz r) := do eax ← (EA.r RAX).read' sz, edx ← (EA.r RDX).read' sz, let n := edx.to_nat * (2 ^ sz.to_nat) + eax.to_nat, k ← pstate.get, d ← bitvec.to_nat <$> (r.ea k).read' sz, pstate.assert $ λ _ (_:unit), d ≠ 0 ∧ n / d < 2 ^ sz.to_nat, (EA.r RAX).write' sz (bitvec.of_nat _ (n / d)), (EA.r RDX).write' sz (bitvec.of_nat _ (n % d)), erase_flags | (ast.lea sz ds) := do k ← pstate.get, (ea_dest k ds).write' sz (ea_src k ds).addr | (ast.movsx sz1 ds sz2) := do w ← pstate.assert $ λ k, (ea_src k ds).read k sz1, k ← pstate.get, (ea_dest k ds).write' sz2 (EXTZ (EXTS w : bitvec sz2.to_nat)) | (ast.movzx sz1 ds sz2) := do w ← pstate.assert $ λ k, (ea_src k ds).read k sz1, k ← pstate.get, (ea_dest k ds).write' sz2 (EXTZ w) | (ast.xchg sz r n) := do let src := EA.r n, k ← pstate.get, let dst := r.ea k, val_src ← src.read' sz, val_dst ← dst.read' sz, src.write' sz val_dst, dst.write' sz val_src | (ast.cmpxchg sz r n) := do let src := EA.r n, let acc := EA.r RAX, k ← pstate.get, let dst := r.ea k, val_dst ← dst.read' sz, val_acc ← acc.read' sz, write_binop sz src val_acc val_dst binop.cmp, if val_acc = val_dst then src.read' sz >>= dst.write' sz else acc.write' sz val_dst | (ast.xadd sz r n) := do let src := EA.r n, k ← pstate.get, let dst := r.ea k, val_src ← src.read' sz, val_dst ← dst.read' sz, src.write' sz val_dst, write_binop sz dst val_src val_dst binop.add | (ast.cmov c sz ds) := do k ← pstate.get, when (c.read k.flags) $ (ea_src k ds).read' sz >>= (ea_dest k ds).write' sz | (ast.setcc c b r) := do k ← pstate.get, (r.ea k).write' (Sz8 b) (EXTZ $ S $ c.read k.flags) | (ast.jump rm) := do k ← pstate.get, (rm.ea k).read' Sz64 >>= write_rip | (ast.jcc c i) := do k ← pstate.get, when (c.read k.flags) (write_rip (k.rip + i)) | (ast.call i) := do push_rip, pstate.lift $ λ k _, (i.ea k).jump k | (ast.ret i) := do pop_rip, sp ← (EA.r RSP).read' Sz64, (EA.r RSP).write' Sz64 (sp + i) | (ast.push i) := push i | (ast.pop r) := pop r | ast.leave := do (EA.r RBP).read' Sz64 >>= (EA.r RSP).write' Sz64, pop (RM.reg RBP) | ast.clc := write_flags $ λ _ f, {CF := ff, ..f} | ast.cmc := write_flags $ λ _ f, {CF := bnot f.CF, ..f} | ast.stc := write_flags $ λ _ f, {CF := tt, ..f} -- | (ast.int _) := pstate.fail | ast.syscall := pstate.fail inductive config.step (k : config) : config → Prop | mk {l a k'} : k.mem.readX k.rip l → decode a l → ((do write_rip (k.rip + bitvec.of_nat _ l.length), execute a) k).P () k' → config.step k' inductive config.isIO (k : config) : config → Prop | mk {l k'} : k.mem.readX k.rip l → decode ast.syscall l → ((do let rip := k.rip + bitvec.of_nat _ l.length, write_rip rip, (EA.r RCX).write' Sz64 rip, r11 ← pstate.any, (EA.r 11).write' Sz64 r11) k).P () k' → config.isIO k' structure kcfg := (input : list byte) (output : list byte) (k : config) inductive config.read_cstr (k : config) (a : qword) : string → Prop | mk {s : string} : (∀ c : char, c ∈ s.to_list → c.1 ≠ 0) → k.mem.read a s.to_cstr → config.read_cstr s inductive read_from_fd (fd : qword) : list byte → list byte → list byte → Prop | other {i buf} : fd ≠ 0 → read_from_fd i buf i | stdin {i' buf} : fd = 0 → (buf = [] → i' = []) → read_from_fd (buf ++ i') buf i' inductive exec_read (i : list byte) (k : config) (fd : qword) (count : ℕ) : list byte → config → qword → Prop | fail {ret} : MSB Sz32 ret → exec_read i k ret | success {i' dat k' ret} : ¬ MSB Sz32 ret → ret.to_nat ≤ count → read_from_fd fd i dat i' → k.write_mem (k.regs RSI) dat k' → exec_read i' k' ret inductive exec_io (i o : list byte) (k : config) (rax : qword) : list byte → list byte → config → qword → Prop | _open {pathname fd} : k.read_cstr (k.regs RDI) pathname → let flags := k.regs RSI in flags.to_nat ∈ [0, 0x241] → -- O_RDONLY, or O_WRONLY | O_CREAT | O_TRUNC rax = 2 → exec_io i o k fd | _read {buf i' k' ret} : let fd := k.regs RDI, count := (k.regs RDX).to_nat in k.mem.read (k.regs RSI) buf → buf.length = count → exec_read i k fd count i' k' ret → rax = 0 → exec_io i' o k' ret -- TODO: write, fstat, mmap inductive exec_exit (k : config) : qword → Prop | mk : k.regs RAX = 0x3c → exec_exit (k.regs RDI) def config.exit (k : config) (a : qword) : Prop := ∃ k', config.isIO k k' ∧ exec_exit k' a inductive kcfg.step : kcfg → kcfg → Prop | noio {i o k k'} : config.step k k' → kcfg.step ⟨i, o, k⟩ ⟨i, o, k'⟩ | io {i o k k₁ i' o' k' ret} : config.isIO k k₁ → exec_io i o k₁ (k₁.regs RAX) i' o' k' ret → kcfg.step ⟨i, o, k⟩ ⟨i', o', k'.set_reg RAX ret⟩ def kcfg.steps : kcfg → kcfg → Prop := relation.refl_trans_gen kcfg.step def kcfg.valid (k : kcfg) : Prop := (∃ k', k.step k') ∨ ∃ ret, k.k.exit ret def kcfg.safe (k : kcfg) : Prop := ∀ k', k.steps k' → k'.valid def terminates (k : config) (i o : list byte) := ∀ K', kcfg.steps ⟨i, [], k⟩ K' → ∃ i' o' k' ret, kcfg.steps K' ⟨i', o', k'⟩ ∧ k'.exit ret ∧ (ret = 0 → i' = [] ∧ o' = o) def succeeds (k : config) (i o : list byte) := ∃ i' k', kcfg.steps ⟨i, [], k⟩ ⟨i', o, k'⟩ ∧ k'.exit 0 inductive hoare_p (Q : kcfg → Prop) : kcfg → Prop | zero {{k}} : Q k → hoare_p k | step {{k}} : (∃ k', kcfg.step k k') → (∀ k', k.step k' → hoare_p k') → hoare_p k | exit (k : kcfg) (ret) : k.k.exit ret → (ret = 0 → Q k) → hoare_p k end x86
f913ae5440117ec738728d66d0d927e91aa32a8e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Match/Value.lean
39667cd59b77f303e210de01c1ca8894f67a4ebd
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,483
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean.Meta -- TODO: move? private def UIntTypeNames : Array Name := #[``UInt8, ``UInt16, ``UInt32, ``UInt64, ``USize] private def isUIntTypeName (n : Name) : Bool := UIntTypeNames.contains n def isFinPatLit (e : Expr) : Bool := e.isAppOfArity `Fin.ofNat 2 && e.appArg!.isNatLit /-- Return `some (typeName, numLit)` if `v` is of the form `UInt*.mk (Fin.ofNat _ numLit)` -/ def isUIntPatLit? (v : Expr) : Option (Name × Expr) := match v with | Expr.app (Expr.const (Name.str typeName "mk" ..) ..) val .. => if isUIntTypeName typeName && isFinPatLit val then some (typeName, val.appArg!) else none | _ => none def isUIntPatLit (v : Expr) : Bool := isUIntPatLit? v |>.isSome /-- The frontend expands uint numerals occurring in patterns into `UInt*.mk ..` contructor applications. This method convert them back into `UInt*.ofNat ..` applications. -/ def foldPatValue (v : Expr) : Expr := match isUIntPatLit? v with | some (typeName, numLit) => mkApp (mkConst (Name.mkStr typeName "ofNat")) numLit | _ => v /-- Return true is `e` is a term that should be processed by the `match`-compiler using `casesValues` -/ def isMatchValue (e : Expr) : Bool := e.isNatLit || e.isCharLit || e.isStringLit || isFinPatLit e || isUIntPatLit e end Lean.Meta
09b5a0576a69fd04994cbc0a0dfcf7569fa2e789
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/regular_expressions.lean
27b502cea40ca02584b6995c3f11eb97754b5a17
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,432
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Fox Thomson. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.basic import Mathlib.data.finset.basic import Mathlib.tactic.rcases import Mathlib.tactic.omega.default import Mathlib.computability.language import Mathlib.PostPort universes u l namespace Mathlib /-! # Regular Expressions This file contains the formal definition for regular expressions and basic lemmas. Note these are regular expressions in terms of formal language theory. Note this is different to regex's used in computer science such as the POSIX standard. TODO * Show that this regular expressions and DFA/NFA's are equivalent. * `attribute [pattern] has_mul.mul` has been added into this file, it could be moved. -/ /-- This is the definition of regular expressions. The names used here is to mirror the definition of a Kleene algebra (https://en.wikipedia.org/wiki/Kleene_algebra). * `0` (`zero`) matches nothing * `1` (`epsilon`) matches only the empty string * `char a` matches only the string 'a' * `star P` matches any finite concatenation of strings which match `P` * `P + Q` (`plus P Q`) matches anything which match `P` or `Q` * `P * Q` (`comp P Q`) matches `x ++ y` if `x` matches `P` and `y` matches `Q` -/ inductive regular_expression (α : Type u) where | zero : regular_expression α | epsilon : regular_expression α | char : α → regular_expression α | plus : regular_expression α → regular_expression α → regular_expression α | comp : regular_expression α → regular_expression α → regular_expression α | star : regular_expression α → regular_expression α namespace regular_expression protected instance inhabited {α : Type u} : Inhabited (regular_expression α) := { default := zero } protected instance has_add {α : Type u} : Add (regular_expression α) := { add := plus } protected instance has_mul {α : Type u} : Mul (regular_expression α) := { mul := comp } protected instance has_one {α : Type u} : HasOne (regular_expression α) := { one := epsilon } protected instance has_zero {α : Type u} : HasZero (regular_expression α) := { zero := zero } @[simp] theorem zero_def {α : Type u} : zero = 0 := rfl @[simp] theorem one_def {α : Type u} : epsilon = 1 := rfl @[simp] theorem plus_def {α : Type u} (P : regular_expression α) (Q : regular_expression α) : plus P Q = P + Q := rfl @[simp] theorem comp_def {α : Type u} (P : regular_expression α) (Q : regular_expression α) : comp P Q = P * Q := rfl /-- `matches P` provides a language which contains all strings that `P` matches -/ def matches {α : Type u} : regular_expression α → language α := sorry @[simp] theorem matches_zero_def {α : Type u} : matches 0 = 0 := rfl @[simp] theorem matches_epsilon_def {α : Type u} : matches 1 = 1 := rfl @[simp] theorem matches_add_def {α : Type u} (P : regular_expression α) (Q : regular_expression α) : matches (P + Q) = matches P + matches Q := rfl @[simp] theorem matches_mul_def {α : Type u} (P : regular_expression α) (Q : regular_expression α) : matches (P * Q) = matches P * matches Q := rfl @[simp] theorem matches_star_def {α : Type u} (P : regular_expression α) : matches (star P) = language.star (matches P) := rfl /-- `match_epsilon P` is true if and only if `P` matches the empty string -/ def match_epsilon {α : Type u} : regular_expression α → Bool := sorry /-- `P.deriv a` matches `x` if `P` matches `a :: x`, the Brzozowski derivative of `P` with respect to `a` -/ def deriv {α : Type u} [dec : DecidableEq α] : regular_expression α → α → regular_expression α := sorry /-- `P.rmatch x` is true if and only if `P` matches `x`. This is a computable definition equivalent to `matches`. -/ def rmatch {α : Type u} [dec : DecidableEq α] : regular_expression α → List α → Bool := sorry @[simp] theorem zero_rmatch {α : Type u} [dec : DecidableEq α] (x : List α) : rmatch 0 x = false := sorry theorem one_rmatch_iff {α : Type u} [dec : DecidableEq α] (x : List α) : ↥(rmatch 1 x) ↔ x = [] := sorry theorem char_rmatch_iff {α : Type u} [dec : DecidableEq α] (a : α) (x : List α) : ↥(rmatch (char a) x) ↔ x = [a] := sorry theorem add_rmatch_iff {α : Type u} [dec : DecidableEq α] (P : regular_expression α) (Q : regular_expression α) (x : List α) : ↥(rmatch (P + Q) x) ↔ ↥(rmatch P x) ∨ ↥(rmatch Q x) := sorry theorem mul_rmatch_iff {α : Type u} [dec : DecidableEq α] (P : regular_expression α) (Q : regular_expression α) (x : List α) : ↥(rmatch (P * Q) x) ↔ ∃ (t : List α), ∃ (u : List α), x = t ++ u ∧ ↥(rmatch P t) ∧ ↥(rmatch Q u) := sorry theorem star_rmatch_iff {α : Type u} [dec : DecidableEq α] (P : regular_expression α) (x : List α) : ↥(rmatch (star P) x) ↔ ∃ (S : List (List α)), x = list.join S ∧ ∀ (t : List α), t ∈ S → t ≠ [] ∧ ↥(rmatch P t) := sorry @[simp] theorem rmatch_iff_matches {α : Type u} [dec : DecidableEq α] (P : regular_expression α) (x : List α) : ↥(rmatch P x) ↔ x ∈ matches P := sorry protected instance matches.decidable_pred {α : Type u} [dec : DecidableEq α] (P : regular_expression α) : decidable_pred (matches P) := id fun (x : List α) => id (eq.mpr sorry (eq.decidable (rmatch P x) tt))
94b9d4f00affc8b4c4d99b7dc27a17baac50ad3b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/computability/NFA.lean
665f223ef2d22b00360edbfe244ea6b516d45c46
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,111
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import computability.DFA /-! # Nondeterministic Finite Automata This file contains the definition of a Nondeterministic Finite Automaton (NFA), a state machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set by evaluating the string over every possible path. We show that DFA's are equivalent to NFA's however the construction from NFA to DFA uses an exponential number of states. Note that this definition allows for Automaton with infinite states, a `fintype` instance must be supplied for true NFA's. -/ universes u v /-- An NFA is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). Note the transition function sends a state to a `set` of states. These are the states that it may be sent to. -/ structure NFA (α : Type u) (σ : Type v) := (step : σ → α → set σ) (start : set σ) (accept : set σ) variables {α : Type u} {σ σ' : Type v} (M : NFA α σ) namespace NFA instance : inhabited (NFA α σ) := ⟨ NFA.mk (λ _ _, ∅) ∅ ∅ ⟩ /-- `M.step_set S a` is the union of `M.step s a` for all `s ∈ S`. -/ def step_set : set σ → α → set σ := λ Ss a, Ss >>= (λ S, (M.step S a)) lemma mem_step_set (s : σ) (S : set σ) (a : α) : s ∈ M.step_set S a ↔ ∃ t ∈ S, s ∈ M.step t a := by simp only [step_set, set.mem_Union, set.bind_def] /-- `M.eval_from S x` computes all possible paths though `M` with input `x` starting at an element of `S`. -/ def eval_from (start : set σ) : list α → set σ := list.foldl M.step_set start /-- `M.eval x` computes all possible paths though `M` with input `x` starting at an element of `M.start`. -/ def eval := M.eval_from M.start /-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/ def accepts : language α := λ x, ∃ S ∈ M.accept, S ∈ M.eval x /-- `M.to_DFA` is an `DFA` constructed from a `NFA` `M` using the subset construction. The states is the type of `set`s of `M.state` and the step function is `M.step_set`. -/ def to_DFA : DFA α (set σ) := { step := M.step_set, start := M.start, accept := {S | ∃ s ∈ S, s ∈ M.accept} } @[simp] lemma to_DFA_correct : M.to_DFA.accepts = M.accepts := begin ext x, rw [accepts, DFA.accepts, eval, DFA.eval], change list.foldl _ _ _ ∈ {S | _} ↔ _, finish end lemma pumping_lemma [fintype σ] {x : list α} (hx : x ∈ M.accepts) (hlen : fintype.card (set σ) + 1 ≤ list.length x) : ∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ fintype.card (set σ) + 1 ∧ b ≠ [] ∧ {a} * language.star {b} * {c} ≤ M.accepts := begin rw ←to_DFA_correct at hx ⊢, exact M.to_DFA.pumping_lemma hx hlen end end NFA namespace DFA /-- `M.to_NFA` is an `NFA` constructed from a `DFA` `M` by using the same start and accept states and a transition function which sends `s` with input `a` to the singleton `M.step s a`. -/ def to_NFA (M : DFA α σ') : NFA α σ' := { step := λ s a, {M.step s a}, start := {M.start}, accept := M.accept } @[simp] lemma to_NFA_eval_from_match (M : DFA α σ) (start : σ) (s : list α) : M.to_NFA.eval_from {start} s = {M.eval_from start s} := begin change list.foldl M.to_NFA.step_set {start} s = {list.foldl M.step start s}, induction s with a s ih generalizing start, { tauto }, { rw [list.foldl, list.foldl], have h : M.to_NFA.step_set {start} a = {M.step start a}, { rw NFA.step_set, finish }, rw h, tauto } end @[simp] lemma to_NFA_correct (M : DFA α σ) : M.to_NFA.accepts = M.accepts := begin ext x, change (∃ S H, S ∈ M.to_NFA.eval_from {M.start} x) ↔ _, rw to_NFA_eval_from_match, split, { rintro ⟨ S, hS₁, hS₂ ⟩, rw set.mem_singleton_iff at hS₂, rw hS₂ at hS₁, assumption }, { intro h, use M.eval x, finish } end end DFA
992c8de34d5b337d26a234a8d995de257ce93606
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Util/ForEachExpr.lean
7018bfe7fbcc243333f9c661654b670afe3e0b42
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,477
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr import Lean.Util.MonadCache namespace Lean /- Remark: we cannot use the caching trick used at `FindExpr` and `ReplaceExpr` because they may visit the same expression multiple times if they are stored in different memory addresses. Note that the following code is parametric in a monad `m`. -/ variables {ω : Type} {m : Type → Type} [STWorld ω m] [MonadLiftT (ST ω) m] [Monad m] namespace ForEachExpr @[specialize] partial def visit (g : Expr → m Bool) (e : Expr) : MonadCacheT Expr Unit m Unit := checkCache e fun e => do if (← g e) then match e with | Expr.forallE _ d b _ => do visit g d; visit g b | Expr.lam _ d b _ => do visit g d; visit g b | Expr.letE _ t v b _ => do visit g t; visit g v; visit g b | Expr.app f a _ => do visit g f; visit g a | Expr.mdata _ b _ => visit g b | Expr.proj _ _ b _ => visit g b | _ => pure () end ForEachExpr /-- Apply `f` to each sub-expression of `e`. If `f t` return true, then t's children are not visited. -/ @[inline] def Expr.forEach' (e : Expr) (f : Expr → m Bool) : m Unit := (ForEachExpr.visit f e).run @[inline] def Expr.forEach (e : Expr) (f : Expr → m Unit) : m Unit := e.forEach' fun e => do f e; pure true end Lean
11d555c8663737c8c5700771af56f1217c32fa34
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/universal/instances.lean
e7885cc8ad651b3477f62876e962750d52678fcc
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
5,786
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .universal import ..util.finite open categories open categories.functor open categories.isomorphism open categories.initial open categories.types open categories.util open categories.util.finite namespace categories.universal class has_InitialObject ( C : Category ) := ( initial_object : InitialObject C ) class has_BinaryProducts ( C : Category ) := ( binary_product : Π X Y : C.Obj, BinaryProduct X Y ) class has_FiniteProducts ( C : Category ) := ( product : Π { I : Type } [ Finite I ] ( f : I → C.Obj ), Product f ) class has_Products ( C : Category ) := ( product : Π { I : Type } ( f : I → C.Obj ), Product f ) class has_TerminalObject ( C : Category ) := ( terminal_object : TerminalObject C ) class has_BinaryCoproducts ( C : Category ) := ( binary_coproduct : Π X Y : C.Obj, BinaryCoproduct X Y ) class has_FiniteCoproducts ( C : Category ) := ( coproduct : Π { I : Type } [ Finite I ] ( f : I → C.Obj ), Coproduct f ) class has_Coproducts ( C : Category ) := ( coproduct : Π { I : Type } ( f : I → C.Obj ), Coproduct f ) class has_Equalizers ( C : Category ) := ( equalizer : Π { X Y : C.Obj } ( f g : C.Hom X Y ), Equalizer f g ) class has_Coequalizers ( C : Category ) := ( coequalizer : Π { X Y : C.Obj } ( f g : C.Hom X Y ), Coequalizer f g ) definition initial_object { C : Category } [ has_InitialObject C ] : C.Obj := has_InitialObject.initial_object C definition terminal_object { C : Category } [ has_TerminalObject C ] : C.Obj := has_TerminalObject.terminal_object C definition binary_product { C : Category } [ has_BinaryProducts C ] ( X Y : C.Obj ) := has_BinaryProducts.binary_product X Y definition finite_product { C : Category } [ has_FiniteProducts C ] { I : Type } [ fin : Finite I ] ( f : I → C.Obj ) := @has_FiniteProducts.product C _ I fin f definition product { C : Category } [ has_Products C ] { I : Type } ( F : I → C.Obj ) := has_Products.product F definition binary_coproduct { C : Category } [ has_BinaryCoproducts C ] ( X Y : C.Obj ) := has_BinaryCoproducts.binary_coproduct X Y definition finite_coproduct { C : Category } [ has_FiniteCoproducts C ] { I : Type } [ fin : Finite I ] ( f : I → C.Obj ) := @has_FiniteCoproducts.coproduct C _ I fin f definition coproduct { C : Category } [ has_Coproducts C ] { I : Type } ( F : I → C.Obj ) := has_Coproducts.coproduct F definition equalizer { C : Category } [ has_Equalizers C ] { X Y : C.Obj } ( f g : C.Hom X Y ) := has_Equalizers.equalizer f g definition coequalizer { C : Category } [ has_Coequalizers C ] { X Y : C.Obj } ( f g : C.Hom X Y ) := has_Coequalizers.coequalizer f g instance FiniteProducts_give_a_TerminalObject ( C : Category ) [ has_FiniteProducts C ] : has_TerminalObject C := { terminal_object := let empty_product := @has_FiniteProducts.product C _ empty _ empty_function in { terminal_object := empty_product.product, morphism_to_terminal_object_from := λ X, empty_product.map empty_dependent_function, uniqueness_of_morphisms_to_terminal_object := λ X f g, empty_product.uniqueness f g empty_dependent_function } } instance FiniteProducts_from_Products ( C : Category ) [ has_Products C ] : has_FiniteProducts C := { product := λ _ _ f, has_Products.product f } instance FiniteCoproducts_give_an_InitialObject ( C : Category ) [ has_FiniteCoproducts C ] : has_InitialObject C := { initial_object := let empty_coproduct := @has_FiniteCoproducts.coproduct C _ empty _ empty_function in { initial_object := empty_coproduct.coproduct, morphism_from_initial_object_to := λ X, empty_coproduct.map empty_dependent_function, uniqueness_of_morphisms_from_initial_object := λ X f g, empty_coproduct.uniqueness f g empty_dependent_function } } instance FiniteCoproducts_from_Coproducts ( C : Category ) [ has_Coproducts C ] : has_FiniteCoproducts C := { coproduct := λ _ _ f, has_Coproducts.coproduct f } instance BinaryProducts_from_FiniteProducts ( C : Category ) [ has_FiniteProducts C ] : has_BinaryProducts C := { binary_product := λ X Y : C.Obj, let F := Two.choice X Y in let p := finite_product F in { product := p.product, left_projection := p.projection Two._0, right_projection := p.projection Two._1, map := λ _ f g, p.map (Two.dependent_choice f g), left_factorisation := λ _ f g, p.factorisation (Two.dependent_choice f g) Two._0, right_factorisation := λ _ f g, p.factorisation (Two.dependent_choice f g) Two._1, uniqueness := λ _ f g u v, p.uniqueness f g (Two.split_choice u v) } } -- PROJECT: -- open nat -- definition construct_finite_product ( C : Category ) [ has_TerminalObject C ] [ has_BinaryProducts C ] -- : Π n : nat, Π ( I : Type ) ( fin : Finite I ) ( p : fin.cardinality = n ) ( f : I → C.Obj ), Product f -- | 0 := λ { I : Type } [ fin : Finite I ] ( p : fin.cardinality = 0 ) ( f : I → C.Obj ), { -- product := terminal_object, -- projection := begin intros, admit end, -- map := sorry, -- factorisation := sorry, -- uniqueness := sorry -- } -- | (succ n) := sorry -- instance FiniteProducts_from_BinaryProducts ( C : Category ) [ has_TerminalObject C ] [ has_BinaryProducts C ] : has_FiniteProducts C := { -- product := λ { I : Type } [ fin : Finite I ] ( f : I → C.Obj ), construct_finite_product C fin.cardinality I fin ♯ f -- } end categories.universal
8088412252a919bcb3113164f6fd9d47e68c51f9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/combinatorics/hall/finite.lean
db339cc948d5eebc2554da4effd51e2d5eda7f30
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,640
lean
/- Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller -/ import data.fintype.basic import data.rel import data.set.finite /-! # Hall's Marriage Theorem for finite index types This module proves the basic form of Hall's theorem. In constrast to the theorem described in `combinatorics.hall.basic`, this version requires that the indexed family `t : ι → finset α` have `ι` be a `fintype`. The `combinatorics.hall.basic` module applies a compactness argument to this version to remove the `fintype` constraint on `ι`. The modules are split like this since the generalized statement depends on the topology and category theory libraries, but the finite case in this module has few dependencies. A description of this formalization is in [Gusakov2021]. ## Main statements * `finset.all_card_le_bUnion_card_iff_exists_injective'` is Hall's theorem with a finite index set. This is elsewhere generalized to `finset.all_card_le_bUnion_card_iff_exists_injective`. ## Tags Hall's Marriage Theorem, indexed families -/ open finset universes u v namespace hall_marriage_theorem variables {ι : Type u} {α : Type v} [fintype ι] theorem hall_hard_inductive_zero (t : ι → finset α) (hn : fintype.card ι = 0) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin rw fintype.card_eq_zero_iff at hn, exactI ⟨is_empty_elim, is_empty_elim, is_empty_elim⟩, end variables {t : ι → finset α} [decidable_eq α] lemma hall_cond_of_erase {x : ι} (a : α) (ha : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card) (s' : finset {x' : ι | x' ≠ x}) : s'.card ≤ (s'.bUnion (λ x', (t x').erase a)).card := begin haveI := classical.dec_eq ι, specialize ha (s'.image coe), rw [nonempty.image_iff, finset.card_image_of_injective s' subtype.coe_injective] at ha, by_cases he : s'.nonempty, { have ha' : s'.card < (s'.bUnion (λ x, t x)).card, { specialize ha he (λ h, by { have h' := mem_univ x, rw ←h at h', simpa using h' }), convert ha using 2, ext x, simp only [mem_image, mem_bUnion, exists_prop, set_coe.exists, exists_and_distrib_right, exists_eq_right, subtype.coe_mk], }, rw ←erase_bUnion, by_cases hb : a ∈ s'.bUnion (λ x, t x), { rw card_erase_of_mem hb, exact nat.le_pred_of_lt ha' }, { rw erase_eq_of_not_mem hb, exact nat.le_of_lt ha' }, }, { rw [nonempty_iff_ne_empty, not_not] at he, subst s', simp }, end /-- First case of the inductive step: assuming that `∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card` and that the statement of **Hall's Marriage Theorem** is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`. -/ lemma hall_hard_inductive_step_A {n : ℕ} (hn : fintype.card ι = n + 1) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α), by exactI fintype.card ι' ≤ n → (∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) → ∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x) (ha : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin haveI : nonempty ι := fintype.card_pos_iff.mp (hn.symm ▸ nat.succ_pos _), haveI := classical.dec_eq ι, /- Choose an arbitrary element `x : ι` and `y : t x`. -/ let x := classical.arbitrary ι, have tx_ne : (t x).nonempty, { rw ←finset.card_pos, apply nat.lt_of_lt_of_le nat.one_pos, convert ht {x}, rw finset.singleton_bUnion, }, rcases classical.indefinite_description _ tx_ne with ⟨y, hy⟩, /- Restrict to everything except `x` and `y`. -/ let ι' := {x' : ι | x' ≠ x}, let t' : ι' → finset α := λ x', (t x').erase y, have card_ι' : fintype.card ι' = n, { convert congr_arg (λ m, m - 1) hn, convert set.card_ne_eq _, }, rcases ih t' card_ι'.le (hall_cond_of_erase y ha) with ⟨f', hfinj, hfr⟩, /- Extend the resulting function. -/ refine ⟨λ z, if h : z = x then y else f' ⟨z, h⟩, _, _⟩, { rintro z₁ z₂, have key : ∀ {x}, y ≠ f' x, { intros x h, specialize hfr x, rw ←h at hfr, simpa using hfr, }, by_cases h₁ : z₁ = x; by_cases h₂ : z₂ = x; simp [h₁, h₂, hfinj.eq_iff, key, key.symm], }, { intro z, split_ifs with hz, { rwa hz }, { specialize hfr ⟨z, hz⟩, rw mem_erase at hfr, exact hfr.2, }, }, end lemma hall_cond_of_restrict {ι : Type u} {t : ι → finset α} {s : finset ι} (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (s' : finset (s : set ι)) : s'.card ≤ (s'.bUnion (λ a', t a')).card := begin haveI := classical.dec_eq ι, convert ht (s'.image coe) using 1, { rw card_image_of_injective _ subtype.coe_injective, }, { apply congr_arg, ext y, simp, }, end lemma hall_cond_of_compl {ι : Type u} {t : ι → finset α} {s : finset ι} (hus : s.card = (s.bUnion t).card) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (s' : finset (sᶜ : set ι)) : s'.card ≤ (s'.bUnion (λ x', t x' \ s.bUnion t)).card := begin haveI := classical.dec_eq ι, have : s'.card = (s ∪ s'.image coe).card - s.card, { rw [card_disjoint_union, add_tsub_cancel_left, card_image_of_injective _ subtype.coe_injective], simp only [disjoint_left, not_exists, mem_image, exists_prop, set_coe.exists, exists_and_distrib_right, exists_eq_right, subtype.coe_mk], intros x hx hc h, exact (hc hx).elim }, rw [this, hus], apply (tsub_le_tsub_right (ht _) _).trans _, rw ← card_sdiff, { have : (s ∪ s'.image subtype.val).bUnion t \ s.bUnion t ⊆ s'.bUnion (λ x', t x' \ s.bUnion t), { intros t, simp only [mem_bUnion, mem_sdiff, not_exists, mem_image, and_imp, mem_union, exists_and_distrib_right, exists_imp_distrib], rintro x (hx | ⟨x', hx', rfl⟩) rat hs, { exact (hs x hx rat).elim }, { exact ⟨⟨x', hx', rat⟩, hs⟩, } }, exact (card_le_of_subset this).trans le_rfl, }, { apply bUnion_subset_bUnion_of_subset_left, apply subset_union_left } end /-- Second case of the inductive step: assuming that `∃ (s : finset ι), s ≠ univ → s.card = (s.bUnion t).card` and that the statement of Hall's Marriage Theorem is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`. -/ lemma hall_hard_inductive_step_B {n : ℕ} (hn : fintype.card ι = n + 1) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α), by exactI fintype.card ι' ≤ n → (∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) → ∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x) (s : finset ι) (hs : s.nonempty) (hns : s ≠ univ) (hus : s.card = (s.bUnion t).card) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin haveI := classical.dec_eq ι, /- Restrict to `s` -/ let t' : s → finset α := λ x', t x', rw nat.add_one at hn, have card_ι'_le : fintype.card s ≤ n, { apply nat.le_of_lt_succ, rw ←hn, convert (card_lt_iff_ne_univ _).mpr hns, convert fintype.card_coe _ }, rcases ih t' card_ι'_le (hall_cond_of_restrict ht) with ⟨f', hf', hsf'⟩, /- Restrict to `sᶜ` in the domain and `(s.bUnion t)ᶜ` in the codomain. -/ set ι'' := (s : set ι)ᶜ with ι''_def, let t'' : ι'' → finset α := λ a'', t a'' \ s.bUnion t, have card_ι''_le : fintype.card ι'' ≤ n, { apply nat.le_of_lt_succ, rw ←hn, convert (card_compl_lt_iff_nonempty _).mpr hs, convert fintype.card_coe (sᶜ), exact (finset.coe_compl s).symm }, rcases ih t'' card_ι''_le (hall_cond_of_compl hus ht) with ⟨f'', hf'', hsf''⟩, /- Put them together -/ have f'_mem_bUnion : ∀ {x'} (hx' : x' ∈ s), f' ⟨x', hx'⟩ ∈ s.bUnion t, { intros x' hx', rw mem_bUnion, exact ⟨x', hx', hsf' _⟩, }, have f''_not_mem_bUnion : ∀ {x''} (hx'' : ¬ x'' ∈ s), ¬ f'' ⟨x'', hx''⟩ ∈ s.bUnion t, { intros x'' hx'', have h := hsf'' ⟨x'', hx''⟩, rw mem_sdiff at h, exact h.2, }, have im_disj : ∀ {x' x'' : ι} {hx' : x' ∈ s} {hx'' : ¬x'' ∈ s}, f' ⟨x', hx'⟩ ≠ f'' ⟨x'', hx''⟩, { intros _ _ hx' hx'' h, apply f''_not_mem_bUnion hx'', rw ←h, apply f'_mem_bUnion, }, refine ⟨λ x, if h : x ∈ s then f' ⟨x, h⟩ else f'' ⟨x, h⟩, _, _⟩, { exact hf'.dite _ hf'' @im_disj }, { intro x, split_ifs, { exact hsf' ⟨x, h⟩ }, { exact sdiff_subset _ _ (hsf'' ⟨x, h⟩) } } end /-- If `ι` has cardinality `n + 1` and the statement of Hall's Marriage Theorem is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι`. -/ theorem hall_hard_inductive_step {n : ℕ} (hn : fintype.card ι = n + 1) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) (ih : ∀ {ι' : Type u} [fintype ι'] (t' : ι' → finset α), by exactI fintype.card ι' ≤ n → (∀ (s' : finset ι'), s'.card ≤ (s'.bUnion t').card) → ∃ (f : ι' → α), function.injective f ∧ ∀ x, f x ∈ t' x) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin by_cases h : ∀ (s : finset ι), s.nonempty → s ≠ univ → s.card < (s.bUnion t).card, { exact hall_hard_inductive_step_A hn ht @ih h, }, { push_neg at h, rcases h with ⟨s, sne, snu, sle⟩, have seq := nat.le_antisymm (ht _) sle, exact hall_hard_inductive_step_B hn ht @ih s sne snu seq, }, end /-- Here we combine the base case and the inductive step into a full strong induction proof, thus completing the proof of the second direction. -/ theorem hall_hard_inductive {n : ℕ} (hn : fintype.card ι = n) (ht : ∀ (s : finset ι), s.card ≤ (s.bUnion t).card) : ∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x := begin tactic.unfreeze_local_instances, revert ι, refine nat.strong_induction_on n (λ n' ih, _), intros _ _ t hn ht, rcases n' with (_|_), { exact hall_hard_inductive_zero t hn }, { apply hall_hard_inductive_step hn ht, introsI ι' _ _ hι', exact ih (fintype.card ι') (nat.lt_succ_of_le hι') rfl, }, end end hall_marriage_theorem /-- This is the version of **Hall's Marriage Theorem** in terms of indexed families of finite sets `t : ι → finset α` with `ι` a `fintype`. It states that there is a set of distinct representatives if and only if every union of `k` of the sets has at least `k` elements. See `finset.all_card_le_bUnion_card_iff_exists_injective` for a version where the `fintype ι` constraint is removed. -/ theorem finset.all_card_le_bUnion_card_iff_exists_injective' {ι α : Type*} [fintype ι] [decidable_eq α] (t : ι → finset α) : (∀ (s : finset ι), s.card ≤ (s.bUnion t).card) ↔ (∃ (f : ι → α), function.injective f ∧ ∀ x, f x ∈ t x) := begin split, { exact hall_marriage_theorem.hall_hard_inductive rfl }, { rintro ⟨f, hf₁, hf₂⟩ s, rw ←card_image_of_injective s hf₁, apply card_le_of_subset, intro _, rw [mem_image, mem_bUnion], rintros ⟨x, hx, rfl⟩, exact ⟨x, hx, hf₂ x⟩, }, end
7481209f2b3ac8a06664f4a123f26cf137e5f9fc
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/structure_test.lean
02646bce98e79bb652cb5dce4bb3b77a381d11d4
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
677
lean
inductive point (A B : Type*) | mk : Π (x : A) (y : B), point inductive [class] color | red | green | blue constant {u} foo (A : Type u) [H : decidable_eq A] : Type u constants a : num section universe variable l variable A : Type.{l} variable Ha : decidable_eq A include Ha variable E : Type₂ include E -- include Ha structure point3d_color (B C : Type*) (D : B → Type*) extends point (foo A) B, sigma D renaming pr1→y pr2→w := mk :: (c : color) (H : x == y) check point3d_color.c check point3d_color.to_point end section universe l parameters A : Type.{l} parameters B : Type.{l} structure tst := mk :: (a : A) (b : B) end
a0e0698b00ebd4aa76892d6296e9326011ca51d0
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/nat/log.lean
cc4a971b95a945ef11cd9e6f4366af89d954ee82
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,843
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Yaël Dillies -/ import data.nat.pow /-! # Natural number logarithms This file defines two `ℕ`-valued analogs of the logarithm of `n` with base `b`: * `log b n`: Lower logarithm, or floor **log**. Greatest `k` such that `b^k ≤ n`. * `clog b n`: Upper logarithm, or **c**eil **log**. Least `k` such that `n ≤ b^k`. These are interesting because, for `1 < b`, `nat.log b` and `nat.clog b` are respectively right and left adjoints of `nat.pow b`. See `pow_le_iff_le_log` and `le_pow_iff_clog_le`. -/ namespace nat /-! ### Floor logarithm -/ /-- `log b n`, is the logarithm of natural number `n` in base `b`. It returns the largest `k : ℕ` such that `b^k ≤ n`, so if `b^k = n`, it returns exactly `k`. -/ @[pp_nodot] def log (b : ℕ) : ℕ → ℕ | n := if h : b ≤ n ∧ 1 < b then have n / b < n, from div_lt_self ((zero_lt_one.trans h.2).trans_le h.1) h.2, log (n / b) + 1 else 0 lemma log_eq_zero {b n : ℕ} (hnb : n < b ∨ b ≤ 1) : log b n = 0 := begin rw [or_iff_not_and_not, not_lt, not_le] at hnb, rw [log, ←ite_not, if_pos hnb], end lemma log_of_lt {b n : ℕ} (hnb : n < b) : log b n = 0 := by rw [log, if_neg (λ h : b ≤ n ∧ 1 < b, h.1.not_lt hnb)] lemma log_of_left_le_one {b n : ℕ} (hb : b ≤ 1) : log b n = 0 := by rw [log, if_neg (λ h : b ≤ n ∧ 1 < b, h.2.not_le hb)] @[simp] lemma log_zero_left (n : ℕ) : log 0 n = 0 := log_of_left_le_one zero_le_one @[simp] lemma log_zero_right (b : ℕ) : log b 0 = 0 := by { rw log, cases b; refl } @[simp] lemma log_one_left (n : ℕ) : log 1 n = 0 := log_of_left_le_one le_rfl @[simp] lemma log_one_right (b : ℕ) : log b 1 = 0 := if h : b ≤ 1 then log_of_left_le_one h else log_of_lt (not_le.mp h) /-- `pow b` and `log b` (almost) form a Galois connection. -/ lemma pow_le_iff_le_log {b : ℕ} (hb : 1 < b) {x y : ℕ} (hy : 0 < y) : b^x ≤ y ↔ x ≤ log b y := begin induction y using nat.strong_induction_on with y ih generalizing x, cases x, { exact iff_of_true hy (zero_le _) }, rw log, split_ifs, { have b_pos : 0 < b := zero_le_one.trans_lt hb, rw [succ_eq_add_one, add_le_add_iff_right, ←ih (y / b) (div_lt_self hy hb) (nat.div_pos h.1 b_pos), le_div_iff_mul_le _ _ b_pos, pow_succ'] }, { refine iff_of_false (λ hby, h ⟨le_trans _ hby, hb⟩) (not_succ_le_zero _), convert pow_mono hb.le (zero_lt_succ x), exact (pow_one b).symm } end lemma log_pow {b : ℕ} (hb : 1 < b) (x : ℕ) : log b (b ^ x) = x := eq_of_forall_le_iff $ λ z, by { rw ←pow_le_iff_le_log hb (pow_pos (zero_lt_one.trans hb) _), exact (pow_right_strict_mono hb).le_iff_le } lemma log_pos {b n : ℕ} (hb : 1 < b) (hn : b ≤ n) : 0 < log b n := by { rwa [←succ_le_iff, ←pow_le_iff_le_log hb (hb.le.trans hn), pow_one] } lemma lt_pow_succ_log_self {b : ℕ} (hb : 1 < b) {x : ℕ} (hx : 0 < x) : x < b ^ (log b x).succ := begin rw [←not_le, pow_le_iff_le_log hb hx, not_le], exact lt_succ_self _, end lemma pow_log_le_self {b : ℕ} (hb : 1 < b) {x : ℕ} (hx : 0 < x) : b ^ log b x ≤ x := (pow_le_iff_le_log hb hx).2 le_rfl lemma log_le_log_of_le {b n m : ℕ} (h : n ≤ m) : log b n ≤ log b m := begin cases le_or_lt b 1 with hb hb, { rw log_of_left_le_one hb, exact zero_le _ }, { cases nat.eq_zero_or_pos n with hn hn, { rw [hn, log_zero_right], exact zero_le _ }, { rw ←pow_le_iff_le_log hb (hn.trans_le h), exact (pow_log_le_self hb hn).trans h } } end lemma log_le_log_of_left_ge {b c n : ℕ} (hc : 1 < c) (hb : c ≤ b) : log b n ≤ log c n := begin cases n, { simp }, rw ← pow_le_iff_le_log hc (zero_lt_succ n), exact calc c ^ log b n.succ ≤ b ^ log b n.succ : pow_le_pow_of_le_left (le_of_lt $ zero_lt_one.trans hc) hb _ ... ≤ n.succ : pow_log_le_self (lt_of_lt_of_le hc hb) (zero_lt_succ n) end lemma log_monotone {b : ℕ} : monotone (λ n : ℕ, log b n) := λ x y, log_le_log_of_le lemma log_antitone_left {n : ℕ} : antitone_on (λ b, log b n) (set.Ioi 1) := λ _ hc _ _ hb, log_le_log_of_left_ge (set.mem_Iio.1 hc) hb private lemma add_pred_div_lt {b n : ℕ} (hb : 1 < b) (hn : 2 ≤ n) : (n + b - 1)/b < n := begin rw [div_lt_iff_lt_mul _ _ (zero_lt_one.trans hb), ←succ_le_iff, ←pred_eq_sub_one, succ_pred_eq_of_pos (add_pos (zero_lt_one.trans hn) (zero_lt_one.trans hb))], exact add_le_mul hn hb, end /-! ### Ceil logarithm -/ /-- `clog b n`, is the upper logarithm of natural number `n` in base `b`. It returns the smallest `k : ℕ` such that `n ≤ b^k`, so if `b^k = n`, it returns exactly `k`. -/ @[pp_nodot] def clog (b : ℕ) : ℕ → ℕ | n := if h : 1 < b ∧ 1 < n then have (n + b - 1)/b < n := add_pred_div_lt h.1 h.2, clog ((n + b - 1)/b) + 1 else 0 lemma clog_of_left_le_one {b : ℕ} (hb : b ≤ 1) (n : ℕ) : clog b n = 0 := by rw [clog, if_neg (λ h : 1 < b ∧ 1 < n, h.1.not_le hb)] lemma clog_of_right_le_one {n : ℕ} (hn : n ≤ 1) (b : ℕ) : clog b n = 0 := by rw [clog, if_neg (λ h : 1 < b ∧ 1 < n, h.2.not_le hn)] @[simp] lemma clog_zero_left (n : ℕ) : clog 0 n = 0 := clog_of_left_le_one zero_le_one _ @[simp] lemma clog_zero_right (b : ℕ) : clog b 0 = 0 := clog_of_right_le_one zero_le_one _ @[simp] lemma clog_one_left (n : ℕ) : clog 1 n = 0 := clog_of_left_le_one le_rfl _ @[simp] lemma clog_one_right (b : ℕ) : clog b 1 = 0 := clog_of_right_le_one le_rfl _ lemma clog_of_two_le {b n : ℕ} (hb : 1 < b) (hn : 2 ≤ n) : clog b n = clog b ((n + b - 1)/b) + 1 := by rw [clog, if_pos (⟨hb, hn⟩ : 1 < b ∧ 1 < n)] lemma clog_pos {b n : ℕ} (hb : 1 < b) (hn : 2 ≤ n) : 0 < clog b n := by { rw clog_of_two_le hb hn, exact zero_lt_succ _ } lemma clog_eq_one {b n : ℕ} (hn : 2 ≤ n) (h : n ≤ b) : clog b n = 1 := begin rw [clog_of_two_le (hn.trans h) hn, clog_of_right_le_one], have n_pos : 0 < n := zero_lt_two.trans_le hn, rw [←lt_succ_iff, nat.div_lt_iff_lt_mul _ _ (n_pos.trans_le h), ←succ_le_iff, ←pred_eq_sub_one, succ_pred_eq_of_pos (add_pos n_pos (n_pos.trans_le h)), succ_mul, one_mul], exact add_le_add_right h _, end /--`clog b` and `pow b` form a Galois connection. -/ lemma le_pow_iff_clog_le {b : ℕ} (hb : 1 < b) {x y : ℕ} : x ≤ b^y ↔ clog b x ≤ y := begin induction x using nat.strong_induction_on with x ih generalizing y, cases y, { rw [pow_zero], refine ⟨λ h, (clog_of_right_le_one h b).le, _⟩, simp_rw ←not_lt, contrapose!, exact clog_pos hb }, have b_pos : 0 < b := zero_lt_two.trans_le hb, rw clog, split_ifs, { rw [succ_eq_add_one, add_le_add_iff_right, ←ih ((x + b - 1)/b) (add_pred_div_lt hb h.2), nat.div_le_iff_le_mul_add_pred b_pos, ←pow_succ, nat.add_sub_assoc b_pos, add_le_add_iff_right] }, { exact iff_of_true ((not_lt.1 (not_and.1 h hb)).trans $ succ_le_of_lt $ pow_pos b_pos _) (zero_le _) } end lemma clog_pow (b x : ℕ) (hb : 1 < b) : clog b (b ^ x) = x := eq_of_forall_ge_iff $ λ z, by { rw ←le_pow_iff_clog_le hb, exact (pow_right_strict_mono hb).le_iff_le } lemma pow_pred_clog_lt_self {b : ℕ} (hb : 1 < b) {x : ℕ} (hx : 1 < x) : b ^ (clog b x).pred < x := begin rw [←not_le, le_pow_iff_clog_le hb, not_le], exact pred_lt (clog_pos hb hx).ne', end lemma le_pow_clog {b : ℕ} (hb : 1 < b) (x : ℕ) : x ≤ b ^ clog b x := (le_pow_iff_clog_le hb).2 le_rfl lemma clog_le_clog_of_le (b : ℕ) {n m : ℕ} (h : n ≤ m) : clog b n ≤ clog b m := begin cases le_or_lt b 1 with hb hb, { rw clog_of_left_le_one hb, exact zero_le _ }, { obtain rfl | hn := n.eq_zero_or_pos, { rw [clog_zero_right], exact zero_le _ }, { rw ←le_pow_iff_clog_le hb, exact h.trans (le_pow_clog hb _) } } end lemma clog_le_clog_of_left_ge {b c n : ℕ} (hc : 1 < c) (hb : c ≤ b) : clog b n ≤ clog c n := begin cases n, { simp }, rw ← le_pow_iff_clog_le (lt_of_lt_of_le hc hb), exact calc n.succ ≤ c ^ clog c n.succ : le_pow_clog hc _ ... ≤ b ^ clog c n.succ : pow_le_pow_of_le_left (le_of_lt $ zero_lt_one.trans hc) hb _ end lemma clog_monotone (b : ℕ) : monotone (clog b) := λ x y, clog_le_clog_of_le _ lemma clog_antitone_left {n : ℕ} : antitone_on (λ b : ℕ, clog b n) (set.Ioi 1) := λ _ hc _ _ hb, clog_le_clog_of_left_ge (set.mem_Iio.1 hc) hb lemma log_le_clog (b n : ℕ) : log b n ≤ clog b n := begin obtain hb | hb := le_or_lt b 1, { rw log_of_left_le_one hb, exact zero_le _}, cases n, { rw log_zero_right, exact zero_le _}, exact (pow_right_strict_mono hb).le_iff_le.1 ((pow_log_le_self hb $ succ_pos _).trans $ le_pow_clog hb _), end end nat
7bd02bc6d2472c7da6d2c98fc9dbe963941e7bb5
dc253be9829b840f15d96d986e0c13520b085033
/algebra/free_group.hlean
3427bfe424e3fc6a39b4e88b35ab858ee7e56785
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
27,040
hlean
/- Copyright (c) 2015-2018 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke, Ulrik Buchholtz Constructions with groups -/ import algebra.group_theory hit.set_quotient types.list types.sum ..move_to_lib open eq algebra is_trunc set_quotient relation sigma sigma.ops prod sum list trunc function equiv prod.ops decidable is_equiv pointed universe variable u namespace group variables {G G' : Group} {g g' h h' k : G} {A B : AbGroup} /- Free Group of a pointed set -/ variables (X : Type*) [is_set X] {l l' : list (X ⊎ X)} namespace free_group inductive free_group_rel : list (X ⊎ X) → list (X ⊎ X) → Type := | rrefl : Πl, free_group_rel l l | cancel1 : Πx, free_group_rel [inl x, inr x] [] | cancel2 : Πx, free_group_rel [inr x, inl x] [] | cancelpt1 : free_group_rel [inl pt] [] | cancelpt2 : free_group_rel [inr pt] [] | resp_append : Π{l₁ l₂ l₃ l₄}, free_group_rel l₁ l₂ → free_group_rel l₃ l₄ → free_group_rel (l₁ ++ l₃) (l₂ ++ l₄) | rtrans : Π{l₁ l₂ l₃}, free_group_rel l₁ l₂ → free_group_rel l₂ l₃ → free_group_rel l₁ l₃ open free_group_rel local abbreviation R [reducible] := free_group_rel attribute free_group_rel.rrefl [refl] definition free_group_carrier [reducible] : Type := set_quotient (λx y, ∥R X x y∥) local abbreviation FG := free_group_carrier definition is_reflexive_R : is_reflexive (λx y, ∥R X x y∥) := begin constructor, intro s, apply tr, unfold R end local attribute is_reflexive_R [instance] variable {X} theorem rel_respect_flip (r : R X l l') : R X (map sum.flip l) (map sum.flip l') := begin induction r with l x x l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂, { reflexivity}, { repeat esimp [map], exact cancel2 x}, { repeat esimp [map], exact cancel1 x}, { exact cancelpt2 X }, { exact cancelpt1 X }, { rewrite [+map_append], exact resp_append IH₁ IH₂}, { exact rtrans IH₁ IH₂} end theorem rel_respect_reverse (r : R X l l') : R X (reverse l) (reverse l') := begin induction r with l x x l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂, { reflexivity}, { repeat esimp [map], exact cancel2 x}, { repeat esimp [map], exact cancel1 x}, { exact cancelpt1 X }, { exact cancelpt2 X }, { rewrite [+reverse_append], exact resp_append IH₂ IH₁}, { exact rtrans IH₁ IH₂} end definition free_group_one [constructor] : FG X := class_of [] definition free_group_inv [unfold 3] : FG X → FG X := quotient_unary_map (reverse ∘ map sum.flip) (λl l', trunc_functor -1 (rel_respect_reverse ∘ rel_respect_flip)) definition free_group_mul [unfold 3 4] : FG X → FG X → FG X := quotient_binary_map append (λl l', trunc.elim (λr m m', trunc.elim (λs, tr (resp_append r s)))) section local notation 1 := free_group_one local postfix ⁻¹ := free_group_inv local infix * := free_group_mul theorem free_group_mul_assoc (g₁ g₂ g₃ : FG X) : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) := begin refine set_quotient.rec_prop _ g₁, refine set_quotient.rec_prop _ g₂, refine set_quotient.rec_prop _ g₃, clear g₁ g₂ g₃, intro g₁ g₂ g₃, exact ap class_of !append.assoc end theorem free_group_one_mul (g : FG X) : 1 * g = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !append_nil_left end theorem free_group_mul_one (g : FG X) : g * 1 = g := begin refine set_quotient.rec_prop _ g, clear g, intro g, exact ap class_of !append_nil_right end theorem free_group_mul_left_inv (g : FG X) : g⁻¹ * g = 1 := begin refine set_quotient.rec_prop _ g, clear g, intro g, apply eq_of_rel, apply tr, induction g with s l IH, { reflexivity}, { rewrite [▸*, map_cons, reverse_cons, concat_append], refine rtrans _ IH, apply resp_append, reflexivity, change R X ([flip s, s] ++ l) ([] ++ l), apply resp_append, induction s, apply cancel2, apply cancel1, reflexivity} end end end free_group open free_group -- export [reduce_hints] free_group variables (X) definition group_free_group [constructor] : group (free_group_carrier X) := group.mk _ free_group_mul free_group_mul_assoc free_group_one free_group_one_mul free_group_mul_one free_group_inv free_group_mul_left_inv definition free_group [constructor] : Group := Group.mk _ (group_free_group X) /- The universal property of the free group -/ variables {X G} definition free_group_inclusion [constructor] : X →* free_group X := ppi.mk (λ x, class_of [inl x]) (eq_of_rel (tr (free_group_rel.cancelpt1 X))) definition fgh_helper [unfold 6] (f : X → G) (g : G) (x : X ⊎ X) : G := g * sum.rec (λz, f z) (λz, (f z)⁻¹) x theorem fgh_helper_respect_rel (f : X →* G) (r : free_group_rel X l l') : Π(g : G), foldl (fgh_helper f) g l = foldl (fgh_helper f) g l' := begin induction r with l x x l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂: intro g, { reflexivity}, { unfold [foldl], apply mul_inv_cancel_right}, { unfold [foldl], apply inv_mul_cancel_right}, { unfold [foldl], rewrite (respect_pt f), apply mul_one }, { unfold [foldl], rewrite [respect_pt f, one_inv], apply mul_one }, { rewrite [+foldl_append, IH₁, IH₂]}, { exact !IH₁ ⬝ !IH₂} end theorem fgh_helper_mul (f : X → G) (l) : Π(g : G), foldl (fgh_helper f) g l = g * foldl (fgh_helper f) 1 l := begin induction l with s l IH: intro g, { unfold [foldl], exact !mul_one⁻¹}, { rewrite [+foldl_cons, IH], refine _ ⬝ (ap (λx, g * x) !IH⁻¹), rewrite [-mul.assoc, ↑fgh_helper, one_mul]} end definition free_group_hom [constructor] (f : X →* G) : free_group X →g G := begin fapply homomorphism.mk, { intro g, refine set_quotient.elim _ _ g, { intro l, exact foldl (fgh_helper f) 1 l}, { intro l l' r, esimp at *, refine trunc.rec _ r, clear r, intro r, exact fgh_helper_respect_rel f r 1}}, { refine set_quotient.rec_prop _, intro l, refine set_quotient.rec_prop _, intro l', esimp, refine !foldl_append ⬝ _, esimp, apply fgh_helper_mul} end definition free_group_hom_eq [constructor] {φ ψ : free_group X →g G} (H : Πx, φ (free_group_inclusion x) = ψ (free_group_inclusion x)) : φ ~ ψ := begin refine set_quotient.rec_prop _, intro l, induction l with s l IH, { exact respect_one φ ⬝ (respect_one ψ)⁻¹ }, { refine respect_mul φ (class_of [s]) (class_of l) ⬝ _ ⬝ (respect_mul ψ (class_of [s]) (class_of l))⁻¹, refine ap011 mul _ IH, induction s with x x, exact H x, refine respect_inv φ (class_of [inl x]) ⬝ ap inv (H x) ⬝ (respect_inv ψ (class_of [inl x]))⁻¹ } end definition fn_of_free_group_hom [unfold_full] (φ : free_group X →g G) : X →* G := ppi.mk (φ ∘ free_group_inclusion) begin refine (_ ⬝ respect_one φ), apply ap φ, apply eq_of_rel, apply tr, exact (free_group_rel.cancelpt1 X) end variables (X G) definition free_group_hom_equiv_fn : (free_group X →g G) ≃ (X →* G) := begin fapply equiv.MK, { exact fn_of_free_group_hom}, { exact free_group_hom}, { intro f, apply eq_of_phomotopy, fapply phomotopy.mk, { intro x, esimp, unfold [foldl], apply one_mul }, { apply is_prop.elim } }, { intro φ, apply homomorphism_eq, apply free_group_hom_eq, intro x, apply one_mul } end end group /- alternative definition of free group on a set with decidable equality -/ namespace list variables {X : Type.{u}} {v w : X ⊎ X} {l : list (X ⊎ X)} inductive is_reduced {X : Type} : list (X ⊎ X) → Type := | nil : is_reduced [] | singleton : Πv, is_reduced [v] | cons : Π⦃v w l⦄, sum.flip v ≠ w → is_reduced (w::l) → is_reduced (v::w::l) definition is_reduced_code (H : is_reduced l) : Type.{u} := begin cases l with v l, { exact is_reduced.nil = H }, cases l with w l, { exact is_reduced.singleton v = H }, exact Σ(pH : sum.flip v ≠ w × is_reduced (w::l)), is_reduced.cons pH.1 pH.2 = H end definition is_reduced_encode (H : is_reduced l) : is_reduced_code H := begin induction H with v v w l p Hl IH, { exact idp }, { exact idp }, { exact ⟨(p, Hl), idp⟩ } end definition is_prop_is_reduced (l : list (X ⊎ X)) : is_prop (is_reduced l) := begin apply is_prop.mk, intro H₁ H₂, induction H₁ with v v w l p Hl IH, { exact is_reduced_encode H₂ }, { exact is_reduced_encode H₂ }, { cases is_reduced_encode H₂ with pH' q, cases pH' with p' Hl', esimp at q, subst q, exact ap011 (λx y, is_reduced.cons x y) !is_prop.elim (IH Hl') } end definition rlist (X : Type) : Type := Σ(l : list (X ⊎ X)), is_reduced l local attribute [instance] is_prop_is_reduced definition rlist_eq {l l' : rlist X} (p : l.1 = l'.1) : l = l' := subtype_eq p definition is_trunc_rlist {n : ℕ₋₂} {X : Type} (H : is_trunc (n.+2) X) : is_trunc (n.+2) (rlist X) := begin apply is_trunc_sigma, { apply is_trunc_list, apply is_trunc_sum }, intro l, exact is_trunc_succ_of_is_prop _ _ _ end definition is_reduced_invert (v : X ⊎ X) : is_reduced (v::l) → is_reduced l := begin assert H : Π⦃l'⦄, is_reduced l' → l' = v::l → is_reduced l, { intro l' Hl', revert l, induction Hl' with v' v' w' l' p' Hl' IH: intro l p, { cases p }, { cases cons_eq_cons p with q r, subst r, apply is_reduced.nil }, { cases cons_eq_cons p with q r, subst r, exact Hl' }}, intro Hl, exact H Hl idp end definition is_reduced_invert_rev (v : X ⊎ X) : is_reduced (l++[v]) → is_reduced l := begin assert H : Π⦃l'⦄, is_reduced l' → l' = l++[v] → is_reduced l, { intro l' Hl', revert l, induction Hl' with v' v' w' l' p' Hl' IH: intro l p, { induction l: cases p }, { induction l with v'' l IH, apply is_reduced.nil, esimp [append] at p, cases cons_eq_cons p with q r, induction l: cases r }, { induction l with v'' l IH', cases p, induction l with v''' l IH'', apply is_reduced.singleton, do 2 esimp [append] at p, cases cons_eq_cons p with q r, cases cons_eq_cons r with r₁ r₂, subst r₁, subst q, subst r₂, apply is_reduced.cons p' (IH _ idp) }}, intro Hl, exact H Hl idp end definition rnil [constructor] : rlist X := ⟨[], !is_reduced.nil⟩ definition rsingleton [constructor] (x : X ⊎ X) : rlist X := ⟨[x], !is_reduced.singleton⟩ definition is_reduced_doubleton [constructor] {x y : X ⊎ X} (p : flip x ≠ y) : is_reduced [x, y] := is_reduced.cons p !is_reduced.singleton definition rdoubleton [constructor] {x y : X ⊎ X} (p : flip x ≠ y) : rlist X := ⟨[x, y], is_reduced_doubleton p⟩ definition is_reduced_concat (Hn : sum.flip v ≠ w) (Hl : is_reduced (concat v l)) : is_reduced (concat w (concat v l)) := begin assert H : Π⦃l'⦄, is_reduced l' → l' = concat v l → is_reduced (concat w l'), { clear Hl, intro l' Hl', revert l, induction Hl' with v' v' w' l' p' Hl' IH: intro l p, { exfalso, exact concat_neq_nil _ _ p⁻¹ }, { cases concat_eq_singleton p⁻¹ with q r, subst q, exact is_reduced_doubleton Hn }, { do 2 esimp [concat], apply is_reduced.cons p', cases l with x l, { cases p }, { apply IH l, esimp [concat] at p, revert p, generalize concat v l, intro l'' p, cases cons_eq_cons p with q r, exact r }}}, exact H Hl idp end definition is_reduced_reverse (H : is_reduced l) : is_reduced (reverse l) := begin induction H with v v w l p Hl IH, { apply is_reduced.nil }, { apply is_reduced.singleton }, { refine is_reduced_concat _ IH, intro q, apply p, subst q, apply flip_flip } end definition rreverse [constructor] (l : rlist X) : rlist X := ⟨reverse l.1, is_reduced_reverse l.2⟩ definition rreverse_rreverse (l : rlist X) : rreverse (rreverse l) = l := subtype_eq (reverse_reverse l.1) definition is_reduced_flip (H : is_reduced l) : is_reduced (map flip l) := begin induction H with v v w l p Hl IH, { apply is_reduced.nil }, { apply is_reduced.singleton }, { refine is_reduced.cons _ IH, intro q, apply p, exact !flip_flip⁻¹ ⬝ ap flip q ⬝ !flip_flip } end definition rflip [constructor] (l : rlist X) : rlist X := ⟨map flip l.1, is_reduced_flip l.2⟩ definition rcons' [decidable_eq X] (v : X ⊎ X) (l : list (X ⊎ X)) : list (X ⊎ X) := begin cases l with w l, { exact [v] }, { exact if q : sum.flip v = w then l else v::w::l } end definition is_reduced_rcons [decidable_eq X] (v : X ⊎ X) (Hl : is_reduced l) : is_reduced (rcons' v l) := begin cases l with w l, apply is_reduced.singleton, apply dite (sum.flip v = w): intro q, { have is_set (X ⊎ X), from !is_trunc_sum, rewrite [↑rcons', dite_true q _], exact is_reduced_invert w Hl }, { rewrite [↑rcons', dite_false q], exact is_reduced.cons q Hl, } end definition rcons [constructor] [decidable_eq X] (v : X ⊎ X) (l : rlist X) : rlist X := ⟨rcons' v l.1, is_reduced_rcons v l.2⟩ definition rcons_eq [decidable_eq X] : is_reduced (v::l) → rcons' v l = v :: l := begin assert H : Π⦃l'⦄, is_reduced l' → l' = v::l → rcons' v l = l', { intro l' Hl', revert l, induction Hl' with v' v' w' l' p' Hl' IH: intro l p, { cases p }, { cases cons_eq_cons p with q r, subst r, cases p, reflexivity }, { cases cons_eq_cons p with q r, subst q, subst r, rewrite [↑rcons', dite_false p'], }}, intro Hl, exact H Hl idp end definition rcons_eq2 [decidable_eq X] (H : is_reduced (v::l)) : ⟨v :: l, H⟩ = rcons v ⟨l, is_reduced_invert _ H⟩ := subtype_eq (rcons_eq H)⁻¹ definition rcons_rcons_eq [decidable_eq X] (p : flip v = w) (l : rlist X) : rcons v (rcons w l) = l := begin have is_set (X ⊎ X), from !is_trunc_sum, induction l with l Hl, apply rlist_eq, esimp, induction l with u l IH, { exact dite_true p _ }, { apply dite (sum.flip w = u): intro q, { rewrite [↑rcons' at {1}, dite_true q _], subst p, induction (!flip_flip⁻¹ ⬝ q), exact rcons_eq Hl }, { rewrite [↑rcons', dite_false q, dite_true p _] }} end definition rlist.rec [decidable_eq X] {P : rlist X → Type} (P1 : P rnil) (Pcons : Πv l, P l → P (rcons v l)) (l : rlist X) : P l := begin induction l with l Hl, induction Hl with v v w l p Hl IH, { exact P1 }, { exact Pcons v rnil P1 }, { exact transport P (subtype_eq (rcons_eq (is_reduced.cons p Hl))) (Pcons v ⟨w :: l, Hl⟩ IH) } end definition reduce_list' [decidable_eq X] (l : list (X ⊎ X)) : list (X ⊎ X) := begin induction l with v l IH, { exact [] }, { exact rcons' v IH } end definition is_reduced_reduce_list [decidable_eq X] (l : list (X ⊎ X)) : is_reduced (reduce_list' l) := begin induction l with v l IH, apply is_reduced.nil, apply is_reduced_rcons, exact IH end definition reduce_list [constructor] [decidable_eq X] (l : list (X ⊎ X)) : rlist X := ⟨reduce_list' l, is_reduced_reduce_list l⟩ definition rappend' [decidable_eq X] (l : list (X ⊎ X)) (l' : rlist X) : rlist X := foldr rcons l' l definition rappend_rcons' [decidable_eq X] (x : X ⊎ X) (l₁ : list (X ⊎ X)) (l₂ : rlist X) : rappend' (rcons' x l₁) l₂ = rcons x (rappend' l₁ l₂) := begin induction l₁ with x' l₁ IH, { reflexivity }, { apply dite (sum.flip x = x'): intro p, { have is_set (X ⊎ X), from !is_trunc_sum, rewrite [↑rcons', dite_true p _], exact (rcons_rcons_eq p _)⁻¹ }, { rewrite [↑rcons', dite_false p] }} end definition rappend_cons' [decidable_eq X] (x : X ⊎ X) (l₁ : list (X ⊎ X)) (l₂ : rlist X) : rappend' (x::l₁) l₂ = rcons x (rappend' l₁ l₂) := idp definition rappend [decidable_eq X] (l l' : rlist X) : rlist X := rappend' l.1 l' definition rappend_rcons [decidable_eq X] (x : X ⊎ X) (l₁ l₂ : rlist X) : rappend (rcons x l₁) l₂ = rcons x (rappend l₁ l₂) := rappend_rcons' x l₁.1 l₂ definition rappend_assoc [decidable_eq X] (l₁ l₂ l₃ : rlist X) : rappend (rappend l₁ l₂) l₃ = rappend l₁ (rappend l₂ l₃) := begin induction l₁ with l₁ h, unfold rappend, clear h, induction l₁ with x l₁ IH, { reflexivity }, { rewrite [rappend_cons', ▸*, rappend_rcons', IH] } end definition rappend_rnil [decidable_eq X] (l : rlist X) : rappend l rnil = l := begin induction l with l H, apply rlist_eq, esimp, induction H with v v w l p Hl IH, { reflexivity }, { reflexivity }, { rewrite [↑rappend at *, rappend_cons', ↑rcons, IH, ↑rcons', dite_false p] } end definition rnil_rappend [decidable_eq X] (l : rlist X) : rappend rnil l = l := by reflexivity definition rsingleton_rappend [decidable_eq X] (x : X ⊎ X) (l : rlist X) : rappend (rsingleton x) l = rcons x l := by reflexivity definition rappend_left_inv [decidable_eq X] (l : rlist X) : rappend (rflip (rreverse l)) l = rnil := begin induction l with l H, apply rlist_eq, induction l with x l IH, { reflexivity }, { have is_set (X ⊎ X), from !is_trunc_sum, rewrite [↑rappend, ↑rappend', reverse_cons, map_concat, foldr_concat], refine ap (λx, (rappend' _ x).1) (rlist_eq (dite_true !flip_flip _)) ⬝ IH (is_reduced_invert _ H) } end definition rappend'_eq [decidable_eq X] (v : X ⊎ X) (l : list (X ⊎ X)) (H : is_reduced (l ++ [v])) : ⟨l ++ [v], H⟩ = rappend' l (rsingleton v) := begin assert Hlem : Π⦃l'⦄ (Hl' : is_reduced l'), l' = l ++ [v] → rappend' l (rsingleton v) = ⟨l', Hl'⟩, { intro l' Hl', clear H, revert l, induction Hl' with v' v' w' l' p' Hl' IH: intro l p, { induction l: cases p }, { induction l with v'' l IH, { cases cons_eq_cons p with q r, subst q }, { esimp [append] at p, cases cons_eq_cons p with q r, induction l: cases r }}, { induction l with v'' l IH', cases p, induction l with v''' l IH'', { do 2 esimp [append] at p, cases cons_eq_cons p with q r, subst q, cases cons_eq_cons r with q r', subst q, subst r', apply subtype_eq, exact dite_false p' }, { do 2 esimp [append] at p, cases cons_eq_cons p with q r, cases cons_eq_cons r with r₁ r₂, subst r₁, subst q, subst r₂, rewrite [rappend_cons', IH (w' :: l) idp], apply subtype_eq, apply rcons_eq, apply is_reduced.cons p' Hl' }}}, exact (Hlem H idp)⁻¹ end definition rappend_eq [decidable_eq X] (v : X ⊎ X) (l : list (X ⊎ X)) (H : is_reduced (l ++ [v])) : ⟨l ++ [v], H⟩ = rappend ⟨l, is_reduced_invert_rev _ H⟩ (rsingleton v) := rappend'_eq v l H definition rreverse_cons [decidable_eq X] (v : X ⊎ X) (l : list (X ⊎ X)) (H : is_reduced (v :: l)) : rreverse ⟨v::l, H⟩ = rappend ⟨reverse l, is_reduced_reverse (is_reduced_invert _ H)⟩ (rsingleton v) := begin refine dpair_eq_dpair (reverse_cons _ _) !pathover_tr ⬝ _, refine dpair_eq_dpair (concat_eq_append _ _) !pathover_tr ⬝ _, refine !rappend_eq ⬝ _, exact ap (λx, rappend ⟨_, x⟩ _) !is_prop.elim end definition rreverse_rcons [decidable_eq X] (v : X ⊎ X) (l : rlist X) : rreverse (rcons v l) = rappend (rreverse l) (rsingleton v) := begin induction l with l Hl, induction l with v' l IH, reflexivity, { symmetry, refine ap (λx, rappend x _) !rreverse_cons ⬝ _, apply dite (sum.flip v = v'): intro p, { have is_set (X ⊎ X), from !is_trunc_sum, rewrite [↑rcons, ↑rcons', dpair_eq_dpair (dite_true p _) !pathover_tr ], refine !rappend_assoc ⬝ _, refine ap (rappend _) !rsingleton_rappend ⬝ _, refine ap (rappend _) (subtype_eq _) ⬝ !rappend_rnil, exact dite_true (ap flip p⁻¹ ⬝ flip_flip v) _ }, { rewrite [↑rcons, ↑rcons', dpair_eq_dpair (dite_false p) !pathover_tr], note H1 := is_reduced_reverse (transport is_reduced (dite_false p) (is_reduced_rcons v Hl)), rewrite [+reverse_cons at H1, +concat_eq_append at H1], note H2 := is_reduced_invert_rev _ H1, refine ap (λx, rappend x _) (rappend_eq _ _ H2)⁻¹ ⬝ _, refine (rappend_eq _ _ H1)⁻¹ ⬝ _, apply subtype_eq, rewrite [-+concat_eq_append] }} end definition rlist.rec_rev [decidable_eq X] {P : rlist X → Type} (P1 : P rnil) (Pappend : Πl v, P l → P (rappend l (rsingleton v))) : Π(l : rlist X), P l := begin assert H : Π(l : rlist X), P (rreverse l), { refine rlist.rec _ _, exact P1, intro v l p, rewrite [rreverse_rcons], apply Pappend, exact p }, intro l, exact transport P (rreverse_rreverse l) (H (rreverse l)) end end list open list namespace group open sigma.ops variables (X : Type) [decidable_eq X] {G : InfGroup} definition group_dfree_group [constructor] : group (rlist X) := group.mk (is_trunc_rlist _) rappend rappend_assoc rnil rnil_rappend rappend_rnil (rflip ∘ rreverse) rappend_left_inv definition dfree_group [constructor] : Group := Group.mk _ (group_dfree_group X) variable {X} definition dfree_group_inclusion [constructor] [reducible] (x : X) : dfree_group X := rsingleton (inl x) definition rsingleton_inr [constructor] (x : X) : rsingleton (inr x) = (dfree_group_inclusion x)⁻¹ :> dfree_group X := by reflexivity local attribute [instance] is_prop_is_reduced definition dfree_group.rec {P : dfree_group X → Type} (P1 : P 1) (Pcons : Πv g, P g → P (rsingleton v * g)) : Π(g : dfree_group X), P g := rlist.rec P1 Pcons definition dfree_group.rec_rev {P : dfree_group X → Type} (P1 : P 1) (Pcons : Πg v, P g → P (g * rsingleton v)) : Π(g : dfree_group X), P g := rlist.rec_rev P1 Pcons -- definition dfree_group.rec2 [constructor] {P : dfree_group X → Type} -- (P1 : P 1) (Pcons : Πg x, P g → P (dfree_group_inclusion x * g)) -- (Pinv : Πg, P g → P g⁻¹) : Π(g : dfree_group X), P g := -- begin -- refine dfree_group.rec _ _, exact P1, -- intro g v p, induction v with x x, exact Pcons g x p, -- end definition dfgh_helper [unfold 6] (f : X → G) (g : G) (x : X ⊎ X) : G := g * sum.rec (λx, f x) (λx, (f x)⁻¹) x theorem dfgh_helper_mul (f : X → G) (l : list (X ⊎ X)) : Π(g : G), foldl (dfgh_helper f) g l = g * foldl (dfgh_helper f) 1 l := begin induction l with s l IH: intro g, { unfold [foldl], exact !mul_one⁻¹}, { rewrite [+foldl_cons, IH], refine _ ⬝ (ap (λx, g * x) !IH⁻¹), rewrite [-mul.assoc, ↑dfgh_helper, one_mul] } end definition dfgh_helper_rcons (f : X → G) (g : G) (x : X ⊎ X) {l : list (X ⊎ X)} : foldl (dfgh_helper f) g (rcons' x l) = foldl (dfgh_helper f) g (x :: l) := begin cases l with x' l, reflexivity, apply dite (sum.flip x = x'): intro q, { have is_set (X ⊎ X), from !is_trunc_sum, rewrite [↑rcons', dite_true q _, foldl_cons, foldl_cons, -q], induction x with x, rewrite [↑dfgh_helper,mul_inv_cancel_right], rewrite [↑dfgh_helper,inv_mul_cancel_right] }, { rewrite [↑rcons', dite_false q] } end definition dfgh_helper_rappend (f : X → G) (g : G) (l l' : rlist X) : foldl (dfgh_helper f) g (rappend l l').1 = foldl (dfgh_helper f) g (l.1 ++ l'.1) := begin revert g, induction l with l lH, unfold rappend, clear lH, induction l with v l IH: intro g, reflexivity, rewrite [rappend_cons', ↑rcons, dfgh_helper_rcons, foldl_cons, IH] end local attribute [coercion] InfGroup_of_Group definition dfree_group_inf_hom [constructor] (G : InfGroup) (f : X → G) : dfree_group X →∞g G := inf_homomorphism.mk (λx, foldl (dfgh_helper f) 1 x.1) (λl₁ l₂, !dfgh_helper_rappend ⬝ !foldl_append ⬝ !dfgh_helper_mul) definition dfree_group_inf_hom_eq [constructor] {G : InfGroup} {φ ψ : dfree_group X →∞g G} (H : Πx, φ (dfree_group_inclusion x) = ψ (dfree_group_inclusion x)) : φ ~ ψ := begin assert H2 : Πv, φ (rsingleton v) = ψ (rsingleton v), { intro v, induction v with x x, exact H x, exact to_respect_inv_inf φ _ ⬝ ap inv (H x) ⬝ (to_respect_inv_inf ψ _)⁻¹ }, refine dfree_group.rec _ _, { exact !to_respect_one_inf ⬝ !to_respect_one_inf⁻¹ }, { intro v g p, exact !to_respect_mul_inf ⬝ ap011 mul (H2 v) p ⬝ !to_respect_mul_inf⁻¹ } end theorem dfree_group_inf_hom_inclusion [constructor] (G : InfGroup) (f : X → G) (x : X) : dfree_group_inf_hom G f (dfree_group_inclusion x) = f x := by rewrite [▸*, foldl_cons, foldl_nil, ↑dfgh_helper, one_mul] definition dfree_group_hom [constructor] {G : Group} (f : X → G) : dfree_group X →g G := homomorphism_of_inf_homomorphism (dfree_group_inf_hom G f) -- todo: use the inf-version definition dfree_group_hom_eq [constructor] {G : Group} {φ ψ : dfree_group X →g G} (H : Πx, φ (dfree_group_inclusion x) = ψ (dfree_group_inclusion x)) : φ ~ ψ := begin assert H2 : Πv, φ (rsingleton v) = ψ (rsingleton v), { intro v, induction v with x x, exact H x, exact to_respect_inv φ _ ⬝ ap inv (H x) ⬝ (to_respect_inv ψ _)⁻¹ }, refine dfree_group.rec _ _, { exact !to_respect_one ⬝ !to_respect_one⁻¹ }, { intro v g p, exact !to_respect_mul ⬝ ap011 mul (H2 v) p ⬝ !to_respect_mul⁻¹ } end definition is_mul_hom_dfree_group_fun {G : InfGroup} {f : dfree_group X → G} (H1 : f 1 = 1) (H2 : Πv g, f (rsingleton v * g) = f (rsingleton v) * f g) : is_mul_hom f := begin refine dfree_group.rec _ _, { intro g, exact ap f (one_mul g) ⬝ (ap (λx, x * _) H1 ⬝ one_mul (f g))⁻¹ }, { intro g v p h, exact ap f !mul.assoc ⬝ !H2 ⬝ ap (mul _) !p ⬝ (ap (λx, x * _) !H2 ⬝ !mul.assoc)⁻¹ } end definition dfree_group_hom_of_fun [constructor] {G : InfGroup} (f : dfree_group X → G) (H1 : f 1 = 1) (H2 : Πv g, f (rsingleton v * g) = f (rsingleton v) * f g) : dfree_group X →∞g G := inf_homomorphism.mk f (is_mul_hom_dfree_group_fun H1 H2) variable (X) open option definition free_group_of_dfree_group [constructor] : dfree_group X →g free_group X₊ := dfree_group_hom (free_group_inclusion ∘ some) definition dfree_group_of_free_group [constructor] : free_group X₊ →g dfree_group X := free_group_hom (ppi.mk (option.rec 1 dfree_group_inclusion) idp) definition dfree_group_isomorphism : dfree_group X ≃g free_group X₊ := begin apply isomorphism.MK (free_group_of_dfree_group X) (dfree_group_of_free_group X), { apply free_group_hom_eq, intro x, induction x with x, { symmetry, apply eq_of_rel, apply tr, exact free_group.free_group_rel.cancelpt1 X₊ }, { reflexivity } }, { apply dfree_group_hom_eq, intro x, reflexivity } end end group
eb9f3c49272456b967e016bd35dd687f102d5dc7
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/finset/interval.lean
c1a5738da2ec126d0ab9352a9b2ba3160c89bb2f
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,681
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite /-! # Intervals of finsets as finsets This file provides the `locally_finite_order` instance for `finset α` and calculates the cardinality of finite intervals of finsets. If `s t : finset α`, then `finset.Icc s t` is the finset of finsets which include `s` and are included in `t`. For example, `finset.Icc {0, 1} {0, 1, 2, 3} = {{0, 1}, {0, 1, 2}, {0, 1, 3}, {0, 1, 2, 3}}` and `finset.Icc {0, 1, 2} {0, 1, 3} = {}`. -/ variables {α : Type*} namespace finset variables [decidable_eq α] (s t : finset α) instance : locally_finite_order (finset α) := { finset_Icc := λ s t, t.powerset.filter ((⊆) s), finset_Ico := λ s t, t.ssubsets.filter ((⊆) s), finset_Ioc := λ s t, t.powerset.filter ((⊂) s), finset_Ioo := λ s t, t.ssubsets.filter ((⊂) s), finset_mem_Icc := λ s t u, by {rw [mem_filter, mem_powerset], exact and_comm _ _ }, finset_mem_Ico := λ s t u, by {rw [mem_filter, mem_ssubsets], exact and_comm _ _ }, finset_mem_Ioc := λ s t u, by {rw [mem_filter, mem_powerset], exact and_comm _ _ }, finset_mem_Ioo := λ s t u, by {rw [mem_filter, mem_ssubsets], exact and_comm _ _ } } lemma Icc_eq_filter_powerset : Icc s t = t.powerset.filter ((⊆) s) := rfl lemma Ico_eq_filter_ssubsets : Ico s t = t.ssubsets.filter ((⊆) s) := rfl lemma Ioc_eq_filter_powerset : Ioc s t = t.powerset.filter ((⊂) s) := rfl lemma Ioo_eq_filter_ssubsets : Ioo s t = t.ssubsets.filter ((⊂) s) := rfl lemma Iic_eq_powerset : Iic s = s.powerset := filter_true_of_mem $ λ t _, empty_subset t lemma Iio_eq_ssubsets : Iio s = s.ssubsets := filter_true_of_mem $ λ t _, empty_subset t variables {s t} lemma Icc_eq_image_powerset (h : s ⊆ t) : Icc s t = (t \ s).powerset.image ((∪) s) := begin ext u, simp_rw [mem_Icc, mem_image, exists_prop, mem_powerset], split, { rintro ⟨hs, ht⟩, exact ⟨u \ s, sdiff_le_sdiff_right ht, sup_sdiff_cancel_right hs⟩ }, { rintro ⟨v, hv, rfl⟩, exact ⟨le_sup_left, union_subset h $ hv.trans $ sdiff_subset _ _⟩ } end lemma Ico_eq_image_ssubsets (h : s ⊆ t) : Ico s t = (t \ s).ssubsets.image ((∪) s) := begin ext u, simp_rw [mem_Ico, mem_image, exists_prop, mem_ssubsets], split, { rintro ⟨hs, ht⟩, exact ⟨u \ s, sdiff_lt_sdiff_right ht hs, sup_sdiff_cancel_right hs⟩ }, { rintro ⟨v, hv, rfl⟩, exact ⟨le_sup_left, sup_lt_of_lt_sdiff_left hv h⟩ } end /-- Cardinality of a non-empty `Icc` of finsets. -/ lemma card_Icc_finset (h : s ⊆ t) : (Icc s t).card = 2 ^ (t.card - s.card) := begin rw [←card_sdiff h, ←card_powerset, Icc_eq_image_powerset h, finset.card_image_eq_iff_inj_on], rintro u hu v hv (huv : s ⊔ u = s ⊔ v), rw [mem_coe, mem_powerset] at hu hv, rw [←(disjoint_sdiff.mono_right hu : disjoint s u).sup_sdiff_cancel_left, ←(disjoint_sdiff.mono_right hv : disjoint s v).sup_sdiff_cancel_left, huv], end /-- Cardinality of an `Ico` of finsets. -/ lemma card_Ico_finset (h : s ⊆ t) : (Ico s t).card = 2 ^ (t.card - s.card) - 1 := by rw [card_Ico_eq_card_Icc_sub_one (le_iff_subset.2 h), card_Icc_finset h] /-- Cardinality of an `Ioc` of finsets. -/ lemma card_Ioc_finset (h : s ⊆ t) : (Ioc s t).card = 2 ^ (t.card - s.card) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one (le_iff_subset.2 h), card_Icc_finset h] /-- Cardinality of an `Ioo` of finsets. -/ lemma card_Ioo_finset (h : s ⊆ t) : (Ioo s t).card = 2 ^ (t.card - s.card) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two (le_iff_subset.2 h), card_Icc_finset h] end finset
190e6d843c72b5f378978077e15571efc81a11c0
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/category_theory/natural_isomorphism.lean
15cc7731ea109b318496b2c29b0f42a3bad6763f
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
4,808
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.isomorphism import category_theory.functor_category open category_theory namespace category_theory.nat_iso universes u₁ u₂ v₁ v₂ variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒞 𝒟 def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← functor.category.comp_app, iso.hom_inv_id], refl, end, inv_hom_id' := begin rw [← functor.category.comp_app, iso.inv_hom_id], refl, end } @[simp] lemma comp_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : app (α ≪≫ β) X = app α X ≪≫ app β X := rfl @[simp] lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (app α X).hom = α.hom.app X := rfl @[simp] lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (app α X).inv = α.inv.app X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end, inv_hom_id' := begin rw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end, inv_hom_id' := begin rw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end } variables {X Y : C} @[simp] lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end @[simp] lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end def of_components (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ ((app Y).hom) = ((app X).hom) ≫ (G.map f)) : F ≅ G := { hom := { app := λ X, ((app X).hom), }, inv := { app := λ X, ((app X).inv), naturality' := λ X Y f, begin let p := congr_arg (λ f, (app X).inv ≫ (f ≫ (app Y).inv)) (eq.symm (naturality f)), dsimp at *, simp at *, erw [←p, ←category.assoc, is_iso.hom_inv_id, category.id_comp], end } }. @[simp] def of_components.app (app' : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : app (of_components app' naturality) X = app' X := by tidy @[simp] def of_components.hom_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] def of_components.inv_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl end category_theory.nat_iso namespace category_theory.functor universes u₁ u₂ v₁ v₂ section variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒞 𝒟 @[simp] def id_comp (F : C ⥤ D) : functor.id C ⋙ F ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simp] def comp_id (F : C ⥤ D) : F ⋙ functor.id D ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } universes u₃ v₃ u₄ v₄ variables {A : Type u₃} [𝒜 : category.{u₃ v₃} A] {B : Type u₄} [ℬ : category.{u₄ v₄} B] include 𝒜 ℬ variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) @[simp] def assoc : (F ⋙ G) ⋙ H ≅ F ⋙ (G ⋙ H ):= { hom := { app := λ X, 𝟙 (H.obj (G.obj (F.obj X))) }, inv := { app := λ X, 𝟙 (H.obj (G.obj (F.obj X))) } } -- When it's time to define monoidal categories and 2-categories, -- we'll need to add lemmas relating these natural isomorphisms, -- in particular the pentagon for the associator. end section variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] include 𝒞 def ulift_down_up : ulift_down.{u₁ v₁ u₂} C ⋙ ulift_up C ≅ functor.id (ulift.{u₂} C) := { hom := { app := λ X, @category.id (ulift.{u₂} C) _ X }, inv := { app := λ X, @category.id (ulift.{u₂} C) _ X } } def ulift_up_down : ulift_up.{u₁ v₁ u₂} C ⋙ ulift_down C ≅ functor.id C := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } end end category_theory.functor
2cca407a38b127592b4c0070b781ab7eaa38a930
d98f8063520761a65549cff3a6e0b1f33c180b92
/super/heapex.lean
0f362d76940b097b9806e1f556d0b5e58896fe44
[]
no_license
gebner/POPL17_tutorial
76cb1f3164b2f62812f718538d83e3c39bcda927
04aaaea171736317bf20bc849b96069188d73a55
refs/heads/master
1,610,408,282,574
1,504,117,783,000
1,504,117,783,000
78,612,687
0
0
null
1,484,118,765,000
1,484,118,765,000
null
UTF-8
Lean
false
false
718
lean
import tools.super constant heap : Type constant ptr : Type constant val : Type constant pt : ptr → val → heap constant hunion : heap → heap → heap constant is_def : heap → Prop infix `∙`:60 := hunion infix `↣`:70 := pt axiom hcomm : ∀ x y, x ∙ y = y ∙ x axiom hassoc : ∀ x y z, (x ∙ y) ∙ z = x ∙ (y ∙ z) axiom hnoalias : ∀ h y w₁ w₂, ¬is_def (h ∙ y ↣ w₁ ∙ y ↣ w₂) set_option trace.super true lemma ex (h₁ h₂ : heap) (x₁ x₂ x₃ x₄ : ptr) (v₁ v₂ v₃ : val) : is_def (h₁ ∙ (x₁ ↣ v₁ ∙ x₂ ↣ v₂) ∙ h₂ ∙ (x₃ ↣ v₃)) → x₁ ≠ x₃ ∧ x₁ ≠ x₂ ∧ x₂ ≠ x₃ := by super hnoalias with hcomm hassoc
cfaf7075c246e45230afdba75de4f8370882aefc
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/affine_space/affine_equiv.lean
2024106fa25d9313789b1b7a0fbc7cc918aa9e2b
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
16,386
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import linear_algebra.affine_space.affine_map import algebra.invertible /-! # Affine equivalences In this file we define `affine_equiv k P₁ P₂` (notation: `P₁ ≃ᵃ[k] P₂`) to be the type of affine equivalences between `P₁` and `P₂, i.e., equivalences such that both forward and inverse maps are affine maps. We define the following equivalences: * `affine_equiv.refl k P`: the identity map as an `affine_equiv`; * `e.symm`: the inverse map of an `affine_equiv` as an `affine_equiv`; * `e.trans e'`: composition of two `affine_equiv`s; note that the order follows `mathlib`'s `category_theory` convention (apply `e`, then `e'`), not the convention used in function composition and compositions of bundled morphisms. We equip `affine_equiv k P P` with a `group` structure with multiplication corresponding to composition in `affine_equiv.group`. ## Tags affine space, affine equivalence -/ open function set open_locale affine /-- An affine equivalence is an equivalence between affine spaces such that both forward and inverse maps are affine. We define it using an `equiv` for the map and a `linear_equiv` for the linear part in order to allow affine equivalences with good definitional equalities. -/ @[nolint has_inhabited_instance] structure affine_equiv (k P₁ P₂ : Type*) {V₁ V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] extends P₁ ≃ P₂ := (linear : V₁ ≃ₗ[k] V₂) (map_vadd' : ∀ (p : P₁) (v : V₁), to_equiv (v +ᵥ p) = linear v +ᵥ to_equiv p) notation P₁ ` ≃ᵃ[`:25 k:25 `] `:0 P₂:0 := affine_equiv k P₁ P₂ variables {k P₁ P₂ P₃ P₄ V₁ V₂ V₃ V₄ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] [add_comm_group V₃] [module k V₃] [add_torsor V₃ P₃] [add_comm_group V₄] [module k V₄] [add_torsor V₄ P₄] namespace affine_equiv include V₁ V₂ instance : has_coe_to_fun (P₁ ≃ᵃ[k] P₂) (λ _, P₁ → P₂) := ⟨λ e, e.to_fun⟩ instance : has_coe (P₁ ≃ᵃ[k] P₂) (P₁ ≃ P₂) := ⟨affine_equiv.to_equiv⟩ variables (k P₁) omit V₂ /-- Identity map as an `affine_equiv`. -/ @[refl] def refl : P₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.refl P₁, linear := linear_equiv.refl k V₁, map_vadd' := λ _ _, rfl } @[simp] lemma coe_refl : ⇑(refl k P₁) = id := rfl @[simp] lemma refl_apply (x : P₁) : refl k P₁ x = x := rfl @[simp] lemma to_equiv_refl : (refl k P₁).to_equiv = equiv.refl P₁ := rfl @[simp] lemma linear_refl : (refl k P₁).linear = linear_equiv.refl k V₁ := rfl variables {k P₁} include V₂ @[simp] lemma map_vadd (e : P₁ ≃ᵃ[k] P₂) (p : P₁) (v : V₁) : e (v +ᵥ p) = e.linear v +ᵥ e p := e.map_vadd' p v @[simp] lemma coe_to_equiv (e : P₁ ≃ᵃ[k] P₂) : ⇑e.to_equiv = e := rfl /-- Reinterpret an `affine_equiv` as an `affine_map`. -/ def to_affine_map (e : P₁ ≃ᵃ[k] P₂) : P₁ →ᵃ[k] P₂ := { to_fun := e, .. e } instance : has_coe (P₁ ≃ᵃ[k] P₂) (P₁ →ᵃ[k] P₂) := ⟨to_affine_map⟩ @[simp] lemma coe_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : (e.to_affine_map : P₁ → P₂) = (e : P₁ → P₂) := rfl @[simp] lemma to_affine_map_mk (f : P₁ ≃ P₂) (f' : V₁ ≃ₗ[k] V₂) (h) : to_affine_map (mk f f' h) = ⟨f, f', h⟩ := rfl @[norm_cast, simp] lemma coe_coe (e : P₁ ≃ᵃ[k] P₂) : ((e : P₁ →ᵃ[k] P₂) : P₁ → P₂) = e := rfl @[simp] lemma linear_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : e.to_affine_map.linear = e.linear := rfl lemma to_affine_map_injective : injective (to_affine_map : (P₁ ≃ᵃ[k] P₂) → (P₁ →ᵃ[k] P₂)) := begin rintros ⟨e, el, h⟩ ⟨e', el', h'⟩ H, simp only [to_affine_map_mk, equiv.coe_inj, linear_equiv.to_linear_map_inj] at H, congr, exacts [H.1, H.2] end @[simp] lemma to_affine_map_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_affine_map = e'.to_affine_map ↔ e = e' := to_affine_map_injective.eq_iff @[ext] lemma ext {e e' : P₁ ≃ᵃ[k] P₂} (h : ∀ x, e x = e' x) : e = e' := to_affine_map_injective $ affine_map.ext h lemma coe_fn_injective : @injective (P₁ ≃ᵃ[k] P₂) (P₁ → P₂) coe_fn := λ e e' H, ext $ congr_fun H @[simp, norm_cast] lemma coe_fn_inj {e e' : P₁ ≃ᵃ[k] P₂} : (e : P₁ → P₂) = e' ↔ e = e' := coe_fn_injective.eq_iff lemma to_equiv_injective : injective (to_equiv : (P₁ ≃ᵃ[k] P₂) → (P₁ ≃ P₂)) := λ e e' H, ext $ equiv.ext_iff.1 H @[simp] lemma to_equiv_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_equiv = e'.to_equiv ↔ e = e' := to_equiv_injective.eq_iff @[simp] lemma coe_mk (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (h) : ((⟨e, e', h⟩ : P₁ ≃ᵃ[k] P₂) : P₁ → P₂) = e := rfl /-- Construct an affine equivalence by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `e : P₁ → P₂`, a linear equivalence `e' : V₁ ≃ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `e p' = e' (p' -ᵥ p) +ᵥ e p`. -/ def mk' (e : P₁ → P₂) (e' : V₁ ≃ₗ[k] V₂) (p : P₁) (h : ∀ p' : P₁, e p' = e' (p' -ᵥ p) +ᵥ e p) : P₁ ≃ᵃ[k] P₂ := { to_fun := e, inv_fun := λ q' : P₂, e'.symm (q' -ᵥ e p) +ᵥ p, left_inv := λ p', by simp [h p'], right_inv := λ q', by simp [h (e'.symm (q' -ᵥ e p) +ᵥ p)], linear := e', map_vadd' := λ p' v, by { simp [h p', h (v +ᵥ p'), vadd_vsub_assoc, vadd_vadd] } } @[simp] lemma coe_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl @[simp] lemma linear_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : (mk' e e' p h).linear = e' := rfl /-- Inverse of an affine equivalence as an affine equivalence. -/ @[symm] def symm (e : P₁ ≃ᵃ[k] P₂) : P₂ ≃ᵃ[k] P₁ := { to_equiv := e.to_equiv.symm, linear := e.linear.symm, map_vadd' := λ v p, e.to_equiv.symm.apply_eq_iff_eq_symm_apply.2 $ by simpa using (e.to_equiv.apply_symm_apply v).symm } @[simp] lemma symm_to_equiv (e : P₁ ≃ᵃ[k] P₂) : e.to_equiv.symm = e.symm.to_equiv := rfl @[simp] lemma symm_linear (e : P₁ ≃ᵃ[k] P₂) : e.linear.symm = e.symm.linear := rfl /-- See Note [custom simps projection] -/ def simps.apply (e : P₁ ≃ᵃ[k] P₂) : P₁ → P₂ := e /-- See Note [custom simps projection] -/ def simps.symm_apply (e : P₁ ≃ᵃ[k] P₂) : P₂ → P₁ := e.symm initialize_simps_projections affine_equiv (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, linear → linear as_prefix, -to_equiv) protected lemma bijective (e : P₁ ≃ᵃ[k] P₂) : bijective e := e.to_equiv.bijective protected lemma surjective (e : P₁ ≃ᵃ[k] P₂) : surjective e := e.to_equiv.surjective protected lemma injective (e : P₁ ≃ᵃ[k] P₂) : injective e := e.to_equiv.injective @[simp] lemma range_eq (e : P₁ ≃ᵃ[k] P₂) : range e = univ := e.surjective.range_eq @[simp] lemma apply_symm_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₂) : e (e.symm p) = p := e.to_equiv.apply_symm_apply p @[simp] lemma symm_apply_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₁) : e.symm (e p) = p := e.to_equiv.symm_apply_apply p lemma apply_eq_iff_eq_symm_apply (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂} : e p₁ = p₂ ↔ p₁ = e.symm p₂ := e.to_equiv.apply_eq_iff_eq_symm_apply @[simp] lemma apply_eq_iff_eq (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂ : P₁} : e p₁ = e p₂ ↔ p₁ = p₂ := e.to_equiv.apply_eq_iff_eq omit V₂ @[simp] lemma symm_refl : (refl k P₁).symm = refl k P₁ := rfl include V₂ V₃ /-- Composition of two `affine_equiv`alences, applied left to right. -/ @[trans] def trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : P₁ ≃ᵃ[k] P₃ := { to_equiv := e.to_equiv.trans e'.to_equiv, linear := e.linear.trans e'.linear, map_vadd' := λ p v, by simp only [linear_equiv.trans_apply, coe_to_equiv, (∘), equiv.coe_trans, map_vadd] } @[simp] lemma coe_trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : ⇑(e.trans e') = e' ∘ e := rfl @[simp] lemma trans_apply (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) (p : P₁) : e.trans e' p = e' (e p) := rfl include V₄ lemma trans_assoc (e₁ : P₁ ≃ᵃ[k] P₂) (e₂ : P₂ ≃ᵃ[k] P₃) (e₃ : P₃ ≃ᵃ[k] P₄) : (e₁.trans e₂).trans e₃ = e₁.trans (e₂.trans e₃) := ext $ λ _, rfl omit V₃ V₄ @[simp] lemma trans_refl (e : P₁ ≃ᵃ[k] P₂) : e.trans (refl k P₂) = e := ext $ λ _, rfl @[simp] lemma refl_trans (e : P₁ ≃ᵃ[k] P₂) : (refl k P₁).trans e = e := ext $ λ _, rfl @[simp] lemma self_trans_symm (e : P₁ ≃ᵃ[k] P₂) : e.trans e.symm = refl k P₁ := ext e.symm_apply_apply @[simp] lemma symm_trans_self (e : P₁ ≃ᵃ[k] P₂) : e.symm.trans e = refl k P₂ := ext e.apply_symm_apply @[simp] lemma apply_line_map (e : P₁ ≃ᵃ[k] P₂) (a b : P₁) (c : k) : e (affine_map.line_map a b c) = affine_map.line_map (e a) (e b) c := e.to_affine_map.apply_line_map a b c omit V₂ instance : group (P₁ ≃ᵃ[k] P₁) := { one := refl k P₁, mul := λ e e', e'.trans e, inv := symm, mul_assoc := λ e₁ e₂ e₃, trans_assoc _ _ _, one_mul := trans_refl, mul_one := refl_trans, mul_left_inv := self_trans_symm } lemma one_def : (1 : P₁ ≃ᵃ[k] P₁) = refl k P₁ := rfl @[simp] lemma coe_one : ⇑(1 : P₁ ≃ᵃ[k] P₁) = id := rfl lemma mul_def (e e' : P₁ ≃ᵃ[k] P₁) : e * e' = e'.trans e := rfl @[simp] lemma coe_mul (e e' : P₁ ≃ᵃ[k] P₁) : ⇑(e * e') = e ∘ e' := rfl lemma inv_def (e : P₁ ≃ᵃ[k] P₁) : e⁻¹ = e.symm := rfl /-- `affine_equiv.linear` on automorphisms is a `monoid_hom`. -/ @[simps] def linear_hom : (P₁ ≃ᵃ[k] P₁) →* (V₁ ≃ₗ[k] V₁) := { to_fun := linear, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The group of `affine_equiv`s are equivalent to the group of units of `affine_map`. This is the affine version of `linear_map.general_linear_group.general_linear_equiv`. -/ @[simps] def equiv_units_affine_map : (P₁ ≃ᵃ[k] P₁) ≃* (P₁ →ᵃ[k] P₁)ˣ := { to_fun := λ e, ⟨e, e.symm, congr_arg coe e.symm_trans_self, congr_arg coe e.self_trans_symm⟩, inv_fun := λ u, { to_fun := (u : P₁ →ᵃ[k] P₁), inv_fun := (↑(u⁻¹) : P₁ →ᵃ[k] P₁), left_inv := affine_map.congr_fun u.inv_mul, right_inv := affine_map.congr_fun u.mul_inv, linear := linear_map.general_linear_group.general_linear_equiv _ _ $ units.map (by exact affine_map.linear_hom) u, map_vadd' := λ _ _, (u : P₁ →ᵃ[k] P₁).map_vadd _ _ }, left_inv := λ e, affine_equiv.ext $ λ x, rfl, right_inv := λ u, units.ext $ affine_map.ext $ λ x, rfl, map_mul' := λ e₁ e₂, rfl } variable (k) /-- The map `v ↦ v +ᵥ b` as an affine equivalence between a module `V` and an affine space `P` with tangent space `V`. -/ @[simps] def vadd_const (b : P₁) : V₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.vadd_const b, linear := linear_equiv.refl _ _, map_vadd' := λ p v, add_vadd _ _ _ } /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P₁) : P₁ ≃ᵃ[k] V₁ := { to_equiv := equiv.const_vsub p, linear := linear_equiv.neg k, map_vadd' := λ p' v, by simp [vsub_vadd_eq_vsub_sub, neg_add_eq_sub] } @[simp] lemma coe_const_vsub (p : P₁) : ⇑(const_vsub k p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P₁) : ⇑(const_vsub k p).symm = λ v, -v +ᵥ p := rfl variable (P₁) /-- The map `p ↦ v +ᵥ p` as an affine automorphism of an affine space. -/ @[simps] def const_vadd (v : V₁) : P₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.const_vadd P₁ v, linear := linear_equiv.refl _ _, map_vadd' := λ p w, vadd_comm _ _ _ } section homothety omit V₁ variables {R V P : Type*} [comm_ring R] [add_comm_group V] [module R V] [affine_space V P] include V /-- Fixing a point in affine space, homothety about this point gives a group homomorphism from (the centre of) the units of the scalars into the group of affine equivalences. -/ def homothety_units_mul_hom (p : P) : Rˣ →* P ≃ᵃ[R] P := equiv_units_affine_map.symm.to_monoid_hom.comp $ units.map (affine_map.homothety_hom p) @[simp] lemma coe_homothety_units_mul_hom_apply (p : P) (t : Rˣ) : (homothety_units_mul_hom p t : P → P) = affine_map.homothety p (t : R) := rfl @[simp] lemma coe_homothety_units_mul_hom_apply_symm (p : P) (t : Rˣ) : ((homothety_units_mul_hom p t).symm : P → P) = affine_map.homothety p (↑t⁻¹ : R) := rfl @[simp] lemma coe_homothety_units_mul_hom_eq_homothety_hom_coe (p : P) : (coe : (P ≃ᵃ[R] P) → P →ᵃ[R] P) ∘ homothety_units_mul_hom p = (affine_map.homothety_hom p) ∘ (coe : Rˣ → R) := funext $ λ _, rfl end homothety variable {P₁} open function /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : P₁) : P₁ ≃ᵃ[k] P₁ := (const_vsub k x).trans (vadd_const k x) lemma point_reflection_apply (x y : P₁) : point_reflection k x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_symm (x : P₁) : (point_reflection k x).symm = point_reflection k x := to_equiv_injective $ equiv.point_reflection_symm x @[simp] lemma to_equiv_point_reflection (x : P₁) : (point_reflection k x).to_equiv = equiv.point_reflection x := rfl @[simp] lemma point_reflection_self (x : P₁) : point_reflection k x x = x := vsub_vadd _ _ lemma point_reflection_involutive (x : P₁) : involutive (point_reflection k x : P₁ → P₁) := equiv.point_reflection_involutive x /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_injective_bit0 {x y : P₁} (h : injective (bit0 : V₁ → V₁)) : point_reflection k x y = y ↔ y = x := equiv.point_reflection_fixed_iff_of_injective_bit0 h lemma injective_point_reflection_left_of_injective_bit0 (h : injective (bit0 : V₁ → V₁)) (y : P₁) : injective (λ x : P₁, point_reflection k x y) := equiv.injective_point_reflection_left_of_injective_bit0 h y lemma injective_point_reflection_left_of_module [invertible (2:k)]: ∀ y, injective (λ x : P₁, point_reflection k x y) := injective_point_reflection_left_of_injective_bit0 k $ λ x y h, by rwa [bit0, bit0, ← two_smul k x, ← two_smul k y, (is_unit_of_invertible (2:k)).smul_left_cancel] at h lemma point_reflection_fixed_iff_of_module [invertible (2:k)] {x y : P₁} : point_reflection k x y = y ↔ y = x := ((injective_point_reflection_left_of_module k y).eq_iff' (point_reflection_self k y)).trans eq_comm end affine_equiv namespace linear_equiv /-- Interpret a linear equivalence between modules as an affine equivalence. -/ def to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : V₁ ≃ᵃ[k] V₂ := { to_equiv := e.to_equiv, linear := e, map_vadd' := λ p v, e.map_add v p } @[simp] lemma coe_to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : ⇑e.to_affine_equiv = e := rfl end linear_equiv namespace affine_map open affine_equiv include V₁ lemma line_map_vadd (v v' : V₁) (p : P₁) (c : k) : line_map v v' c +ᵥ p = line_map (v +ᵥ p) (v' +ᵥ p) c := (vadd_const k p).apply_line_map v v' c lemma line_map_vsub (p₁ p₂ p₃ : P₁) (c : k) : line_map p₁ p₂ c -ᵥ p₃ = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₃) c := (vadd_const k p₃).symm.apply_line_map p₁ p₂ c lemma vsub_line_map (p₁ p₂ p₃ : P₁) (c : k) : p₁ -ᵥ line_map p₂ p₃ c = line_map (p₁ -ᵥ p₂) (p₁ -ᵥ p₃) c := (const_vsub k p₁).apply_line_map p₂ p₃ c lemma vadd_line_map (v : V₁) (p₁ p₂ : P₁) (c : k) : v +ᵥ line_map p₁ p₂ c = line_map (v +ᵥ p₁) (v +ᵥ p₂) c := (const_vadd k P₁ v).apply_line_map p₁ p₂ c variables {R' : Type*} [comm_ring R'] [module R' V₁] lemma homothety_neg_one_apply (c p : P₁) : homothety c (-1:R') p = point_reflection R' c p := by simp [homothety_apply, point_reflection_apply] end affine_map
a7dfb19d10a7cd57007bb20f0babf2ea0e3ccf42
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/category/Compactum.lean
ea7c426794b200fdeadc22d13eec28e06abe2383
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
16,510
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.monad.types import category_theory.monad.limits import category_theory.equivalence import topology.category.CompHaus import data.set.constructions /-! # Compacta and Compact Hausdorff Spaces Recall that, given a monad `M` on `Type*`, an *algebra* for `M` consists of the following data: - A type `X : Type*` - A "structure" map `M X → X`. This data must also satisfy a distributivity and unit axiom, and algebras for `M` form a category in an evident way. See the file `category_theory.monad.algebra` for a general version, as well as the following link. https://ncatlab.org/nlab/show/monad This file proves the equivalence between the category of *compact Hausdorff topological spaces* and the category of algebras for the *ultrafilter monad*. ## Notation: Here are the main objects introduced in this file. - `Compactum` is the type of compacta, which we define as algebras for the ultrafilter monad. - `Compactum_to_CompHaus` is the functor `Compactum ⥤ CompHaus`. Here `CompHaus` is the usual category of compact Hausdorff spaces. - `Compactum_to_CompHaus.is_equivalence` is a term of type `is_equivalence Compactum_to_CompHaus`. The proof of this equivalence is a bit technical. But the idea is quite simply that the structure map `ultrafilter X → X` for an algebra `X` of the ultrafilter monad should be considered as the map sending an ultrafilter to its limit in `X`. The topology on `X` is then defined by mimicking the characterization of open sets in terms of ultrafilters. Any `X : Compactum` is endowed with a coercion to `Type*`, as well as the following instances: - `topological_space X`. - `compact_space X`. - `t2_space X`. Any morphism `f : X ⟶ Y` of is endowed with a coercion to a function `X → Y`, which is shown to be continuous in `continuous_of_hom`. The function `Compactum.of_topological_space` can be used to construct a `Compactum` from a topological space which satisfies `compact_space` and `t2_space`. We also add wrappers around structures which already exist. Here are the main ones, all in the `Compactum` namespace: - `forget : Compactum ⥤ Type*` is the forgetful functor, which induces a `concrete_category` instance for `Compactum`. - `free : Type* ⥤ Compactum` is the left adjoint to `forget`, and the adjunction is in `adj`. - `str : ultrafilter X → X` is the structure map for `X : Compactum`. The notation `X.str` is preferred. - `join : ultrafilter (ultrafilter X) → ultrafilter X` is the monadic join for `X : Compactum`. Again, the notation `X.join` is preferred. - `incl : X → ultrafilter X` is the unit for `X : Compactum`. The notation `X.incl` is preferred. ## References - E. Manes, Algebraic Theories, Graduate Texts in Mathematics 26, Springer-Verlag, 1976. - https://ncatlab.org/nlab/show/ultrafilter -/ open category_theory filter ultrafilter topological_space category_theory.limits has_finite_inter open_locale classical topological_space local notation `β` := of_type_monad ultrafilter /-- The type `Compactum` of Compacta, defined as algebras for the ultrafilter monad. -/ @[derive [category, inhabited]] def Compactum := monad.algebra β namespace Compactum /-- The forgetful functor to Type* -/ @[derive [creates_limits,faithful]] def forget : Compactum ⥤ Type* := monad.forget _ /-- The "free" Compactum functor. -/ def free : Type* ⥤ Compactum := monad.free _ /-- The adjunction between `free` and `forget`. -/ def adj : free ⊣ forget := monad.adj _ -- Basic instances instance : concrete_category Compactum := { forget := forget } instance : has_coe_to_sort Compactum := ⟨Type*,forget.obj⟩ instance {X Y : Compactum} : has_coe_to_fun (X ⟶ Y) := ⟨λ f, X → Y, λ f, f.f⟩ instance : has_limits Compactum := has_limits_of_has_limits_creates_limits forget /-- The structure map for a compactum, essentially sending an ultrafilter to its limit. -/ def str (X : Compactum) : ultrafilter X → X := X.a /-- The monadic join. -/ def join (X : Compactum) : ultrafilter (ultrafilter X) → ultrafilter X := β .μ.app _ /-- The inclusion of `X` into `ultrafilter X`. -/ def incl (X : Compactum) : X → ultrafilter X := β .η.app _ @[simp] lemma str_incl (X : Compactum) (x : X) : X.str (X.incl x) = x := begin change (β .η.app _ ≫ X.a) _ = _, rw monad.algebra.unit, refl, end @[simp] lemma str_hom_commute (X Y : Compactum) (f : X ⟶ Y) (xs : ultrafilter X) : f (X.str xs) = Y.str (map f xs) := begin change (X.a ≫ f.f) _ = _, rw ←f.h, refl, end @[simp] lemma join_distrib (X : Compactum) (uux : ultrafilter (ultrafilter X)) : X.str (X.join uux) = X.str (map X.str uux) := begin change (β .μ.app _ ≫ X.a) _ = _, rw monad.algebra.assoc, refl, end instance {X : Compactum} : topological_space X := { is_open := λ U, ∀ (F : ultrafilter X), X.str F ∈ U → U ∈ F, is_open_univ := λ _ _, filter.univ_sets _, is_open_inter := λ S T h3 h4 h5 h6, filter.inter_sets _ (h3 _ h6.1) (h4 _ h6.2), is_open_sUnion := λ S h1 F ⟨T,hT,h2⟩, mem_sets_of_superset (h1 T hT _ h2) (set.subset_sUnion_of_mem hT) } theorem is_closed_iff {X : Compactum} (S : set X) : is_closed S ↔ (∀ F : ultrafilter X, S ∈ F → X.str F ∈ S) := begin rw ← is_open_compl_iff, split, { intros cond F h, by_contradiction c, specialize cond F c, rw compl_mem_iff_not_mem at cond, contradiction }, { intros h1 F h2, specialize h1 F, cases F.mem_or_compl_mem S; finish } end instance {X : Compactum} : compact_space X := begin constructor, rw is_compact_iff_ultrafilter_le_nhds, intros F h, refine ⟨X.str F, by tauto, _⟩, rw le_nhds_iff, intros S h1 h2, exact h2 F h1 end /-- A local definition used only in the proofs. -/ private def basic {X : Compactum} (A : set X) : set (ultrafilter X) := {F | A ∈ F} /-- A local definition used only in the proofs. -/ private def cl {X : Compactum} (A : set X) : set X := X.str '' (basic A) private lemma basic_inter {X : Compactum} (A B : set X) : basic (A ∩ B) = basic A ∩ basic B := begin ext G, split, { intro hG, split; filter_upwards [hG]; intro x, exacts [and.left, and.right] }, { rintros ⟨h1, h2⟩, exact inter_mem_sets h1 h2 } end private lemma subset_cl {X : Compactum} (A : set X) : A ⊆ cl A := λ a ha, ⟨X.incl a, ha,by simp⟩ private theorem cl_cl {X : Compactum} (A : set X) : cl (cl A) ⊆ cl A := begin rintros _ ⟨F,hF,rfl⟩, -- Notation to be used in this proof. let fsu := finset (set (ultrafilter X)), let ssu := set (set (ultrafilter X)), let ι : fsu → ssu := coe, let C0 : ssu := {Z | ∃ B ∈ F, X.str ⁻¹' B = Z}, let AA := {G : ultrafilter X | A ∈ G}, let C1 := insert AA C0, let C2 := finite_inter_closure C1, -- C0 is closed under intersections. have claim1 : ∀ B C ∈ C0, B ∩ C ∈ C0, { rintros B C ⟨Q,hQ,rfl⟩ ⟨R,hR,rfl⟩, use Q ∩ R, simp only [and_true, eq_self_iff_true, set.preimage_inter, subtype.val_eq_coe], exact inter_sets _ hQ hR }, -- All sets in C0 are nonempty. have claim2 : ∀ B ∈ C0, set.nonempty B, { rintros B ⟨Q,hQ,rfl⟩, obtain ⟨q⟩ := nonempty_of_mem hQ, use X.incl q, simpa, }, -- The intersection of AA with every set in C0 is nonempty. have claim3 : ∀ B ∈ C0, (AA ∩ B).nonempty, { rintros B ⟨Q,hQ,rfl⟩, have : (Q ∩ cl A).nonempty := nonempty_of_mem_sets (inter_mem_sets hQ hF), rcases this with ⟨q,hq1,P,hq2,hq3⟩, refine ⟨P,hq2,_⟩, rw ←hq3 at hq1, simpa }, -- Suffices to show that the intersection of any finite subcollection of C1 is nonempty. suffices : ∀ (T : fsu), ι T ⊆ C1 → (⋂₀ ι T).nonempty, { obtain ⟨G, h1⟩ := exists_ultrafilter_of_finite_inter_nonempty _ this, use X.join G, have : G.map X.str = F := ultrafilter.coe_le_coe.1 (λ S hS, h1 (or.inr ⟨S, hS, rfl⟩)), rw [join_distrib, this], exact ⟨h1 (or.inl rfl), rfl⟩ }, -- C2 is closed under finite intersections (by construction!). have claim4 := finite_inter_closure_has_finite_inter C1, -- C0 is closed under finite intersections by claim1. have claim5 : has_finite_inter C0 := ⟨⟨_, univ_mem_sets, set.preimage_univ⟩, claim1⟩, -- Every element of C2 is nonempty. have claim6 : ∀ P ∈ C2, (P : set (ultrafilter X)).nonempty, { suffices : ∀ P ∈ C2, P ∈ C0 ∨ ∃ Q ∈ C0, P = AA ∩ Q, { intros P hP, cases this P hP, { exact claim2 _ h }, { rcases h with ⟨Q, hQ, rfl⟩, exact claim3 _ hQ } }, intros P hP, exact claim5.finite_inter_closure_insert _ hP }, intros T hT, -- Suffices to show that the intersection of the T's is contained in C2. suffices : ⋂₀ ι T ∈ C2, by exact claim6 _ this, -- Finish apply claim4.finite_inter_mem, intros t ht, exact finite_inter_closure.basic (@hT t ht), end lemma is_closed_cl {X : Compactum} (A : set X) : is_closed (cl A) := begin rw is_closed_iff, intros F hF, exact cl_cl _ ⟨F, hF, rfl⟩, end lemma str_eq_of_le_nhds {X : Compactum} (F : ultrafilter X) (x : X) : ↑F ≤ 𝓝 x → X.str F = x := begin -- Notation to be used in this proof. let fsu := finset (set (ultrafilter X)), let ssu := set (set (ultrafilter X)), let ι : fsu → ssu := coe, let T0 : ssu := { S | ∃ A ∈ F, S = basic A }, let AA := (X.str ⁻¹' {x}), let T1 := insert AA T0, let T2 := finite_inter_closure T1, intro cond, -- If F contains a closed set A, then x is contained in A. have claim1 : ∀ (A : set X), is_closed A → A ∈ F → x ∈ A, { intros A hA h, by_contradiction H, rw le_nhds_iff at cond, specialize cond Aᶜ H hA.is_open_compl, rw [ultrafilter.mem_coe, ultrafilter.compl_mem_iff_not_mem] at cond, contradiction }, -- If A ∈ F, then x ∈ cl A. have claim2 : ∀ (A : set X), A ∈ F → x ∈ cl A, { intros A hA, exact claim1 (cl A) (is_closed_cl A) (mem_sets_of_superset hA (subset_cl A)) }, -- T0 is closed under intersections. have claim3 : ∀ (S1 S2 ∈ T0), S1 ∩ S2 ∈ T0, { rintros S1 S2 ⟨S1, hS1, rfl⟩ ⟨S2, hS2, rfl⟩, exact ⟨S1 ∩ S2, inter_mem_sets hS1 hS2, by simp [basic_inter]⟩ }, -- For every S ∈ T0, the intersection AA ∩ S is nonempty. have claim4 : ∀ (S ∈ T0), (AA ∩ S).nonempty, { rintros S ⟨S, hS, rfl⟩, rcases claim2 _ hS with ⟨G, hG, hG2⟩, exact ⟨G, hG2, hG⟩ }, -- Every element of T0 is nonempty. have claim5 : ∀ (S ∈ T0), set.nonempty S, { rintros S ⟨S, hS, rfl⟩, exact ⟨F, hS⟩ }, -- Every element of T2 is nonempty. have claim6 : ∀ (S ∈ T2), set.nonempty S, { suffices : ∀ S ∈ T2, S ∈ T0 ∨ ∃ Q ∈ T0, S = AA ∩ Q, { intros S hS, cases this _ hS with h h, { exact claim5 S h }, { rcases h with ⟨Q, hQ, rfl⟩, exact claim4 Q hQ } }, intros S hS, apply finite_inter_closure_insert, { split, { use set.univ, refine ⟨filter.univ_sets _, _⟩, ext, refine ⟨_, by tauto⟩, { intro, apply filter.univ_sets, } }, { exact claim3} }, { exact hS} }, -- It suffices to show that the intersection of any finite subset of T1 is nonempty. suffices : ∀ (F : fsu), ↑F ⊆ T1 → (⋂₀ ι F).nonempty, { obtain ⟨G,h1⟩ := ultrafilter.exists_ultrafilter_of_finite_inter_nonempty _ this, have c1 : X.join G = F := ultrafilter.coe_le_coe.1 (λ P hP, h1 (or.inr ⟨P, hP, rfl⟩)), have c2 : G.map X.str = X.incl x, { refine ultrafilter.coe_le_coe.1 (λ P hP, _), apply mem_sets_of_superset (h1 (or.inl rfl)), rintros x ⟨rfl⟩, exact hP }, simp [←c1, c2] }, -- Finish... intros T hT, refine claim6 _ (finite_inter_mem (finite_inter_closure_has_finite_inter _) _ _), intros t ht, exact finite_inter_closure.basic (@hT t ht) end lemma le_nhds_of_str_eq {X : Compactum} (F : ultrafilter X) (x : X) : X.str F = x → ↑F ≤ 𝓝 x := λ h, le_nhds_iff.mpr (λ s hx hs, hs _ $ by rwa h) -- All the hard work above boils down to this t2_space instance. instance {X : Compactum} : t2_space X := begin rw t2_iff_ultrafilter, intros _ _ F hx hy, rw [← str_eq_of_le_nhds _ _ hx, ← str_eq_of_le_nhds _ _ hy] end /-- The structure map of a compactum actually computes limits. -/ lemma Lim_eq_str {X : Compactum} (F : ultrafilter X) : F.Lim = X.str F := begin rw [ultrafilter.Lim_eq_iff_le_nhds, le_nhds_iff], tauto, end lemma cl_eq_closure {X : Compactum} (A : set X) : cl A = closure A := begin ext, rw mem_closure_iff_ultrafilter, split, { rintro ⟨F, h1, h2⟩, exact ⟨F, h1, le_nhds_of_str_eq _ _ h2⟩ }, { rintro ⟨F, h1, h2⟩, exact ⟨F, h1, str_eq_of_le_nhds _ _ h2⟩ } end /-- Any morphism of compacta is continuous. -/ lemma continuous_of_hom {X Y : Compactum} (f : X ⟶ Y) : continuous f := begin rw continuous_iff_ultrafilter, intros x _ h, rw [tendsto, ← coe_map], apply le_nhds_of_str_eq, rw [← str_hom_commute, str_eq_of_le_nhds _ x h] end /-- Given any compact Hausdorff space, we construct a Compactum. -/ noncomputable def of_topological_space (X : Type*) [topological_space X] [compact_space X] [t2_space X] : Compactum := { A := X, a := ultrafilter.Lim, unit' := by {ext x, exact Lim_eq (by finish [le_nhds_iff]) }, assoc' := begin ext FF, change ultrafilter (ultrafilter X) at FF, set x := (ultrafilter.map ultrafilter.Lim FF).Lim with c1, have c2 : ∀ (U : set X) (F : ultrafilter X), F.Lim ∈ U → is_open U → U ∈ F, { intros U F h1 hU, exact c1 ▸ is_open_iff_ultrafilter.mp hU _ h1 _ (ultrafilter.le_nhds_Lim _) }, have c3 : ↑(ultrafilter.map ultrafilter.Lim FF) ≤ 𝓝 x, { rw le_nhds_iff, intros U hx hU, exact mem_coe.2 (c2 _ _ (by rwa ← c1) hU) }, have c4 : ∀ (U : set X), x ∈ U → is_open U → { G : ultrafilter X | U ∈ G } ∈ FF, { intros U hx hU, suffices : ultrafilter.Lim ⁻¹' U ∈ FF, { apply mem_sets_of_superset this, intros P hP, exact c2 U P hP hU }, exact @c3 U (is_open.mem_nhds hU hx) }, apply Lim_eq, rw le_nhds_iff, exact c4, end } /-- Any continuous map between Compacta is a morphism of compacta. -/ def hom_of_continuous {X Y : Compactum} (f : X → Y) (cont : continuous f) : X ⟶ Y := { f := f, h' := begin rw continuous_iff_ultrafilter at cont, ext (F : ultrafilter X), specialize cont (X.str F) F (le_nhds_of_str_eq F (X.str F) rfl), have := str_eq_of_le_nhds (ultrafilter.map f F) _ cont, simpa only [←this, types_comp_apply, of_type_functor_map], end } end Compactum /-- The functor functor from Compactum to CompHaus. -/ def Compactum_to_CompHaus : Compactum ⥤ CompHaus := { obj := λ X, { to_Top := { α := X } }, map := λ X Y f, { to_fun := f, continuous_to_fun := Compactum.continuous_of_hom _ }} namespace Compactum_to_CompHaus /-- The functor Compactum_to_CompHaus is full. -/ def full : full Compactum_to_CompHaus := { preimage := λ X Y f, Compactum.hom_of_continuous f.1 f.2 } /-- The functor Compactum_to_CompHaus is faithful. -/ lemma faithful : faithful Compactum_to_CompHaus := {} /-- This definition is used to prove essential surjectivity of Compactum_to_CompHaus. -/ noncomputable def iso_of_topological_space {D : CompHaus} : Compactum_to_CompHaus.obj (Compactum.of_topological_space D) ≅ D := { hom := { to_fun := id, continuous_to_fun := continuous_def.2 $ λ _ h, by {rw is_open_iff_ultrafilter' at h, exact h} }, inv := { to_fun := id, continuous_to_fun := continuous_def.2 $ λ _ h1, by {rw is_open_iff_ultrafilter', intros _ h2, exact h1 _ h2} } } /-- The functor Compactum_to_CompHaus is essentially surjective. -/ lemma ess_surj : ess_surj Compactum_to_CompHaus := { mem_ess_image := λ X, ⟨Compactum.of_topological_space X, ⟨iso_of_topological_space⟩⟩ } /-- The functor Compactum_to_CompHaus is an equivalence of categories. -/ noncomputable def is_equivalence : is_equivalence Compactum_to_CompHaus := begin apply equivalence.of_fully_faithfully_ess_surj _, exact Compactum_to_CompHaus.full, exact Compactum_to_CompHaus.faithful, exact Compactum_to_CompHaus.ess_surj, end end Compactum_to_CompHaus
698cd02a1e5237bfeca3e53945c433c76f68a046
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Init/Coe.lean
46a06b2bda3a9e880ac80953d1b51c1fc5fc98ca
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
13,219
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ prelude import Init.Prelude set_option linter.missingDocs true -- keep it documented /-! # Coercion Lean uses a somewhat elaborate system of typeclasses to drive the coercion system. Here a *coercion* means an invisible function that is automatically inserted to fix what would otherwise be a type error. For example, if we have: ``` def f (x : Nat) : Int := x ``` then this is clearly not type correct as is, because `x` has type `Nat` but type `Int` is expected, and normally you will get an error message saying exactly that. But before it shows that message, it will attempt to synthesize an instance of `CoeT Nat x Int`, which will end up going through all the other typeclasses defined below, to discover that there is an instance of `Coe Nat Int` defined. This instance is defined as: ``` instance : Coe Nat Int := ⟨Int.ofNat⟩ ``` so Lean will elaborate the original function `f` as if it said: ``` def f (x : Nat) : Int := Int.ofNat x ``` which is not a type error anymore. You can also use the `↑` operator to explicitly indicate a coercion. Using `↑x` instead of `x` in the example will result in the same output. Because there are many polymorphic functions in Lean, it is often ambiguous where the coercion can go. For example: ``` def f (x y : Nat) : Int := x + y ``` This could be either `↑x + ↑y` where `+` is the addition on `Int`, or `↑(x + y)` where `+` is addition on `Nat`, or even `x + y` using a heterogeneous addition with the type `Nat → Nat → Int`. You can use the `↑` operator to disambiguate between these possibilities, but generally Lean will elaborate working from the "outside in", meaning that it will first look at the expression `_ + _ : Int` and assign the `+` to be the one for `Int`, and then need to insert coercions for the subterms `↑x : Int` and `↑y : Int`, resulting in the `↑x + ↑y` version. Note that unlike most operators like `+`, `↑` is always eagerly unfolded at parse time into its definition. So if we look at the definition of `f` from before, we see no trace of the `CoeT.coe` function: ``` def f (x : Nat) : Int := x #print f -- def f : Nat → Int := -- fun (x : Nat) => Int.ofNat x ``` ## Important typeclasses Lean resolves a coercion by either inserting a `CoeDep` instance or chaining `CoeHead? CoeOut* Coe* CoeTail?` instances. (That is, zero or one `CoeHead` instances, an arbitrary number of `CoeOut` instances, etc.) The `CoeHead? CoeOut*` instances are chained from the "left" side. So if Lean looks for a coercion from `Nat` to `Int`, it starts by trying coerce `Nat` using `CoeHead` by looking for a `CoeHead Nat ?α` instance, and then continuing with `CoeOut`. Similarly `Coe* CoeTail?` are chained from the "right". These classes should be implemented for coercions: * `Coe α β` is the most basic class, and the usual one you will want to use when implementing a coercion for your own types. The variables in the type `α` must be a subset of the variables in `β` (or out-params of type class parameters), because `Coe` is chained right-to-left. * `CoeOut α β` is like `Coe α β` but chained left-to-right. Use this if the variables in the type `α` are a superset of the variables in `β`. * `CoeTail α β` is like `Coe α β`, but only applied once. Use this for coercions that would cause loops, like `[Ring R] → CoeTail Nat R`. * `CoeHead α β` is similar to `CoeOut α β`, but only applied once. Use this for coercions that would cause loops, like `[SetLike S α] → CoeHead S (Set α)`. * `CoeDep α (x : α) β` allows `β` to depend not only on `α` but on the value `x : α` itself. This is useful when the coercion function is dependent. An example of a dependent coercion is the instance for `Prop → Bool`, because it only holds for `Decidable` propositions. It is defined as: ``` instance (p : Prop) [Decidable p] : CoeDep Prop p Bool := ... ``` * `CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a (coercion-to-)function type, and this is triggered whenever an element `f : α` appears in an application like `f x` which would not make sense since `f` does not have a function type. `CoeFun` instances apply to `CoeOut` as well. * `CoeSort α β` is a coercion to a sort. `β` must be a universe, and if `a : α` appears in a place where a type is expected, like `(x : a)` or `a → a`. `CoeSort` instances apply to `CoeOut` as well. On top of these instances this file defines several auxiliary type classes: * `CoeTC := Coe*` * `CoeOTC := CoeOut* Coe*` * `CoeHTC := CoeHead? CoeOut* Coe*` * `CoeHTCT := CoeHead? CoeOut* Coe* CoeTail?` * `CoeDep := CoeHead? CoeOut* Coe* CoeTail? | CoeDep` -/ universe u v w w' /-- `Coe α β` is the typeclass for coercions from `α` to `β`. It can be transitively chained with other `Coe` instances, and coercion is automatically used when `x` has type `α` but it is used in a context where `β` is expected. You can use the `↑x` operator to explicitly trigger coercion. -/ class Coe (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β attribute [coe_decl] Coe.coe /-- Auxiliary class implementing `Coe*`. Users should generally not implement this directly. -/ class CoeTC (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β attribute [coe_decl] CoeTC.coe instance [Coe β γ] [CoeTC α β] : CoeTC α γ where coe a := Coe.coe (CoeTC.coe a : β) instance [Coe α β] : CoeTC α β where coe a := Coe.coe a instance : CoeTC α α where coe a := a /-- `CoeOut α β` is for coercions that are applied from left-to-right. -/ class CoeOut (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β attribute [coe_decl] CoeOut.coe /-- Auxiliary class implementing `CoeOut* Coe*`. Users should generally not implement this directly. -/ class CoeOTC (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β attribute [coe_decl] CoeOTC.coe instance [CoeOut α β] [CoeOTC β γ] : CoeOTC α γ where coe a := CoeOTC.coe (CoeOut.coe a : β) instance [CoeTC α β] : CoeOTC α β where coe a := CoeTC.coe a instance : CoeOTC α α where coe a := a -- Note: ^^ We add reflexivity instances for CoeOTC/etc. so that we avoid going -- through a user-defined CoeTC/etc. instance. (Instances like -- `CoeTC F (A →+ B)` apply even when the two sides are defeq.) /-- `CoeHead α β` is for coercions that are applied from left-to-right at most once at beginning of the coercion chain. -/ class CoeHead (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β attribute [coe_decl] CoeHead.coe /-- Auxiliary class implementing `CoeHead CoeOut* Coe*`. Users should generally not implement this directly. -/ class CoeHTC (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β attribute [coe_decl] CoeHTC.coe instance [CoeHead α β] [CoeOTC β γ] : CoeHTC α γ where coe a := CoeOTC.coe (CoeHead.coe a : β) instance [CoeOTC α β] : CoeHTC α β where coe a := CoeOTC.coe a instance : CoeHTC α α where coe a := a /-- `CoeTail α β` is for coercions that can only appear at the end of a sequence of coercions. That is, `α` can be further coerced via `Coe σ α` and `CoeHead τ σ` instances but `β` will only be the expected type of the expression. -/ class CoeTail (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β attribute [coe_decl] CoeTail.coe /-- Auxiliary class implementing `CoeHead* Coe* CoeTail?`. Users should generally not implement this directly. -/ class CoeHTCT (α : Sort u) (β : Sort v) where /-- Coerces a value of type `α` to type `β`. Accessible by the notation `↑x`, or by double type ascription `((x : α) : β)`. -/ coe : α → β attribute [coe_decl] CoeHTCT.coe instance [CoeTail β γ] [CoeHTC α β] : CoeHTCT α γ where coe a := CoeTail.coe (CoeHTC.coe a : β) instance [CoeHTC α β] : CoeHTCT α β where coe a := CoeHTC.coe a instance : CoeHTCT α α where coe a := a /-- `CoeDep α (x : α) β` is a typeclass for dependent coercions, that is, the type `β` can depend on `x` (or rather, the value of `x` is available to typeclass search so an instance that relates `β` to `x` is allowed). Dependent coercions do not participate in the transitive chaining process of regular coercions: they must exactly match the type mismatch on both sides. -/ class CoeDep (α : Sort u) (_ : α) (β : Sort v) where /-- The resulting value of type `β`. The input `x : α` is a parameter to the type class, so the value of type `β` may possibly depend on additional typeclasses on `x`. -/ coe : β attribute [coe_decl] CoeDep.coe /-- `CoeT` is the core typeclass which is invoked by Lean to resolve a type error. It can also be triggered explicitly with the notation `↑x` or by double type ascription `((x : α) : β)`. A `CoeT` chain has the grammar `CoeHead? CoeOut* Coe* CoeTail? | CoeDep`. -/ class CoeT (α : Sort u) (_ : α) (β : Sort v) where /-- The resulting value of type `β`. The input `x : α` is a parameter to the type class, so the value of type `β` may possibly depend on additional typeclasses on `x`. -/ coe : β attribute [coe_decl] CoeT.coe instance [CoeHTCT α β] : CoeT α a β where coe := CoeHTCT.coe a instance [CoeDep α a β] : CoeT α a β where coe := CoeDep.coe a instance : CoeT α a α where coe := a /-- `CoeFun α (γ : α → Sort v)` is a coercion to a function. `γ a` should be a (coercion-to-)function type, and this is triggered whenever an element `f : α` appears in an application like `f x` which would not make sense since `f` does not have a function type. This is automatically turned into `CoeFun.coe f x`. -/ class CoeFun (α : Sort u) (γ : outParam (α → Sort v)) where /-- Coerces a value `f : α` to type `γ f`, which should be either be a function type or another `CoeFun` type, in order to resolve a mistyped application `f x`. -/ coe : (f : α) → γ f attribute [coe_decl] CoeFun.coe instance [CoeFun α fun _ => β] : CoeOut α β where coe a := CoeFun.coe a /-- `CoeSort α β` is a coercion to a sort. `β` must be a universe, and if `a : α` appears in a place where a type is expected, like `(x : a)` or `a → a`, then it will be turned into `(x : CoeSort.coe a)`. -/ class CoeSort (α : Sort u) (β : outParam (Sort v)) where /-- Coerces a value of type `α` to `β`, which must be a universe. -/ coe : α → β attribute [coe_decl] CoeSort.coe instance [CoeSort α β] : CoeOut α β where coe a := CoeSort.coe a /-- `↑x` represents a coercion, which converts `x` of type `α` to type `β`, using typeclasses to resolve a suitable conversion function. You can often leave the `↑` off entirely, since coercion is triggered implicitly whenever there is a type error, but in ambiguous cases it can be useful to use `↑` to disambiguate between e.g. `↑x + ↑y` and `↑(x + y)`. -/ syntax:1024 (name := coeNotation) "↑" term:1024 : term /-! # Basic instances -/ instance boolToProp : Coe Bool Prop where coe b := Eq b true instance boolToSort : CoeSort Bool Prop where coe b := b instance decPropToBool (p : Prop) [Decidable p] : CoeDep Prop p Bool where coe := decide p instance optionCoe {α : Type u} : Coe α (Option α) where coe := some instance subtypeCoe {α : Sort u} {p : α → Prop} : CoeOut (Subtype p) α where coe v := v.val /-! # Coe bridge -/ /-- Helper definition used by the elaborator. It is not meant to be used directly by users. This is used for coercions between monads, in the case where we want to apply a monad lift and a coercion on the result type at the same time. -/ @[inline, coe_decl] def Lean.Internal.liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β := do let a ← liftM x pure (CoeT.coe a) /-- Helper definition used by the elaborator. It is not meant to be used directly by users. This is used for coercing the result type under a monad. -/ @[inline, coe_decl] def Lean.Internal.coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β := do let a ← x pure (CoeT.coe a)
5ff961e8d4e65aab411306f585afe2039235519d
fef48cac17c73db8662678da38fd75888db97560
/src/Zalpha_real.lean
31214e7e5acfb01fae178ae9a3dfda471b9ba6fa
[]
no_license
kbuzzard/lean-squares-in-fibonacci
6c0d924f799d6751e19798bb2530ee602ec7087e
8cea20e5ce88ab7d17b020932d84d316532a84a8
refs/heads/master
1,584,524,504,815
1,582,387,156,000
1,582,387,156,000
134,576,655
3
1
null
1,541,538,497,000
1,527,083,406,000
Lean
UTF-8
Lean
false
false
7,141
lean
import data.real.irrational Zalpha linear_algebra.basic import data.real.basic data.nat.prime import tactic.norm_num tactic.ring noncomputable theory open nat.prime local attribute [instance] nat.decidable_prime_1 theorem prime_five : nat.prime 5 := dec_trivial def αℝ := (real.sqrt 5 + 1) / 2 lemma αℝ_ne_zero : αℝ ≠ 0 := begin unfold αℝ, apply ne.symm, simp, rw [eq_div_iff_mul_eq (0 : ℝ) _ two_ne_zero], apply ne.symm, simp, rw [← eq_sub_iff_add_eq], simp, rw [eq_neg_iff_eq_neg], intro h, suffices : (-1 < (0 : ℝ)), from ne_of_lt (lt_of_lt_of_le this (real.sqrt_nonneg 5)) (eq.symm h), apply lt_of_add_lt_add_right _, exact 1, simp, exact zero_lt_one, end def to_real : ℤα → ℝ := λ z, z.1 + z.2 * αℝ def irrat_ext_add {x : ℝ} (q : ℚ) : irrational x → irrational (x + q) := begin intro h, intro nq, apply exists.elim nq, intro q', simp, intro hadd, have : x = q' - q, from eq_sub_of_add_eq hadd, rw this at h, have h2 : irrational q, revert h, simp, apply h2, existsi q, refl, end def irrat_ext_mul {x : ℝ} (q : ℚ) : q ≠ 0 → irrational x → irrational (x / q) := begin intro qne0, intro h, intro nq, apply exists.elim nq, intro q', simp, intro hmul, have qne0' : (↑ q : ℝ) ≠ 0, { simp, exact qne0, }, have : x = q' * q, from eq.symm ((eq_div_iff_mul_eq _ _ qne0').1 (eq.symm hmul)), rw this at h, apply h, existsi (q' * q), simp, end def irrat_ext_neg {x : ℝ} : irrational x → irrational (-x) := begin intro h, have neg1ne0 := neg_ne_zero.2 (@one_ne_zero ℚ _), have := irrat_ext_mul (-1) neg1ne0 h, simp at this, rw [div_neg x (one_ne_zero), div_one] at this, exact this, end def irrat_ext_inv {x : ℝ} : x ≠ 0 → irrational x → irrational (x⁻¹) := begin intro xne0, intro h, intro nq, apply exists.elim nq, intro q, simp, intro hinv, rw [← division_ring.inv_inv xne0] at h, apply h, apply exists.intro (q⁻¹), rw hinv, exact eq.symm (rat.cast_inv q), end section open real rat theorem sqrt_five_irrational : irrational (sqrt 5) | ⟨⟨n, d, h, c⟩, e⟩ := begin simp [num_denom', mk_eq_div] at e, have := @mul_self_sqrt 5 (le_of_lt (add_pos four_pos zero_lt_one)), have d0 : (0:ℝ) < d := nat.cast_pos.2 h, rw [e, div_mul_div, div_eq_iff_mul_eq (ne_of_gt $ mul_pos d0 d0), ← int.cast_mul, ← int.nat_abs_mul_self] at this, revert c this, generalize : n.nat_abs = a, intros, have E : 5 * (d * d) = a * a := (@nat.cast_inj ℝ _ _ _ _ _).1 (by simpa), have ae : 5 ∣ a, { refine (or_self _).1 (prime_five.dvd_mul.1 _), rw ← E, apply dvd_mul_right }, have de : 5 ∣ d, { have := mul_dvd_mul ae ae, refine (or_self _).1 (prime_five.dvd_mul.1 _), rwa [← E, nat.mul_dvd_mul_iff_left (nat.succ_pos 4)] at this }, refine nat.not_coprime_of_dvd_of_dvd _ ae de c, from dec_trivial, end end def one_half : ℚ := (1 : ℚ) / (2 : ℚ) theorem αℝ_irrational : irrational αℝ := begin have irrat := irrat_ext_add (one_half) (irrat_ext_mul 2 two_ne_zero sqrt_five_irrational), have alphar : real.sqrt 5 / ↑(2 : ℚ) + ↑(one_half) = αℝ, unfold one_half, unfold αℝ, rw [eq_div_iff_mul_eq _ _ two_ne_zero], rw [right_distrib], have : (one_half : ℝ) * 2 = (1 : ℝ), show (one_half : ℝ) * 2 = (1 : ℝ), symmetry, transitivity, symmetry, exact rat.cast_one, have : (2 : ℝ) = (2 : ℚ), show (1 + 1 : ℝ) = (1 + 1 : ℚ), rw [rat.cast_add, rat.cast_one], rw this, rw [← rat.cast_mul, rat.cast_inj], refl, unfold_coes, unfold_coes at this, unfold one_half at this, rw this, have : (rat.cast 2 : ℝ) = 2, show (rat.cast (1 + 1) : ℝ) = 1 + 1, show (↑ (1 + 1 : ℚ) : ℝ) = 1 + 1, rw [rat.cast_add, rat.cast_one], rw this, simp, exact div_mul_cancel (real.sqrt 5) two_ne_zero, rw alphar at irrat, exact irrat, end lemma αℝ.linear_independent : ∀ z : ℤα, to_real z = 0 → z = 0 := begin intro z, intro h, unfold to_real at h, rw [← eq_sub_iff_add_eq] at h, simp at h, rw [eq_neg_iff_eq_neg] at h, suffices : z.i = 0, { rw this at h, simp at h, cases h, exact Zalpha.ext this h, exfalso, revert h, exact αℝ_ne_zero, }, by_contradiction zine0, have zine0' : (↑ z.i : ℝ) ≠ 0, { simp, exact zine0, }, rw [iff.intro eq.symm eq.symm] at h, rw [neg_eq_neg_one_mul, ← eq_div_iff_mul_eq _ _ zine0'] at h, rw [mul_div_assoc, mul_div_comm] at h, rw [mul_comm, iff.intro eq.symm eq.symm, ← eq_div_iff_mul_eq _ (-1) αℝ_ne_zero] at h, have : ∀ (i : ℤ), (i : ℝ) = ↑ (↑ (i : ℤ) : ℚ), { intro i, symmetry, apply int.eq_cast (rat.cast ∘ int.cast), simp, show rat.cast (int.cast (1 : ℤ)) = (1 : ℝ), show rat.cast (↑ (1 : ℤ)) = (1 : ℝ), show ↑ (↑ (1 : ℤ) : ℚ) = (1 : ℝ), simp, intros, simp, show rat.cast (int.cast (x + y)) = rat.cast (int.cast x) + rat.cast (int.cast y), show rat.cast (↑ (x + y)) = rat.cast (↑ x) + rat.cast (↑ y), show (↑ (↑ (x + y) : ℚ) : ℝ) = ↑ (↑ x : ℚ) + ↑ (↑ y : ℚ), simp, }, rw [this z.i, this z.r] at h, rw [← @rat.cast_div ℝ _ _ z.r z.i] at h, rw [division_def (-1) αℝ, mul_comm, mul_neg_one] at h, apply irrat_ext_neg (irrat_ext_inv αℝ_ne_zero αℝ_irrational), apply exists.intro, exact eq.symm h, end @[simp] lemma to_real_α : to_real Zalpha.α = αℝ := by unfold to_real; simp @[simp] lemma to_real_0 : to_real (0 : ℤα) = (0 : ℝ) := by unfold to_real; simp @[simp] lemma to_real_1 : to_real 1 = 1 := by unfold to_real; simp lemma αℝ.sqrd : αℝ*αℝ = αℝ + 1 := have h : (0 : ℝ) ≤ 5 := by norm_num, begin unfold αℝ, rw [div_mul_div, mul_add, mul_one, add_mul, one_mul, ← pow_two, real.sqr_sqrt h], ring, end instance : is_ring_hom to_real := { map_add := begin intros, unfold to_real, simp [right_distrib], end , map_mul := begin intros, unfold to_real, simp [left_distrib, right_distrib], have : (↑(x.r) * αℝ * ((y.r) * αℝ)) = x.r * y.r * (αℝ * αℝ), ac_refl, rw [this, αℝ.sqrd], simp [left_distrib], ac_refl, end , map_one := begin unfold to_real, simp, end } lemma to_real.injective : function.injective to_real := begin intros z₁ z₂ h, rw [← sub_eq_zero] at h, rw [← sub_eq_zero], rw [← is_ring_hom.map_sub to_real] at h, exact αℝ.linear_independent _ h, end lemma to_real.inj : ∀ a b, to_real a = to_real b ↔ a = b := begin intros, constructor, exact @to_real.injective a b, intro h, rw h end /-instance : integral_domain Zalpha := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros a b h, rw [← to_real.inj, to_real.is_ring_hom.map_mul] at h, simp at h, have := eq_zero_or_eq_zero_of_mul_eq_zero h, cases this, rw [← to_real_0, to_real.inj _ 0] at this, left, exact this, rw [← to_real_0, to_real.inj _ 0] at this, right, exact this, end, zero_ne_one := dec_trivial, ..Zalpha.comm_ring }-/
2dcfffdcf3ab90a11d165783f103198acb93115d
4fa161becb8ce7378a709f5992a594764699e268
/src/data/rat/cast.lean
79bd348ff1042550c7ef1d852fef493602cc3632
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
12,158
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.order /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ namespace rat variable {α : Type*} open_locale rat section with_div_ring variable [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℚ α := ⟨λ r, r.1 / r.2⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp, norm_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem cast_commute (r : ℚ) (a : α) : commute ↑r a := (r.1.cast_commute a).div_left (r.2.cast_commute a) theorem commute_cast (a : α) (r : ℚ) : commute a r := (r.cast_commute a).symm @[norm_cast] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a * b⁻¹ : α) = n / d, rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end @[norm_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv', d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, (nat.cast_commute _ _).eq], simp [d₁0, mul_assoc] end @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹), by rw [int.cast_neg, neg_mul_eq_neg_mul] @[norm_cast] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)] @[norm_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv', d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [(d₁.commute_cast (_:α)).inv_right'.eq] end @[norm_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end @[norm_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp, norm_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂:α)).inv_left'.eq, ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_add [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_sub [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_mul [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_bit0 [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl variable (α) /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom [char_zero α] : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ variable {α} @[simp] lemma coe_cast_hom [char_zero α] : ⇑(cast_hom α) = coe := rfl @[simp, norm_cast] theorem cast_inv [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := (cast_hom α).map_inv @[simp, norm_cast] theorem cast_div [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := (cast_hom α).map_div @[norm_cast] theorem cast_mk [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := by simp only [mk_eq_div, cast_div, cast_coe_int] @[simp, norm_cast] theorem cast_pow [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := (cast_hom α).map_pow q k end with_div_ring @[simp, norm_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ), by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h), mul_nonneg_iff_right_nonneg_of_pos ((@inv_pos α _ _).2 (nat.cast_pos.2 h)), int.cast_nonneg] @[simp, norm_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div] @[simp, norm_cast] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end rat open rat ring_hom lemma ring_hom.eq_rat_cast {k} [division_ring k] (f : ℚ →+* k) (r : ℚ) : f r = r := calc f r = f (r.1 / r.2) : by conv_lhs { rw [← @num_denom r, mk_eq_div, int.cast_coe_nat] } ... = (f.comp $ int.cast_ring_hom ℚ) r.1 / (f.comp $ nat.cast_ring_hom ℚ) r.2 : f.map_div ... = r.1 / r.2 : by rw [eq_nat_cast, eq_int_cast] -- This seems to be true for a `[char_p k]` too because `k'` must have the same characteristic -- but the proof would be much longer lemma ring_hom.map_rat_cast {k k'} [division_ring k] [char_zero k] [division_ring k'] (f : k →+* k') (r : ℚ) : f r = r := (f.comp (cast_hom k)).eq_rat_cast r lemma ring_hom.ext_rat {R : Type*} [semiring R] (f g : ℚ →+* R) : f = g := begin ext r, refine rat.num_denom_cases_on' r _, intros a b b0, let φ : ℤ →+* R := f.comp (int.cast_ring_hom ℚ), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom ℚ), rw [rat.mk_eq_div, int.cast_coe_nat], have b0' : (b:ℚ) ≠ 0 := nat.cast_ne_zero.2 b0, have : ∀ n : ℤ, f n = g n := λ n, show φ n = ψ n, by rw [φ.ext_int ψ], calc f (a * b⁻¹) = f a * f b⁻¹ * (g (b:ℤ) * g b⁻¹) : by rw [int.cast_coe_nat, ← g.map_mul, mul_inv_cancel b0', g.map_one, mul_one, f.map_mul] ... = g a * f b⁻¹ * (f (b:ℤ) * g b⁻¹) : by rw [this a, ← this b] ... = g (a * b⁻¹) : by rw [int.cast_coe_nat, mul_assoc, ← mul_assoc (f b⁻¹), ← f.map_mul, inv_mul_cancel b0', f.map_one, one_mul, g.map_mul] end instance rat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℚ →+* R) := ⟨ring_hom.ext_rat⟩
d6cbb9dbd22ddc51d9c7a78bf0f3106c46a7917c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/level_auto.lean
60ea1d0c76cfa86273df0374f4066ccc4739ce40
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
417
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.name import Mathlib.Lean3Lib.init.meta.format namespace Mathlib /-- A type universe term. eg `max u v`. Reflect a C++ level object. The VM replaces it with the C++ implementation. -/ end Mathlib
a9980c734265c20860ba333176a7acc82e3bd487
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/type_library/box.lean
abd4414e6d02963738a3e3909bc0852991cfd5ff
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
486
lean
namespace hidden /- This polymorpmic box type allows one to enclose/wrap a value of any ordinary computational type (of type, Type) "in" a box structure. Using "structure" to define this type as specified here provide a projection function with the same name, val, as the field who value it projects (i.e., accesses and returns). -/ universe u structure box (α : Type u) : Type u := mk :: (val : α) def b3 := box.mk 3 #reduce b3 #reduce (box.val b3) #reduce b3.val end hidden
02d6a84e68ac44639495834e7afcd847e384010e
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Elab/Tactic/Basic.lean
56089fdc84fa44bdd2c80e7217c2020ba30d8fe3
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,663
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Util.CollectMVars import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Subst import Lean.Elab.Util import Lean.Elab.Term import Lean.Elab.Binders namespace Lean.Elab open Meta def goalsToMessageData (goals : List MVarId) : MessageData := MessageData.joinSep (goals.map $ MessageData.ofGoal) (Format.line ++ Format.line) def Term.reportUnsolvedGoals (goals : List MVarId) : TermElabM Unit := do throwError! "unsolved goals\n{goalsToMessageData goals}" namespace Tactic structure Context := (main : MVarId) structure State := (goals : List MVarId) instance : Inhabited State := ⟨{ goals := [] }⟩ structure BacktrackableState := (env : Environment) (mctx : MetavarContext) (term : Term.State) (goals : List MVarId) abbrev TacticM := ReaderT Context $ StateRefT State TermElabM abbrev Tactic := Syntax → TacticM Unit def saveBacktrackableState : TacticM BacktrackableState := do pure { env := (← getEnv), mctx := (← getMCtx), term := (← getThe Term.State), goals := (← get).goals } def BacktrackableState.restore (b : BacktrackableState) : TacticM Unit := do setEnv b.env setMCtx b.mctx let msgLog ← Term.getMessageLog -- we do not backtrack the message log set b.term Term.setMessageLog msgLog modify fun s => { s with goals := b.goals } @[inline] protected def tryCatch {α} (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do let b ← saveBacktrackableState try x catch ex => b.restore; h ex instance : MonadExcept Exception TacticM := { throw := throw, tryCatch := Tactic.tryCatch } @[inline] protected def orElse {α} (x y : TacticM α) : TacticM α := do try x catch _ => y instance {α} : OrElse (TacticM α) := ⟨Tactic.orElse⟩ structure SavedState := (core : Core.State) (meta : Meta.State) (term : Term.State) (tactic : State) instance : Inhabited SavedState := ⟨⟨arbitrary _, arbitrary _, arbitrary _, arbitrary _⟩⟩ def saveAllState : TacticM SavedState := do pure { core := (← getThe Core.State), meta := (← getThe Meta.State), term := (← getThe Term.State), tactic := (← get) } def SavedState.restore (s : SavedState) : TacticM Unit := do set s.core; set s.meta; set s.term; set s.tactic @[inline] def liftTermElabM {α} (x : TermElabM α) : TacticM α := liftM x @[inline] def liftMetaM {α} (x : MetaM α) : TacticM α := liftTermElabM $ Term.liftMetaM x def ensureHasType (expectedType? : Option Expr) (e : Expr) : TacticM Expr := liftTermElabM $ Term.ensureHasType expectedType? e def reportUnsolvedGoals (goals : List MVarId) : TacticM Unit := liftTermElabM $ Term.reportUnsolvedGoals goals protected def getCurrMacroScope : TacticM MacroScope := do pure (← readThe Term.Context).currMacroScope protected def getMainModule : TacticM Name := do pure (← getEnv).mainModule unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) := mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic" @[builtinInit mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic private def evalTacticUsing (s : SavedState) (stx : Syntax) (tactics : List Tactic) : TacticM Unit := do let rec loop : List Tactic → TacticM Unit | [] => throwErrorAt! stx "unexpected syntax {indentD stx}" | evalFn::evalFns => do try evalFn stx catch | ex@(Exception.error _ _) => match evalFns with | [] => throw ex | evalFns => s.restore; loop evalFns | ex@(Exception.internal id) => if id == unsupportedSyntaxExceptionId then s.restore; loop evalFns else throw ex loop tactics /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α := withTheReader Term.Context (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x mutual partial def expandTacticMacroFns (stx : Syntax) (macros : List Macro) : TacticM Unit := let rec loop : List Macro → TacticM Unit | [] => throwErrorAt! stx "tactic '{stx.getKind}' has not been implemented" | m::ms => do let scp ← getCurrMacroScope try let stx' ← adaptMacro m stx evalTactic stx' catch ex => if ms.isEmpty then throw ex loop ms loop macros partial def expandTacticMacro (stx : Syntax) : TacticM Unit := do let k := stx.getKind let table := (macroAttribute.ext.getState (← getEnv)).table let macroFns := (table.find? k).getD [] expandTacticMacroFns stx macroFns partial def evalTactic : Syntax → TacticM Unit | stx => withRef stx $ withIncRecDepth $ withFreshMacroScope $ match stx with | Syntax.node k args => if k == nullKind then -- Macro writers create a sequence of tactics `t₁ ... tₙ` using `mkNullNode #[t₁, ..., tₙ]` stx.getArgs.forM evalTactic else do trace `Elab.step fun _ => stx let env ← getEnv let s ← saveAllState let table := (tacticElabAttribute.ext.getState env).table let k := stx.getKind match table.find? k with | some evalFns => evalTacticUsing s stx evalFns | none => expandTacticMacro stx | _ => throwError "unexpected command" end /-- Adapt a syntax transformation to a regular tactic evaluator. -/ def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' $ evalTactic stx' def getGoals : TacticM (List MVarId) := do pure (← get).goals def setGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := gs } def appendGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := s.goals ++ gs } def pruneSolvedGoals : TacticM Unit := do let gs ← getGoals let gs ← gs.filterM fun g => not <$> isExprMVarAssigned g setGoals gs def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals; getGoals def getMainGoal : TacticM (MVarId × List MVarId) := do let (g::gs) ← getUnsolvedGoals | throwError "no goals to be solved"; pure (g, gs) def getMainTag : TacticM Name := do let (g, _) ← getMainGoal pure (← getMVarDecl g).userName def ensureHasNoMVars (e : Expr) : TacticM Unit := do let e ← instantiateMVars e let pendingMVars ← getMVars e Term.logUnassignedUsingErrorInfos pendingMVars if e.hasExprMVar then throwError! "tactic failed, resulting expression contains metavariables{indentExpr e}" def withMainMVarContext {α} (x : TacticM α) : TacticM α := do let (mvarId, _) ← getMainGoal withMVarContext mvarId x @[inline] def liftMetaMAtMain {α} (x : MVarId → MetaM α) : TacticM α := do let (g, _) ← getMainGoal withMVarContext g $ liftMetaM $ x g @[inline] def liftMetaTacticAux {α} (tactic : MVarId → MetaM (α × List MVarId)) : TacticM α := do let (g, gs) ← getMainGoal withMVarContext g do let (a, gs') ← tactic g setGoals (gs' ++ gs) pure a @[inline] def liftMetaTactic (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit := liftMetaTacticAux fun mvarId => do let gs ← tactic mvarId pure ((), gs) def done : TacticM Unit := do let gs ← getUnsolvedGoals; unless gs.isEmpty do reportUnsolvedGoals gs @[builtinTactic Lean.Parser.Tactic.«done»] def evalDone : Tactic := fun _ => done def focusAux {α} (tactic : TacticM α) : TacticM α := do let (g, gs) ← getMainGoal setGoals [g] let a ← tactic let gs' ← getGoals setGoals (gs' ++ gs) pure a def focus {α} (tactic : TacticM α) : TacticM α := focusAux do let a ← tactic; done; pure a /- Close the main goal using the given tactic. If it fails, log the error and `admit` -/ def closeUsingOrAdmit (tac : Syntax) : TacticM Unit := do let (mvarId, rest) ← getMainGoal try evalTactic tac done catch ex => logException ex let mvarType ← inferType (mkMVar mvarId) assignExprMVar mvarId (← mkSorry mvarType (synthetic := true)) setGoals rest def try? {α} (tactic : TacticM α) : TacticM (Option α) := do try pure (some (← tactic)) catch _ => pure none -- TODO: rename? def «try» {α} (tactic : TacticM α) : TacticM Bool := do try tactic; pure true catch _ => pure false /-- Use `parentTag` to tag untagged goals at `newGoals`. If there are multiple new untagged goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`. If there is only one new untagged goal, then we just use `parentTag` -/ def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do let mctx ← getMCtx let mut numAnonymous := 0 for g in newGoals do if mctx.isAnonymousMVar g then numAnonymous := numAnonymous + 1 modifyMCtx fun mctx => do let mut mctx := mctx let mut idx := 1 for g in newGoals do if mctx.isAnonymousMVar g then if numAnonymous == 1 then mctx := mctx.renameMVar g parentTag else mctx := mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx) idx := idx + 1 pure mctx @[builtinTactic seq1] def evalSeq1 : Tactic := fun stx => stx[0].getSepArgs.forM evalTactic @[builtinTactic paren] def evalParen : Tactic := fun stx => evalTactic stx[1] @[builtinTactic tacticSeq1Indented] def evalTacticSeq1Indented : Tactic := fun stx => stx[0].forArgsM fun seqElem => evalTactic seqElem[0] @[builtinTactic tacticSeqBracketed] def evalTacticSeqBracketed : Tactic := fun stx => withRef stx[2] $ focus $ stx[1].forArgsM fun seqElem => evalTactic seqElem[0] @[builtinTactic Parser.Tactic.focus] def evalFocus : Tactic := fun stx => focus $ evalTactic stx[1] @[builtinTactic tacticSeq] def evalTacticSeq : Tactic := fun stx => evalTactic stx[0] partial def evalChoiceAux (tactics : Array Syntax) (i : Nat) : TacticM Unit := if h : i < tactics.size then let tactic := tactics.get ⟨i, h⟩ catchInternalId unsupportedSyntaxExceptionId (evalTactic tactic) (fun _ => evalChoiceAux tactics (i+1)) else throwUnsupportedSyntax @[builtinTactic choice] def evalChoice : Tactic := fun stx => evalChoiceAux stx.getArgs 0 @[builtinTactic skip] def evalSkip : Tactic := fun stx => pure () @[builtinTactic failIfSuccess] def evalFailIfSuccess : Tactic := fun stx => do let tactic := stx[1] if (← try evalTactic tactic; pure true catch _ => pure false) then throwError "tactic succeeded" @[builtinTactic traceState] def evalTraceState : Tactic := fun stx => do let gs ← getUnsolvedGoals; logInfo (goalsToMessageData gs) @[builtinTactic Lean.Parser.Tactic.assumption] def evalAssumption : Tactic := fun stx => liftMetaTactic fun mvarId => do Meta.assumption mvarId; pure [] private def introStep (n : Name) : TacticM Unit := liftMetaTactic fun mvarId => do let (_, mvarId) ← Meta.intro mvarId n pure [mvarId] @[builtinTactic Lean.Parser.Tactic.intro] def evalIntro : Tactic := fun stx => match_syntax stx with | `(tactic| intro) => liftMetaTactic fun mvarId => do let (_, mvarId) ← Meta.intro1 mvarId; pure [mvarId] | `(tactic| intro $h:ident) => introStep h.getId | `(tactic| intro _) => introStep `_ | `(tactic| intro $pat:term) => do let stxNew ← `(tactic| intro h; match h with | $pat:term => _; clear h) withMacroExpansion stx stxNew $ evalTactic stxNew | `(tactic| intro $hs:term*) => do let h0 := hs.get! 0 let hs := hs.extract 1 hs.size let stxNew ← `(tactic| intro $h0:term; intro $hs:term*) withMacroExpansion stx stxNew $ evalTactic stxNew | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.introMatch] def evalIntroMatch : Tactic := fun stx => do let matchAlts := stx[1] let stxNew ← liftMacroM $ Term.expandMatchAltsIntoMatchTactic stx matchAlts withMacroExpansion stx stxNew $ evalTactic stxNew private def getIntrosSize : Expr → Nat | Expr.forallE _ _ b _ => getIntrosSize b + 1 | Expr.letE _ _ _ b _ => getIntrosSize b + 1 | _ => 0 @[builtinTactic «intros»] def evalIntros : Tactic := fun stx => match_syntax stx with | `(tactic| intros) => liftMetaTactic fun mvarId => do let type ← Meta.getMVarType mvarId let type ← instantiateMVars type let n := getIntrosSize type let (_, mvarId) ← Meta.introN mvarId n pure [mvarId] | `(tactic| intros $ids*) => liftMetaTactic fun mvarId => do let (_, mvarId) ← Meta.introN mvarId ids.size (ids.map Syntax.getId).toList pure [mvarId] | _ => throwUnsupportedSyntax def getFVarId (id : Syntax) : TacticM FVarId := withRef id do let fvar? ← liftTermElabM $ Term.isLocalIdent? id; match fvar? with | some fvar => pure fvar.fvarId! | none => throwError! "unknown variable '{id.getId}'" def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do withMainMVarContext $ ids.mapM getFVarId @[builtinTactic Lean.Parser.Tactic.revert] def evalRevert : Tactic := fun stx => match_syntax stx with | `(tactic| revert $hs*) => do let (g, gs) ← getMainGoal let fvarIds ← getFVarIds hs let (_, g) ← Meta.revert g fvarIds setGoals (g :: gs) | _ => throwUnsupportedSyntax /- Sort free variables using an order `x < y` iff `x` was defined after `y` -/ private def sortFVarIds (fvarIds : Array FVarId) : TacticM (Array FVarId) := withMainMVarContext do let lctx ← getLCtx pure $ fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index > d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁ fvarId₂ @[builtinTactic Lean.Parser.Tactic.clear] def evalClear : Tactic := fun stx => match_syntax stx with | `(tactic| clear $hs*) => do let fvarIds ← getFVarIds hs let fvarIds ← sortFVarIds fvarIds for fvarId in fvarIds do let (g, gs) ← getMainGoal withMVarContext g do let g ← clear g fvarId setGoals (g :: gs) | _ => throwUnsupportedSyntax def forEachVar (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit := do for h in hs do let (g, gs) ← getMainGoal; withMVarContext g do let fvarId ← getFVarId h let g ← tac g fvarId setGoals (g :: gs) @[builtinTactic Lean.Parser.Tactic.subst] def evalSubst : Tactic := fun stx => match_syntax stx with | `(tactic| subst $hs*) => forEachVar hs Meta.subst | _ => throwUnsupportedSyntax /-- First method searches for a metavariable `g` s.t. `tag` is a suffix of its name. If none is found, then it searches for a metavariable `g` s.t. `tag` is a prefix of its name. -/ private def findTag? (gs : List MVarId) (tag : Name) : TacticM (Option MVarId) := do let g? ← gs.findM? (fun g => do pure $ tag.isSuffixOf (← getMVarDecl g).userName); match g? with | some g => pure g | none => gs.findM? (fun g => do pure $ tag.isPrefixOf (← getMVarDecl g).userName) @[builtinTactic «case»] def evalCase : Tactic := fun stx => match_syntax stx with | `(tactic| case $tag => $tac:tacticSeq) => do let tag := tag.getId let gs ← getUnsolvedGoals let some g ← findTag? gs tag | throwError "tag not found" let gs := gs.erase g setGoals [g] let savedTag ← liftM $ getMVarTag g liftM $ setMVarTag g Name.anonymous try closeUsingOrAdmit tac finally liftM $ setMVarTag g savedTag done setGoals gs | _ => throwUnsupportedSyntax @[builtinTactic «orelse»] def evalOrelse : Tactic := fun stx => match_syntax stx with | `(tactic| $tac1 <|> $tac2) => evalTactic tac1 <|> evalTactic tac2 | _ => throwUnsupportedSyntax builtin_initialize registerTraceClass `Elab.tactic @[inline] def TacticM.run {α} (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) := x ctx $.run s @[inline] def TacticM.run' {α} (x : TacticM α) (ctx : Context) (s : State) : TermElabM α := Prod.fst <$> x.run ctx s end Lean.Elab.Tactic
2a7d94bc9b1805a2e2f58712381df1cafce24f47
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/ordered_monoid.lean
36a0f49c65bc9b2869d4586b78f860a0ecedaac1
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
37,159
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.group.with_one import algebra.group.type_tags import algebra.group.prod import algebra.order_functions import order.bounded_lattice import algebra.ordered_monoid_lemmas /-! # Ordered monoids This file develops the basics of ordered monoids. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true universe u variable {α : Type u} /-- An ordered commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c * a ≤ c * b` (multiplication is monotone) * `a * b < a * c → b < c`. -/ @[protect_proj, ancestor comm_monoid partial_order] class ordered_comm_monoid (α : Type*) extends comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) /-- An ordered (additive) commutative monoid is a commutative monoid with a partial order such that * `a ≤ b → c + a ≤ c + b` (addition is monotone) * `a + b < a + c → b < c`. -/ @[protect_proj, ancestor add_comm_monoid partial_order] class ordered_add_comm_monoid (α : Type*) extends add_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (lt_of_add_lt_add_left : ∀ a b c : α, a + b < a + c → b < c) attribute [to_additive] ordered_comm_monoid section ordered_instances @[to_additive] instance ordered_comm_monoid.to_covariant_class_left (M : Type*) [ordered_comm_monoid M] : covariant_class M M (*) (≤) := { elim := λ a b c bc, ordered_comm_monoid.mul_le_mul_left _ _ bc a } @[to_additive] instance ordered_comm_monoid.to_contravariant_class_left (M : Type*) [ordered_comm_monoid M] : contravariant_class M M (*) (<) := { elim := λ a b c, ordered_comm_monoid.lt_of_mul_lt_mul_left _ _ _ } /- This instance can be proven with `by apply_instance`. However, `with_bot ℕ` does not pick up a `covariant_class M M (function.swap (*)) (≤)` instance without it (see PR #7940). -/ @[to_additive] instance ordered_comm_monoid.to_covariant_class_right (M : Type*) [ordered_comm_monoid M] : covariant_class M M (function.swap (*)) (≤) := covariant_swap_mul_le_of_covariant_mul_le M /- This instance can be proven with `by apply_instance`. However, by analogy with the instance `ordered_comm_monoid.to_covariant_class_right` above, I imagine that without this instance, some Type would not have a `contravariant_class M M (function.swap (*)) (≤)` instance. -/ @[to_additive] instance ordered_comm_monoid.to_contravariant_class_right (M : Type*) [ordered_comm_monoid M] : contravariant_class M M (function.swap (*)) (<) := contravariant_swap_mul_lt_of_contravariant_mul_lt M end ordered_instances /-- An `ordered_comm_monoid` with one-sided 'division' in the sense that if `a ≤ b`, there is some `c` for which `a * c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_monoid`. -/ class has_exists_mul_of_le (α : Type u) [ordered_comm_monoid α] : Prop := (exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a * c) /-- An `ordered_add_comm_monoid` with one-sided 'subtraction' in the sense that if `a ≤ b`, then there is some `c` for which `a + c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_add_monoid`. -/ class has_exists_add_of_le (α : Type u) [ordered_add_comm_monoid α] : Prop := (exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a + c) attribute [to_additive] has_exists_mul_of_le export has_exists_mul_of_le (exists_mul_of_le) export has_exists_add_of_le (exists_add_of_le) /-- A linearly ordered additive commutative monoid. -/ @[protect_proj, ancestor linear_order ordered_add_comm_monoid] class linear_ordered_add_comm_monoid (α : Type*) extends linear_order α, ordered_add_comm_monoid α := (lt_of_add_lt_add_left := λ x y z, by { -- type-class inference uses `a : linear_order α` which it can't unfold, unless we provide this! -- `lt_iff_le_not_le` gets filled incorrectly with `autoparam` if we don't provide that field. letI : linear_order α := by refine { le := le, lt := lt, lt_iff_le_not_le := _, .. }; assumption, apply lt_imp_lt_of_le_imp_le, exact λ h, add_le_add_left _ _ h _ }) /-- A linearly ordered commutative monoid. -/ @[protect_proj, ancestor linear_order ordered_comm_monoid, to_additive] class linear_ordered_comm_monoid (α : Type*) extends linear_order α, ordered_comm_monoid α := (lt_of_mul_lt_mul_left := λ x y z, by { -- type-class inference uses `a : linear_order α` which it can't unfold, unless we provide this! -- `lt_iff_le_not_le` gets filled incorrectly with `autoparam` if we don't provide that field. letI : linear_order α := by refine { le := le, lt := lt, lt_iff_le_not_le := _, .. }; assumption, apply lt_imp_lt_of_le_imp_le, exact λ h, mul_le_mul_left _ _ h _ }) /-- A linearly ordered commutative monoid with a zero element. -/ class linear_ordered_comm_monoid_with_zero (α : Type*) extends linear_ordered_comm_monoid α, comm_monoid_with_zero α := (zero_le_one : (0 : α) ≤ 1) /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid order_top] class linear_ordered_add_comm_monoid_with_top (α : Type*) extends linear_ordered_add_comm_monoid α, order_top α := (top_add' : ∀ x : α, ⊤ + x = ⊤) section linear_ordered_add_comm_monoid_with_top variables [linear_ordered_add_comm_monoid_with_top α] {a b : α} @[simp] lemma top_add (a : α) : ⊤ + a = ⊤ := linear_ordered_add_comm_monoid_with_top.top_add' a @[simp] lemma add_top (a : α) : a + ⊤ = ⊤ := trans (add_comm _ _) (top_add _) end linear_ordered_add_comm_monoid_with_top /-- Pullback an `ordered_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_add_comm_monoid "Pullback an `ordered_add_comm_monoid` under an injective map."] def function.injective.ordered_comm_monoid [ordered_comm_monoid α] {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_comm_monoid β := { mul_le_mul_left := λ a b ab c, show f (c * a) ≤ f (c * b), by { rw [mul, mul], apply mul_le_mul_left', exact ab }, lt_of_mul_lt_mul_left := λ a b c bc, show f b < f c, from lt_of_mul_lt_mul_left' (by rwa [← mul, ← mul] : (f a) * _ < _), ..partial_order.lift f hf, ..hf.comm_monoid f one mul } /-- Pullback a `linear_ordered_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_add_comm_monoid "Pullback an `ordered_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_comm_monoid [linear_ordered_comm_monoid α] {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_comm_monoid β := { .. hf.ordered_comm_monoid f one mul, .. linear_order.lift f hf } lemma bit0_pos [ordered_add_comm_monoid α] {a : α} (h : 0 < a) : 0 < bit0 a := add_pos h h namespace units @[to_additive] instance [monoid α] [preorder α] : preorder (units α) := preorder.lift (coe : units α → α) @[simp, norm_cast, to_additive] theorem coe_le_coe [monoid α] [preorder α] {a b : units α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl -- should `to_additive` do this? attribute [norm_cast] add_units.coe_le_coe @[simp, norm_cast, to_additive] theorem coe_lt_coe [monoid α] [preorder α] {a b : units α} : (a : α) < b ↔ a < b := iff.rfl attribute [norm_cast] add_units.coe_lt_coe @[to_additive] instance [monoid α] [partial_order α] : partial_order (units α) := partial_order.lift coe units.ext @[to_additive] instance [monoid α] [linear_order α] : linear_order (units α) := linear_order.lift coe units.ext @[simp, norm_cast, to_additive] theorem max_coe [monoid α] [linear_order α] {a b : units α} : (↑(max a b) : α) = max a b := by by_cases b ≤ a; simp [max, h] attribute [norm_cast] add_units.max_coe @[simp, norm_cast, to_additive] theorem min_coe [monoid α] [linear_order α] {a b : units α} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [min, h] attribute [norm_cast] add_units.min_coe end units namespace with_zero local attribute [semireducible] with_zero instance [preorder α] : preorder (with_zero α) := with_bot.preorder instance [partial_order α] : partial_order (with_zero α) := with_bot.partial_order instance [partial_order α] : order_bot (with_zero α) := with_bot.order_bot lemma zero_le [partial_order α] (a : with_zero α) : 0 ≤ a := order_bot.bot_le a lemma zero_lt_coe [preorder α] (a : α) : (0 : with_zero α) < a := with_bot.bot_lt_coe a @[simp, norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_zero α) < b ↔ a < b := with_bot.coe_lt_coe @[simp, norm_cast] lemma coe_le_coe [partial_order α] {a b : α} : (a : with_zero α) ≤ b ↔ a ≤ b := with_bot.coe_le_coe instance [lattice α] : lattice (with_zero α) := with_bot.lattice instance [linear_order α] : linear_order (with_zero α) := with_bot.linear_order lemma mul_le_mul_left {α : Type u} [has_mul α] [preorder α] [covariant_class α α (*) (≤)] : ∀ (a b : with_zero α), a ≤ b → ∀ (c : with_zero α), c * a ≤ c * b := begin rintro (_ | a) (_ | b) h (_ | c); try { exact λ f hf, option.no_confusion hf }, { exact false.elim (not_lt_of_le h (with_zero.zero_lt_coe a))}, { simp_rw [some_eq_coe] at h ⊢, norm_cast at h ⊢, exact covariant_class.elim _ h } end lemma lt_of_mul_lt_mul_left {α : Type u} [has_mul α] [partial_order α] [contravariant_class α α (*) (<)] : ∀ (a b c : with_zero α), a * b < a * c → b < c := begin rintro (_ | a) (_ | b) (_ | c) h; try { exact false.elim (lt_irrefl none h) }, { exact with_zero.zero_lt_coe c }, { exact false.elim (not_le_of_lt h (with_zero.zero_le _)) }, { simp_rw [some_eq_coe] at h ⊢, norm_cast at h ⊢, apply lt_of_mul_lt_mul_left' h } end instance [ordered_comm_monoid α] : ordered_comm_monoid (with_zero α) := { mul_le_mul_left := with_zero.mul_le_mul_left, lt_of_mul_lt_mul_left := with_zero.lt_of_mul_lt_mul_left, ..with_zero.comm_monoid_with_zero, ..with_zero.partial_order } /- Note 1 : the below is not an instance because it requires `zero_le`. It seems like a rather pathological definition because α already has a zero. Note 2 : there is no multiplicative analogue because it does not seem necessary. Mathematicians might be more likely to use the order-dual version, where all elements are ≤ 1 and then 1 is the top element. -/ /-- If `0` is the least element in `α`, then `with_zero α` is an `ordered_add_comm_monoid`. -/ def ordered_add_comm_monoid [ordered_add_comm_monoid α] (zero_le : ∀ a : α, 0 ≤ a) : ordered_add_comm_monoid (with_zero α) := begin suffices, refine { add_le_add_left := this, ..with_zero.partial_order, ..with_zero.add_comm_monoid, .. }, { intros a b c h, have h' := lt_iff_le_not_le.1 h, rw lt_iff_le_not_le at ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases c with c, { cases h'.2 (this _ _ bot_le a) }, { refine ⟨_, rfl, _⟩, cases a with a, { exact with_bot.some_le_some.1 h'.1 }, { exact le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h), } } }, { intros a b h c ca h₂, cases b with b, { rw le_antisymm h bot_le at h₂, exact ⟨_, h₂, le_refl _⟩ }, cases a with a, { change c + 0 = some ca at h₂, simp at h₂, simp [h₂], exact ⟨_, rfl, by simpa using add_le_add_left (zero_le b) _⟩ }, { simp at h, cases c with c; change some _ = _ at h₂; simp [-add_comm] at h₂; subst ca; refine ⟨_, rfl, _⟩, { exact h }, { exact add_le_add_left h _ } } } end end with_zero namespace with_top section has_one variables [has_one α] @[to_additive] instance : has_one (with_top α) := ⟨(1 : α)⟩ @[simp, to_additive] lemma coe_one : ((1 : α) : with_top α) = 1 := rfl @[simp, to_additive] lemma coe_eq_one {a : α} : (a : with_top α) = 1 ↔ a = 1 := coe_eq_coe @[simp, to_additive] theorem one_eq_coe {a : α} : 1 = (a : with_top α) ↔ a = 1 := trans eq_comm coe_eq_one attribute [norm_cast] coe_one coe_eq_one coe_zero coe_eq_zero one_eq_coe zero_eq_coe @[simp, to_additive] theorem top_ne_one : ⊤ ≠ (1 : with_top α) . @[simp, to_additive] theorem one_ne_top : (1 : with_top α) ≠ ⊤ . end has_one instance [has_add α] : has_add (with_top α) := ⟨λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a + b))⟩ local attribute [semireducible] with_zero instance [add_semigroup α] : add_semigroup (with_top α) := { add := (+), ..(infer_instance : add_semigroup (additive (with_zero (multiplicative α)))) } @[norm_cast] lemma coe_add [has_add α] {a b : α} : ((a + b : α) : with_top α) = a + b := rfl @[norm_cast] lemma coe_bit0 [has_add α] {a : α} : ((bit0 a : α) : with_top α) = bit0 a := rfl @[norm_cast] lemma coe_bit1 [has_add α] [has_one α] {a : α} : ((bit1 a : α) : with_top α) = bit1 a := rfl @[simp] lemma add_top [has_add α] : ∀{a : with_top α}, a + ⊤ = ⊤ | none := rfl | (some a) := rfl @[simp] lemma top_add [has_add α] {a : with_top α} : ⊤ + a = ⊤ := rfl lemma add_eq_top [has_add α] {a b : with_top α} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by cases a; cases b; simp [none_eq_top, some_eq_coe, ←with_top.coe_add, ←with_zero.coe_add] lemma add_lt_top [has_add α] [partial_order α] {a b : with_top α} : a + b < ⊤ ↔ a < ⊤ ∧ b < ⊤ := by simp [lt_top_iff_ne_top, add_eq_top, not_or_distrib] lemma add_eq_coe [has_add α] : ∀ {a b : with_top α} {c : α}, a + b = c ↔ ∃ (a' b' : α), ↑a' = a ∧ ↑b' = b ∧ a' + b' = c | none b c := by simp [none_eq_top] | (some a) none c := by simp [none_eq_top] | (some a) (some b) c := by simp only [some_eq_coe, ← coe_add, coe_eq_coe, exists_and_distrib_left, exists_eq_left] instance [add_comm_semigroup α] : add_comm_semigroup (with_top α) := { ..@additive.add_comm_semigroup _ $ @with_zero.comm_semigroup (multiplicative α) _ } instance [add_monoid α] : add_monoid (with_top α) := { zero := some 0, add := (+), ..@additive.add_monoid _ $ @monoid_with_zero.to_monoid _ $ @with_zero.monoid_with_zero (multiplicative α) _ } instance [add_comm_monoid α] : add_comm_monoid (with_top α) := { zero := 0, add := (+), ..@additive.add_comm_monoid _ $ @comm_monoid_with_zero.to_comm_monoid _ $ @with_zero.comm_monoid_with_zero (multiplicative α) _ } instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_top α) := { add_le_add_left := begin rintros a b h (_|c), { simp [none_eq_top] }, rcases b with (_|b), { simp [none_eq_top] }, rcases le_coe_iff.1 h with ⟨a, rfl, h⟩, simp only [some_eq_coe, ← coe_add, coe_le_coe] at h ⊢, exact add_le_add_left h c end, lt_of_add_lt_add_left := begin intros a b c h, rcases lt_iff_exists_coe.1 h with ⟨ab, hab, hlt⟩, rcases add_eq_coe.1 hab with ⟨a, b, rfl, rfl, rfl⟩, rw coe_lt_iff, rintro c rfl, exact lt_of_add_lt_add_left (coe_lt_coe.1 hlt) end, ..with_top.partial_order, ..with_top.add_comm_monoid } instance [linear_ordered_add_comm_monoid α] : linear_ordered_add_comm_monoid_with_top (with_top α) := { top_add' := λ x, with_top.top_add, ..with_top.order_top, ..with_top.linear_order, ..with_top.ordered_add_comm_monoid, ..option.nontrivial } /-- Coercion from `α` to `with_top α` as an `add_monoid_hom`. -/ def coe_add_hom [add_monoid α] : α →+ with_top α := ⟨coe, rfl, λ _ _, rfl⟩ @[simp] lemma coe_coe_add_hom [add_monoid α] : ⇑(coe_add_hom : α →+ with_top α) = coe := rfl @[simp] lemma zero_lt_top [ordered_add_comm_monoid α] : (0 : with_top α) < ⊤ := coe_lt_top 0 @[simp, norm_cast] lemma zero_lt_coe [ordered_add_comm_monoid α] (a : α) : (0 : with_top α) < a ↔ 0 < a := coe_lt_coe end with_top namespace with_bot instance [has_zero α] : has_zero (with_bot α) := with_top.has_zero instance [has_one α] : has_one (with_bot α) := with_top.has_one instance [add_semigroup α] : add_semigroup (with_bot α) := with_top.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (with_bot α) := with_top.add_comm_semigroup instance [add_monoid α] : add_monoid (with_bot α) := with_top.add_monoid instance [add_comm_monoid α] : add_comm_monoid (with_bot α) := with_top.add_comm_monoid instance [ordered_add_comm_monoid α] : ordered_add_comm_monoid (with_bot α) := begin suffices, refine { add_le_add_left := this, ..with_bot.partial_order, ..with_bot.add_comm_monoid, ..}, { intros a b c h, have h' := h, rw lt_iff_le_not_le at h' ⊢, refine ⟨λ b h₂, _, λ h₂, h'.2 $ this _ _ h₂ _⟩, cases h₂, cases a with a, { exact (not_le_of_lt h).elim bot_le }, cases c with c, { exact (not_le_of_lt h).elim bot_le }, { exact ⟨_, rfl, le_of_lt (lt_of_add_lt_add_left $ with_bot.some_lt_some.1 h)⟩ } }, { intros a b h c ca h₂, cases c with c, {cases h₂}, cases a with a; cases h₂, cases b with b, {cases le_antisymm h bot_le}, simp at h, exact ⟨_, rfl, add_le_add_left h _⟩, } end instance [linear_ordered_add_comm_monoid α] : linear_ordered_add_comm_monoid (with_bot α) := { ..with_bot.linear_order, ..with_bot.ordered_add_comm_monoid } -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_zero [has_zero α] : ((0 : α) : with_bot α) = 0 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_one [has_one α] : ((1 : α) : with_bot α) = 1 := rfl -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_eq_zero {α : Type*} [add_monoid α] {a : α} : (a : with_bot α) = 0 ↔ a = 0 := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_add [add_semigroup α] (a b : α) : ((a + b : α) : with_bot α) = a + b := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit0 [add_semigroup α] {a : α} : ((bit0 a : α) : with_bot α) = bit0 a := by norm_cast -- `by norm_cast` proves this lemma, so I did not tag it with `norm_cast` lemma coe_bit1 [add_semigroup α] [has_one α] {a : α} : ((bit1 a : α) : with_bot α) = bit1 a := by norm_cast @[simp] lemma bot_add [ordered_add_comm_monoid α] (a : with_bot α) : ⊥ + a = ⊥ := rfl @[simp] lemma add_bot [ordered_add_comm_monoid α] (a : with_bot α) : a + ⊥ = ⊥ := by cases a; refl end with_bot /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the subtractibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other nontrivial `ordered_add_comm_group`s. -/ @[protect_proj, ancestor ordered_add_comm_monoid order_bot] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, order_bot α := (le_iff_exists_add : ∀ a b : α, a ≤ b ↔ ∃ c, b = a + c) /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a * c`. Examples seem rare; it seems more likely that the `order_dual` of a naturally-occurring lattice satisfies this than the lattice itself (for example, dual of the lattice of ideals of a PID or Dedekind domain satisfy this; collections of all things ≤ 1 seem to be more natural that collections of all things ≥ 1). -/ @[protect_proj, ancestor ordered_comm_monoid order_bot, to_additive] class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α, order_bot α := (le_iff_exists_mul : ∀ a b : α, a ≤ b ↔ ∃ c, b = a * c) section canonically_ordered_monoid variables [canonically_ordered_monoid α] {a b c d : α} @[to_additive] lemma le_iff_exists_mul : a ≤ b ↔ ∃c, b = a * c := canonically_ordered_monoid.le_iff_exists_mul a b @[to_additive] lemma self_le_mul_right (a b : α) : a ≤ a * b := le_iff_exists_mul.mpr ⟨b, rfl⟩ @[to_additive] lemma self_le_mul_left (a b : α) : a ≤ b * a := by { rw [mul_comm], exact self_le_mul_right a b } @[simp, to_additive zero_le] lemma one_le (a : α) : 1 ≤ a := le_iff_exists_mul.mpr ⟨a, (one_mul _).symm⟩ @[simp, to_additive] lemma bot_eq_one : (⊥ : α) = 1 := le_antisymm bot_le (one_le ⊥) @[simp, to_additive] lemma mul_eq_one_iff : a * b = 1 ↔ a = 1 ∧ b = 1 := mul_eq_one_iff' (one_le _) (one_le _) @[simp, to_additive] lemma le_one_iff_eq_one : a ≤ 1 ↔ a = 1 := iff.intro (assume h, le_antisymm h (one_le a)) (assume h, h ▸ le_refl a) @[to_additive] lemma one_lt_iff_ne_one : 1 < a ↔ a ≠ 1 := iff.intro ne_of_gt $ assume hne, lt_of_le_of_ne (one_le _) hne.symm @[to_additive] lemma exists_pos_mul_of_lt (h : a < b) : ∃ c > 1, a * c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_mul.1 h.le, refine ⟨c, one_lt_iff_ne_one.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end @[to_additive] lemma le_mul_left (h : a ≤ c) : a ≤ b * c := calc a = 1 * a : by simp ... ≤ b * c : mul_le_mul' (one_le _) h @[to_additive] lemma le_mul_self : a ≤ b * a := le_mul_left (le_refl a) @[to_additive] lemma le_mul_right (h : a ≤ b) : a ≤ b * c := calc a = a * 1 : by simp ... ≤ b * c : mul_le_mul' h (one_le _) @[to_additive] lemma le_self_mul : a ≤ a * c := le_mul_right (le_refl a) local attribute [semireducible] with_zero -- This instance looks absurd: a monoid already has a zero /-- Adding a new zero to a canonically ordered additive monoid produces another one. -/ instance with_zero.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] : canonically_ordered_add_monoid (with_zero α) := { le_iff_exists_add := λ a b, begin cases a with a, { exact iff_of_true bot_le ⟨b, (zero_add b).symm⟩ }, cases b with b, { exact iff_of_false (mt (le_antisymm bot_le) (by simp)) (λ ⟨c, h⟩, by cases c; cases h) }, { simp [le_iff_exists_add, -add_comm], split; intro h; rcases h with ⟨c, h⟩, { exact ⟨some c, congr_arg some h⟩ }, { cases c; cases h, { exact ⟨_, (add_zero _).symm⟩ }, { exact ⟨_, rfl⟩ } } } end, bot := 0, bot_le := assume a a' h, option.no_confusion h, .. with_zero.ordered_add_comm_monoid zero_le } instance with_top.canonically_ordered_add_monoid {α : Type u} [canonically_ordered_add_monoid α] : canonically_ordered_add_monoid (with_top α) := { le_iff_exists_add := assume a b, match a, b with | a, none := show a ≤ ⊤ ↔ ∃c, ⊤ = a + c, by simp; refine ⟨⊤, _⟩; cases a; refl | (some a), (some b) := show (a:with_top α) ≤ ↑b ↔ ∃c:with_top α, ↑b = ↑a + c, begin simp [canonically_ordered_add_monoid.le_iff_exists_add, -add_comm], split, { rintro ⟨c, rfl⟩, refine ⟨c, _⟩, norm_cast }, { exact assume h, match b, h with _, ⟨some c, rfl⟩ := ⟨_, rfl⟩ end } end | none, some b := show (⊤ : with_top α) ≤ b ↔ ∃c:with_top α, ↑b = ⊤ + c, by simp end, .. with_top.order_bot, .. with_top.ordered_add_comm_monoid } @[priority 100, to_additive] instance canonically_ordered_monoid.has_exists_mul_of_le (α : Type u) [canonically_ordered_monoid α] : has_exists_mul_of_le α := { exists_mul_of_le := λ a b hab, le_iff_exists_mul.mp hab } end canonically_ordered_monoid lemma pos_of_gt {M : Type*} [canonically_ordered_add_monoid M] {n m : M} (h : n < m) : 0 < m := lt_of_le_of_lt (zero_le _) h /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_add_monoid linear_order] class canonically_linear_ordered_add_monoid (α : Type*) extends canonically_ordered_add_monoid α, linear_order α /-- A canonically linear-ordered monoid is a canonically ordered monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_monoid linear_order, to_additive] class canonically_linear_ordered_monoid (α : Type*) extends canonically_ordered_monoid α, linear_order α section canonically_linear_ordered_monoid variables @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_linear_ordered_monoid.semilattice_sup_bot [canonically_linear_ordered_monoid α] : semilattice_sup_bot α := { ..lattice_of_linear_order, ..canonically_ordered_monoid.to_order_bot α } instance with_top.canonically_linear_ordered_add_monoid (α : Type*) [canonically_linear_ordered_add_monoid α] : canonically_linear_ordered_add_monoid (with_top α) := { .. (infer_instance : canonically_ordered_add_monoid (with_top α)), .. (infer_instance : linear_order (with_top α)) } @[to_additive] lemma min_mul_distrib [canonically_linear_ordered_monoid α] (a b c : α) : min a (b * c) = min a (min a b * min a c) := begin cases le_total a b with hb hb, { simp [hb, le_mul_right] }, { cases le_total a c with hc hc, { simp [hc, le_mul_left] }, { simp [hb, hc] } } end @[to_additive] lemma min_mul_distrib' [canonically_linear_ordered_monoid α] (a b c : α) : min (a * b) c = min (min a c * min b c) c := by simpa [min_comm _ c] using min_mul_distrib c a b end canonically_linear_ordered_monoid /-- An ordered cancellative additive commutative monoid is an additive commutative monoid with a partial order, in which addition is cancellative and monotone. -/ @[protect_proj, ancestor add_cancel_comm_monoid partial_order] class ordered_cancel_add_comm_monoid (α : Type u) extends add_cancel_comm_monoid α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c) /-- An ordered cancellative commutative monoid is a commutative monoid with a partial order, in which multiplication is cancellative and monotone. -/ @[protect_proj, ancestor cancel_comm_monoid partial_order, to_additive] class ordered_cancel_comm_monoid (α : Type u) extends cancel_comm_monoid α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] {a b c d : α} @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_cancel_comm_monoid.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, lt_of_le_not_le (ordered_cancel_comm_monoid.le_of_mul_le_mul_left a b c h.le) $ mt (λ h, ordered_cancel_comm_monoid.mul_le_mul_left _ _ h _) (not_le_of_gt h), ..‹ordered_cancel_comm_monoid α› } /-- Pullback an `ordered_cancel_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_cancel_add_comm_monoid "Pullback an `ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.ordered_cancel_comm_monoid {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : ordered_cancel_comm_monoid β := { le_of_mul_le_mul_left := λ a b c (bc : f (a * b) ≤ f (a * c)), (mul_le_mul_iff_left (f a)).mp (by rwa [← mul, ← mul]), ..hf.left_cancel_semigroup f mul, ..hf.ordered_comm_monoid f one mul } end ordered_cancel_comm_monoid section ordered_cancel_add_comm_monoid variable [ordered_cancel_add_comm_monoid α] lemma with_top.add_lt_add_iff_left : ∀{a b c : with_top α}, a < ⊤ → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊤ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_top.none_eq_top, with_top.some_eq_coe, with_top.coe_lt_top, with_top.coe_lt_coe], { norm_cast, exact with_top.coe_lt_top _ }, { norm_cast, exact add_lt_add_iff_left _ } end lemma with_bot.add_lt_add_iff_left : ∀{a b c : with_bot α}, ⊥ < a → (a + c < a + b ↔ c < b) | none := assume b c h, (lt_irrefl ⊥ h).elim | (some a) := begin assume b c h, cases b; cases c; simp [with_bot.none_eq_bot, with_bot.some_eq_coe, with_bot.bot_lt_coe, with_bot.coe_lt_coe], { norm_cast, exact with_bot.bot_lt_coe _ }, { norm_cast, exact add_lt_add_iff_left _ } end local attribute [semireducible] with_zero lemma with_top.add_lt_add_iff_right {a b c : with_top α} : a < ⊤ → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_top.add_lt_add_iff_left _ _ a b c lemma with_bot.add_lt_add_iff_right {a b c : with_bot α} : ⊥ < a → (c + a < b + a ↔ c < b) := by simpa [add_comm] using @with_bot.add_lt_add_iff_left _ _ a b c end ordered_cancel_add_comm_monoid /-! Some lemmas about types that have an ordering and a binary operation, with no rules relating them. -/ @[to_additive] lemma fn_min_mul_fn_max {β} [linear_order α] [comm_semigroup β] (f : α → β) (n m : α) : f (min n m) * f (max n m) = f n * f m := by { cases le_total n m with h h; simp [h, mul_comm] } @[to_additive] lemma min_mul_max [linear_order α] [comm_semigroup α] (n m : α) : min n m * max n m = n * m := fn_min_mul_fn_max id n m /-- A linearly ordered cancellative additive commutative monoid is an additive commutative monoid with a decidable linear order in which addition is cancellative and monotone. -/ @[protect_proj, ancestor ordered_cancel_add_comm_monoid linear_ordered_add_comm_monoid] class linear_ordered_cancel_add_comm_monoid (α : Type u) extends ordered_cancel_add_comm_monoid α, linear_ordered_add_comm_monoid α /-- A linearly ordered cancellative commutative monoid is a commutative monoid with a linear order in which multiplication is cancellative and monotone. -/ @[protect_proj, ancestor ordered_cancel_comm_monoid linear_ordered_comm_monoid, to_additive] class linear_ordered_cancel_comm_monoid (α : Type u) extends ordered_cancel_comm_monoid α, linear_ordered_comm_monoid α section covariant_class_mul_le variables [cancel_comm_monoid α] [linear_order α] [covariant_class α α (*) (≤)] @[to_additive] lemma min_mul_mul_left (a b c : α) : min (a * b) (a * c) = a * min b c := (monotone_id.const_mul' a).map_min.symm @[to_additive] lemma min_mul_mul_right (a b c : α) : min (a * c) (b * c) = min a b * c := (monotone_id.mul_const' c).map_min.symm @[to_additive] lemma max_mul_mul_left (a b c : α) : max (a * b) (a * c) = a * max b c := (monotone_id.const_mul' a).map_max.symm @[to_additive] lemma max_mul_mul_right (a b c : α) : max (a * c) (b * c) = max a b * c := (monotone_id.mul_const' c).map_max.symm @[to_additive] lemma min_le_mul_of_one_le_right {a b : α} (hb : 1 ≤ b) : min a b ≤ a * b := min_le_iff.2 $ or.inl $ le_mul_of_one_le_right' hb @[to_additive] lemma min_le_mul_of_one_le_left {a b : α} (ha : 1 ≤ a) : min a b ≤ a * b := min_le_iff.2 $ or.inr $ le_mul_of_one_le_left' ha @[to_additive] lemma max_le_mul_of_one_le {a b : α} (ha : 1 ≤ a) (hb : 1 ≤ b) : max a b ≤ a * b := max_le_iff.2 ⟨le_mul_of_one_le_right' hb, le_mul_of_one_le_left' ha⟩ end covariant_class_mul_le section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_comm_monoid α] /-- Pullback a `linear_ordered_cancel_comm_monoid` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_cancel_add_comm_monoid "Pullback a `linear_ordered_cancel_add_comm_monoid` under an injective map."] def function.injective.linear_ordered_cancel_comm_monoid {β : Type*} [has_one β] [has_mul β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) : linear_ordered_cancel_comm_monoid β := { ..hf.linear_ordered_comm_monoid f one mul, ..hf.ordered_cancel_comm_monoid f one mul } end linear_ordered_cancel_comm_monoid namespace order_dual @[to_additive] instance [h : has_mul α] : has_mul (order_dual α) := h @[to_additive] instance [ordered_comm_monoid α] : ordered_comm_monoid (order_dual α) := { mul_le_mul_left := λ a b h c, show (id c : α) * b ≤ c * a, from mul_le_mul_left' h _, lt_of_mul_lt_mul_left := λ a b c h, by apply lt_of_mul_lt_mul_left' (by convert h : (id a : α) * c < a * b), ..order_dual.partial_order α, ..show comm_monoid α, by apply_instance } @[to_additive ordered_cancel_add_comm_monoid.to_contravariant_class] instance ordered_cancel_comm_monoid.to_contravariant_class [ordered_cancel_comm_monoid α] : contravariant_class (order_dual α) (order_dual α) has_mul.mul has_le.le := { elim := λ a b c bc, (ordered_cancel_comm_monoid.le_of_mul_le_mul_left a c b (dual_le.mp bc)) } @[to_additive] instance [ordered_cancel_comm_monoid α] : ordered_cancel_comm_monoid (order_dual α) := { le_of_mul_le_mul_left := λ a b c : α, le_of_mul_le_mul_left', mul_left_cancel := @mul_left_cancel α _, ..order_dual.ordered_comm_monoid } @[to_additive] instance [linear_ordered_cancel_comm_monoid α] : linear_ordered_cancel_comm_monoid (order_dual α) := { .. order_dual.linear_order α, .. order_dual.ordered_cancel_comm_monoid } @[to_additive] instance [linear_ordered_comm_monoid α] : linear_ordered_comm_monoid (order_dual α) := { .. order_dual.linear_order α, .. order_dual.ordered_comm_monoid } end order_dual namespace prod variables {M N : Type*} @[to_additive] instance [ordered_cancel_comm_monoid M] [ordered_cancel_comm_monoid N] : ordered_cancel_comm_monoid (M × N) := { mul_le_mul_left := λ a b h c, ⟨mul_le_mul_left' h.1 _, mul_le_mul_left' h.2 _⟩, le_of_mul_le_mul_left := λ a b c h, ⟨le_of_mul_le_mul_left' h.1, le_of_mul_le_mul_left' h.2⟩, .. prod.cancel_comm_monoid, .. prod.partial_order M N } end prod section type_tags instance : Π [preorder α], preorder (multiplicative α) := id instance : Π [preorder α], preorder (additive α) := id instance : Π [partial_order α], partial_order (multiplicative α) := id instance : Π [partial_order α], partial_order (additive α) := id instance : Π [linear_order α], linear_order (multiplicative α) := id instance : Π [linear_order α], linear_order (additive α) := id instance [ordered_add_comm_monoid α] : ordered_comm_monoid (multiplicative α) := { mul_le_mul_left := @ordered_add_comm_monoid.add_le_add_left α _, lt_of_mul_lt_mul_left := @ordered_add_comm_monoid.lt_of_add_lt_add_left α _, ..multiplicative.partial_order, ..multiplicative.comm_monoid } instance [ordered_comm_monoid α] : ordered_add_comm_monoid (additive α) := { add_le_add_left := @ordered_comm_monoid.mul_le_mul_left α _, lt_of_add_lt_add_left := @ordered_comm_monoid.lt_of_mul_lt_mul_left α _, ..additive.partial_order, ..additive.add_comm_monoid } instance [ordered_cancel_add_comm_monoid α] : ordered_cancel_comm_monoid (multiplicative α) := { le_of_mul_le_mul_left := @ordered_cancel_add_comm_monoid.le_of_add_le_add_left α _, ..multiplicative.left_cancel_semigroup, ..multiplicative.ordered_comm_monoid } instance [ordered_cancel_comm_monoid α] : ordered_cancel_add_comm_monoid (additive α) := { le_of_add_le_add_left := @ordered_cancel_comm_monoid.le_of_mul_le_mul_left α _, ..additive.add_left_cancel_semigroup, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_monoid α] : linear_ordered_comm_monoid (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_monoid } instance [linear_ordered_comm_monoid α] : linear_ordered_add_comm_monoid (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_monoid } instance [sub_neg_monoid α] : sub_neg_monoid (order_dual α) := { ..show sub_neg_monoid α, from infer_instance } instance [div_inv_monoid α] : div_inv_monoid (order_dual α) := { ..show div_inv_monoid α, from infer_instance } end type_tags
e48c92cac9c051aa2959b76a84aa86041fe8e3d4
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/lagrange.lean
905064fb7fe3fa0a59632c1b90a26ec3b4f7e684
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,086
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau. -/ import ring_theory.polynomial import algebra.big_operators.basic /-! # Lagrange interpolation ## Main definitions * `lagrange.basis s x` where `s : finset F` and `x : F`: the Lagrange basis polynomial that evaluates to `1` at `x` and `0` at other elements of `s`. * `lagrange.interpolate s f` where `s : finset F` and `f : s → F`: the Lagrange interpolant that evaluates to `f x` at `x` for `x ∈ s`. -/ noncomputable theory open_locale big_operators classical universe u namespace lagrange variables {F : Type u} [decidable_eq F] [field F] (s : finset F) variables {F' : Type u} [field F'] (s' : finset F') open polynomial /-- Lagrange basis polynomials that evaluate to 1 at `x` and 0 at other elements of `s`. -/ def basis (x : F) : polynomial F := ∏ y in s.erase x, C (x - y)⁻¹ * (X - C y) @[simp] theorem basis_empty (x : F) : basis ∅ x = 1 := rfl @[simp] theorem eval_basis_self (x : F) : (basis s x).eval x = 1 := begin rw [basis, ← (s.erase x).prod_hom (eval x), finset.prod_eq_one], intros y hy, simp_rw [eval_mul, eval_sub, eval_C, eval_X], exact inv_mul_cancel (sub_ne_zero_of_ne (finset.ne_of_mem_erase hy).symm) end @[simp] theorem eval_basis_ne (x y : F) (h1 : y ∈ s) (h2 : y ≠ x) : (basis s x).eval y = 0 := begin rw [basis, ← (s.erase x).prod_hom (eval y), finset.prod_eq_zero (finset.mem_erase.2 ⟨h2, h1⟩)], simp_rw [eval_mul, eval_sub, eval_C, eval_X, sub_self, mul_zero] end theorem eval_basis (x y : F) (h : y ∈ s) : (basis s x).eval y = if y = x then 1 else 0 := by { split_ifs with H, { subst H, apply eval_basis_self }, { exact eval_basis_ne s x y h H } } @[simp] theorem nat_degree_basis (x : F) (hx : x ∈ s) : (basis s x).nat_degree = s.card - 1 := begin unfold basis, generalize hsx : s.erase x = sx, have : x ∉ sx := hsx ▸ finset.not_mem_erase x s, rw [← finset.insert_erase hx, hsx, finset.card_insert_of_not_mem this, nat.add_sub_cancel], clear hx hsx s, revert this, apply sx.induction_on, { intros hx, rw [finset.prod_empty, nat_degree_one], refl }, { intros y s hys ih hx, rw [finset.mem_insert, not_or_distrib] at hx, have h1 : C (x - y)⁻¹ ≠ C 0 := λ h, hx.1 (eq_of_sub_eq_zero $ inv_eq_zero.1 $ C_inj.1 h), have h2 : X ^ 1 - C y ≠ 0 := by convert X_pow_sub_C_ne_zero zero_lt_one y, rw C_0 at h1, rw pow_one at h2, rw [finset.prod_insert hys, nat_degree_mul (mul_ne_zero h1 h2), ih hx.2, finset.card_insert_of_not_mem hys, nat_degree_mul h1 h2, nat_degree_C, zero_add, nat_degree, degree_X_sub_C, add_comm], refl, rw [ne, finset.prod_eq_zero_iff], rintro ⟨z, hzs, hz⟩, rw mul_eq_zero at hz, cases hz with hz hz, { rw [← C_0, C_inj, inv_eq_zero, sub_eq_zero] at hz, exact hx.2 (hz.symm ▸ hzs) }, { rw ← pow_one (X : polynomial F) at hz, exact X_pow_sub_C_ne_zero zero_lt_one _ hz } } end variables (f : (↑s : set F) → F) /-- Lagrange interpolation: given a finset `s` and a function `f : s → F`, `interpolate s f` is the unique polynomial of degree `< s.card` that takes value `f x` on all `x` in `s`. -/ def interpolate : polynomial F := ∑ x in s.attach, C (f x) * basis s x @[simp] theorem interpolate_empty (f) : interpolate (∅ : finset F) f = 0 := rfl @[simp] theorem eval_interpolate (x) (H : x ∈ s) : eval x (interpolate s f) = f ⟨x, H⟩ := begin rw [interpolate, ← finset.sum_hom _ (eval x), finset.sum_eq_single (⟨x, H⟩ : { x // x ∈ s })], { rw [eval_mul, eval_C, subtype.coe_mk, eval_basis_self, mul_one] }, { rintros ⟨y, hy⟩ _ hyx, rw [eval_mul, subtype.coe_mk, eval_basis_ne s y x H, mul_zero], { rintros rfl, exact hyx rfl } }, { intro h, exact absurd (finset.mem_attach _ _) h } end theorem degree_interpolate_lt : (interpolate s f).degree < s.card := if H : s = ∅ then by { subst H, rw [interpolate_empty, degree_zero], exact with_bot.bot_lt_coe _ } else (degree_sum_le _ _).trans_lt $ (finset.sup_lt_iff $ with_bot.bot_lt_coe s.card).2 $ λ b _, calc (C (f b) * basis s b).degree ≤ (C (f b)).degree + (basis s b).degree : degree_mul_le _ _ ... ≤ 0 + (basis s b).degree : add_le_add_right degree_C_le _ ... = (basis s b).degree : zero_add _ ... ≤ (basis s b).nat_degree : degree_le_nat_degree ... = (s.card - 1 : ℕ) : by { rw nat_degree_basis s b b.2 } ... < s.card : with_bot.coe_lt_coe.2 (nat.pred_lt $ mt finset.card_eq_zero.1 H) /-- Linear version of `interpolate`. -/ def linterpolate : ((↑s : set F) → F) →ₗ[F] polynomial F := { to_fun := interpolate s, map_add' := λ f g, by { simp_rw [interpolate, ← finset.sum_add_distrib, ← add_mul, ← C_add], refl }, map_smul' := λ c f, by { simp_rw [interpolate, finset.smul_sum, C_mul', smul_smul], refl } } @[simp] lemma interpolate_add (f g) : interpolate s (f + g) = interpolate s f + interpolate s g := (linterpolate s).map_add f g @[simp] lemma interpolate_zero : interpolate s 0 = 0 := (linterpolate s).map_zero @[simp] lemma interpolate_neg (f) : interpolate s (-f) = -interpolate s f := (linterpolate s).map_neg f @[simp] lemma interpolate_sub (f g) : interpolate s (f - g) = interpolate s f - interpolate s g := (linterpolate s).map_sub f g @[simp] lemma interpolate_smul (c : F) (f) : interpolate s (c • f) = c • interpolate s f := (linterpolate s).map_smul c f theorem eq_zero_of_eval_eq_zero {f : polynomial F'} (hf1 : f.degree < s'.card) (hf2 : ∀ x ∈ s', f.eval x = 0) : f = 0 := by_contradiction $ λ hf3, not_le_of_lt hf1 $ calc (s'.card : with_bot ℕ) ≤ f.roots.to_finset.card : with_bot.coe_le_coe.2 $ finset.card_le_of_subset $ λ x hx, (multiset.mem_to_finset).mpr $ (mem_roots hf3).2 $ hf2 x hx ... ≤ f.roots.card : with_bot.coe_le_coe.2 $ f.roots.to_finset_card_le ... ≤ f.degree : card_roots hf3 theorem eq_of_eval_eq {f g : polynomial F'} (hf : f.degree < s'.card) (hg : g.degree < s'.card) (hfg : ∀ x ∈ s', f.eval x = g.eval x) : f = g := eq_of_sub_eq_zero $ eq_zero_of_eval_eq_zero s' (lt_of_le_of_lt (degree_sub_le f g) $ max_lt hf hg) (λ x hx, by rw [eval_sub, hfg x hx, sub_self]) theorem eq_interpolate (f : polynomial F) (hf : f.degree < s.card) : interpolate s (λ x, f.eval x) = f := eq_of_eval_eq s (degree_interpolate_lt s _) hf $ λ x hx, eval_interpolate s _ x hx /-- Lagrange interpolation induces isomorphism between functions from `s` and polynomials of degree less than `s.card`. -/ def fun_equiv_degree_lt : degree_lt F s.card ≃ₗ[F] ((↑s : set F) → F) := { to_fun := λ f x, f.1.eval x, map_add' := λ f g, funext $ λ x, eval_add, map_smul' := λ c f, funext $ λ x, by { rw [pi.smul_apply, smul_eq_mul, ← @eval_C F c _ x, ← eval_mul, eval_C, C_mul'], refl }, inv_fun := λ f, ⟨interpolate s f, mem_degree_lt.2 $ degree_interpolate_lt s f⟩, left_inv := λ f, subtype.eq $ eq_interpolate s f $ mem_degree_lt.1 f.2, right_inv := λ f, funext $ λ ⟨x, hx⟩, eval_interpolate s f x hx } end lagrange
5d2bb14f2434f324b8271c0c794e20bce61cbef9
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0219.lean
fc8b297b8098ec2f08ae1f24dac5fc20eea1e701
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
67
lean
example : 2 + 3 = 5 := begin generalize h : 3 = x, rw ←h end
f9835489a41b71167683f1fc3a3108db8e2b5dab
9dc8cecdf3c4634764a18254e94d43da07142918
/src/set_theory/game/impartial.lean
0b63c30ebc1176ba717d5d1af44708f30fa4e2b5
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,917
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import set_theory.game.basic import tactic.nth_rewrite.default /-! # Basic definitions about impartial (pre-)games We will define an impartial game, one in which left and right can make exactly the same moves. Our definition differs slightly by saying that the game is always equivalent to its negative, no matter what moves are played. This allows for games such as poker-nim to be classifed as impartial. -/ universe u open_locale pgame namespace pgame /-- The definition for a impartial game, defined using Conway induction. -/ def impartial_aux : pgame → Prop | G := G ≈ -G ∧ (∀ i, impartial_aux (G.move_left i)) ∧ ∀ j, impartial_aux (G.move_right j) using_well_founded { dec_tac := pgame_wf_tac } lemma impartial_aux_def {G : pgame} : G.impartial_aux ↔ G ≈ -G ∧ (∀ i, impartial_aux (G.move_left i)) ∧ ∀ j, impartial_aux (G.move_right j) := by rw impartial_aux /-- A typeclass on impartial games. -/ class impartial (G : pgame) : Prop := (out : impartial_aux G) lemma impartial_iff_aux {G : pgame} : G.impartial ↔ G.impartial_aux := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma impartial_def {G : pgame} : G.impartial ↔ G ≈ -G ∧ (∀ i, impartial (G.move_left i)) ∧ ∀ j, impartial (G.move_right j) := by simpa only [impartial_iff_aux] using impartial_aux_def namespace impartial instance impartial_zero : impartial 0 := by { rw impartial_def, dsimp, simp } instance impartial_star : impartial star := by { rw impartial_def, simpa using impartial.impartial_zero } lemma neg_equiv_self (G : pgame) [h : G.impartial] : G ≈ -G := (impartial_def.1 h).1 @[simp] lemma mk_neg_equiv_self (G : pgame) [h : G.impartial] : -⟦G⟧ = ⟦G⟧ := quot.sound (neg_equiv_self G).symm instance move_left_impartial {G : pgame} [h : G.impartial] (i : G.left_moves) : (G.move_left i).impartial := (impartial_def.1 h).2.1 i instance move_right_impartial {G : pgame} [h : G.impartial] (j : G.right_moves) : (G.move_right j).impartial := (impartial_def.1 h).2.2 j theorem impartial_congr : ∀ {G H : pgame} (e : G ≡r H) [G.impartial], H.impartial | G H := λ e, begin introI h, exact impartial_def.2 ⟨e.symm.equiv.trans ((neg_equiv_self G).trans (neg_equiv_neg_iff.2 e.equiv)), λ i, impartial_congr (e.move_left_symm i), λ j, impartial_congr (e.move_right_symm j)⟩ end using_well_founded { dec_tac := pgame_wf_tac } instance impartial_add : ∀ (G H : pgame) [G.impartial] [H.impartial], (G + H).impartial | G H := begin introsI hG hH, rw impartial_def, refine ⟨(add_congr (neg_equiv_self _) (neg_equiv_self _)).trans (neg_add_relabelling _ _).equiv.symm, λ k, _, λ k, _⟩, { apply left_moves_add_cases k, all_goals { intro i, simp only [add_move_left_inl, add_move_left_inr], apply impartial_add } }, { apply right_moves_add_cases k, all_goals { intro i, simp only [add_move_right_inl, add_move_right_inr], apply impartial_add } } end using_well_founded { dec_tac := pgame_wf_tac } instance impartial_neg : ∀ (G : pgame) [G.impartial], (-G).impartial | G := begin introI hG, rw impartial_def, refine ⟨_, λ i, _, λ i, _⟩, { rw neg_neg, exact (neg_equiv_self G).symm }, { rw move_left_neg', apply impartial_neg }, { rw move_right_neg', apply impartial_neg } end using_well_founded { dec_tac := pgame_wf_tac } variables (G : pgame) [impartial G] lemma nonpos : ¬ 0 < G := λ h, begin have h' := neg_lt_neg_iff.2 h, rw [pgame.neg_zero, lt_congr_left (neg_equiv_self G).symm] at h', exact (h.trans h').false end lemma nonneg : ¬ G < 0 := λ h, begin have h' := neg_lt_neg_iff.2 h, rw [pgame.neg_zero, lt_congr_right (neg_equiv_self G).symm] at h', exact (h.trans h').false end /-- In an impartial game, either the first player always wins, or the second player always wins. -/ lemma equiv_or_fuzzy_zero : G ≈ 0 ∨ G ∥ 0 := begin rcases lt_or_equiv_or_gt_or_fuzzy G 0 with h | h | h | h, { exact ((nonneg G) h).elim }, { exact or.inl h }, { exact ((nonpos G) h).elim }, { exact or.inr h } end @[simp] lemma not_equiv_zero_iff : ¬ G ≈ 0 ↔ G ∥ 0 := ⟨(equiv_or_fuzzy_zero G).resolve_left, fuzzy.not_equiv⟩ @[simp] lemma not_fuzzy_zero_iff : ¬ G ∥ 0 ↔ G ≈ 0 := ⟨(equiv_or_fuzzy_zero G).resolve_right, equiv.not_fuzzy⟩ lemma add_self : G + G ≈ 0 := (add_congr_left (neg_equiv_self G)).trans (add_left_neg_equiv G) @[simp] lemma mk_add_self : ⟦G⟧ + ⟦G⟧ = 0 := quot.sound (add_self G) /-- This lemma doesn't require `H` to be impartial. -/ lemma equiv_iff_add_equiv_zero (H : pgame) : H ≈ G ↔ H + G ≈ 0 := by { rw [equiv_iff_game_eq, equiv_iff_game_eq, ←@add_right_cancel_iff _ _ (-⟦G⟧)], simpa } /-- This lemma doesn't require `H` to be impartial. -/ lemma equiv_iff_add_equiv_zero' (H : pgame) : G ≈ H ↔ G + H ≈ 0 := by { rw [equiv_iff_game_eq, equiv_iff_game_eq, ←@add_left_cancel_iff _ _ (-⟦G⟧), eq_comm], simpa } lemma le_zero_iff {G : pgame} [G.impartial] : G ≤ 0 ↔ 0 ≤ G := by rw [←zero_le_neg_iff, le_congr_right (neg_equiv_self G)] lemma lf_zero_iff {G : pgame} [G.impartial] : G ⧏ 0 ↔ 0 ⧏ G := by rw [←zero_lf_neg_iff, lf_congr_right (neg_equiv_self G)] lemma equiv_zero_iff_le: G ≈ 0 ↔ G ≤ 0 := ⟨and.left, λ h, ⟨h, le_zero_iff.1 h⟩⟩ lemma fuzzy_zero_iff_lf : G ∥ 0 ↔ G ⧏ 0 := ⟨and.left, λ h, ⟨h, lf_zero_iff.1 h⟩⟩ lemma equiv_zero_iff_ge : G ≈ 0 ↔ 0 ≤ G := ⟨and.right, λ h, ⟨le_zero_iff.2 h, h⟩⟩ lemma fuzzy_zero_iff_gf : G ∥ 0 ↔ 0 ⧏ G := ⟨and.right, λ h, ⟨lf_zero_iff.2 h, h⟩⟩ lemma forall_left_moves_fuzzy_iff_equiv_zero : (∀ i, G.move_left i ∥ 0) ↔ G ≈ 0 := begin refine ⟨λ hb, _, λ hp i, _⟩, { rw [equiv_zero_iff_le G, le_zero_lf], exact λ i, (hb i).1 }, { rw fuzzy_zero_iff_lf, exact hp.1.move_left_lf i } end lemma forall_right_moves_fuzzy_iff_equiv_zero : (∀ j, G.move_right j ∥ 0) ↔ G ≈ 0 := begin refine ⟨λ hb, _, λ hp i, _⟩, { rw [equiv_zero_iff_ge G, zero_le_lf], exact λ i, (hb i).2 }, { rw fuzzy_zero_iff_gf, exact hp.2.lf_move_right i } end lemma exists_left_move_equiv_iff_fuzzy_zero : (∃ i, G.move_left i ≈ 0) ↔ G ∥ 0 := begin refine ⟨λ ⟨i, hi⟩, (fuzzy_zero_iff_gf G).2 (lf_of_le_move_left hi.2), λ hn, _⟩, rw [fuzzy_zero_iff_gf G, zero_lf_le] at hn, cases hn with i hi, exact ⟨i, (equiv_zero_iff_ge _).2 hi⟩ end lemma exists_right_move_equiv_iff_fuzzy_zero : (∃ j, G.move_right j ≈ 0) ↔ G ∥ 0 := begin refine ⟨λ ⟨i, hi⟩, (fuzzy_zero_iff_lf G).2 (lf_of_move_right_le hi.1), λ hn, _⟩, rw [fuzzy_zero_iff_lf G, lf_zero_le] at hn, cases hn with i hi, exact ⟨i, (equiv_zero_iff_le _).2 hi⟩ end end impartial end pgame
c5d6506e90bd441c3b713a6afaf5d1888395916d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/linarith/datatypes.lean
8c05d9eca773887c494cdc49124bc4b028c6f72c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,793
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.meta.rb_map import Mathlib.tactic.ring import Mathlib.tactic.linarith.lemmas import Mathlib.PostPort universes l namespace Mathlib /-! # Datatypes for `linarith` Some of the data structures here are used in multiple parts of the tactic. We split them into their own file. This file also contains a few convenient auxiliary functions. -/ namespace linarith /-- A shorthand for tracing when the `trace.linarith` option is set to true. -/ /-- A shorthand for tracing the types of a list of proof terms when the `trace.linarith` option is set to true. -/ /-! ### Linear expressions -/ /-- A linear expression is a list of pairs of variable indices and coefficients, representing the sum of the products of each coefficient with its corresponding variable. Some functions on `linexp` assume that `n : ℕ` occurs at most once as the first element of a pair, and that the list is sorted in decreasing order of the first argument. This is not enforced by the type but the operations here preserve it. -/ def linexp := List (ℕ × ℤ) namespace linexp /-- Add two `linexp`s together componentwise. Preserves sorting and uniqueness of the first argument. -/ /-- `l.scale c` scales the values in `l` by `c` without modifying the order or keys. -/ def scale (c : ℤ) (l : linexp) : linexp := ite (c = 0) [] (ite (c = 1) l (list.map (fun (_x : ℕ × ℤ) => sorry) l)) /-- `l.get n` returns the value in `l` associated with key `n`, if it exists, and `none` otherwise. This function assumes that `l` is sorted in decreasing order of the first argument, that is, it will return `none` as soon as it finds a key smaller than `n`. -/ def get (n : ℕ) : linexp → Option ℤ := sorry /-- `l.contains n` is true iff `n` is the first element of a pair in `l`. -/ def contains (n : ℕ) : linexp → Bool := option.is_some ∘ get n /-- `l.zfind n` returns the value associated with key `n` if there is one, and 0 otherwise. -/ def zfind (n : ℕ) (l : linexp) : ℤ := sorry /-- `l.vars` returns the list of variables that occur in `l`. -/ def vars (l : linexp) : List ℕ := list.map prod.fst l /-- Defines a lex ordering on `linexp`. This function is performance critical. -/ def cmp : linexp → linexp → ordering := sorry end linexp /-! ### Inequalities -/ /-- The three-element type `ineq` is used to represent the strength of a comparison between terms. -/ inductive ineq where | eq : ineq | le : ineq | lt : ineq namespace ineq /-- `max R1 R2` computes the strength of the sum of two inequalities. If `t1 R1 0` and `t2 R2 0`, then `t1 + t2 (max R1 R2) 0`. -/ def max : ineq → ineq → ineq := sorry /-- `ineq` is ordered `eq < le < lt`. -/ def cmp : ineq → ineq → ordering := sorry /-- Prints an `ineq` as the corresponding infix symbol. -/ def to_string : ineq → string := sorry /-- Finds the name of a multiplicative lemma corresponding to an inequality strength. -/ protected instance has_to_string : has_to_string ineq := has_to_string.mk to_string end ineq /-! ### Comparisons with 0 -/ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is `coeffs.sum (λ ⟨k, v⟩, v * Var[k])`. str determines the strength of the comparison -- is it < 0, ≤ 0, or = 0? -/ structure comp where str : ineq coeffs : linexp /-- `c.vars` returns the list of variables that appear in the linear expression contained in `c`. -/ def comp.vars : comp → List ℕ := linexp.vars ∘ comp.coeffs /-- `comp.coeff_of c a` projects the coefficient of variable `a` out of `c`. -/ def comp.coeff_of (c : comp) (a : ℕ) : ℤ := linexp.zfind a (comp.coeffs c) /-- `comp.scale c n` scales the coefficients of `c` by `n`. -/ def comp.scale (c : comp) (n : ℕ) : comp := comp.mk (comp.str c) (linexp.scale (↑n) (comp.coeffs c)) /-- `comp.add c1 c2` adds the expressions represented by `c1` and `c2`. The coefficient of variable `a` in `c1.add c2` is the sum of the coefficients of `a` in `c1` and `c2`. -/ /-- `comp` has a lex order. First the `ineq`s are compared, then the `coeff`s. -/ /-- A `comp` represents a contradiction if its expression has no coefficients and its strength is <, that is, it represents the fact `0 < 0`. -/ /-! ### Parsing into linear form -/ /-! ### Control -/ /-- A preprocessor transforms a proof of a proposition into a proof of a different propositon. The return type is `list expr`, since some preprocessing steps may create multiple new hypotheses, and some may remove a hypothesis from the list. A "no-op" preprocessor should return its input as a singleton list. -/ /-- Some preprocessors need to examine the full list of hypotheses instead of working item by item. As with `preprocessor`, the input to a `global_preprocessor` is replaced by, not added to, its output. -/ /-- Some preprocessors perform branching case splits. A `branch` is used to track one of these case splits. The first component, an `expr`, is the goal corresponding to this branch of the split, given as a metavariable. The `list expr` component is the list of hypotheses for `linarith` in this branch. Every `expr` in this list should be type correct in the context of the associated goal. -/ /-- Some preprocessors perform branching case splits. A `global_branching_preprocessor` produces a list of branches to run. Each branch is independent, so hypotheses that appear in multiple branches should be duplicated. The preprocessor is responsible for making sure that each branch contains the correct goal metavariable. -/ /-- A `preprocessor` lifts to a `global_preprocessor` by folding it over the input list. -/ /-- A `global_preprocessor` lifts to a `global_branching_preprocessor` by producing only one branch. -/ /-- `process pp l` runs `pp.transform` on `l` and returns the result, tracing the result if `trace.linarith` is on. -/ /-- A `certificate_oracle` is a function `produce_certificate : list comp → ℕ → tactic (rb_map ℕ ℕ)`. `produce_certificate hyps max_var` tries to derive a contradiction from the comparisons in `hyps` by eliminating all variables ≤ `max_var`. If successful, it returns a map `coeff : ℕ → ℕ` as a certificate. This map represents that we can find a contradiction by taking the sum `∑ (coeff i) * hyps[i]`. The default `certificate_oracle` used by `linarith` is `linarith.fourier_motzkin.produce_certificate` -/ /-- A configuration object for `linarith`. -/
9ba4006d982a034ee8256734e97a98aa9a0628eb
abd85493667895c57a7507870867b28124b3998f
/src/data/seq/wseq.lean
495a0ff41b09fcdd3594930d82c159cba2e0c5ea
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
55,024
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.seq.seq import data.dlist universes u v w /- coinductive wseq (α : Type u) : Type u | nil : wseq α | cons : α → wseq α → wseq α | think : wseq α → wseq α -/ /-- Weak sequences. While the `seq` structure allows for lists which may not be finite, a weak sequence also allows the computation of each element to involve an indeterminate amount of computation, including possibly an infinite loop. This is represented as a regular `seq` interspersed with `none` elements to indicate that computation is ongoing. This model is appropriate for Haskell style lazy lists, and is closed under most interesting computation patterns on infinite lists, but conversely it is difficult to extract elements from it. -/ def wseq (α) := seq (option α) namespace wseq variables {α : Type u} {β : Type v} {γ : Type w} /-- Turn a sequence into a weak sequence -/ def of_seq : seq α → wseq α := (<$>) some /-- Turn a list into a weak sequence -/ def of_list (l : list α) : wseq α := of_seq l /-- Turn a stream into a weak sequence -/ def of_stream (l : stream α) : wseq α := of_seq l instance coe_seq : has_coe (seq α) (wseq α) := ⟨of_seq⟩ instance coe_list : has_coe (list α) (wseq α) := ⟨of_list⟩ instance coe_stream : has_coe (stream α) (wseq α) := ⟨of_stream⟩ /-- The empty weak sequence -/ def nil : wseq α := seq.nil instance : inhabited (wseq α) := ⟨nil⟩ /-- Prepend an element to a weak sequence -/ def cons (a : α) : wseq α → wseq α := seq.cons (some a) /-- Compute for one tick, without producing any elements -/ def think : wseq α → wseq α := seq.cons none /-- Destruct a weak sequence, to (eventually possibly) produce either `none` for `nil` or `some (a, s)` if an element is produced. -/ def destruct : wseq α → computation (option (α × wseq α)) := computation.corec (λs, match seq.destruct s with | none := sum.inl none | some (none, s') := sum.inr s' | some (some a, s') := sum.inl (some (a, s')) end) def cases_on {C : wseq α → Sort v} (s : wseq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s := seq.cases_on s h1 (λ o, option.cases_on o h3 h2) protected def mem (a : α) (s : wseq α) := seq.mem (some a) s instance : has_mem α (wseq α) := ⟨wseq.mem⟩ theorem not_mem_nil (a : α) : a ∉ @nil α := seq.not_mem_nil a /-- Get the head of a weak sequence. This involves a possibly infinite computation. -/ def head (s : wseq α) : computation (option α) := computation.map ((<$>) prod.fst) (destruct s) /-- Encode a computation yielding a weak sequence into additional `think` constructors in a weak sequence -/ def flatten : computation (wseq α) → wseq α := seq.corec (λc, match computation.destruct c with | sum.inl s := seq.omap return (seq.destruct s) | sum.inr c' := some (none, c') end) /-- Get the tail of a weak sequence. This doesn't need a `computation` wrapper, unlike `head`, because `flatten` allows us to hide this in the construction of the weak sequence itself. -/ def tail (s : wseq α) : wseq α := flatten $ (λo, option.rec_on o nil prod.snd) <$> destruct s /-- drop the first `n` elements from `s`. -/ def drop (s : wseq α) : ℕ → wseq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop /-- Get the nth element of `s`. -/ def nth (s : wseq α) (n : ℕ) : computation (option α) := head (drop s n) /-- Convert `s` to a list (if it is finite and completes in finite time). -/ def to_list (s : wseq α) : computation (list α) := @computation.corec (list α) (list α × wseq α) (λ⟨l, s⟩, match seq.destruct s with | none := sum.inl l.reverse | some (none, s') := sum.inr (l, s') | some (some a, s') := sum.inr (a::l, s') end) ([], s) /-- Get the length of `s` (if it is finite and completes in finite time). -/ def length (s : wseq α) : computation ℕ := @computation.corec ℕ (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s with | none := sum.inl n | some (none, s') := sum.inr (n, s') | some (some a, s') := sum.inr (n+1, s') end) (0, s) /-- A weak sequence is finite if `to_list s` terminates. Equivalently, it is a finite number of `think` and `cons` applied to `nil`. -/ @[class] def is_finite (s : wseq α) : Prop := (to_list s).terminates instance to_list_terminates (s : wseq α) [h : is_finite s] : (to_list s).terminates := h /-- Get the list corresponding to a finite weak sequence. -/ def get (s : wseq α) [is_finite s] : list α := (to_list s).get /-- A weak sequence is *productive* if it never stalls forever - there are always a finite number of `think`s between `cons` constructors. The sequence itself is allowed to be infinite though. -/ @[class] def productive (s : wseq α) : Prop := ∀ n, (nth s n).terminates instance nth_terminates (s : wseq α) [h : productive s] : ∀ n, (nth s n).terminates := h instance head_terminates (s : wseq α) [h : productive s] : (head s).terminates := h 0 /-- Replace the `n`th element of `s` with `a`. -/ def update_nth (s : wseq α) (n : ℕ) (a : α) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (some a, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Remove the `n`th element of `s`. -/ def remove_nth (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match seq.destruct s, n with | none, n := none | some (none, s'), n := some (none, n, s') | some (some a', s'), 0 := some (some a', 0, s') | some (some a', s'), 1 := some (none, 0, s') | some (some a', s'), (n+2) := some (some a', n+1, s') end) (n+1, s) /-- Map the elements of `s` over `f`, removing any values that yield `none`. -/ def filter_map (f : α → option β) : wseq α → wseq β := seq.corec (λs, match seq.destruct s with | none := none | some (none, s') := some (none, s') | some (some a, s') := some (f a, s') end) /-- Select the elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] : wseq α → wseq α := filter_map (λa, if p a then some a else none) -- example of infinite list manipulations /-- Get the first element of `s` satisfying `p`. -/ def find (p : α → Prop) [decidable_pred p] (s : wseq α) : computation (option α) := head $ filter p s /-- Zip a function over two weak sequences -/ def zip_with (f : α → β → γ) (s1 : wseq α) (s2 : wseq β) : wseq γ := @seq.corec (option γ) (wseq α × wseq β) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (none, s1, s2') | some (none, s1'), some (some a2, s2') := some (none, s1', s2) | some (some a1, s1'), some (some a2, s2') := some (some (f a1 a2), s1', s2') | _, _ := none end) (s1, s2) /-- Zip two weak sequences into a single sequence of pairs -/ def zip : wseq α → wseq β → wseq (α × β) := zip_with prod.mk /-- Get the list of indexes of elements of `s` satisfying `p` -/ def find_indexes (p : α → Prop) [decidable_pred p] (s : wseq α) : wseq ℕ := (zip s (stream.nats : wseq ℕ)).filter_map (λ ⟨a, n⟩, if p a then some n else none) /-- Get the index of the first element of `s` satisfying `p` -/ def find_index (p : α → Prop) [decidable_pred p] (s : wseq α) : computation ℕ := (λ o, option.get_or_else o 0) <$> head (find_indexes p s) /-- Get the index of the first occurrence of `a` in `s` -/ def index_of [decidable_eq α] (a : α) : wseq α → computation ℕ := find_index (eq a) /-- Get the indexes of occurrences of `a` in `s` -/ def indexes_of [decidable_eq α] (a : α) : wseq α → wseq ℕ := find_indexes (eq a) /-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in some order (nondeterministically). -/ def union (s1 s2 : wseq α) : wseq α := @seq.corec (option α) (wseq α × wseq α) (λ⟨s1, s2⟩, match seq.destruct s1, seq.destruct s2 with | none, none := none | some (a1, s1'), none := some (a1, s1', nil) | none, some (a2, s2') := some (a2, nil, s2') | some (none, s1'), some (none, s2') := some (none, s1', s2') | some (some a1, s1'), some (none, s2') := some (some a1, s1', s2') | some (none, s1'), some (some a2, s2') := some (some a2, s1', s2') | some (some a1, s1'), some (some a2, s2') := some (some a1, cons a2 s1', s2') end) (s1, s2) /-- Returns `tt` if `s` is `nil` and `ff` if `s` has an element -/ def is_empty (s : wseq α) : computation bool := computation.map option.is_none $ head s /-- Calculate one step of computation -/ def compute (s : wseq α) : wseq α := match seq.destruct s with | some (none, s') := s' | _ := s end /-- Get the first `n` elements of a weak sequence -/ def take (s : wseq α) (n : ℕ) : wseq α := @seq.corec (option α) (ℕ × wseq α) (λ⟨n, s⟩, match n, seq.destruct s with | 0, _ := none | m+1, none := none | m+1, some (none, s') := some (none, m+1, s') | m+1, some (some a, s') := some (some a, m, s') end) (n, s) /-- Split the sequence at position `n` into a finite initial segment and the weak sequence tail -/ def split_at (s : wseq α) (n : ℕ) : computation (list α × wseq α) := @computation.corec (list α × wseq α) (ℕ × list α × wseq α) (λ⟨n, l, s⟩, match n, seq.destruct s with | 0, _ := sum.inl (l.reverse, s) | m+1, none := sum.inl (l.reverse, s) | m+1, some (none, s') := sum.inr (n, l, s') | m+1, some (some a, s') := sum.inr (m, a::l, s') end) (n, [], s) /-- Returns `tt` if any element of `s` satisfies `p` -/ def any (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl ff | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inl tt else sum.inr s' end) s /-- Returns `tt` if every element of `s` satisfies `p` -/ def all (s : wseq α) (p : α → bool) : computation bool := computation.corec (λs : wseq α, match seq.destruct s with | none := sum.inl tt | some (none, s') := sum.inr s' | some (some a, s') := if p a then sum.inr s' else sum.inl ff end) s /-- Apply a function to the elements of the sequence to produce a sequence of partial results. (There is no `scanr` because this would require working from the end of the sequence, which may not exist.) -/ def scanl (f : α → β → α) (a : α) (s : wseq β) : wseq α := cons a $ @seq.corec (option α) (α × wseq β) (λ⟨a, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, a, s') | some (some b, s') := let a' := f a b in some (some a', a', s') end) (a, s) /-- Get the weak sequence of initial segments of the input sequence -/ def inits (s : wseq α) : wseq (list α) := cons [] $ @seq.corec (option (list α)) (dlist α × wseq α) (λ ⟨l, s⟩, match seq.destruct s with | none := none | some (none, s') := some (none, l, s') | some (some a, s') := let l' := l.concat a in some (some l'.to_list, l', s') end) (dlist.empty, s) /-- Like take, but does not wait for a result. Calculates `n` steps of computation and returns the sequence computed so far -/ def collect (s : wseq α) (n : ℕ) : list α := (seq.take n s).filter_map id /-- Append two weak sequences. As with `seq.append`, this may not use the second sequence if the first one takes forever to compute -/ def append : wseq α → wseq α → wseq α := seq.append /-- Map a function over a weak sequence -/ def map (f : α → β) : wseq α → wseq β := seq.map (option.map f) /-- Flatten a sequence of weak sequences. (Note that this allows empty sequences, unlike `seq.join`.) -/ def join (S : wseq (wseq α)) : wseq α := seq.join ((λo : option (wseq α), match o with | none := seq1.ret none | some s := (none, s) end) <$> S) /-- Monadic bind operator for weak sequences -/ def bind (s : wseq α) (f : α → wseq β) : wseq β := join (map f s) @[simp] def lift_rel_o (R : α → β → Prop) (C : wseq α → wseq β → Prop) : option (α × wseq α) → option (β × wseq β) → Prop | none none := true | (some (a, s)) (some (b, t)) := R a b ∧ C s t | _ _ := false theorem lift_rel_o.imp {R S : α → β → Prop} {C D : wseq α → wseq β → Prop} (H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) : ∀ {o p}, lift_rel_o R C o p → lift_rel_o S D o p | none none h := trivial | (some (a, s)) (some (b, t)) h := and.imp (H1 _ _) (H2 _ _) h | none (some _) h := false.elim h | (some (_, _)) none h := false.elim h theorem lift_rel_o.imp_right (R : α → β → Prop) {C D : wseq α → wseq β → Prop} (H : ∀ s t, C s t → D s t) {o p} : lift_rel_o R C o p → lift_rel_o R D o p := lift_rel_o.imp (λ _ _, id) H @[simp] def bisim_o (R : wseq α → wseq α → Prop) : option (α × wseq α) → option (α × wseq α) → Prop := lift_rel_o (=) R theorem bisim_o.imp {R S : wseq α → wseq α → Prop} (H : ∀ s t, R s t → S s t) {o p} : bisim_o R o p → bisim_o S o p := lift_rel_o.imp_right _ H /-- Two weak sequences are `lift_rel R` related if they are either both empty, or they are both nonempty and the heads are `R` related and the tails are `lift_rel R` related. (This is a coinductive definition.) -/ def lift_rel (R : α → β → Prop) (s : wseq α) (t : wseq β) : Prop := ∃ C : wseq α → wseq β → Prop, C s t ∧ ∀ {s t}, C s t → computation.lift_rel (lift_rel_o R C) (destruct s) (destruct t) /-- If two sequences are equivalent, then they have the same values and the same computational behavior (i.e. if one loops forever then so does the other), although they may differ in the number of `think`s needed to arrive at the answer. -/ def equiv : wseq α → wseq α → Prop := lift_rel (=) theorem lift_rel_destruct {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t → computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) | ⟨R, h1, h2⟩ := by refine computation.lift_rel.imp _ _ _ (h2 h1); apply lift_rel_o.imp_right; exact λ s' t' h', ⟨R, h', @h2⟩ theorem lift_rel_destruct_iff {R : α → β → Prop} {s : wseq α} {t : wseq β} : lift_rel R s t ↔ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t) := ⟨lift_rel_destruct, λ h, ⟨λ s t, lift_rel R s t ∨ computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), or.inr h, λ s t h, begin have h : computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct s) (destruct t), { cases h with h h, exact lift_rel_destruct h, assumption }, apply computation.lift_rel.imp _ _ _ h, intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end⟩⟩ infix ~ := equiv theorem destruct_congr {s t : wseq α} : s ~ t → computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct theorem destruct_congr_iff {s t : wseq α} : s ~ t ↔ computation.lift_rel (bisim_o (~)) (destruct s) (destruct t) := lift_rel_destruct_iff theorem lift_rel.refl (R : α → α → Prop) (H : reflexive R) : reflexive (lift_rel R) := λ s, begin refine ⟨(=), rfl, λ s t (h : s = t), _⟩, rw ←h, apply computation.lift_rel.refl, intro a, cases a with a, simp, cases a; simp, apply H end theorem lift_rel_o.swap (R : α → β → Prop) (C) : function.swap (lift_rel_o R C) = lift_rel_o (function.swap R) (function.swap C) := by funext x y; cases x with x; [skip, cases x]; { cases y with y; [skip, cases y]; refl } theorem lift_rel.swap_lem {R : α → β → Prop} {s1 s2} (h : lift_rel R s1 s2) : lift_rel (function.swap R) s2 s1 := begin refine ⟨function.swap (lift_rel R), h, λ s t (h : lift_rel R t s), _⟩, rw [←lift_rel_o.swap, computation.lift_rel.swap], apply lift_rel_destruct h end theorem lift_rel.swap (R : α → β → Prop) : function.swap (lift_rel R) = lift_rel (function.swap R) := funext $ λ x, funext $ λ y, propext ⟨lift_rel.swap_lem, lift_rel.swap_lem⟩ theorem lift_rel.symm (R : α → α → Prop) (H : symmetric R) : symmetric (lift_rel R) := λ s1 s2 (h : function.swap (lift_rel R) s2 s1), by rwa [lift_rel.swap, show function.swap R = R, from funext $ λ a, funext $ λ b, propext $ by constructor; apply H] at h theorem lift_rel.trans (R : α → α → Prop) (H : transitive R) : transitive (lift_rel R) := λ s t u h1 h2, begin refine ⟨λ s u, ∃ t, lift_rel R s t ∧ lift_rel R t u, ⟨t, h1, h2⟩, λ s u h, _⟩, rcases h with ⟨t, h1, h2⟩, have h1 := lift_rel_destruct h1, have h2 := lift_rel_destruct h2, refine computation.lift_rel_def.2 ⟨(computation.terminates_of_lift_rel h1).trans (computation.terminates_of_lift_rel h2), λ a c ha hc, _⟩, rcases h1.left ha with ⟨b, hb, t1⟩, have t2 := computation.rel_of_lift_rel h2 hb hc, cases a with a; cases c with c, { trivial }, { cases b, {cases t2}, {cases t1} }, { cases a, cases b with b, {cases t1}, {cases b, cases t2} }, { cases a with a s, cases b with b, {cases t1}, cases b with b t, cases c with c u, cases t1 with ab st, cases t2 with bc tu, exact ⟨H ab bc, t, st, tu⟩ } end theorem lift_rel.equiv (R : α → α → Prop) : equivalence R → equivalence (lift_rel R) | ⟨refl, symm, trans⟩ := ⟨lift_rel.refl R refl, lift_rel.symm R symm, lift_rel.trans R trans⟩ @[refl] theorem equiv.refl : ∀ (s : wseq α), s ~ s := lift_rel.refl (=) eq.refl @[symm] theorem equiv.symm : ∀ {s t : wseq α}, s ~ t → t ~ s := lift_rel.symm (=) (@eq.symm _) @[trans] theorem equiv.trans : ∀ {s t u : wseq α}, s ~ t → t ~ u → s ~ u := lift_rel.trans (=) (@eq.trans _) theorem equiv.equivalence : equivalence (@equiv α) := ⟨@equiv.refl _, @equiv.symm _, @equiv.trans _⟩ open computation local notation `return` := computation.return @[simp] theorem destruct_nil : destruct (nil : wseq α) = return none := computation.destruct_eq_ret rfl @[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = return (some (a, s)) := computation.destruct_eq_ret $ by simp [destruct, cons, computation.rmap] @[simp] theorem destruct_think (s : wseq α) : destruct (think s) = (destruct s).think := computation.destruct_eq_think $ by simp [destruct, think, computation.rmap] @[simp] theorem seq_destruct_nil : seq.destruct (nil : wseq α) = none := seq.destruct_nil @[simp] theorem seq_destruct_cons (a : α) (s) : seq.destruct (cons a s) = some (some a, s) := seq.destruct_cons _ _ @[simp] theorem seq_destruct_think (s : wseq α) : seq.destruct (think s) = some (none, s) := seq.destruct_cons _ _ @[simp] theorem head_nil : head (nil : wseq α) = return none := by simp [head]; refl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = return (some a) := by simp [head]; refl @[simp] theorem head_think (s : wseq α) : head (think s) = (head s).think := by simp [head]; refl @[simp] theorem flatten_ret (s : wseq α) : flatten (return s) = s := begin refine seq.eq_of_bisim (λs1 s2, flatten (return s2) = s1) _ rfl, intros s' s h, rw ←h, simp [flatten], cases seq.destruct s, { simp }, { cases val with o s', simp } end @[simp] theorem flatten_think (c : computation (wseq α)) : flatten c.think = think (flatten c) := seq.destruct_eq_cons $ by simp [flatten, think] @[simp] theorem destruct_flatten (c : computation (wseq α)) : destruct (flatten c) = c >>= destruct := begin refine computation.eq_of_bisim (λc1 c2, c1 = c2 ∨ ∃ c, c1 = destruct (flatten c) ∧ c2 = computation.bind c destruct) _ (or.inr ⟨c, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, (or.inr ⟨c, rfl, rfl⟩) := begin apply c.cases_on (λa, _) (λc', _); repeat {simp}, { cases (destruct a).destruct; simp }, { exact or.inr ⟨c', rfl, rfl⟩ } end end end theorem head_terminates_iff (s : wseq α) : terminates (head s) ↔ terminates (destruct s) := terminates_map_iff _ (destruct s) @[simp] theorem tail_nil : tail (nil : wseq α) = nil := by simp [tail] @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail] @[simp] theorem tail_think (s : wseq α) : tail (think s) = (tail s).think := by simp [tail] @[simp] theorem dropn_nil (n) : drop (nil : wseq α) n = nil := by induction n; simp [*, drop] @[simp] theorem dropn_cons (a : α) (s) (n) : drop (cons a s) (n+1) = drop s n := by induction n; simp [*, drop] @[simp] theorem dropn_think (s : wseq α) (n) : drop (think s) n = (drop s n).think := by induction n; simp [*, drop] theorem dropn_add (s : wseq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 := rfl | (n+1) := congr_arg tail (dropn_add n) theorem dropn_tail (s : wseq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_add (s : wseq α) (m n) : nth s (m + n) = nth (drop s m) n := congr_arg head (dropn_add _ _ _) theorem nth_tail (s : wseq α) (n) : nth (tail s) n = nth s (n + 1) := congr_arg head (dropn_tail _ _) @[simp] theorem join_nil : join nil = (nil : wseq α) := seq.join_nil @[simp] theorem join_think (S : wseq (wseq α)) : join (think S) = think (join S) := by { simp [think, join], unfold functor.map, simp [join, seq1.ret] } @[simp] theorem join_cons (s : wseq α) (S) : join (cons s S) = think (append s (join S)) := by { simp [think, join], unfold functor.map, simp [join, cons, append] } @[simp] theorem nil_append (s : wseq α) : append nil s = s := seq.nil_append _ @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := seq.cons_append _ _ _ @[simp] theorem think_append (s t : wseq α) : append (think s) t = think (append s t) := seq.cons_append _ _ _ @[simp] theorem append_nil (s : wseq α) : append s nil = s := seq.append_nil _ @[simp] theorem append_assoc (s t u : wseq α) : append (append s t) u = append s (append t u) := seq.append_assoc _ _ _ @[simp] def tail.aux : option (α × wseq α) → computation (option (α × wseq α)) | none := return none | (some (a, s)) := destruct s theorem destruct_tail (s : wseq α) : destruct (tail s) = destruct s >>= tail.aux := begin dsimp [tail], simp, rw [← bind_pure_comp_eq_map, is_lawful_monad.bind_assoc], apply congr_arg, funext o, rcases o with _|⟨a, s⟩; apply (@pure_bind computation _ _ _ _ _ _).trans _; simp end @[simp] def drop.aux : ℕ → option (α × wseq α) → computation (option (α × wseq α)) | 0 := return | (n+1) := λ a, tail.aux a >>= drop.aux n theorem drop.aux_none : ∀ n, @drop.aux α n none = return none | 0 := rfl | (n+1) := show computation.bind (return none) (drop.aux n) = return none, by rw [ret_bind, drop.aux_none] theorem destruct_dropn : ∀ (s : wseq α) n, destruct (drop s n) = destruct s >>= drop.aux n | s 0 := (bind_ret' _).symm | s (n+1) := by rw [← dropn_tail, destruct_dropn _ n, destruct_tail, is_lawful_monad.bind_assoc]; refl theorem head_terminates_of_head_tail_terminates (s : wseq α) [T : terminates (head (tail s))] : terminates (head s) := (head_terminates_iff _).2 $ begin cases (head_terminates_iff _).1 T with a h, simp [tail] at h, rcases exists_of_mem_bind h with ⟨s', h1, h2⟩, unfold functor.map at h1, exact let ⟨t, h3, h4⟩ := exists_of_mem_map h1 in terminates_of_mem h3 end theorem destruct_some_of_destruct_tail_some {s : wseq α} {a} (h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s := begin unfold tail functor.map at h, simp at h, rcases exists_of_mem_bind h with ⟨t, tm, td⟩, clear h, rcases exists_of_mem_map tm with ⟨t', ht', ht2⟩, clear tm, cases t' with t'; rw ←ht2 at td; simp at td, { have := mem_unique td (ret_mem _), contradiction }, { exact ⟨_, ht'⟩ } end theorem head_some_of_head_tail_some {s : wseq α} {a} (h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s := begin unfold head at h, rcases exists_of_mem_map h with ⟨o, md, e⟩, clear h, cases o with o; injection e with h', clear e h', cases destruct_some_of_destruct_tail_some md with a am, exact ⟨_, mem_map ((<$>) (@prod.fst α (wseq α))) am⟩ end theorem head_some_of_nth_some {s : wseq α} {a n} (h : some a ∈ nth s n) : ∃ a', some a' ∈ head s := begin revert a, induction n with n IH; intros, exacts [⟨_, h⟩, let ⟨a', h'⟩ := head_some_of_head_tail_some h in IH h'] end instance productive_tail (s : wseq α) [productive s] : productive (tail s) := λ n, by rw [nth_tail]; apply_instance instance productive_dropn (s : wseq α) [productive s] (n) : productive (drop s n) := λ m, by rw [←nth_add]; apply_instance /-- Given a productive weak sequence, we can collapse all the `think`s to produce a sequence. -/ def to_seq (s : wseq α) [productive s] : seq α := ⟨λ n, (nth s n).get, λn h, begin cases e : computation.get (nth s (n + 1)), {assumption}, have := mem_of_get_eq _ e, simp [nth] at this h, cases head_some_of_head_tail_some this with a' h', have := mem_unique h' (@mem_of_get_eq _ _ _ _ h), contradiction end⟩ theorem nth_terminates_le {s : wseq α} {m n} (h : m ≤ n) : terminates (nth s n) → terminates (nth s m) := by induction h with m' h IH; [exact id, exact λ T, IH (@head_terminates_of_head_tail_terminates _ _ T)] theorem head_terminates_of_nth_terminates {s : wseq α} {n} : terminates (nth s n) → terminates (head s) := nth_terminates_le (nat.zero_le n) theorem destruct_terminates_of_nth_terminates {s : wseq α} {n} (T : terminates (nth s n)) : terminates (destruct s) := (head_terminates_iff _).1 $ head_terminates_of_nth_terminates T theorem mem_rec_on {C : wseq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) (h2 : ∀ s, C s → C (think s)) : C s := begin apply seq.mem_rec_on M, intros o s' h, cases o with b, { apply h2, cases h, {contradiction}, {assumption} }, { apply h1, apply or.imp_left _ h, intro h, injection h } end @[simp] theorem mem_think (s : wseq α) (a) : a ∈ think s ↔ a ∈ s := begin cases s with f al, change some (some a) ∈ some none :: f ↔ some (some a) ∈ f, constructor; intro h, { apply (stream.eq_or_mem_of_mem_cons h).resolve_left, intro, injections }, { apply stream.mem_cons_of_mem _ h } end theorem eq_or_mem_iff_mem {s : wseq α} {a a' s'} : some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') := begin generalize e : destruct s = c, intro h, revert s, apply computation.mem_rec_on h _ (λ c IH, _); intro s; apply s.cases_on _ (λ x s, _) (λ s, _); intros m; have := congr_arg computation.destruct m; simp at this; cases this with i1 i2, { rw [i1, i2], cases s' with f al, unfold cons has_mem.mem wseq.mem seq.mem seq.cons, simp, have h_a_eq_a' : a = a' ↔ some (some a) = some (some a'), {simp}, rw [h_a_eq_a'], refine ⟨stream.eq_or_mem_of_mem_cons, λo, _⟩, { cases o with e m, { rw e, apply stream.mem_cons }, { exact stream.mem_cons_of_mem _ m } } }, { simp, exact IH this } end @[simp] theorem mem_cons_iff (s : wseq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s := eq_or_mem_iff_mem $ by simp [ret_mem] theorem mem_cons_of_mem {s : wseq α} (b) {a} (h : a ∈ s) : a ∈ cons b s := (mem_cons_iff _ _).2 (or.inr h) theorem mem_cons (s : wseq α) (a) : a ∈ cons a s := (mem_cons_iff _ _).2 (or.inl rfl) theorem mem_of_mem_tail {s : wseq α} {a} : a ∈ tail s → a ∈ s := begin intro h, have := h, cases h with n e, revert s, simp [stream.nth], induction n with n IH; intro s; apply s.cases_on _ (λx s, _) (λ s, _); repeat{simp}; intros m e; injections, { exact or.inr m }, { exact or.inr m }, { apply IH m, rw e, cases tail s, refl } end theorem mem_of_mem_dropn {s : wseq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s | 0 h := h | (n+1) h := @mem_of_mem_dropn n (mem_of_mem_tail h) theorem nth_mem {s : wseq α} {a n} : some a ∈ nth s n → a ∈ s := begin revert s, induction n with n IH; intros s h, { rcases exists_of_mem_map h with ⟨o, h1, h2⟩, cases o with o; injection h2 with h', cases o with a' s', exact (eq_or_mem_iff_mem h1).2 (or.inl h'.symm) }, { have := @IH (tail s), rw nth_tail at this, exact mem_of_mem_tail (this h) } end theorem exists_nth_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n, some a ∈ nth s n := begin apply mem_rec_on h, { intros a' s' h, cases h with h h, { existsi 0, simp [nth], rw h, apply ret_mem }, { cases h with n h, existsi n+1, simp [nth], exact h } }, { intros s' h, cases h with n h, existsi n, simp [nth], apply think_mem h } end theorem exists_dropn_of_mem {s : wseq α} {a} (h : a ∈ s) : ∃ n s', some (a, s') ∈ destruct (drop s n) := let ⟨n, h⟩ := exists_nth_of_mem h in ⟨n, begin cases (head_terminates_iff _).1 ⟨_, h⟩ with o om, have := mem_unique (mem_map _ om) h, cases o with o; injection this with i, cases o with a' s', dsimp at i, rw i at om, exact ⟨_, om⟩ end⟩ theorem lift_rel_dropn_destruct {R : α → β → Prop} {s t} (H : lift_rel R s t) : ∀ n, computation.lift_rel (lift_rel_o R (lift_rel R)) (destruct (drop s n)) (destruct (drop t n)) | 0 := lift_rel_destruct H | (n+1) := begin simp [destruct_tail], apply lift_rel_bind, apply lift_rel_dropn_destruct n, exact λ a b o, match a, b, o with | none, none, _ := by simp | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp [tail.aux]; apply lift_rel_destruct h2 end end theorem exists_of_lift_rel_left {R : α → β → Prop} {s t} (H : lift_rel R s t) {a} (h : a ∈ s) : ∃ {b}, b ∈ t ∧ R a b := let ⟨n, h⟩ := exists_nth_of_mem h, ⟨some (._, s'), sd, rfl⟩ := exists_of_mem_map h, ⟨some (b, t'), td, ⟨ab, _⟩⟩ := (lift_rel_dropn_destruct H n).left sd in ⟨b, nth_mem (mem_map ((<$>) prod.fst.{v v}) td), ab⟩ theorem exists_of_lift_rel_right {R : α → β → Prop} {s t} (H : lift_rel R s t) {b} (h : b ∈ t) : ∃ {a}, a ∈ s ∧ R a b := by rw ←lift_rel.swap at H; exact exists_of_lift_rel_left H h theorem head_terminates_of_mem {s : wseq α} {a} (h : a ∈ s) : terminates (head s) := let ⟨n, h⟩ := exists_nth_of_mem h in head_terminates_of_nth_terminates ⟨_, h⟩ theorem of_mem_append {s₁ s₂ : wseq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ := seq.of_mem_append theorem mem_append_left {s₁ s₂ : wseq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ := seq.mem_append_left theorem exists_of_mem_map {f} {b : β} : ∀ {s : wseq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := seq.exists_of_mem_map h in by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩ @[simp] theorem lift_rel_nil (R : α → β → Prop) : lift_rel R nil nil := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_cons (R : α → β → Prop) (a b s t) : lift_rel R (cons a s) (cons b t) ↔ R a b ∧ lift_rel R s t := by rw [lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_left (R : α → β → Prop) (s t) : lift_rel R (think s) t ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp @[simp] theorem lift_rel_think_right (R : α → β → Prop) (s t) : lift_rel R s (think t) ↔ lift_rel R s t := by rw [lift_rel_destruct_iff, lift_rel_destruct_iff]; simp theorem cons_congr {s t : wseq α} (a : α) (h : s ~ t) : cons a s ~ cons a t := by unfold equiv; simp; exact h theorem think_equiv (s : wseq α) : think s ~ s := by unfold equiv; simp; apply equiv.refl theorem think_congr {s t : wseq α} (a : α) (h : s ~ t) : think s ~ think t := by unfold equiv; simp; exact h theorem head_congr : ∀ {s t : wseq α}, s ~ t → head s ~ head t := suffices ∀ {s t : wseq α}, s ~ t → ∀ {o}, o ∈ head s → o ∈ head t, from λ s t h o, ⟨this h, this h.symm⟩, begin intros s t h o ho, rcases @computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩, rw ←dse, cases destruct_congr h with l r, rcases l dsm with ⟨dt, dtm, dst⟩, cases ds with a; cases dt with b, { apply mem_map _ dtm }, { cases b, cases dst }, { cases a, cases dst }, { cases a with a s', cases b with b t', rw dst.left, exact @mem_map _ _ (@functor.map _ _ (α × wseq α) _ prod.fst) _ (destruct t) dtm } end theorem flatten_equiv {c : computation (wseq α)} {s} (h : s ∈ c) : flatten c ~ s := begin apply computation.mem_rec_on h, { simp }, { intro s', apply equiv.trans, simp [think_equiv] } end theorem lift_rel_flatten {R : α → β → Prop} {c1 : computation (wseq α)} {c2 : computation (wseq β)} (h : c1.lift_rel (lift_rel R) c2) : lift_rel R (flatten c1) (flatten c2) := let S := λ s t, ∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ computation.lift_rel (lift_rel R) c1 c2 in ⟨S, ⟨c1, c2, rfl, rfl, h⟩, λ s t h, match s, t, h with ._, ._, ⟨c1, c2, rfl, rfl, h⟩ := begin simp, apply lift_rel_bind _ _ h, intros a b ab, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct ab), intros a b, apply lift_rel_o.imp_right, intros s t h, refine ⟨return s, return t, _, _, _⟩; simp [h] end end⟩ theorem flatten_congr {c1 c2 : computation (wseq α)} : computation.lift_rel equiv c1 c2 → flatten c1 ~ flatten c2 := lift_rel_flatten theorem tail_congr {s t : wseq α} (h : s ~ t) : tail s ~ tail t := begin apply flatten_congr, unfold functor.map, rw [←bind_ret, ←bind_ret], apply lift_rel_bind _ _ (destruct_congr h), intros a b h, simp, cases a with a; cases b with b, { trivial }, { cases h }, { cases a, cases h }, { cases a with a s', cases b with b t', exact h.right } end theorem dropn_congr {s t : wseq α} (h : s ~ t) (n) : drop s n ~ drop t n := by induction n; simp [*, tail_congr] theorem nth_congr {s t : wseq α} (h : s ~ t) (n) : nth s n ~ nth t n := head_congr (dropn_congr h _) theorem mem_congr {s t : wseq α} (h : s ~ t) (a) : a ∈ s ↔ a ∈ t := suffices ∀ {s t : wseq α}, s ~ t → a ∈ s → a ∈ t, from ⟨this h, this h.symm⟩, λ s t h as, let ⟨n, hn⟩ := exists_nth_of_mem as in nth_mem ((nth_congr h _ _).1 hn) theorem productive_congr {s t : wseq α} (h : s ~ t) : productive s ↔ productive t := forall_congr $ λn, terminates_congr $ nth_congr h _ theorem equiv.ext {s t : wseq α} (h : ∀ n, nth s n ~ nth t n) : s ~ t := ⟨λ s t, ∀ n, nth s n ~ nth t n, h, λs t h, begin refine lift_rel_def.2 ⟨_, _⟩, { rw [←head_terminates_iff, ←head_terminates_iff], exact terminates_congr (h 0) }, { intros a b ma mb, cases a with a; cases b with b, { trivial }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) }, { cases a with a s', cases b with b t', injection mem_unique (mem_map _ ma) ((h 0 _).2 (mem_map _ mb)) with ab, refine ⟨ab, λ n, _⟩, refine (nth_congr (flatten_equiv (mem_map _ ma)) n).symm.trans ((_ : nth (tail s) n ~ nth (tail t) n).trans (nth_congr (flatten_equiv (mem_map _ mb)) n)), rw [nth_tail, nth_tail], apply h } } end⟩ theorem length_eq_map (s : wseq α) : length s = computation.map list.length (to_list s) := begin refine eq_of_bisim (λ c1 c2, ∃ (l : list α) (s : wseq α), c1 = corec length._match_2 (l.length, s) ∧ c2 = computation.map list.length (corec to_list._match_2 (l, s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l, s, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l, s, _, _⟩; simp }, { refine ⟨l, s, _, _⟩; simp } end @[simp] theorem of_list_nil : of_list [] = (nil : wseq α) := rfl @[simp] theorem of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := show seq.map some (seq.of_list (a :: l)) = seq.cons (some a) (seq.map some (seq.of_list l)), by simp @[simp] theorem to_list'_nil (l : list α) : corec to_list._match_2 (l, nil) = return l.reverse := destruct_eq_ret rfl @[simp] theorem to_list'_cons (l : list α) (s : wseq α) (a : α) : corec to_list._match_2 (l, cons a s) = (corec to_list._match_2 (a::l, s)).think := destruct_eq_think $ by simp [to_list, cons] @[simp] theorem to_list'_think (l : list α) (s : wseq α) : corec to_list._match_2 (l, think s) = (corec to_list._match_2 (l, s)).think := destruct_eq_think $ by simp [to_list, think] theorem to_list'_map (l : list α) (s : wseq α) : corec to_list._match_2 (l, s) = ((++) l.reverse) <$> to_list s := begin refine eq_of_bisim (λ c1 c2, ∃ (l' : list α) (s : wseq α), c1 = corec to_list._match_2 (l' ++ l, s) ∧ c2 = computation.map ((++) l.reverse) (corec to_list._match_2 (l', s))) _ ⟨[], s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨l', s, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); repeat {simp [to_list, nil, cons, think, length]}, { refine ⟨a::l', s, _, _⟩; simp }, { refine ⟨l', s, _, _⟩; simp } end @[simp] theorem to_list_cons (a : α) (s) : to_list (cons a s) = (list.cons a <$> to_list s).think := destruct_eq_think $ by unfold to_list; simp; rw to_list'_map; simp; refl @[simp] theorem to_list_nil : to_list (nil : wseq α) = return [] := destruct_eq_ret rfl theorem to_list_of_list (l : list α) : l ∈ to_list (of_list l) := by induction l with a l IH; simp [ret_mem]; exact think_mem (mem_map _ IH) @[simp] theorem destruct_of_seq (s : seq α) : destruct (of_seq s) = return (s.head.map $ λ a, (a, of_seq s.tail)) := destruct_eq_ret $ begin simp [of_seq, head, destruct, seq.destruct, seq.head], rw [show seq.nth (some <$> s) 0 = some <$> seq.nth s 0, by apply seq.map_nth], cases seq.nth s 0 with a, { refl }, unfold functor.map, simp [destruct] end @[simp] theorem head_of_seq (s : seq α) : head (of_seq s) = return s.head := by simp [head]; cases seq.head s; refl @[simp] theorem tail_of_seq (s : seq α) : tail (of_seq s) = of_seq s.tail := begin simp [tail], apply s.cases_on _ (λ x s, _); simp [of_seq], {refl}, rw [seq.head_cons, seq.tail_cons], refl end @[simp] theorem dropn_of_seq (s : seq α) : ∀ n, drop (of_seq s) n = of_seq (s.drop n) | 0 := rfl | (n+1) := by dsimp [drop]; rw [dropn_of_seq, tail_of_seq] theorem nth_of_seq (s : seq α) (n) : nth (of_seq s) n = return (seq.nth s n) := by dsimp [nth]; rw [dropn_of_seq, head_of_seq, seq.head_dropn] instance productive_of_seq (s : seq α) : productive (of_seq s) := λ n, by rw nth_of_seq; apply_instance theorem to_seq_of_seq (s : seq α) : to_seq (of_seq s) = s := begin apply subtype.eq, funext n, dsimp [to_seq], apply get_eq_of_mem, rw nth_of_seq, apply ret_mem end /-- The monadic `return a` is a singleton list containing `a`. -/ def ret (a : α) : wseq α := of_list [a] @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (cons a s) = cons (f a) (map f s) := seq.map_cons _ _ _ @[simp] theorem map_think (f : α → β) (s) : map f (think s) = think (map f s) := seq.map_cons _ _ _ @[simp] theorem map_id (s : wseq α) : map id s = s := by simp [map] @[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret] @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := seq.map_append _ _ _ theorem map_comp (f : α → β) (g : β → γ) (s : wseq α) : map (g ∘ f) s = map g (map f s) := begin dsimp [map], rw ←seq.map_comp, apply congr_fun, apply congr_arg, funext o, cases o; refl end theorem mem_map (f : α → β) {a : α} {s : wseq α} : a ∈ s → f a ∈ map f s := seq.mem_map (option.map f) -- The converse is not true without additional assumptions theorem exists_of_mem_join {a : α} : ∀ {S : wseq (wseq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s := suffices ∀ ss : wseq α, a ∈ ss → ∀ s S, append s (join S) = ss → a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s, from λ S h, (this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _), begin intros ss h, apply mem_rec_on h (λ b ss o, _) (λ ss IH, _); intros s S, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try {cases this}; try {contradiction}, substs b' ss, simp at m ⊢, cases o with e IH, { simp [e] }, cases m with e m, { simp [e] }, exact or.imp_left or.inr (IH _ _ rfl m) }, { refine s.cases_on (S.cases_on _ (λ s S, _) (λ S, _)) (λ b' s, _) (λ s, _); intros ej m; simp at ej; have := congr_arg seq.destruct ej; simp at this; try { try {have := this.1}, contradiction }; subst ss, { apply or.inr, simp at m ⊢, cases IH s S rfl m with as ex, { exact ⟨s, or.inl rfl, as⟩ }, { rcases ex with ⟨s', sS, as⟩, exact ⟨s', or.inr sS, as⟩ } }, { apply or.inr, simp at m, rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩, exact ⟨s, by simp [sS], as⟩ }, { simp at m IH ⊢, apply IH _ _ rfl m } } end theorem exists_of_mem_bind {s : wseq α} {f : α → wseq β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨t, tm, bt⟩ := exists_of_mem_join h, ⟨a, as, e⟩ := exists_of_mem_map tm in ⟨a, as, by rwa e⟩ theorem destruct_map (f : α → β) (s : wseq α) : destruct (map f s) = computation.map (option.map (prod.map f (map f))) (destruct s) := begin apply eq_of_bisim (λ c1 c2, ∃ s, c1 = destruct (map f s) ∧ c2 = computation.map (option.map (prod.map f (map f))) (destruct s)), { intros c1 c2 h, cases h with s h, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp, exact ⟨s, rfl, rfl⟩ }, { exact ⟨s, rfl, rfl⟩ } end theorem lift_rel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → γ} {f2 : β → δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : lift_rel S (map f1 s1) (map f2 s2) := ⟨λ s1 s2, ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ lift_rel R s t, ⟨s1, s2, rfl, rfl, h1⟩, λ s1 s2 h, match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl, h⟩ := begin simp [destruct_map], apply computation.lift_rel_map _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b; simp, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, exact ⟨h2 r, s, rfl, t, rfl, h⟩ } end end⟩ theorem map_congr (f : α → β) {s t : wseq α} (h : s ~ t) : map f s ~ map f t := lift_rel_map _ _ h (λ _ _, congr_arg _) @[simp] def destruct_append.aux (t : wseq α) : option (α × wseq α) → computation (option (α × wseq α)) | none := destruct t | (some (a, s)) := return (some (a, append s t)) theorem destruct_append (s t : wseq α) : destruct (append s t) = (destruct s).bind (destruct_append.aux t) := begin apply eq_of_bisim (λ c1 c2, ∃ s t, c1 = destruct (append s t) ∧ c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩, intros c1 c2 h, rcases h with ⟨s, t, h⟩, rw [h.left, h.right], apply s.cases_on _ (λ a s, _) (λ s, _); simp, { apply t.cases_on _ (λ b t, _) (λ t, _); simp, { refine ⟨nil, t, _, _⟩; simp } }, { exact ⟨s, t, rfl, rfl⟩ } end @[simp] def destruct_join.aux : option (wseq α × wseq (wseq α)) → computation (option (α × wseq α)) | none := return none | (some (s, S)) := (destruct (append s (join S))).think theorem destruct_join (S : wseq (wseq α)) : destruct (join S) = (destruct S).bind destruct_join.aux := begin apply eq_of_bisim (λ c1 c2, c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧ c2 = (destruct S).bind destruct_join.aux) _ (or.inr ⟨S, rfl, rfl⟩), intros c1 c2 h, exact match c1, c2, h with | _, _, (or.inl $ eq.refl c) := by cases c.destruct; simp | _, _, or.inr ⟨S, rfl, rfl⟩ := begin apply S.cases_on _ (λ s S, _) (λ S, _); simp, { refine or.inr ⟨S, rfl, rfl⟩ } end end end theorem lift_rel_append (R : α → β → Prop) {s1 s2 : wseq α} {t1 t2 : wseq β} (h1 : lift_rel R s1 t1) (h2 : lift_rel R s2 t2) : lift_rel R (append s1 s2) (append t1 t2) := ⟨λ s t, lift_rel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ lift_rel R s1 t1, or.inr ⟨s1, t1, rfl, rfl, h1⟩, λ s t h, match s, t, h with | s, t, or.inl h := begin apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl end | ._, ._, or.inr ⟨s1, t1, rfl, rfl, h⟩ := begin simp [destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct h), intros o p h, cases o with a; cases p with b, { simp, apply computation.lift_rel.imp _ _ _ (lift_rel_destruct h2), intros a b, apply lift_rel_o.imp_right, intros s t, apply or.inl }, { cases b; cases h }, { cases a; cases h }, { cases a with a s; cases b with b t, cases h with r h, simp, exact ⟨r, or.inr ⟨s, rfl, t, rfl, h⟩⟩ } end end⟩ theorem lift_rel_join.lem (R : α → β → Prop) {S T} {U : wseq α → wseq β → Prop} (ST : lift_rel (lift_rel R) S T) (HU : ∀ s1 s2, (∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) : ∃ {b}, b ∈ destruct (join T) ∧ lift_rel_o R U a b := begin cases exists_results_of_mem ma with n h, clear ma, revert a S T, apply nat.strong_induction_on n _, intros n IH a S T ST ra, simp [destruct_join] at ra, exact let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra, ⟨p, mT, rop⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct ST) rs1.mem in by exact match o, p, rop, rs1, rs2, mT with | none, none, _, rs1, rs2, mT := by simp [destruct_join]; exact ⟨none, mem_bind mT (ret_mem _), by rw eq_of_ret_mem rs2.mem; trivial⟩ | some (s, S'), some (t, T'), ⟨st, ST'⟩, rs1, rs2, mT := by simp [destruct_append] at rs2; exact let ⟨k1, rs3, ek⟩ := of_results_think rs2, ⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3, ⟨p', mt, rop'⟩ := computation.exists_of_lift_rel_left (lift_rel_destruct st) rs4.mem in by exact match o', p', rop', rs4, rs5, mt with | none, none, _, rs4, rs5', mt := have n1 < n, begin rw [en, ek, ek1], apply lt_of_lt_of_le _ (nat.le_add_right _ _), apply nat.lt_succ_of_le (nat.le_add_right _ _) end, let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' in by refine ⟨ob, _, rob⟩; { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, exact mb } | some (a, s'), some (b, t'), ⟨ab, st'⟩, rs4, rs5, mt := begin simp at rs5, refine ⟨some (b, append t' (join T')), _, _⟩, { simp [destruct_join], apply mem_bind mT, simp [destruct_append], apply think_mem, apply mem_bind mt, apply ret_mem }, rw eq_of_ret_mem rs5.mem, exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩ end end end end theorem lift_rel_join (R : α → β → Prop) {S : wseq (wseq α)} {T : wseq (wseq β)} (h : lift_rel (lift_rel R) S T) : lift_rel R (join S) (join T) := ⟨λ s1 s2, ∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ lift_rel R s t ∧ lift_rel (lift_rel R) S T, ⟨nil, nil, S, T, by simp, by simp, by simp, h⟩, λs1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, begin clear _fun_match _x, rw [h1, h2], rw [destruct_append, destruct_append], apply computation.lift_rel_bind _ _ (lift_rel_destruct st), exact λ o p h, match o, p, h with | some (a, s), some (b, t), ⟨h1, h2⟩ := by simp; exact ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩ | none, none, _ := begin dsimp [destruct_append.aux, computation.lift_rel], constructor, { intro, apply lift_rel_join.lem _ ST (λ _ _, id) }, { intros b mb, rw [←lift_rel_o.swap], apply lift_rel_join.lem (function.swap R), { rw [←lift_rel.swap R, ←lift_rel.swap], apply ST }, { rw [←lift_rel.swap R, ←lift_rel.swap (lift_rel R)], exact λ s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩, ⟨t, s, T, S, h2, h1, st, ST⟩ }, { exact mb } } end end end⟩ theorem join_congr {S T : wseq (wseq α)} (h : lift_rel equiv S T) : join S ~ join T := lift_rel_join _ h theorem lift_rel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : wseq α} {s2 : wseq β} {f1 : α → wseq γ} {f2 : β → wseq δ} (h1 : lift_rel R s1 s2) (h2 : ∀ {a b}, R a b → lift_rel S (f1 a) (f2 b)) : lift_rel S (bind s1 f1) (bind s2 f2) := lift_rel_join _ (lift_rel_map _ _ h1 @h2) theorem bind_congr {s1 s2 : wseq α} {f1 f2 : α → wseq β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := lift_rel_bind _ _ h1 (λ a b h, by rw h; apply h2) @[simp] theorem join_ret (s : wseq α) : join (ret s) ~ s := by simp [ret]; apply think_equiv @[simp] theorem join_map_ret (s : wseq α) : join (map ret s) ~ s := begin refine ⟨λ s1 s2, join (map ret s2) = s1, rfl, _⟩, intros s' s h, rw ←h, apply lift_rel_rec (λ c1 c2, ∃ s, c1 = destruct (join (map ret s)) ∧ c2 = destruct s), { exact λ c1 c2 h, match c1, c2, h with | ._, ._, ⟨s, rfl, rfl⟩ := begin clear h _match, apply s.cases_on _ (λ a s, _) (λ s, _); simp [ret], { refine ⟨_, ret_mem _, _⟩, simp }, { exact ⟨s, rfl, rfl⟩ } end end }, { exact ⟨s, rfl, rfl⟩ } end @[simp] theorem join_append (S T : wseq (wseq α)) : join (append S T) ~ append (join S) (join T) := begin refine ⟨λ s1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ (s : wseq α) S T, c1 = destruct (append s (join (append S T))) ∧ c2 = destruct (append s (append (join S) (join T)))) _ _ _ (let ⟨s, S, T, h1, h2⟩ := h in ⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { apply wseq.cases_on T _ (λ s T, _) (λ T, _); simp, { refine ⟨s, nil, T, _, _⟩; simp }, { refine ⟨nil, nil, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { refine ⟨nil, S, T, _, _⟩; simp } }, { exact ⟨s, S, T, rfl, rfl⟩ }, { exact ⟨s, S, T, rfl, rfl⟩ } end end end @[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ map f s := begin dsimp [bind], change (λx, ret (f x)) with (ret ∘ f), rw [map_comp], apply join_map_ret end @[simp] theorem ret_bind (a : α) (f : α → wseq β) : bind (ret a) f ~ f a := by simp [bind] @[simp] theorem map_join (f : α → β) (S) : map f (join S) = join (map (map f) S) := begin apply seq.eq_of_bisim (λs1 s2, ∃ s S, s1 = append s (map f (join S)) ∧ s2 = append s (join (map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { exact ⟨map f s, S, rfl, rfl⟩ }, { refine ⟨nil, S, _, _⟩; simp } }, { exact ⟨_, _, rfl, rfl⟩ }, { exact ⟨_, _, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem join_join (SS : wseq (wseq (wseq α))) : join (join SS) ~ join (map join SS) := begin refine ⟨λ s1 s2, ∃ s S SS, s1 = append s (join (append S (join SS))) ∧ s2 = append s (append (join S) (join (map join SS))), ⟨nil, nil, SS, by simp, by simp⟩, _⟩, intros s1 s2 h, apply lift_rel_rec (λ c1 c2, ∃ s S SS, c1 = destruct (append s (join (append S (join SS)))) ∧ c2 = destruct (append s (append (join S) (join (map join SS))))) _ (destruct s1) (destruct s2) (let ⟨s, S, SS, h1, h2⟩ := h in ⟨s, S, SS, by simp [h1], by simp [h2]⟩), intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨s, S, SS, rfl, rfl⟩ := begin clear _match h h, apply wseq.cases_on s _ (λ a s, _) (λ s, _); simp, { apply wseq.cases_on S _ (λ s S, _) (λ S, _); simp, { apply wseq.cases_on SS _ (λ S SS, _) (λ SS, _); simp, { refine ⟨nil, S, SS, _, _⟩; simp }, { refine ⟨nil, nil, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { refine ⟨nil, S, SS, _, _⟩; simp } }, { exact ⟨s, S, SS, rfl, rfl⟩ }, { exact ⟨s, S, SS, rfl, rfl⟩ } end end end @[simp] theorem bind_assoc (s : wseq α) (f : α → wseq β) (g : β → wseq γ) : bind (bind s f) g ~ bind s (λ (x : α), bind (f x) g) := begin simp [bind], rw [← map_comp f (map g), map_comp (map g ∘ f) join], apply join_join end instance : monad wseq := { map := @map, pure := @ret, bind := @bind } /- Unfortunately, wseq is not a lawful monad, because it does not satisfy the monad laws exactly, only up to sequence equivalence. Furthermore, even quotienting by the equivalence is not sufficient, because the join operation involves lists of quotient elements, with a lifted equivalence relation, and pure quotients cannot handle this type of construction. instance : is_lawful_monad wseq := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } -/ end wseq
8cb2d63ca5c5126477f10429244293f03903fb28
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/function/conditional_expectation/indicator.lean
4925425dcf5c19bb56da3d9ffeaca8f14fc58ab7
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
9,850
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.function.conditional_expectation.basic /-! # Conditional expectation of indicator functions This file proves some results about the conditional expectation of an indicator function and as a corollary, also proves several results about the behaviour of the conditional expectation on a restricted measure. ## Main result * `measure_theory.condexp_indicator`: If `s` is a `m`-measurable set, then the conditional expectation of the indicator function of `s` is almost everywhere equal to the indicator of `s` of the conditional expectation. Namely, `𝔼[s.indicator f | m] = s.indicator 𝔼[f | m]` a.e. -/ noncomputable theory open topological_space measure_theory.Lp filter continuous_linear_map open_locale nnreal ennreal topology big_operators measure_theory namespace measure_theory variables {α 𝕜 E : Type*} {m m0 : measurable_space α} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {μ : measure α} {f : α → E} {s : set α} lemma condexp_ae_eq_restrict_zero (hs : measurable_set[m] s) (hf : f =ᵐ[μ.restrict s] 0) : μ[f | m] =ᵐ[μ.restrict s] 0 := begin by_cases hm : m ≤ m0, swap, { simp_rw condexp_of_not_le hm, }, by_cases hμm : sigma_finite (μ.trim hm), swap, { simp_rw condexp_of_not_sigma_finite hm hμm, }, haveI : sigma_finite (μ.trim hm) := hμm, haveI : sigma_finite ((μ.restrict s).trim hm), { rw ← restrict_trim hm _ hs, exact restrict.sigma_finite _ s, }, by_cases hf_int : integrable f μ, swap, { rw condexp_undef hf_int, }, refine ae_eq_of_forall_set_integral_eq_of_sigma_finite' hm _ _ _ _ _, { exact λ t ht hμt, integrable_condexp.integrable_on.integrable_on, }, { exact λ t ht hμt, (integrable_zero _ _ _).integrable_on, }, { intros t ht hμt, rw [measure.restrict_restrict (hm _ ht), set_integral_condexp hm hf_int (ht.inter hs), ← measure.restrict_restrict (hm _ ht)], refine set_integral_congr_ae (hm _ ht) _, filter_upwards [hf] with x hx h using hx, }, { exact strongly_measurable_condexp.ae_strongly_measurable', }, { exact strongly_measurable_zero.ae_strongly_measurable', }, end /-- Auxiliary lemma for `condexp_indicator`. -/ lemma condexp_indicator_aux (hs : measurable_set[m] s) (hf : f =ᵐ[μ.restrict sᶜ] 0) : μ[s.indicator f | m] =ᵐ[μ] s.indicator (μ[f | m]) := begin by_cases hm : m ≤ m0, swap, { simp_rw [condexp_of_not_le hm, set.indicator_zero'], }, have hsf_zero : ∀ g : α → E, g =ᵐ[μ.restrict sᶜ] 0 → s.indicator g =ᵐ[μ] g, from λ g, indicator_ae_eq_of_restrict_compl_ae_eq_zero (hm _ hs), refine ((hsf_zero (μ[f | m]) (condexp_ae_eq_restrict_zero hs.compl hf)).trans _).symm, exact condexp_congr_ae (hsf_zero f hf).symm, end /-- The conditional expectation of the indicator of a function over an `m`-measurable set with respect to the σ-algebra `m` is a.e. equal to the indicator of the conditional expectation. -/ lemma condexp_indicator (hf_int : integrable f μ) (hs : measurable_set[m] s) : μ[s.indicator f | m] =ᵐ[μ] s.indicator (μ[f | m]) := begin by_cases hm : m ≤ m0, swap, { simp_rw [condexp_of_not_le hm, set.indicator_zero'], }, by_cases hμm : sigma_finite (μ.trim hm), swap, { simp_rw [condexp_of_not_sigma_finite hm hμm, set.indicator_zero'], }, haveI : sigma_finite (μ.trim hm) := hμm, -- use `have` to perform what should be the first calc step because of an error I don't -- understand have : s.indicator (μ[f|m]) =ᵐ[μ] s.indicator (μ[s.indicator f + sᶜ.indicator f|m]), by rw set.indicator_self_add_compl s f, refine (this.trans _).symm, calc s.indicator (μ[s.indicator f + sᶜ.indicator f|m]) =ᵐ[μ] s.indicator (μ[s.indicator f|m] + μ[sᶜ.indicator f|m]) : begin have : μ[s.indicator f + sᶜ.indicator f|m] =ᵐ[μ] μ[s.indicator f|m] + μ[sᶜ.indicator f|m], from condexp_add (hf_int.indicator (hm _ hs)) (hf_int.indicator (hm _ hs.compl)), filter_upwards [this] with x hx, classical, rw [set.indicator_apply, set.indicator_apply, hx], end ... = s.indicator (μ[s.indicator f|m]) + s.indicator (μ[sᶜ.indicator f|m]) : s.indicator_add' _ _ ... =ᵐ[μ] s.indicator (μ[s.indicator f|m]) + s.indicator (sᶜ.indicator (μ[sᶜ.indicator f|m])) : begin refine filter.eventually_eq.rfl.add _, have : sᶜ.indicator (μ[sᶜ.indicator f|m]) =ᵐ[μ] μ[sᶜ.indicator f|m], { refine (condexp_indicator_aux hs.compl _).symm.trans _, { exact indicator_ae_eq_restrict_compl (hm _ hs.compl), }, { rw [set.indicator_indicator, set.inter_self], }, }, filter_upwards [this] with x hx, by_cases hxs : x ∈ s, { simp only [hx, hxs, set.indicator_of_mem], }, { simp only [hxs, set.indicator_of_not_mem, not_false_iff], }, end ... =ᵐ[μ] s.indicator (μ[s.indicator f|m]) : by rw [set.indicator_indicator, set.inter_compl_self, set.indicator_empty', add_zero] ... =ᵐ[μ] μ[s.indicator f|m] : begin refine (condexp_indicator_aux hs _).symm.trans _, { exact indicator_ae_eq_restrict_compl (hm _ hs), }, { rw [set.indicator_indicator, set.inter_self], }, end end lemma condexp_restrict_ae_eq_restrict (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (hs_m : measurable_set[m] s) (hf_int : integrable f μ) : (μ.restrict s)[f | m] =ᵐ[μ.restrict s] μ[f | m] := begin haveI : sigma_finite ((μ.restrict s).trim hm), { rw ← restrict_trim hm _ hs_m, apply_instance, }, rw ae_eq_restrict_iff_indicator_ae_eq (hm _ hs_m), swap, { apply_instance, }, refine eventually_eq.trans _ (condexp_indicator hf_int hs_m), refine ae_eq_condexp_of_forall_set_integral_eq hm (hf_int.indicator (hm _ hs_m)) _ _ _, { intros t ht hμt, rw [← integrable_indicator_iff (hm _ ht), set.indicator_indicator, set.inter_comm, ← set.indicator_indicator], suffices h_int_restrict : integrable (t.indicator ((μ.restrict s)[f|m])) (μ.restrict s), { rw [integrable_indicator_iff (hm _ hs_m), integrable_on], rw [integrable_indicator_iff (hm _ ht), integrable_on] at h_int_restrict ⊢, exact h_int_restrict, }, exact integrable_condexp.indicator (hm _ ht), }, { intros t ht hμt, calc ∫ x in t, s.indicator ((μ.restrict s)[f|m]) x ∂μ = ∫ x in t, ((μ.restrict s)[f|m]) x ∂(μ.restrict s) : by rw [integral_indicator (hm _ hs_m), measure.restrict_restrict (hm _ hs_m), measure.restrict_restrict (hm _ ht), set.inter_comm] ... = ∫ x in t, f x ∂(μ.restrict s) : set_integral_condexp hm hf_int.integrable_on ht ... = ∫ x in t, s.indicator f x ∂μ : by rw [integral_indicator (hm _ hs_m), measure.restrict_restrict (hm _ hs_m), measure.restrict_restrict (hm _ ht), set.inter_comm], }, { exact (strongly_measurable_condexp.indicator hs_m).ae_strongly_measurable', }, end /-- If the restriction to a `m`-measurable set `s` of a σ-algebra `m` is equal to the restriction to `s` of another σ-algebra `m₂` (hypothesis `hs`), then `μ[f | m] =ᵐ[μ.restrict s] μ[f | m₂]`. -/ lemma condexp_ae_eq_restrict_of_measurable_space_eq_on {m m₂ m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) (hm₂ : m₂ ≤ m0) [sigma_finite (μ.trim hm)] [sigma_finite (μ.trim hm₂)] (hs_m : measurable_set[m] s) (hs : ∀ t, measurable_set[m] (s ∩ t) ↔ measurable_set[m₂] (s ∩ t)) : μ[f | m] =ᵐ[μ.restrict s] μ[f | m₂] := begin rw ae_eq_restrict_iff_indicator_ae_eq (hm _ hs_m), have hs_m₂ : measurable_set[m₂] s, { rwa [← set.inter_univ s, ← hs set.univ, set.inter_univ], }, by_cases hf_int : integrable f μ, swap, { simp_rw condexp_undef hf_int, }, refine ((condexp_indicator hf_int hs_m).symm.trans _).trans (condexp_indicator hf_int hs_m₂), refine ae_eq_of_forall_set_integral_eq_of_sigma_finite' hm₂ (λ s hs hμs, integrable_condexp.integrable_on) (λ s hs hμs, integrable_condexp.integrable_on) _ _ strongly_measurable_condexp.ae_strongly_measurable', swap, { have : strongly_measurable[m] (μ[s.indicator f | m]) := strongly_measurable_condexp, refine this.ae_strongly_measurable'.ae_strongly_measurable'_of_measurable_space_le_on hm hs_m (λ t, (hs t).mp) _, exact condexp_ae_eq_restrict_zero hs_m.compl (indicator_ae_eq_restrict_compl (hm _ hs_m)), }, intros t ht hμt, have : ∫ x in t, μ[s.indicator f|m] x ∂μ = ∫ x in s ∩ t, μ[s.indicator f|m] x ∂μ, { rw ← integral_add_compl (hm _ hs_m) integrable_condexp.integrable_on, suffices : ∫ x in sᶜ, μ[s.indicator f|m] x ∂μ.restrict t = 0, by rw [this, add_zero, measure.restrict_restrict (hm _ hs_m)], rw measure.restrict_restrict (measurable_set.compl (hm _ hs_m)), suffices : μ[s.indicator f|m] =ᵐ[μ.restrict sᶜ] 0, { rw [set.inter_comm, ← measure.restrict_restrict (hm₂ _ ht)], calc ∫ (x : α) in t, μ[s.indicator f|m] x ∂μ.restrict sᶜ = ∫ (x : α) in t, 0 ∂μ.restrict sᶜ : begin refine set_integral_congr_ae (hm₂ _ ht) _, filter_upwards [this] with x hx h using hx, end ... = 0 : integral_zero _ _, }, refine condexp_ae_eq_restrict_zero hs_m.compl _, exact indicator_ae_eq_restrict_compl (hm _ hs_m), }, have hst_m : measurable_set[m] (s ∩ t) := (hs _).mpr (hs_m₂.inter ht), simp_rw [this, set_integral_condexp hm₂ (hf_int.indicator (hm _ hs_m)) ht, set_integral_condexp hm (hf_int.indicator (hm _ hs_m)) hst_m, integral_indicator (hm _ hs_m), measure.restrict_restrict (hm _ hs_m), ← set.inter_assoc, set.inter_self], end end measure_theory
cad42995e4474be5f2b07a6383f190f62dd97fa5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/continuous_affine_map.lean
ab2ff1080e777e6290ec1b450b7cff292448bd1b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,606
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import topology.algebra.continuous_affine_map import analysis.normed_space.affine_isometry import analysis.normed_space.operator_norm /-! # Continuous affine maps between normed spaces. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file develops the theory of continuous affine maps between affine spaces modelled on normed spaces. In the particular case that the affine spaces are just normed vector spaces `V`, `W`, we define a norm on the space of continuous affine maps by defining the norm of `f : V →A[𝕜] W` to be `‖f‖ = max ‖f 0‖ ‖f.cont_linear‖`. This is chosen so that we have a linear isometry: `(V →A[𝕜] W) ≃ₗᵢ[𝕜] W × (V →L[𝕜] W)`. The abstract picture is that for an affine space `P` modelled on a vector space `V`, together with a vector space `W`, there is an exact sequence of `𝕜`-modules: `0 → C → A → L → 0` where `C`, `A` are the spaces of constant and affine maps `P → W` and `L` is the space of linear maps `V → W`. Any choice of a base point in `P` corresponds to a splitting of this sequence so in particular if we take `P = V`, using `0 : V` as the base point provides a splitting, and we prove this is an isometric decomposition. On the other hand, choosing a base point breaks the affine invariance so the norm fails to be submultiplicative: for a composition of maps, we have only `‖f.comp g‖ ≤ ‖f‖ * ‖g‖ + ‖f 0‖`. ## Main definitions: * `continuous_affine_map.cont_linear` * `continuous_affine_map.has_norm` * `continuous_affine_map.norm_comp_le` * `continuous_affine_map.to_const_prod_continuous_linear_map` -/ namespace continuous_affine_map variables {𝕜 R V W W₂ P Q Q₂ : Type*} variables [normed_add_comm_group V] [metric_space P] [normed_add_torsor V P] variables [normed_add_comm_group W] [metric_space Q] [normed_add_torsor W Q] variables [normed_add_comm_group W₂] [metric_space Q₂] [normed_add_torsor W₂ Q₂] variables [normed_field R] [normed_space R V] [normed_space R W] [normed_space R W₂] variables [nontrivially_normed_field 𝕜] [normed_space 𝕜 V] [normed_space 𝕜 W] [normed_space 𝕜 W₂] include V W /-- The linear map underlying a continuous affine map is continuous. -/ def cont_linear (f : P →A[R] Q) : V →L[R] W := { to_fun := f.linear, cont := by { rw affine_map.continuous_linear_iff, exact f.cont, }, .. f.linear, } @[simp] lemma coe_cont_linear (f : P →A[R] Q) : (f.cont_linear : V → W) = f.linear := rfl @[simp] lemma coe_cont_linear_eq_linear (f : P →A[R] Q) : (f.cont_linear : V →ₗ[R] W) = (f : P →ᵃ[R] Q).linear := by { ext, refl, } @[simp] lemma coe_mk_const_linear_eq_linear (f : P →ᵃ[R] Q) (h) : ((⟨f, h⟩ : P →A[R] Q).cont_linear : V → W) = f.linear := rfl lemma coe_linear_eq_coe_cont_linear (f : P →A[R] Q) : ((f : P →ᵃ[R] Q).linear : V → W) = (⇑f.cont_linear : V → W) := rfl include W₂ @[simp] lemma comp_cont_linear (f : P →A[R] Q) (g : Q →A[R] Q₂) : (g.comp f).cont_linear = g.cont_linear.comp f.cont_linear := rfl omit W₂ @[simp] lemma map_vadd (f : P →A[R] Q) (p : P) (v : V) : f (v +ᵥ p) = f.cont_linear v +ᵥ f p := f.map_vadd' p v @[simp] lemma cont_linear_map_vsub (f : P →A[R] Q) (p₁ p₂ : P) : f.cont_linear (p₁ -ᵥ p₂) = f p₁ -ᵥ f p₂ := f.to_affine_map.linear_map_vsub p₁ p₂ @[simp] lemma const_cont_linear (q : Q) : (const R P q).cont_linear = 0 := rfl lemma cont_linear_eq_zero_iff_exists_const (f : P →A[R] Q) : f.cont_linear = 0 ↔ ∃ q, f = const R P q := begin have h₁ : f.cont_linear = 0 ↔ (f : P →ᵃ[R] Q).linear = 0, { refine ⟨λ h, _, λ h, _⟩; ext, { rw [← coe_cont_linear_eq_linear, h], refl, }, { rw [← coe_linear_eq_coe_cont_linear, h], refl, }, }, have h₂ : ∀ (q : Q), f = const R P q ↔ (f : P →ᵃ[R] Q) = affine_map.const R P q, { intros q, refine ⟨λ h, _, λ h, _⟩; ext, { rw h, refl, }, { rw [← coe_to_affine_map, h], refl, }, }, simp_rw [h₁, h₂], exact (f : P →ᵃ[R] Q).linear_eq_zero_iff_exists_const, end @[simp] lemma to_affine_map_cont_linear (f : V →L[R] W) : f.to_continuous_affine_map.cont_linear = f := by { ext, refl, } @[simp] lemma zero_cont_linear : (0 : P →A[R] W).cont_linear = 0 := rfl @[simp] lemma add_cont_linear (f g : P →A[R] W) : (f + g).cont_linear = f.cont_linear + g.cont_linear := rfl @[simp] lemma sub_cont_linear (f g : P →A[R] W) : (f - g).cont_linear = f.cont_linear - g.cont_linear := rfl @[simp] lemma neg_cont_linear (f : P →A[R] W) : (-f).cont_linear = -f.cont_linear := rfl @[simp] lemma smul_cont_linear (t : R) (f : P →A[R] W) : (t • f).cont_linear = t • f.cont_linear := rfl lemma decomp (f : V →A[R] W) : (f : V → W) = f.cont_linear + function.const V (f 0) := begin rcases f with ⟨f, h⟩, rw [coe_mk_const_linear_eq_linear, coe_mk, f.decomp, pi.add_apply, linear_map.map_zero, zero_add], end section normed_space_structure variables (f : V →A[𝕜] W) /-- Note that unlike the operator norm for linear maps, this norm is _not_ submultiplicative: we do _not_ necessarily have `‖f.comp g‖ ≤ ‖f‖ * ‖g‖`. See `norm_comp_le` for what we can say. -/ noncomputable instance has_norm : has_norm (V →A[𝕜] W) := ⟨λ f, max ‖f 0‖ ‖f.cont_linear‖⟩ lemma norm_def : ‖f‖ = (max ‖f 0‖ ‖f.cont_linear‖) := rfl lemma norm_cont_linear_le : ‖f.cont_linear‖ ≤ ‖f‖ := le_max_right _ _ lemma norm_image_zero_le : ‖f 0‖ ≤ ‖f‖ := le_max_left _ _ @[simp] lemma norm_eq (h : f 0 = 0) : ‖f‖ = ‖f.cont_linear‖ := calc ‖f‖ = (max ‖f 0‖ ‖f.cont_linear‖) : by rw norm_def ... = (max 0 ‖f.cont_linear‖) : by rw [h, norm_zero] ... = ‖f.cont_linear‖ : max_eq_right (norm_nonneg _) noncomputable instance : normed_add_comm_group (V →A[𝕜] W) := add_group_norm.to_normed_add_comm_group { to_fun := λ f, max ‖f 0‖ ‖f.cont_linear‖, map_zero' := by simp, neg' := λ f, by simp, add_le' := λ f g, begin simp only [pi.add_apply, add_cont_linear, coe_add, max_le_iff], exact ⟨(norm_add_le _ _).trans (add_le_add (le_max_left _ _) (le_max_left _ _)), (norm_add_le _ _).trans (add_le_add (le_max_right _ _) (le_max_right _ _))⟩, end, eq_zero_of_map_eq_zero' := λ f h₀, begin rcases max_eq_iff.mp h₀ with ⟨h₁, h₂⟩ | ⟨h₁, h₂⟩; rw h₁ at h₂, { rw [norm_le_zero_iff, cont_linear_eq_zero_iff_exists_const] at h₂, obtain ⟨q, rfl⟩ := h₂, simp only [function.const_apply, coe_const, norm_eq_zero] at h₁, rw h₁, refl, }, { rw [norm_eq_zero', cont_linear_eq_zero_iff_exists_const] at h₁, obtain ⟨q, rfl⟩ := h₁, simp only [function.const_apply, coe_const, norm_le_zero_iff] at h₂, rw h₂, refl, }, end } instance : normed_space 𝕜 (V →A[𝕜] W) := { norm_smul_le := λ t f, by simp only [norm_def, smul_cont_linear, coe_smul, pi.smul_apply, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg t)], } lemma norm_comp_le (g : W₂ →A[𝕜] V) : ‖f.comp g‖ ≤ ‖f‖ * ‖g‖ + ‖f 0‖ := begin rw [norm_def, max_le_iff], split, { calc ‖f.comp g 0‖ = ‖f (g 0)‖ : by simp ... = ‖f.cont_linear (g 0) + f 0‖ : by { rw f.decomp, simp, } ... ≤ ‖f.cont_linear‖ * ‖g 0‖ + ‖f 0‖ : (norm_add_le _ _).trans (add_le_add_right (f.cont_linear.le_op_norm _) _) ... ≤ ‖f‖ * ‖g‖ + ‖f 0‖ : add_le_add_right (mul_le_mul f.norm_cont_linear_le g.norm_image_zero_le (norm_nonneg _) (norm_nonneg _)) _, }, { calc ‖(f.comp g).cont_linear‖ ≤ ‖f.cont_linear‖ * ‖g.cont_linear‖ : (g.comp_cont_linear f).symm ▸ f.cont_linear.op_norm_comp_le _ ... ≤ ‖f‖ * ‖g‖ : mul_le_mul f.norm_cont_linear_le g.norm_cont_linear_le (norm_nonneg _) (norm_nonneg _) ... ≤ ‖f‖ * ‖g‖ + ‖f 0‖ : by { rw le_add_iff_nonneg_right, apply norm_nonneg, }, }, end variables (𝕜 V W) /-- The space of affine maps between two normed spaces is linearly isometric to the product of the codomain with the space of linear maps, by taking the value of the affine map at `(0 : V)` and the linear part. -/ def to_const_prod_continuous_linear_map : (V →A[𝕜] W) ≃ₗᵢ[𝕜] W × (V →L[𝕜] W) := { to_fun := λ f, ⟨f 0, f.cont_linear⟩, inv_fun := λ p, p.2.to_continuous_affine_map + const 𝕜 V p.1, left_inv := λ f, by { ext, rw f.decomp, simp, }, right_inv := by { rintros ⟨v, f⟩, ext; simp, }, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl, norm_map' := λ f, rfl } @[simp] lemma to_const_prod_continuous_linear_map_fst (f : V →A[𝕜] W) : (to_const_prod_continuous_linear_map 𝕜 V W f).fst = f 0 := rfl @[simp] lemma to_const_prod_continuous_linear_map_snd (f : V →A[𝕜] W) : (to_const_prod_continuous_linear_map 𝕜 V W f).snd = f.cont_linear := rfl end normed_space_structure end continuous_affine_map
be5852a72aeb49fed6490c939d2ae3d897678e6b
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/proposition/9.lean
57a9c09f68092549fa4f0620c9980c90f6ae03fa
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
302
lean
example (A B C D E F G H I J K L : Prop) (f1 : A → B) (f2 : B → E) (f3 : E → D) (f4 : D → A) (f5 : E → F) (f6 : F → C) (f7 : B → C) (f8 : F → G) (f9 : G → J) (f10 : I → J) (f11 : J → I) (f12 : I → H) (f13 : E → H) (f14 : H → K) (f15 : I → L) : A → L := begin cc, end
b541573fcd819432678dbabf794c9d379567465b
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/filter_util.lean
7544b99e459402a8ffa0dc668f2189efb60ff4d8
[ "Apache-2.0" ]
permissive
eric-wieser/formal-ml
e278df5a8df78aa3947bc8376650419e1b2b0a14
630011d19fdd9539c8d6493a69fe70af5d193590
refs/heads/master
1,681,491,589,256
1,612,642,743,000
1,612,642,743,000
360,114,136
0
0
Apache-2.0
1,618,998,189,000
1,618,998,188,000
null
UTF-8
Lean
false
false
39,140
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import order.filter.basic import topology.bases import data.real.nnreal import topology.instances.real import topology.instances.nnreal import topology.instances.ennreal import topology.algebra.infinite_sum import formal_ml.set import formal_ml.finset import formal_ml.nat import formal_ml.ennreal import formal_ml.nnreal import data.finset import order.complete_lattice import formal_ml.real open finset lemma filter_le_intro (α:Type*) (A B:filter α): (∀ a, a∈ B → a∈ A)→ (A≤ B) := begin intros, apply (@filter.le_def α A B).mpr, assumption, end lemma filter_le_intro2 (α:Type*) (A B:filter α): (B.sets ⊆ A.sets)→ (A≤ B) := begin intros, apply (@filter.le_def α A B).mpr, have A1:((B.sets ⊆ A.sets) ↔ (∀ a∈ B.sets, a∈ A.sets)), { refl, }, assumption, end lemma filter_le_elim {α:Type*} {A B:filter α} {a:set α}: (A≤ B) → (a∈ B)→ (a∈ A) := begin intros, apply (@filter.le_def α A B).mp;assumption, end /- filter.map f A is the pre-image of the pre-image of the sets in A. --set.preimage f has type (set β)→ (set α) --set.preimage f B = {x:f x ∈ B} --set.preimage (set.preimage f) has type (set (set α)) → (set (set β)) --set.preimage (set.preimage f) AF = {y:(set.preimage f) y ∈ AF} --set.preimage (set.preimage f) AF = {y:{x:f x∈ y} ∈ AF} -/ lemma filter_map_def (α β:Type*) (A:filter α) (f:α → β): (filter.map f A).sets = set.preimage (set.preimage f) A.sets := begin refl, end lemma filter_mem_def (α:Type*) (A:filter α) (a:set α): (a∈ A) = (a ∈ A.sets) := begin refl, end lemma filter_map_intro (α β : Type*) (A : filter α) (f : α → β) (X : set α) (Y : set β) (a: X∈ A) (a_1 : X=set.preimage f Y) : (Y∈ filter.map f A) := begin rw filter_mem_def, rw filter_map_def, unfold set.preimage, simp, rw filter_mem_def at a, unfold set.preimage at a_1, rw ← a_1, assumption, end lemma filter_map_elim (α β:Type*) (A:filter α) (f:α → β) (Y:set β) (a : Y ∈ filter.map f A) : (∃ (X∈ A), (X=set.preimage f Y)) := begin rw filter_mem_def at a, rw filter_map_def at a, --unfold set.preimage, simp, unfold set.preimage at a, simp at a, apply a, end lemma filter_tendsto_intro (α β:Type*) (f:α → β) (A:filter α) (B:filter β): (∀ b∈ B, set.preimage f b ∈ A) → (@filter.tendsto α β f A B) := begin intros a, unfold filter.tendsto, apply filter_le_intro, intros a_1 a_2, apply filter_map_intro, have A1:a_1 ∈ B → f ⁻¹' a_1 ∈ A, { apply a, }, have A2:f ⁻¹' a_1 ∈ A, { apply A1, apply a_2, }, apply A2, refl, end lemma filter_tendsto_elim {α β:Type*} {f:α → β} {A:filter α} {B:filter β} {s:set β}: (@filter.tendsto α β f A B) →(s∈ B)→ (set.preimage f s ∈ A) := begin intros a a_1, unfold filter.tendsto at a, have A1:s∈ filter.map f A, { apply filter_le_elim, apply a, apply a_1, }, have A2:(∃ (X∈ A), (X=set.preimage f s)), { apply (filter_map_elim), apply A1, }, cases A2, cases A2_h, subst A2_w, exact A2_h_w, end lemma filter_principal_intro {α:Type*} (a:finset α) (b:set (finset α)): ({c : finset α | a ⊆ c} ⊆ b) → b ∈ (filter.principal {c:finset α | a⊆ c}):= begin --apply b∈ (filter.principal {c:finset ℕ | a⊆ c}), intros a_1, unfold filter.principal, have A1:b ∈ {t : set (finset α) | {c : finset α | a ⊆ c} ⊆ t}, { simp, apply a_1, }, apply A1, end lemma filter_principal_elim {α:Type*} (a:finset α) (b:set (finset α)): b ∈ (filter.principal {c:finset α | a⊆ c}) → ({c : finset α | a ⊆ c} ⊆ b) := begin intros a_1, apply (@filter.mem_principal_sets (finset α) b {c:finset α | a⊆ c}).mp, apply a_1, end lemma filter_principal_intro2 {α:Type*} (a:finset α) (b:set (finset α)): (∀ c:finset α, a⊆ c → c∈ b) → b ∈ (filter.principal {c:finset α | a⊆ c}):= begin intros a_1, apply filter_principal_intro, rw set.subset_def, intros a_3 a_2, simp at a_2, apply a_1, apply a_2, end lemma filter_principal_intro3 {α:Type*} (a b:set α): (a⊆ b) → b ∈ filter.principal a:= begin simp [filter.principal], end lemma filter_principal_elim2 {α:Type*} (a:finset α) (b:set (finset α)) (c:finset α): b ∈ (filter.principal {c:finset α | a⊆ c}) → (a ⊆ c) → (c∈ b) := begin intros a_1 a_2, apply (@filter_principal_elim α a b), { apply a_1, }, apply a_2, end lemma filter_principal_elim3 {α:Type*} (a b:set α): b ∈ filter.principal a → (a⊆ b):= begin unfold filter.principal, simp, end /- Let's walk through a simple example. b={1,2} c={2,3} filter.principal {{1,2},{1,2,3},{1,2,3,4}, {1,2,4}} ⊓ filter.principal {{1,3},{1,2,3},{1,2,3,4}, {1,3,4}} = filter.principal {{1,2,3}, {1,2,3,4}} -/ lemma principal_inf (α:Type*) (A B:set α): (filter.principal A ⊓ filter.principal B = filter.principal (A∩B)) := begin simp, end lemma principal_inf_sets2 {α:Type*} [semilattice_sup_bot α] (b c:α): filter.principal {d:α |b ≤ d} ⊓ filter.principal {d: α |c ≤ d} = filter.principal {d:α |(b ⊔ c) ≤ d} := begin have A1:{d:α |b ≤ d} ∩ {d:α |c ≤ d} = {d: α |(b ⊔ c) ≤ d}, { ext, split;intros a, { cases a, simp at a_left, simp at a_right, simp, split;assumption, }, { simp at a, cases a with A2 A3, split;simp;assumption, } }, rw ← A1, apply principal_inf, end -- Use apply principal_inf_sets2, lemma principal_inf_sets {α:Type*} [decidable_eq α] (b c:finset α): filter.principal {d:finset α |b ≤ d} ⊓ filter.principal {d:finset α |c ≤ d} = filter.principal {d:finset α |(b ∪ c) ≤ d} := begin apply principal_inf_sets2, end -- src/data/set/lattice.lean lemma set_Inf_def (α:Type*) (S:set (set α)): (Inf S) = {a | ∀ t ∈ S, a ∈ t } := begin refl, end lemma set_Inf_intro (α:Type*) (S:set (set α)) (x:α): (∀ X∈ S, x∈ X) → x∈ Inf S := begin intros a, rw set_Inf_def, simp, exact a, end lemma set_Inf_range_intro (α β:Type*) (f:α → set (β)) (x:β): (∀ y:α, x∈ f y) → x∈ Inf (set.range (λ (a : α), f a)) := begin intros a, apply set_Inf_intro, intros, unfold set.range at H, simp at H, cases H, rw ← H_h, apply a, end lemma glb_intro {α β:Type*} (f:α → set (β)) (x:β): (∀ a:α, x∈ f a) → x ∈ ⨅ a, f a := begin intros a, unfold infi, unfold Inf, apply set_Inf_range_intro, assumption, end lemma le_Inf_simp (α:Type*) (s : set (filter α)) (a : filter α) : (∀ (b : filter α ), b ∈ s → a ≤ b) → a ≤ complete_lattice.Inf s := begin intros a_1, apply (complete_lattice.le_Inf s), apply a_1, end lemma Inf_le_simp (α : Type*) (s : set (filter α)) (a : filter α) : a ∈ s → complete_lattice.Inf s ≤ a := begin intros a_1, apply (complete_lattice.Inf_le s), assumption, end lemma mem_Inf_intro {α : Type*} {s : set (filter α)} {a : filter α} {t:set α}: t ∈ a → a ∈ s → t∈ complete_lattice.Inf s := begin intros, apply (complete_lattice.Inf_le s), assumption, assumption end -- This is equivalent to filter.mem_infi (or a mem_Inf variant of mem_infi) def inf_filter_sets_def (α:Type*) (S : set (filter α)):set (set α) := {s:set α | ∃ f∈ S, s∈ f} lemma inf_filter_sets_of_superset2 (α:Type*) (S : set (filter α)) (s t:set α): s∈ (inf_filter_sets_def α S) → s⊆ t → t∈ (inf_filter_sets_def α S) := begin intro a, unfold inf_filter_sets_def, simp, unfold inf_filter_sets_def at a, simp at a, cases a, cases a_h, intros a_1, apply exists.intro a_w, split, { assumption, }, { apply filter.sets_of_superset, apply a_h_right, assumption, } end --This suggests the definition is overly simplistic. def inf_filter_sets_inter_sets2 (α:Type*) (S : set (filter α)) (H:∀ a b:filter α, a∈ S→ b∈ S→ a⊓b∈ S) (s t:set α): s∈ (inf_filter_sets_def α S) → t∈ (inf_filter_sets_def α S) → s ∩ t ∈ (inf_filter_sets_def α S) := begin unfold inf_filter_sets_def, simp only [and_imp, exists_prop, set.mem_set_of_eq, exists_imp_distrib], intros x a a_1 x_1 a_2 a_3, apply (exists.intro (x⊓x_1)), split, { apply H;assumption, }, { simp only [filter.mem_inf_sets, ← filter_mem_def], have B1:(s ∩ t) ∈ x ⊓ x_1 ↔ ∃t₁∈x, ∃t₂∈x_1, t₁ ∩ t₂ ⊆ (s ∩ t), apply filter.mem_inf_sets, apply B1.mpr, apply exists.intro s, apply exists.intro a_1, apply exists.intro t, apply exists.intro a_3, refl, } end lemma inf_filter_univ_sets2 (α:Type*) (S : set (filter α)) (b:filter α): (b∈ S) → set.univ ∈ (inf_filter_sets_def α S) := begin unfold inf_filter_sets_def, simp, intros h1, apply exists.intro b, repeat {assumption}, end def inf_filter_def2 (α:Type*) (S : set (filter α)) (b:filter α) (H:b∈ S) (H2:∀ a b:filter α, a∈ S→ b∈ S→ a⊓b∈ S):filter α := { sets := inf_filter_sets_def α S, sets_of_superset := inf_filter_sets_of_superset2 α S, univ_sets := (inf_filter_univ_sets2 α S b H), inter_sets := inf_filter_sets_inter_sets2 α S H2, } /- This definition is a little weak, as it assumes S is nonempty and closed under (binary) infimum. However, given these two constraints, the result is more elegant, and it corresponds to the generic result about filters, filter.eq_Inf_of_mem_sets_iff_exists_mem. -/ lemma Inf_filter_def (α:Type*) (S : set (filter α)) (b:filter α) (H:b∈ S) (H2:∀ a b:filter α, a∈ S→ b∈ S→ a⊓b∈ S) (s:set α): (s ∈ Inf S)↔ (∃ t∈ S, s∈ t) := begin have A1:(inf_filter_def2 α S b H H2) = Inf S, { apply filter.eq_Inf_of_mem_sets_iff_exists_mem, intros, unfold inf_filter_def2, simp, unfold inf_filter_sets_def, simp, }, rw ← A1, unfold inf_filter_def2, simp, unfold inf_filter_sets_def, simp, end lemma eq_Inf_of_mem_sets_iff_exists_mem {α:Type} {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) --def filter_from_element (α:Type) (a:α):filter α := filter.principal (λ a', a=a') --filter.principal s contains all the supersets of s. --if s is in F, then F also contains lemma le_principal (F:filter (finset ℕ)) (s:set (finset ℕ)): (s∈ F)→ (F ≤ filter.principal s) := begin intros a, apply (filter_le_intro2 (finset ℕ) F (filter.principal s)), rw set.subset_def, intros x a_1, unfold filter.principal at a_1, simp at a_1, apply filter.sets_of_superset, { apply a, }, { assumption, } end /- What is a neighborhood of x? First, for every open set containing x, consider the principal filter (set of all supersets). Now, let's consider the infimum of all those settings, keeping in mind that for a set, the inf (filter.principal S) (filter.principal T)=(filter.principal S∪T) (at this point, we should be able to write a proof for this). Since the union of two open sets containing X itself is an open set containing X, and every element has at least one neighborhood that contains it, we are OK. Thus, a neighborhood of x is a superset of an open set containing x. --a more standard definition of neighborhood. lemma mem_nhds_def (x:nnreal) (b:set nnreal): (b∈ nhds x)↔ (∃ u:set nnreal, (u⊆ b) ∧ is_open u ∧ x∈ u) := -/ lemma mem_nhds_elim_real_rat (b:set real) (x:real): b∈ nhds x → (∃ p q:ℚ, (p < q) ∧ ((set.Ioo p q:set ℝ) ⊆ b) ∧ ((p:ℝ) < x) ∧ (x < (q:ℝ))) := begin let rat_basis := (⋃ (a b : ℚ) (h : a < b), {set.Ioo ↑a ↑b}), begin intros a, have A1:topological_space.is_topological_basis rat_basis, { apply real.is_topological_basis_Ioo_rat, }, have A2: (b ∈ nhds x ↔ ∃ (t : set real) (H : t ∈ rat_basis), x ∈ t ∧ t ⊆ b), { apply @topological_space.mem_nhds_of_is_topological_basis, apply A1, }, have A3: (∃ (t : set real) (H : t ∈ rat_basis), x ∈ t ∧ t ⊆ b), { apply A2.mp, apply a, }, /- Now that we have proven A3, we are basically done. We just rewrite A3 into the statement of the theorem. -/ cases A3, cases A3_h, simp at A3_h_w, cases A3_h_w, cases A3_h_w_h, cases A3_h_w_h_h, subst A3_w, cases A3_h_h, apply exists.intro A3_h_w_w, apply exists.intro A3_h_w_h_w, unfold set.Ioo at A3_h_h_left, simp at A3_h_h_left, cases A3_h_h_left, split, { assumption, }, split, { assumption, }, split, { assumption, }, { assumption, }, end end ------ Move theorems here to where they belong ----------------------------------- lemma induced_topological_basis {α β:Type*} [Tα:topological_space α] [Tβ:topological_space β] {f:α → β} {S:set (set β)}:(inducing f) → (topological_space.is_topological_basis S) → (topological_space.is_topological_basis (set.image (set.preimage f) S)) := begin intros A1 A2, rw A1.induced, unfold topological_space.is_topological_basis, split, { intros t₁ A3 t₂ A4 x A5, cases A3 with u₁ A3, cases A4 with u₂ A4, cases A5 with A6 A7, cases A3 with A8 A9, cases A4 with A10 A11, subst t₁, subst t₂, simp at A6, simp at A7, have A12:f x ∈ u₁ ∩ u₂, { simp, apply and.intro A6 A7, }, unfold topological_space.is_topological_basis at A2, have A13 := A2.left u₁ A8 u₂ A10 (f x) A12, cases A13 with u₃ A13, cases A13 with A14 A15, cases A15 with A16 A17, apply exists.intro (f ⁻¹' u₃), have A18:f ⁻¹' u₃ ∈ set.preimage f '' S, { simp, apply exists.intro u₃, split, apply A14, refl, }, apply exists.intro A18, split, apply A16, { rw set.subset_inter_iff at A17, apply set.subset_inter;apply set.preimage_mono, apply A17.left, apply A17.right, }, }, split, { ext a,split;intro A3;simp, unfold topological_space.is_topological_basis at A2, have A4:f a ∈ ⋃₀ S, { rw A2.right.left, simp, }, cases A4 with X A5, cases A5 with A6 A7, apply exists.intro X, apply and.intro A6 A7, }, { unfold topological_space.is_topological_basis at A2, have A3 := A2.right.right, rw A3, apply induced_generate_from_eq, } end lemma nnreal_topological_space_def: nnreal.topological_space = @topological_space.induced nnreal real (@coe nnreal real _) (@uniform_space.to_topological_space real _) := rfl lemma inducing_nnreal_topological_space: inducing (@coe nnreal real _) := { induced := nnreal_topological_space_def, } lemma nnreal_nhds {x:nnreal}: nhds x = filter.comap (@coe nnreal real _) (nhds x.val) := begin apply inducing.nhds_eq_comap, apply inducing_nnreal_topological_space, end lemma nnreal_nhds2 {x:nnreal} {B:set nnreal}: B ∈ nhds x ↔ (∃ C∈ nhds (x.val),set.preimage (@coe nnreal real _) C⊆ B) := begin rw nnreal_nhds, apply filter.mem_comap_sets, end lemma coe_nnreal_real_val:(@coe nnreal real _) = subtype.val := rfl lemma mem_nhds_elim_real {b:set real} {x:real}: b∈ nhds x → (∃ p q:ℝ, (p < q) ∧ ((set.Ioo p q) ⊆ b) ∧ (p < x) ∧ (x < q)) := begin intros a, have A1:(∃ prat qrat:ℚ, (prat < qrat) ∧ ((set.Ioo prat qrat:set ℝ) ⊆ b) ∧ ((prat:ℝ) < x) ∧ (x < (qrat:ℝ))), { apply mem_nhds_elim_real_rat, apply a, }, cases A1, cases A1_h, cases A1_h_h, cases A1_h_h_right, cases A1_h_h_right_right, apply exists.intro (A1_w:ℝ), apply exists.intro (A1_h_w:ℝ), split, { apply (@rat.cast_lt real _ A1_w A1_h_w).mpr, apply A1_h_h_left, }, { split, { assumption, }, split, { apply A1_h_h_right_right_left, }, { apply A1_h_h_right_right_right, } }, end lemma mem_nhds_elim_nnreal {b:set nnreal} {x:nnreal}: b∈ nhds x → (∃ p q:ℝ, (p < q) ∧ (set.preimage (@coe nnreal real _) (set.Ioo p q) ⊆ b) ∧ (p < ↑x) ∧ (↑x < q)) := begin intro A1, rw nnreal_nhds2 at A1, cases A1 with C A1, cases A1 with A2 A3, have A4 := mem_nhds_elim_real A2, cases A4 with p A4, cases A4 with q A4, cases A4 with A5 A6, cases A6 with A7 A8, --cases A8 with A9 A10, apply exists.intro p, apply exists.intro q, split, apply A5, split, apply set.subset.trans, { apply set.preimage_mono, apply A7, }, { apply A3, }, apply A8, end lemma preimage_coe_Ioo {p q:ℝ}:(p < 0) → (0 ≤ q) → set.preimage (@coe nnreal real _) (set.Ioo p q) = set.Iio (nnreal.of_real q) := begin intro A1, intro A2, unfold set.Ioo set.Iio, ext,split;intro A3;simp at A3;simp, { cases A3 with A4 A5, rw ← nnreal.coe_lt_coe, rw nnreal.coe_of_real, apply A5, apply A2, }, { split, { apply lt_of_lt_of_le, apply A1, apply x.property, }, { rw ← nnreal.coe_of_real q, rw nnreal.coe_lt_coe, apply A3, apply A2, }, }, end lemma preimage_coe_Ioo2 {p q:ℝ}:(0 ≤ p) → (p < q) → set.preimage (@coe nnreal real _) (set.Ioo p q) = set.Ioo (nnreal.of_real p) (nnreal.of_real q) := begin intro A1, intro A2, have B1:0 ≤ q, { apply le_trans, apply A1, apply le_of_lt, apply A2, }, unfold set.Ioo, ext,split;intro A3;simp at A3;simp, { cases A3 with A4 A5, split;rw ← nnreal.coe_lt_coe;rw nnreal.coe_of_real, apply A4, apply A1, apply A5, apply B1, }, { cases A3 with A4 A5, split, { rw ← nnreal.coe_of_real p, rw nnreal.coe_lt_coe, apply A4, apply A1, }, { rw ← nnreal.coe_of_real q, rw nnreal.coe_lt_coe, apply A5, apply B1, }, }, end lemma mem_nhds_elim_nnreal2 {b:set nnreal} {x:nnreal}:x ≠ 0 → b∈ nhds x → (∃ p q:nnreal, (p < q) ∧ ((set.Ioo p q) ⊆ b) ∧ (p < x) ∧ (x < q)) := begin intros A1 A2, have A3 := mem_nhds_elim_nnreal A2, cases A3 with p A3, cases A3 with q A3, cases A3 with A4 A5, cases A5 with A6 A7, cases A7 with A8 A9, have A10:p < 0 ∨ 0 ≤ p := lt_or_le p 0, have A11:0 < x := bot_lt_iff_ne_bot.mpr A1, have A12:(@coe nnreal real _ 0) = (0:real) := rfl, have A13:x.val = (@coe nnreal real _ x) := rfl, have A14:0 < x.val, { rw A13, rw ← A12, rw nnreal.coe_lt_coe, apply A11, }, have A15:0 ≤ q, { apply le_trans, apply x.property, apply le_of_lt, apply A9, }, have A16:x < nnreal.of_real q, { rw ← nnreal.coe_lt_coe, rw nnreal.coe_of_real, apply A9, apply A15, }, cases A10, { apply exists.intro (0:nnreal), apply exists.intro (nnreal.of_real q), split, { rw ← nnreal.coe_lt_coe, rw A12, apply lt_trans, apply A14, rw A13, apply lt_of_lt_of_le, apply A9, rw nnreal.coe_of_real, apply A15, }, split, { have B2:set.Ioo 0 (nnreal.of_real q) ⊆ (set.preimage (@coe nnreal real _) (set.Ioo p q)), { rw preimage_coe_Ioo, rw set.subset_def, intros y B2A, unfold set.Iio, unfold set.Ioo at B2A, simp at B2A, simp, apply B2A.right, apply A10, apply A15, }, apply set.subset.trans B2 A6, }, split, { apply A11, }, { apply A16, }, }, { apply exists.intro (nnreal.of_real p), apply exists.intro (nnreal.of_real q), have B1:nnreal.of_real p < x, { rw ← nnreal.coe_lt_coe, rw nnreal.coe_of_real, apply A8, apply A10, }, split, { apply lt_trans B1 A16, }, split, { rw ← preimage_coe_Ioo2, apply A6, apply A10, apply A4, }, split, { apply B1, }, { apply A16, }, }, end lemma mem_nhds_elim_real_bound (b:set real) (x:real): b∈ nhds x → (∃ r>0, (set.Ioo (x-r) (x+r)) ⊆ b) := begin intros a, have A1:(∃ p q:ℝ, (p < q) ∧ ((set.Ioo p q) ⊆ b) ∧ (p < x) ∧ (x < q)), { apply mem_nhds_elim_real, apply a, }, cases A1, cases A1_h, cases A1_h_h, cases A1_h_h_right, cases A1_h_h_right_right, let r := min (x - A1_w) (A1_h_w -x), begin apply exists.intro r, have A2:r>0, { apply lt_min, { apply (@lt_sub real _ 0 x A1_w).mpr, simp, assumption, }, { apply (@lt_sub real _ 0 A1_h_w x).mpr, simp, assumption, } }, apply exists.intro A2, have A3:set.Ioo (x-r) (x+r) ⊆ set.Ioo A1_w A1_h_w, { unfold set.Ioo, simp, intros a_1 a_2 a_3, split, { apply lt_of_le_of_lt, show x - r < a_1, { assumption, }, { have A4:r <= x - A1_w, apply min_le_left, apply (@le_sub real _ r x A1_w).mp, assumption, } }, { apply lt_of_lt_of_le, { apply a_3, }, { -- prove x + r ≤ A1_h_w have A6:r <= A1_h_w - x, apply min_le_right, --rw A7, apply (@le_neg_add_iff_add_le real _ x r A1_h_w).mp, have A7:((-x)+A1_h_w=A1_h_w-x), { apply real.linear_ordered_comm_ring.add_comm, }, rw A7, assumption, } }, }, apply set.subset.trans, apply A3, assumption, end end lemma nnreal_sub_le_sub_of_le2 {a b c:nnreal}:a ≤ b → a - c ≤ b - c := begin intro A1, have A2:(c ≤ a) ∨ (a ≤ c) := le_total c a, cases A2, { rw ← add_le_add_iff_right c, rw nnreal.sub_add_cancel_of_le A2, rw nnreal.sub_add_cancel_of_le (le_trans A2 A1), apply A1, }, { rw nnreal.sub_eq_zero A2, apply bot_le, }, end lemma nnreal_le_sub_of_le_sub_of_le {p x r:nnreal}:p ≤ x → r ≤ x - p → p ≤ x - r := begin intros A1 A2, rw ← add_le_add_iff_right p at A2, rw nnreal.sub_add_cancel_of_le A1 at A2, have A3:(r + p) - r ≤ x - r := nnreal_sub_le_sub_of_le2 A2, rw add_comm r p at A3, rw nnreal.add_sub_cancel at A3, apply A3, end --TODO: remove dependence on x≠0 lemma mem_nhds_elim_nnreal_bound (b:set nnreal) (x:nnreal):x ≠ 0 → b∈ nhds x → (∃ r>0, (set.Ioo (x-r) (x+r)) ⊆ b) := begin intros AX a, have A1:(∃ p q:nnreal, (p < q) ∧ ((set.Ioo p q) ⊆ b) ∧ (p < x) ∧ (x < q)), { apply mem_nhds_elim_nnreal2, apply AX, apply a, }, cases A1 with p A1, cases A1 with q A1, cases A1 with B1 B2, cases B2 with B2 B3, cases B3 with B3 B4, let r := min (x - p) (q -x), begin apply exists.intro r, have A2:r>0, { apply lt_min;rw nnreal.sub_pos, { apply B3, }, { apply B4, } }, apply exists.intro A2, have A3:set.Ioo (x-r) (x+r) ⊆ set.Ioo p q, { apply set.Ioo_subset_Ioo, { have A4:r <= x - p := min_le_left (x-p) (q - x), apply nnreal_le_sub_of_le_sub_of_le (le_of_lt B3) A4, }, { have A4:r <= q - x := min_le_right (x-p) (q - x), rw ← add_le_add_iff_left x at A4, apply le_trans A4, rw add_comm x, rw nnreal.sub_add_cancel_of_le (le_of_lt B4), }, }, apply set.subset.trans, apply A3, assumption, end end --This is filter.at_top_def lemma filter_at_top_def3 {α:Type*} [preorder α]: filter.at_top = ⨅ a:α, filter.principal {b | a ≤ b} := rfl lemma filter_at_top_def (α:Type*): (@filter.at_top (finset α) _)= ⨅ (a:(finset α)), filter.principal {b:finset α | a⊆ b} := rfl --This is (roughly) filter.at_top_mem_sets lemma mem_filter_at_top_def2 {α:Type*} [SL:semilattice_sup_bot α] {S:set α}: (S∈ @filter.at_top α _)↔ (∃ a:α, {b:α|a ≤ b}⊆ S) := begin have B1:order_bot α := semilattice_sup_bot.to_order_bot α, have B2:has_bot α := order_bot.to_has_bot α, rw filter_at_top_def3, unfold infi, have A1:(∀ X Y:filter α, X ∈ (set.range (λ (a :α), filter.principal {b : α | a ≤ b})) → Y ∈ (set.range (λ (a : α), filter.principal {b : α | a ≤ b})) → X ⊓ Y ∈ (set.range (λ (a : α), filter.principal {b : α | a ≤ b}))), { intros X Y a a_1, simp at a, cases a, subst X, simp at a_1, cases a_1, subst Y, --simp, apply exists.intro (a_w ⊔ a_1_w), symmetry, apply principal_inf_sets2, }, have A2:filter.principal {b : α | ⊥ ≤ b} ∈ (set.range (λ (a : α), filter.principal {b : α | a ≤ b})), { rw set.mem_range, apply exists.intro ⊥, refl, }, have A3:(S ∈ Inf (set.range (λ (a : α), filter.principal {b : α | a ≤ b})))↔ (∃ t∈ (set.range (λ (a : α), filter.principal {b : α | a ≤ b})), S∈ t), { apply (@Inf_filter_def (α) (set.range (λ (a : α), filter.principal {b : α | a ≤ b})) (filter.principal {b : α | ⊥ ≤ b}) A2 A1 ), }, apply iff.trans, apply A3, split;intros a, { cases a, cases a_h, simp at a_h_w, cases a_h_w, apply exists.intro a_h_w_w, simp, subst a_w, simp at a_h_h, exact a_h_h, }, { cases a, apply exists.intro (filter.principal {b : α | a_w ≤ b}), have A4:filter.principal {b : α | a_w ≤ b} ∈ set.range (λ (a : α), filter.principal {b : α | a ≤ b}), { simp, }, apply exists.intro A4, apply a_h, } end lemma filter_at_top_def2 (α:Type*) [decidable_eq α] (S:set (finset α)): (S∈ @filter.at_top (finset α) _)↔ (∃ a:finset α, {b:finset α|a ≤ b}⊆ S) := begin apply mem_filter_at_top_def2, end --See alternatives below. lemma filter_at_top_intro {α:Type*} (b:set (finset α)) (c:finset α): (b∈ (filter.principal {d:finset α |c ≤ d} )) → (b ∈ (@filter.at_top (finset α) _)) := begin intros, rw filter_at_top_def, unfold infi, apply Inf_le_simp, { have A1:(filter.principal {d:finset α |c ≤ d} ) ∈ set.range (λ (a : finset α), filter.principal {b : finset α | a ⊆ b}), { unfold set.range, simp, }, apply A1, }, { assumption, } end lemma filter_at_top_elim {α:Type*} [decidable_eq α] {S:set (finset α)} : (S ∈ (@filter.at_top (finset α) _))→ (∃ a:(finset α), {b:finset α|a ≤ b}⊆ S) := begin apply (filter_at_top_def2 α S).mp, end lemma filter_at_top_intro2 {α:Type*} (b:set (finset α)) (c:finset α): ({d:finset α |c ≤ d} ⊆ b) → (b ∈ (@filter.at_top (finset α) _)) := begin intros a, have A1:b∈ filter.principal {d:finset α |c ≤ d}, { unfold filter.principal, simp, apply a, }, apply filter_at_top_intro, apply A1, end lemma filter_contains_preimage_superset (α β:Type) (B:filter β) (S T:set α) (f:β → α): (S⊆ T)→ ({x:β |f x ∈ S}∈ B) → ({x:β |f x ∈ T}∈ B) := begin intros a a_1, have A1:{x:β |f x ∈ S} ⊆ {x:β |f x ∈ T}, { apply set.preimage_mono, assumption, }, apply B.sets_of_superset, apply a_1, assumption, end lemma filter_at_top_intro3 {α β:Type*} (c:finset α) (S:set β) (f:finset α → β): (∀ d ≥ c, f d ∈ S) → ({x:finset α|f x∈ S} ∈ (@filter.at_top (finset α) _)) := begin intros a, have A1:({d:finset α |c ≤ d} ⊆ {x:finset α|f x∈ S}), { rw set.subset_def, intros x a_1, simp, simp at a_1, apply a, apply a_1, }, apply filter_at_top_intro2, apply A1, end lemma mem_filter_at_top_intro {α:Type*} [P:semilattice_sup_bot α] {S:set α} {x:α}: {y|x≤ y}⊆ S → S∈ (@filter.at_top α _) := begin intro A1, rw mem_filter_at_top_def2, apply exists.intro x, apply A1, end lemma mem_filter_at_top_elim {α:Type*} [P:semilattice_sup_bot α] {S:set α} : (S ∈ (@filter.at_top α _))→ (∃ a:α, {b:α|a ≤ b}⊆ S) := begin apply (mem_filter_at_top_def2).mp, end lemma in_own_Ioo {x ε:ℝ}:(0 < ε)→ x ∈ set.Ioo (x -ε) (x + ε) := begin apply x_in_Ioo, end /- Unused. -/ lemma mem_nhds_elim_helper (b:set nnreal) (x:nnreal) (s:set nnreal) (H2 : s ∈ {s : set nnreal | x ∈ s ∧ is_open s}): (set.range (λ (H : s ∈ {s : set nnreal | x ∈ s ∧ is_open s}), filter.principal s)) = {x:filter nnreal| x=filter.principal s} := begin unfold set.range, simp, ext, split, { simp, intros a a_1 a_2, symmetry, exact a_2, }, { simp, intros a, split, { apply H2, }, { symmetry, assumption, } } end lemma lim_Inf_filter_empty (α:Type*): (@Inf (filter α) _ ∅) = ⊤ := begin simp, end lemma set_in_lattice_infih (α:Type*) (s:set α) (S:set (set α)) (H2 : s ∉ S): (set.range (λ (H : s ∈ S), filter.principal s)) = ∅ := begin unfold set.range, simp, rw set.eq_empty_iff_forall_not_mem, intros F, simp, intros B1 B2, apply H2, apply B1 end lemma set_in_lattice_infih2 (α:Type*) (s:set α) (S:set (set α)) (H2 : s ∈ S): (set.range (λ (H : s ∈ S), filter.principal s)) = {filter.principal s} := begin unfold set.range, simp, ext, split, { simp, intros a a_1, symmetry, exact a_1, }, { simp, intros a, split, { apply H2, }, { symmetry, exact a, } } end lemma lower_bounds_top (α:Type*) (S:set (filter α)):lower_bounds S = lower_bounds (S ∪ {⊤}) := begin ext, unfold lower_bounds, split;intros a; simp only [true_and, set.mem_insert_iff, forall_eq_or_imp, le_top, set.mem_set_of_eq, set.union_singleton]; simp only [true_and, set.mem_insert_iff, forall_eq_or_imp, le_top, set.mem_set_of_eq, set.union_singleton] at a;intros; { apply a, assumption, }, end lemma Inf_union_top (α:Type*) (S:set (filter α)): Inf (S∪ {⊤}) = Inf S := begin have A2:is_glb S (Inf S), { apply is_glb_Inf, }, have A3:is_glb (S∪ {⊤}) (Inf S), { cases A2, split, { rw ← lower_bounds_top, exact A2_left, }, { rw ← lower_bounds_top, exact A2_right, } }, apply is_glb.Inf_eq A3, end /- If we unfold infi in nhds, we get a doubly-nested Infimum that is hard to work with. This rewrites it more simply. -/ lemma set_in_lattice_infi (α:Type*) (S:set (set α)): (⨅ (s∈ S), (filter.principal s)) = Inf (set.image (filter.principal) S) := begin unfold infi, rw ← (@set.image_union_image_compl_eq_range (set α) _ S), have A1:(λ (s : set α), Inf (set.range (λ (H : s ∈ S), filter.principal s))) '' (S)ᶜ = (λ (s : set α), ⊤) '' Sᶜ, { rw set.image_congr, intros, have A1AA:set.range (λ (H : a ∈ S), filter.principal a) = ∅, { apply set_in_lattice_infih, apply H, }, rw A1AA, rw lim_Inf_filter_empty, }, rw A1, have A2:(λ (s : set α), Inf (set.range (λ (H : s ∈ S), filter.principal s))) '' (S) = (λ (s : set α), filter.principal s) '' S, { rw set.image_congr, intros, have A2A:set.range (λ (H : a ∈ S), filter.principal a) = {filter.principal a}, { apply set_in_lattice_infih2, apply H, }, rw A2A, simp, }, rw A2, have A4:(Sᶜ = ∅)∨ set.nonempty Sᶜ, { apply set.eq_empty_or_nonempty, }, cases A4, { rw A4, simp, }, { rw set.nonempty_def at A4, cases A4, have A4A:∀ k:filter α,(λ (s : set α), k) '' Sᶜ = {k}, { intros, ext, split;intros a, { cases a, cases a_h, simp at a_h_right, rw a_h_right, apply (set.mem_singleton), }, { split, { split, apply A4_h, simp, simp at a, rw a, } } }, have A4B:(λ (s : set α), ⊤) '' Sᶜ = {⊤}, { apply (A4A ⊤), }, rw A4B, apply Inf_union_top, } end lemma open_nhds_inter (α:Type*) [topological_space α] (x:α) (A B:set α): (A∈ {s:set α|x∈ s∧ is_open s}) → (B∈ {s:set α|x∈ s∧ is_open s}) → ((A∩ B) ∈ {s:set α|x∈ s∧ is_open s}) := begin intros a a_1, cases a, cases a_1, split, { split;assumption, }, { apply is_open_inter;assumption, }, end lemma nhds_def1 (α:Type*) [topological_space α] (x:α): nhds x = Inf (set.image (filter.principal) {S:set α|x∈ S ∧ is_open S}) := begin unfold nhds, unfold infi, apply set_in_lattice_infi, end /- This holds for an arbitrary topology. See @mem_nhds_sets_iff -/ lemma mem_nhds_intro_real2 {b U:set real} {x:real}: x∈ U → is_open U → U ⊆ b → b∈ nhds x := begin intros A1 A2 A3, rw nhds_def1, have A4:b∈ filter.principal U, { apply filter_principal_intro3, apply A3, }, apply mem_Inf_intro A4, { simp, split;assumption, }, end /- This holds for a (closed) order topology (I think) -/ lemma mem_nhds_intro_real (b:set real) (x y z:real): x∈ set.Ioo y z → set.Ioo y z ⊆ b → b∈ nhds x := begin intros A1 A2, apply mem_nhds_intro_real2 A1 _ A2, apply @is_open_Ioo ℝ _ _ _ y z, end lemma mem_nhds_filter_principal_intro (α:Type*) [topological_space α] (x:α) (V:set α): V∈ {S:set α|x∈ S ∧ is_open S}→ filter.principal V ∈ (set.image (filter.principal) {S:set α|x∈ S ∧ is_open S}) := begin intros a, simp only [filter.principal_eq_iff_eq, set.mem_image, exists_eq_right, set.mem_set_of_eq], assumption, end lemma mem_nhds_filter_principal_elim (α:Type*) [topological_space α] (x:α) (V:set α): filter.principal V ∈ (set.image (filter.principal) {S:set α|x∈ S ∧ is_open S}) → V∈ {S:set α|x∈ S ∧ is_open S} := begin intros a, simp at a, apply a, end lemma mem_nhds_filter_principal_elim2 (α:Type*) [topological_space α] (x:α) (Z:filter α): Z ∈ (set.image (filter.principal) {S:set α|x∈ S ∧ is_open S}) → (∃ V:set α, V∈ {S:set α|x∈ S ∧ is_open S} ∧ filter.principal V = Z) := begin intros a, simp at a, apply a, end lemma has_open_neighborhood (α:Type*) [topological_space α] (x:α):∃ U:set α, x∈ U ∧ is_open U := begin apply exists.intro set.univ, split, { simp, }, { apply topological_space.is_open_univ, } end lemma nhds_def2 (α:Type*) [topological_space α] (x:α) (S:set α): S ∈ nhds x ↔ (∃ u:set α, (u⊆ S) ∧ is_open u ∧ (x∈ u)) := begin rw nhds_def1, have H:∃ U:set α, x∈ U ∧ is_open U, apply has_open_neighborhood, cases H, cases H_h, apply iff.trans, { apply Inf_filter_def, { apply mem_nhds_filter_principal_intro, simp, split, { apply H_h_left, }, { apply H_h_right, } }, { intros a b a_1 a_2, have A1:(∃ V:set α, V∈ {S:set α|x∈ S ∧ is_open S} ∧ filter.principal V = a), { apply mem_nhds_filter_principal_elim2, apply a_1, }, cases A1, cases A1_h, subst a, have A2:(∃ V:set α, V∈ {S:set α|x∈ S ∧ is_open S} ∧ filter.principal V = b), { apply mem_nhds_filter_principal_elim2, apply a_2, }, cases A2, cases A2_h, subst b, have A3:((A1_w ∩ A2_w) ∈ {s:set α|x∈ s∧ is_open s}), { apply open_nhds_inter;assumption, }, rw principal_inf, split, { split, { apply A3, }, { refl, } } } }, { split;intros a, { cases a, cases a_h, have A4:(∃ V:set α, V∈ {S:set α|x∈ S ∧ is_open S} ∧ filter.principal V = a_w), { apply mem_nhds_filter_principal_elim2, apply a_h_w, }, cases A4, cases A4_h, subst a_w, apply exists.intro A4_w, cases A4_h_left, split, { assumption, }, split;assumption, }, { cases a, cases a_h, cases a_h_right, apply exists.intro (filter.principal a_w), { have A5:filter.principal a_w ∈ filter.principal '' {S : set α | x ∈ S ∧ is_open S}, { apply mem_nhds_filter_principal_intro, split;assumption, }, apply exists.intro A5, apply filter_principal_intro3, assumption, } } } end lemma nhds_contain_point (α:Type*) [topological_space α] (x:α) (S:set α): S ∈ nhds x → x∈ S := begin intros a, have A1:(∃ u:set α, (u⊆ S) ∧ is_open u ∧ (x∈ u)), { apply (nhds_def2 α x S).mp a, }, cases A1, cases A1_h, rw set.subset_def at A1_h_left, apply A1_h_left, apply A1_h_right.right, end lemma Ioo_nbhd {x ε:ℝ}:(0 < ε)→ set.Ioo (x -ε) (x + ε) ∈ nhds x := begin intro A1, apply mem_nhds_intro_real, apply in_own_Ioo A1, apply set.subset.refl, end --Remove dependency on not equal to zero. lemma set_Ioo_in_nhds_of_ne_zero {x:nnreal} {ε:nnreal}:x ≠ 0 → ε >0 → set.Ioo (x - ε) (x + ε) ∈ nhds x := begin intros A1 A2, rw @mem_nhds_sets_iff, -- have A3:(ε≤x) ∨ (x < ε) := le_or_lt ε x, apply exists.intro (set.Ioo (x - ε) (x + ε)), split, apply @complete_lattice.le_refl (set nnreal) (@set.lattice_set nnreal), split, apply is_open_Ioo, simp, split, { apply nnreal.sub_lt_self, { apply bot_lt_iff_ne_bot.mpr, apply A1, }, { apply A2, }, }, { apply A2, }, end --TODO: remove dependence on x ≠ 0 lemma set_Iio_in_nhds_of_lt {x y:nnreal}:x ≠ 0 → x < y → set.Iio y ∈ nhds x := begin intros AX A1, rw @mem_nhds_sets_iff, apply exists.intro (set.Ioo 0 y), split, { apply set.Ioo_subset_Iio_self, }, split, { apply is_open_Ioo, }, simp, split, { apply bot_lt_iff_ne_bot.mpr, apply AX, }, { apply A1, }, end
59b84c90f1f3acad6dcf9d70112ff7022a53e8fc
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/category_theory/types.lean
47b5a6b5068fd4ded01e8b3b1443b44ff6f384df
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
9,495
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl -/ import category_theory.fully_faithful import data.equiv.basic /-! # The category `Type`. In this section we set up the theory so that Lean's types and functions between them can be viewed as a `large_category` in our framework. Lean can not transparently view a function as a morphism in this category, and needs a hint in order to be able to type check. We provide the abbreviation `as_hom f` to guide type checking, as well as a corresponding notation `↾ f`. (Entered as `\upr `.) We provide various simplification lemmas for functors and natural transformations valued in `Type`. We define `ulift_functor`, from `Type u` to `Type (max u v)`, and show that it is fully faithful (but not, of course, essentially surjective). We prove some basic facts about the category `Type`: * epimorphisms are surjections and monomorphisms are injections, * `iso` is both `iso` and `equiv` to `equiv` (at least within a fixed universe), * every type level `is_lawful_functor` gives a categorical functor `Type ⥤ Type` (the corresponding fact about monads is in `src/category_theory/monad/types.lean`). -/ namespace category_theory universes v v' w u u' -- declare the `v`'s first; see `category_theory.category` for an explanation instance types : large_category (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } lemma types_hom {α β : Type u} : (α ⟶ β) = (α → β) := rfl lemma types_id (X : Type u) : 𝟙 X = id := rfl lemma types_comp {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl @[simp] lemma types_id_apply (X : Type u) (x : X) : ((𝟙 X) : X → X) x = x := rfl @[simp] lemma types_comp_apply {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := rfl /-- `as_hom f` helps Lean type check a function as a morphism in the category `Type`. -/ -- Unfortunately without this wrapper we can't use `category_theory` idioms, such as `is_iso f`. abbreviation as_hom {α β : Type u} (f : α → β) : α ⟶ β := f -- If you don't mind some notation you can use fewer keystrokes: notation `↾` f : 200 := as_hom f -- type as \upr in VScode section -- We verify the expected type checking behaviour of `as_hom`. variables (α β γ : Type u) (f : α → β) (g : β → γ) example : α → γ := ↾f ≫ ↾g example [is_iso ↾f] : mono ↾f := by apply_instance example [is_iso ↾f] : ↾f ≫ inv ↾f = 𝟙 α := by simp end namespace functor variables {J : Type u} [category.{v} J] /-- The sections of a functor `J ⥤ Type` are the choices of a point `u j : F.obj j` for each `j`, such that `F.map f (u j) = u j` for every morphism `f : j ⟶ j'`. We later use these to define limits in `Type` and in many concrete categories. -/ def sections (F : J ⥤ Type w) : set (Π j, F.obj j) := { u | ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'} end functor namespace functor_to_types variables {C : Type u} [category.{v} C] (F G H : C ⥤ Type w) {X Y Z : C} variables (σ : F ⟶ G) (τ : G ⟶ H) @[simp] lemma map_comp_apply (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp [types_comp] @[simp] lemma map_id_apply (a : F.obj X) : (F.map (𝟙 X)) a = a := by simp [types_id] lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) := congr_fun (σ.naturality f) x @[simp] lemma comp (x : F.obj X) : (σ ≫ τ).app X x = τ.app X (σ.app X x) := rfl variables {D : Type u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟶ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl @[simp] lemma map_inv_map_hom_apply (f : X ≅ Y) (x : F.obj X) : F.map f.inv (F.map f.hom x) = x := congr_fun (F.map_iso f).hom_inv_id x @[simp] lemma map_hom_map_inv_apply (f : X ≅ Y) (y : F.obj Y) : F.map f.hom (F.map f.inv y) = y := congr_fun (F.map_iso f).inv_hom_id y end functor_to_types /-- The isomorphism between a `Type` which has been `ulift`ed to the same universe, and the original type. -/ def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy /-- The functor embedding `Type u` into `Type (max u v)`. Write this as `ulift_functor.{5 2}` to get `Type 2 ⥤ Type 5`. -/ def ulift_functor : Type u ⥤ Type (max u v) := { obj := λ X, ulift.{v} X, map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } @[simp] lemma ulift_functor_map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) : ulift_functor.map f x = ulift.up (f x.down) := rfl instance ulift_functor_full : full ulift_functor := { preimage := λ X Y f x, (f (ulift.up x)).down } instance ulift_functor_faithful : faithful ulift_functor := { injectivity' := λ X Y f g p, funext $ λ x, congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) } /-- Any term `x` of a type `X` corresponds to a morphism `punit ⟶ X`. -/ -- TODO We should connect this to a general story about concrete categories -- whose forgetful functor is representable. def hom_of_element {X : Type u} (x : X) : punit ⟶ X := λ _, x lemma hom_of_element_eq_iff {X : Type u} (x y : X) : hom_of_element x = hom_of_element y ↔ x = y := ⟨λ H, congr_fun H punit.star, by cc⟩ lemma mono_iff_injective {X Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intros H x x' h, resetI, rw ←hom_of_element_eq_iff at ⊢ h, exact (cancel_mono f).mp h }, { refine λ H, ⟨λ Z g h H₂, _⟩, ext z, replace H₂ := congr_fun H₂ z, exact H H₂ } end lemma epi_iff_surjective {X Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { intros H, let g : Y ⟶ ulift Prop := λ y, ⟨true⟩, let h : Y ⟶ ulift Prop := λ y, ⟨∃ x, f x = y⟩, suffices : f ≫ g = f ≫ h, { resetI, rw cancel_epi at this, intro y, replace this := congr_fun this y, replace this : true = ∃ x, f x = y := congr_arg ulift.down this, rw ←this, trivial }, ext x, change true ↔ ∃ x', f x' = f x, rw true_iff, exact ⟨x, rfl⟩ }, { intro H, constructor, intros Z g h H₂, apply funext, rw ←forall_iff_forall_surj H, intro x, exact (congr_fun H₂ x : _) } end section /-- `of_type_functor m` converts from Lean's `Type`-based `category` to `category_theory`. This allows us to use these functors in category theory. -/ def of_type_functor (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] : Type u ⥤ Type v := { obj := m, map := λα β, _root_.functor.map, map_id' := assume α, _root_.functor.map_id, map_comp' := assume α β γ f g, funext $ assume a, is_lawful_functor.comp_map f g _ } variables (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] @[simp] lemma of_type_functor_obj : (of_type_functor m).obj = m := rfl @[simp] lemma of_type_functor_map {α β} (f : α → β) : (of_type_functor m).map f = (_root_.functor.map f : m α → m β) := rfl end end category_theory -- Isomorphisms in Type and equivalences. namespace equiv universe u variables {X Y : Type u} /-- Any equivalence between types in the same universe gives a categorical isomorphism between those types. -/ def to_iso (e : X ≃ Y) : X ≅ Y := { hom := e.to_fun, inv := e.inv_fun, hom_inv_id' := funext e.left_inv, inv_hom_id' := funext e.right_inv } @[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl @[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl end equiv namespace category_theory.iso open category_theory universe u variables {X Y : Type u} /-- Any isomorphism between types gives an equivalence. -/ def to_equiv (i : X ≅ Y) : X ≃ Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, congr_fun i.hom_inv_id x, right_inv := λ y, congr_fun i.inv_hom_id y } @[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl @[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl @[simp] lemma to_equiv_id (X : Type u) : (iso.refl X).to_equiv = equiv.refl X := rfl @[simp] lemma to_equiv_comp {X Y Z : Type u} (f : X ≅ Y) (g : Y ≅ Z) : (f ≪≫ g).to_equiv = f.to_equiv.trans (g.to_equiv) := rfl end category_theory.iso universe u -- We prove `equiv_iso_iso` and then use that to sneakily construct `equiv_equiv_iso`. -- (In this order the proofs are handled by `obviously`.) /-- equivalences (between types in the same universe) are the same as (isomorphic to) isomorphisms of types -/ @[simps] def equiv_iso_iso {X Y : Type u} : (X ≃ Y) ≅ (X ≅ Y) := { hom := λ e, e.to_iso, inv := λ i, i.to_equiv, } /-- equivalences (between types in the same universe) are the same as (equivalent to) isomorphisms of types -/ -- We leave `X` and `Y` as explicit arguments here, because the coercions from `equiv` to a function won't fire without them. def equiv_equiv_iso (X Y : Type u) : (X ≃ Y) ≃ (X ≅ Y) := (equiv_iso_iso).to_equiv @[simp] lemma equiv_equiv_iso_hom {X Y : Type u} (e : X ≃ Y) : (equiv_equiv_iso X Y) e = e.to_iso := rfl @[simp] lemma equiv_equiv_iso_inv {X Y : Type u} (e : X ≅ Y) : (equiv_equiv_iso X Y).symm e = e.to_equiv := rfl
9c0ccadaeabe7afc33031e26262b7da95ac24cda
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/rat/cast.lean
4d3f63c462d79397237057fb2ddf0fd925a2de83
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
12,803
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.order import data.int.char_zero /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ namespace rat variable {α : Type*} open_locale rat section with_div_ring variable [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℚ α := ⟨λ r, r.1 / r.2⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp, norm_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem cast_commute (r : ℚ) (a : α) : commute ↑r a := (r.1.cast_commute a).div_left (r.2.cast_commute a) theorem cast_comm (r : ℚ) (a : α) : (r : α) * a = a * r := (cast_commute r a).eq theorem commute_cast (a : α) (r : ℚ) : commute a r := (r.cast_commute a).symm @[norm_cast] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a / b : α) = n / d, rw [div_eq_mul_inv, eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end @[norm_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv_rev', d₁0, d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, (nat.cast_commute _ _).eq], simp [d₁0, mul_assoc] end @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n / d : α) = -(n / d), by rw [div_eq_mul_inv, div_eq_mul_inv, int.cast_neg, neg_mul_eq_neg_mul] @[norm_cast] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)] @[norm_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv_rev', d₁0, d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0]} }, rw [(d₁.commute_cast (_:α)).inv_right'.eq] end @[norm_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end @[norm_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp, norm_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂:α)).inv_left'.eq, ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_add [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_sub [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_mul [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_bit0 [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl variable (α) /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom [char_zero α] : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ variable {α} @[simp] lemma coe_cast_hom [char_zero α] : ⇑(cast_hom α) = coe := rfl @[simp, norm_cast] theorem cast_inv [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := (cast_hom α).map_inv _ @[simp, norm_cast] theorem cast_div [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := (cast_hom α).map_div _ _ @[norm_cast] theorem cast_mk [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := by simp only [mk_eq_div, cast_div, cast_coe_int] @[simp, norm_cast] theorem cast_pow [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := (cast_hom α).map_pow q k end with_div_ring @[simp, norm_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := by { rw [num_denom', cast_mk, mk_eq_div, div_nonneg_iff, div_nonneg_iff], norm_cast } @[simp, norm_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := by rw [num_denom', cast_mk, mk_eq_div] @[simp, norm_cast] theorem cast_min [linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases b ≤ a; simp [h, max] @[simp, norm_cast] theorem cast_abs [linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end rat open rat ring_hom lemma ring_hom.eq_rat_cast {k} [division_ring k] (f : ℚ →+* k) (r : ℚ) : f r = r := calc f r = f (r.1 / r.2) : by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom] ... = f r.1 / f r.2 : f.map_div _ _ ... = r.1 / r.2 : by rw [map_nat_cast, map_int_cast] -- This seems to be true for a `[char_p k]` too because `k'` must have the same characteristic -- but the proof would be much longer lemma ring_hom.map_rat_cast {k k'} [division_ring k] [char_zero k] [division_ring k'] (f : k →+* k') (r : ℚ) : f r = r := (f.comp (cast_hom k)).eq_rat_cast r lemma ring_hom.ext_rat {R : Type*} [semiring R] (f g : ℚ →+* R) : f = g := begin ext r, refine rat.num_denom_cases_on' r _, intros a b b0, let φ : ℤ →+* R := f.comp (int.cast_ring_hom ℚ), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom ℚ), rw [rat.mk_eq_div, int.cast_coe_nat], have b0' : (b:ℚ) ≠ 0 := nat.cast_ne_zero.2 b0, have : ∀ n : ℤ, f n = g n := λ n, show φ n = ψ n, by rw [φ.ext_int ψ], calc f (a * b⁻¹) = f a * f b⁻¹ * (g (b:ℤ) * g b⁻¹) : by rw [int.cast_coe_nat, ← g.map_mul, mul_inv_cancel b0', g.map_one, mul_one, f.map_mul] ... = g a * f b⁻¹ * (f (b:ℤ) * g b⁻¹) : by rw [this a, ← this b] ... = g (a * b⁻¹) : by rw [int.cast_coe_nat, mul_assoc, ← mul_assoc (f b⁻¹), ← f.map_mul, inv_mul_cancel b0', f.map_one, one_mul, g.map_mul] end instance rat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℚ →+* R) := ⟨ring_hom.ext_rat⟩ namespace monoid_with_zero_hom variables {M : Type*} [group_with_zero M] /-- If `f` and `g` agree on the integers then they are equal `φ`. See note [partially-applied ext lemmas] for why `comp` is used here. -/ @[ext] theorem ext_rat {f g : monoid_with_zero_hom ℚ M} (same_on_int : f.comp (int.cast_ring_hom ℚ).to_monoid_with_zero_hom = g.comp (int.cast_ring_hom ℚ).to_monoid_with_zero_hom) : f = g := begin have same_on_int' : ∀ k : ℤ, f k = g k := congr_fun same_on_int, ext x, rw [← @rat.num_denom x, rat.mk_eq_div, f.map_div, g.map_div, same_on_int' x.num, same_on_int' x.denom], end /-- Positive integer values of a morphism `φ` and its value on `-1` completely determine `φ`. -/ theorem ext_rat_on_pnat {f g : monoid_with_zero_hom ℚ M} (same_on_neg_one : f (-1) = g (-1)) (same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g := ext_rat $ ext_int' (by simpa) ‹_› end monoid_with_zero_hom
9e1f1ca53a4dfc5fc0edb7603faaeb4d8904dbd6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/measure/mutually_singular.lean
33b5e4ce06461388770510b9a493cfad2197f3e5
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,085
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Yury Kudryashov -/ import measure_theory.measure.measure_space /-! # Mutually singular measures Two measures `μ`, `ν` are said to be mutually singular (`measure_theory.measure.mutually_singular`, localized notation `μ ⊥ₘ ν`) if there exists a measurable set `s` such that `μ s = 0` and `ν sᶜ = 0`. The measurability of `s` is an unnecessary assumption (see `measure_theory.measure.mutually_singular.mk`) but we keep it because this way `rcases (h : μ ⊥ₘ ν)` gives us a measurable set and usually it is easy to prove measurability. In this file we define the predicate `measure_theory.measure.mutually_singular` and prove basic facts about it. ## Tags measure, mutually singular -/ open set open_locale measure_theory nnreal ennreal namespace measure_theory namespace measure variables {α : Type*} {m0 : measurable_space α} {μ μ₁ μ₂ ν ν₁ ν₂ : measure α} /-- Two measures `μ`, `ν` are said to be mutually singular if there exists a measurable set `s` such that `μ s = 0` and `ν sᶜ = 0`. -/ def mutually_singular {m0 : measurable_space α} (μ ν : measure α) : Prop := ∃ (s : set α), measurable_set s ∧ μ s = 0 ∧ ν sᶜ = 0 localized "infix (name := measure.mutually_singular) ` ⊥ₘ `:60 := measure_theory.measure.mutually_singular" in measure_theory namespace mutually_singular lemma mk {s t : set α} (hs : μ s = 0) (ht : ν t = 0) (hst : univ ⊆ s ∪ t) : mutually_singular μ ν := begin use [to_measurable μ s, measurable_set_to_measurable _ _, (measure_to_measurable _).trans hs], refine measure_mono_null (λ x hx, (hst trivial).resolve_left $ λ hxs, hx _) ht, exact subset_to_measurable _ _ hxs end @[simp] lemma zero_right : μ ⊥ₘ 0 := ⟨∅, measurable_set.empty, measure_empty, rfl⟩ @[symm] lemma symm (h : ν ⊥ₘ μ) : μ ⊥ₘ ν := let ⟨i, hi, his, hit⟩ := h in ⟨iᶜ, hi.compl, hit, (compl_compl i).symm ▸ his⟩ lemma comm : μ ⊥ₘ ν ↔ ν ⊥ₘ μ := ⟨λ h, h.symm, λ h, h.symm⟩ @[simp] lemma zero_left : 0 ⊥ₘ μ := zero_right.symm lemma mono_ac (h : μ₁ ⊥ₘ ν₁) (hμ : μ₂ ≪ μ₁) (hν : ν₂ ≪ ν₁) : μ₂ ⊥ₘ ν₂ := let ⟨s, hs, h₁, h₂⟩ := h in ⟨s, hs, hμ h₁, hν h₂⟩ lemma mono (h : μ₁ ⊥ₘ ν₁) (hμ : μ₂ ≤ μ₁) (hν : ν₂ ≤ ν₁) : μ₂ ⊥ₘ ν₂ := h.mono_ac hμ.absolutely_continuous hν.absolutely_continuous @[simp] lemma sum_left {ι : Type*} [countable ι] {μ : ι → measure α} : (sum μ) ⊥ₘ ν ↔ ∀ i, μ i ⊥ₘ ν := begin refine ⟨λ h i, h.mono (le_sum _ _) le_rfl, λ H, _⟩, choose s hsm hsμ hsν using H, refine ⟨⋂ i, s i, measurable_set.Inter hsm, _, _⟩, { rw [sum_apply _ (measurable_set.Inter hsm), ennreal.tsum_eq_zero], exact λ i, measure_mono_null (Inter_subset _ _) (hsμ i) }, { rwa [compl_Inter, measure_Union_null_iff], } end @[simp] lemma sum_right {ι : Type*} [countable ι] {ν : ι → measure α} : μ ⊥ₘ sum ν ↔ ∀ i, μ ⊥ₘ ν i := comm.trans $ sum_left.trans $ forall_congr $ λ i, comm @[simp] lemma add_left_iff : μ₁ + μ₂ ⊥ₘ ν ↔ μ₁ ⊥ₘ ν ∧ μ₂ ⊥ₘ ν := by rw [← sum_cond, sum_left, bool.forall_bool, cond, cond, and.comm] @[simp] lemma add_right_iff : μ ⊥ₘ ν₁ + ν₂ ↔ μ ⊥ₘ ν₁ ∧ μ ⊥ₘ ν₂ := comm.trans $ add_left_iff.trans $ and_congr comm comm lemma add_left (h₁ : ν₁ ⊥ₘ μ) (h₂ : ν₂ ⊥ₘ μ) : ν₁ + ν₂ ⊥ₘ μ := add_left_iff.2 ⟨h₁, h₂⟩ lemma add_right (h₁ : μ ⊥ₘ ν₁) (h₂ : μ ⊥ₘ ν₂) : μ ⊥ₘ ν₁ + ν₂ := add_right_iff.2 ⟨h₁, h₂⟩ lemma smul (r : ℝ≥0∞) (h : ν ⊥ₘ μ) : r • ν ⊥ₘ μ := h.mono_ac (absolutely_continuous.rfl.smul r) absolutely_continuous.rfl lemma smul_nnreal (r : ℝ≥0) (h : ν ⊥ₘ μ) : r • ν ⊥ₘ μ := h.smul r end mutually_singular end measure end measure_theory
6174b27d355f4703dad3c013deb49d1ef8c5d0af
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/simulate_on.lean
30af9b067dee3b65f7b975daaa1f2a15136f80a4
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
214
lean
example (a b c : nat) : a = 0 → b = 1 → c = 0 → b + a + c = b := begin intros, repeat {subst ‹_ = 0›}, -- substitute all equalities of the form `_ = 0` guard_target b + 0 + 0 = b, reflexivity end
9d5ea1c7641e4856536a73aa324657a2e82eb69f
618003631150032a5676f229d13a079ac875ff77
/src/data/zmod/basic.lean
57d5807c70e86b79b834d103827ed9152140e86e
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
25,468
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq import algebra.char_p import data.nat.totient /-! # Integers mod `n` Definition of the integers mod n, and the field structure on the integers mod p. ## Definitions * `zmod n`, which is for integers modulo a nat `n : ℕ` * `val a` is defined as a natural number: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class * `val_min_abs` returns the integer closest to zero in the equivalence class. * A coercion `cast` is defined from `zmod n` into any ring. This is a ring hom if the ring has characteristic dividing `n` -/ namespace fin /-! ## Ring structure on `fin n` We define a commutative ring structure on `fin n`, but we do not register it as instance. Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions to register the ring structure on `zmod n` as type class instance. -/ open nat nat.modeq int /-- Negation on `fin n` -/ def has_neg (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, begin have npos : 0 < n := lt_of_le_of_lt (nat.zero_le _) a.2, have h : (n : ℤ) ≠ 0 := int.coe_nat_ne_zero_iff_pos.2 npos, have := int.mod_lt (-(a.1 : ℤ)) h, rw [(abs_of_nonneg (int.coe_nat_nonneg n))] at this, rwa [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h)] end⟩⟩ /-- Additive commutative semigroup structure on `fin (n+1)`. -/ def add_comm_semigroup (n : ℕ) : add_comm_semigroup (fin (n+1)) := { add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (show ((a + b) % (n+1) + c) ≡ (a + (b + c) % (n+1)) [MOD (n+1)], from calc ((a + b) % (n+1) + c) ≡ a + b + c [MOD (n+1)] : modeq_add (nat.mod_mod _ _) rfl ... ≡ a + (b + c) [MOD (n+1)] : by rw add_assoc ... ≡ (a + (b + c) % (n+1)) [MOD (n+1)] : modeq_add rfl (nat.mod_mod _ _).symm), add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % (n+1) = (b + a) % (n+1), by rw add_comm), ..fin.has_add } /-- Multiplicative commutative semigroup structure on `fin (n+1)`. -/ def comm_semigroup (n : ℕ) : comm_semigroup (fin (n+1)) := { mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % (n+1) * c) ≡ a * b * c [MOD (n+1)] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD (n+1)] : by rw mul_assoc ... ≡ a * (b * c % (n+1)) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % (n+1) = (b * a) % (n+1), by rw mul_comm), ..fin.has_mul } local attribute [instance] fin.add_comm_semigroup fin.comm_semigroup private lemma one_mul_aux (n : ℕ) (a : fin (n+1)) : (1 : fin (n+1)) * a = a := begin cases n with n, { exact subsingleton.elim _ _ }, { have h₁ : a.1 % n.succ.succ = a.1 := nat.mod_eq_of_lt a.2, have h₂ : 1 % n.succ.succ = 1 := nat.mod_eq_of_lt dec_trivial, refine fin.eq_of_veq _, simp [val_mul, one_val, h₁, h₂] } end private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin (n+1), a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % (n+1)) ≡ a * (b + c) [MOD (n+1)] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD (n+1)] : by rw mul_add ... ≡ (a * b) % (n+1) + (a * c) % (n+1) [MOD (n+1)] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) /-- Commutative ring structure on `fin (n+1)`. -/ def comm_ring (n : ℕ) : comm_ring (fin (n+1)) := { zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % (n+1) = a, by rw zero_add; exact nat.mod_eq_of_lt ha), add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha), add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % (n+1)).to_nat + a) % (n+1) = 0, from int.coe_nat_inj begin have npos : 0 < n+1 := lt_of_le_of_lt (nat.zero_le _) ha, have hn : ((n+1) : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 npos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := one_mul_aux n, mul_one := λ a, by rw mul_comm; exact one_mul_aux n a, left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..fin.has_zero, ..fin.has_one, ..fin.has_neg (n+1), ..fin.add_comm_semigroup n, ..fin.comm_semigroup n } end fin /-- The integers modulo `n : ℕ`. -/ def zmod : ℕ → Type | 0 := ℤ | (n+1) := fin (n+1) namespace zmod instance fintype : Π (n : ℕ) [fact (0 < n)], fintype (zmod n) | 0 _ := false.elim $ nat.not_lt_zero 0 ‹0 < 0› | (n+1) _ := fin.fintype (n+1) lemma card (n : ℕ) [fact (0 < n)] : fintype.card (zmod n) = n := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { exact fintype.card_fin (n+1) } end instance decidable_eq : Π (n : ℕ), decidable_eq (zmod n) | 0 := int.decidable_eq | (n+1) := fin.decidable_eq _ instance has_repr : Π (n : ℕ), has_repr (zmod n) | 0 := int.has_repr | (n+1) := fin.has_repr _ instance comm_ring : Π (n : ℕ), comm_ring (zmod n) | 0 := int.comm_ring | (n+1) := fin.comm_ring n instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩ /-- `val a` is a natural number defined as: - for `a : zmod 0` it is the absolute value of `a` - for `a : zmod n` with `0 < n` it is the least natural number in the equivalence class See `zmod.val_min_abs` for a variant that takes values in the integers. -/ def val : Π {n : ℕ}, zmod n → ℕ | 0 := int.nat_abs | (n+1) := fin.val lemma val_lt {n : ℕ} [fact (0 < n)] (a : zmod n) : a.val < n := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, exact fin.is_lt a end @[simp] lemma val_zero : ∀ {n}, (0 : zmod n).val = 0 | 0 := rfl | (n+1) := rfl lemma val_cast_nat {n : ℕ} (a : ℕ) : (a : zmod n).val = a % n := begin unfreezeI, cases n, { rw [nat.mod_zero, int.nat_cast_eq_coe_nat], exact int.nat_abs_of_nat a, }, rw ← fin.of_nat_eq_coe, refl end instance (n : ℕ) : char_p (zmod n) n := { cast_eq_zero_iff := begin intro k, cases n, { simp only [int.nat_cast_eq_coe_nat, zero_dvd_iff, int.coe_nat_eq_zero], }, rw [fin.eq_iff_veq], show (k : zmod (n+1)).val = (0 : zmod (n+1)).val ↔ _, rw [val_cast_nat, val_zero, nat.dvd_iff_mod_eq_zero], end } @[simp] lemma cast_self (n : ℕ) : (n : zmod n) = 0 := char_p.cast_eq_zero (zmod n) n @[simp] lemma cast_self' (n : ℕ) : (n + 1 : zmod (n + 1)) = 0 := by rw [← nat.cast_add_one, cast_self (n + 1)] section universal_property variables {n : ℕ} {R : Type*} section variables [has_zero R] [has_one R] [has_add R] [has_neg R] /-- Cast an integer modulo `n` to another semiring. This function is a morphism if the characteristic of `R` divides `n`. See `zmod.cast_hom` for a bundled version. -/ def cast : Π {n : ℕ}, zmod n → R | 0 := int.cast | (n+1) := λ i, i.val -- see Note [coercion into rings] @[priority 900] instance (n : ℕ) : has_coe_t (zmod n) R := ⟨cast⟩ @[simp] lemma cast_zero : ((0 : zmod n) : R) = 0 := by { cases n; refl } end lemma nat_cast_surjective [fact (0 < n)] : function.surjective (coe : ℕ → zmod n) := begin assume i, unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { refine ⟨i.val, _⟩, cases i with i hi, induction i with i IH, { ext, refl }, show (i+1 : zmod (n+1)) = _, specialize IH (lt_of_le_of_lt i.le_succ hi), ext, erw [fin.val_add, IH], suffices : fin.val (1 : zmod (n+1)) = 1, { rw this, apply nat.mod_eq_of_lt hi }, show 1 % (n+1) = 1, apply nat.mod_eq_of_lt, apply lt_of_le_of_lt _ hi, exact le_of_inf_eq rfl } end lemma int_cast_surjective : function.surjective (coe : ℤ → zmod n) := begin assume i, cases n, { exact ⟨i, int.cast_id i⟩ }, { rcases nat_cast_surjective i with ⟨k, rfl⟩, refine ⟨k, _⟩, norm_cast } end lemma cast_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : zmod n) = a := begin rcases nat_cast_surjective a with ⟨k, rfl⟩, symmetry, rw [val_cast_nat, ← sub_eq_zero, ← nat.cast_sub, char_p.cast_eq_zero_iff (zmod n) n], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end @[simp, norm_cast] lemma cast_id : ∀ n (i : zmod n), ↑i = i | 0 i := int.cast_id i | (n+1) i := cast_val i variables [ring R] @[simp] lemma nat_cast_val [fact (0 < n)] (i : zmod n) : (i.val : R) = i := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, refl end variable [char_p R n] @[simp] lemma cast_one : ((1 : zmod n) : R) = 1 := begin unfreezeI, cases n, { exact int.cast_one }, show ((1 % (n+1) : ℕ) : R) = 1, cases n, { apply subsingleton.elim }, rw nat.mod_eq_of_lt, { exact nat.cast_one }, exact nat.lt_of_sub_eq_succ rfl end @[simp] lemma cast_add (a b : zmod n) : ((a + b : zmod n) : R) = a + b := begin unfreezeI, cases n, { apply int.cast_add }, show ((fin.val (a + b) : ℕ) : R) = fin.val a + fin.val b, symmetry, resetI, rw [fin.val_add, ← nat.cast_add, ← sub_eq_zero, ← nat.cast_sub, @char_p.cast_eq_zero_iff R _ n.succ], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end @[simp] lemma cast_mul (a b : zmod n) : ((a * b : zmod n) : R) = a * b := begin unfreezeI, cases n, { apply int.cast_mul }, show ((fin.val (a * b) : ℕ) : R) = fin.val a * fin.val b, symmetry, resetI, rw [fin.val_mul, ← nat.cast_mul, ← sub_eq_zero, ← nat.cast_sub, @char_p.cast_eq_zero_iff R _ n.succ], { apply nat.dvd_sub_mod }, { apply nat.mod_le } end /-- The canonical ring homomorphism from `zmod n` to a ring of characteristic `n`. -/ def cast_hom (n : ℕ) (R : Type*) [ring R] [char_p R n] : zmod n →+* R := { to_fun := coe, map_zero' := cast_zero, map_one' := cast_one, map_add' := cast_add, map_mul' := cast_mul } @[simp] lemma cast_hom_apply (i : zmod n) : cast_hom n R i = i := rfl @[simp, norm_cast] lemma cast_nat_cast (k : ℕ) : ((k : zmod n) : R) = k := (cast_hom n R).map_nat_cast k @[simp, norm_cast] lemma cast_int_cast (k : ℤ) : ((k : zmod n) : R) = k := (cast_hom n R).map_int_cast k end universal_property lemma int_coe_eq_int_coe_iff (a b : ℤ) (c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [ZMOD c] := char_p.int_coe_eq_int_coe_iff (zmod c) c a b lemma nat_coe_eq_nat_coe_iff (a b c : ℕ) : (a : zmod c) = (b : zmod c) ↔ a ≡ b [MOD c] := begin convert zmod.int_coe_eq_int_coe_iff a b c, simp [nat.modeq.modeq_iff_dvd, int.modeq.modeq_iff_dvd], end lemma int_coe_zmod_eq_zero_iff_dvd (a : ℤ) (b : ℕ) : (a : zmod b) = 0 ↔ (b : ℤ) ∣ a := begin change (a : zmod b) = ((0 : ℤ) : zmod b) ↔ (b : ℤ) ∣ a, rw [zmod.int_coe_eq_int_coe_iff, int.modeq.modeq_zero_iff], end lemma nat_coe_zmod_eq_zero_iff_dvd (a b : ℕ) : (a : zmod b) = 0 ↔ b ∣ a := begin change (a : zmod b) = ((0 : ℕ) : zmod b) ↔ b ∣ a, rw [zmod.nat_coe_eq_nat_coe_iff, nat.modeq.modeq_zero_iff], end @[push_cast] lemma cast_mod_int (a : ℤ) (b : ℕ) : ((a % b : ℤ) : zmod b) = (a : zmod b) := begin rw zmod.int_coe_eq_int_coe_iff, apply int.modeq.mod_modeq, end lemma val_injective (n : ℕ) [fact (0 < n)] : function.injective (zmod.val : zmod n → ℕ) := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹_› }, assume a b h, ext, exact h end lemma val_one_eq_one_mod (n : ℕ) : (1 : zmod n).val = 1 % n := by rw [← nat.cast_one, val_cast_nat] lemma val_one (n : ℕ) [fact (1 < n)] : (1 : zmod n).val = 1 := by { rw val_one_eq_one_mod, exact nat.mod_eq_of_lt ‹1 < n› } lemma val_add {n : ℕ} [fact (0 < n)] (a b : zmod n) : (a + b).val = (a.val + b.val) % n := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { apply fin.val_add } end lemma val_mul {n : ℕ} (a b : zmod n) : (a * b).val = (a.val * b.val) % n := begin cases n, { rw nat.mod_zero, apply int.nat_abs_mul }, { apply fin.val_mul } end instance nonzero (n : ℕ) [fact (1 < n)] : nonzero (zmod n) := { zero_ne_one := assume h, zero_ne_one $ calc 0 = (0 : zmod n).val : by rw val_zero ... = (1 : zmod n).val : congr_arg zmod.val h ... = 1 : val_one n } /-- The inversion on `zmod n`. It is setup in such a way that `a * a⁻¹` is equal to `gcd a.val n`. In particular, if `a` is coprime to `n`, and hence a unit, `a * a⁻¹ = 1`. -/ def inv : Π (n : ℕ), zmod n → zmod n | 0 i := int.sign i | (n+1) i := nat.gcd_a i.val (n+1) instance (n : ℕ) : has_inv (zmod n) := ⟨inv n⟩ lemma inv_zero : ∀ (n : ℕ), (0 : zmod n)⁻¹ = 0 | 0 := int.sign_zero | (n+1) := show (nat.gcd_a _ (n+1) : zmod (n+1)) = 0, by { rw val_zero, unfold nat.gcd_a nat.xgcd nat.xgcd_aux, refl } lemma mul_inv_eq_gcd {n : ℕ} (a : zmod n) : a * a⁻¹ = nat.gcd a.val n := begin cases n, { calc a * a⁻¹ = a * int.sign a : rfl ... = a.nat_abs : by rw [int.mul_sign, int.nat_cast_eq_coe_nat] ... = a.val.gcd 0 : by rw nat.gcd_zero_right; refl }, { set k := n.succ, calc a * a⁻¹ = a * a⁻¹ + k * nat.gcd_b (val a) k : by rw [cast_self, zero_mul, add_zero] ... = ↑(↑a.val * nat.gcd_a (val a) k + k * nat.gcd_b (val a) k) : by { push_cast, rw cast_val, refl } ... = nat.gcd a.val k : (congr_arg coe (nat.gcd_eq_gcd_ab a.val k)).symm, } end @[simp] lemma cast_mod_nat (n : ℕ) (a : ℕ) : ((a % n : ℕ) : zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp lemma eq_iff_modeq_nat (n : ℕ) {a b : ℕ} : (a : zmod n) = b ↔ a ≡ b [MOD n] := begin cases n, { simp only [nat.modeq, int.coe_nat_inj', nat.mod_zero, int.nat_cast_eq_coe_nat], }, { rw [fin.ext_iff, nat.modeq, ← val_cast_nat, ← val_cast_nat], exact iff.rfl, } end lemma coe_mul_inv_eq_one {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (x * x⁻¹ : zmod n) = 1 := begin rw [nat.coprime, nat.gcd_comm, nat.gcd_rec] at h, rw [mul_inv_eq_gcd, val_cast_nat, h, nat.cast_one], end /-- `unit_of_coprime` makes an element of `units (zmod n)` given a natural number `x` and a proof that `x` is coprime to `n` -/ def unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : units (zmod n) := ⟨x, x⁻¹, coe_mul_inv_eq_one x h, by rw [mul_comm, coe_mul_inv_eq_one x h]⟩ @[simp] lemma cast_unit_of_coprime {n : ℕ} (x : ℕ) (h : nat.coprime x n) : (unit_of_coprime x h : zmod n) = x := rfl lemma val_coe_unit_coprime {n : ℕ} (u : units (zmod n)) : nat.coprime (u : zmod n).val n := begin cases n, { rcases int.units_eq_one_or u with rfl|rfl; exact dec_trivial }, apply nat.modeq.coprime_of_mul_modeq_one ((u⁻¹ : units (zmod (n+1))) : zmod (n+1)).val, have := units.ext_iff.1 (mul_right_inv u), rw [units.coe_one] at this, rw [← eq_iff_modeq_nat, nat.cast_one, ← this], clear this, rw [← cast_val ((u * u⁻¹ : units (zmod (n+1))) : zmod (n+1))], rw [units.coe_mul, val_mul, cast_mod_nat], end @[simp] lemma inv_coe_unit {n : ℕ} (u : units (zmod n)) : (u : zmod n)⁻¹ = (u⁻¹ : units (zmod n)) := begin have := congr_arg (coe : ℕ → zmod n) (val_coe_unit_coprime u), rw [← mul_inv_eq_gcd, nat.cast_one] at this, let u' : units (zmod n) := ⟨u, (u : zmod n)⁻¹, this, by rwa mul_comm⟩, have h : u = u', { apply units.ext, refl }, rw h, refl end lemma mul_inv_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a * a⁻¹ = 1 := begin rcases h with ⟨u, rfl⟩, rw [inv_coe_unit, u.mul_inv], end lemma inv_mul_of_unit {n : ℕ} (a : zmod n) (h : is_unit a) : a⁻¹ * a = 1 := by rw [mul_comm, mul_inv_of_unit a h] /-- Equivalence between the units of `zmod n` and the subtype of terms `x : zmod n` for which `x.val` is comprime to `n` -/ def units_equiv_coprime {n : ℕ} [fact (0 < n)] : units (zmod n) ≃ {x : zmod n // nat.coprime x.val n} := { to_fun := λ x, ⟨x, val_coe_unit_coprime x⟩, inv_fun := λ x, unit_of_coprime x.1.val x.2, left_inv := λ ⟨_, _, _, _⟩, units.ext (cast_val _), right_inv := λ ⟨_, _⟩, by simp } section totient open_locale nat @[simp] lemma card_units_eq_totient (n : ℕ) [fact (0 < n)] : fintype.card (units (zmod n)) = φ n := calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} : fintype.card_congr zmod.units_equiv_coprime ... = φ n : begin apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val), { intro a, simp [a.1.val_lt, a.2.symm] {contextual := tt}, }, { intros _ _ _ _ h, rw subtype.ext, apply val_injective, exact h, }, { intros b hb, rw [finset.mem_filter, finset.mem_range] at hb, refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩, { let u := unit_of_coprime b hb.2.symm, exact val_coe_unit_coprime u }, { show zmod.val (b : zmod n) = b, rw [val_cast_nat, nat.mod_eq_of_lt hb.1], } } end end totient instance subsingleton_units : subsingleton (units (zmod 2)) := ⟨λ x y, begin cases x with x xi, cases y with y yi, revert x y xi yi, exact dec_trivial end⟩ lemma le_div_two_iff_lt_neg (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {x : zmod n} (hx0 : x ≠ 0) : x.val ≤ (n / 2 : ℕ) ↔ (n / 2 : ℕ) < (-x).val := begin haveI npos : fact (0 < n) := by { apply (nat.eq_zero_or_pos n).resolve_left, resetI, rintro rfl, simpa [fact] using hn, }, have hn2 : (n : ℕ) / 2 < n := nat.div_lt_of_lt_mul ((lt_mul_iff_one_lt_left npos).2 dec_trivial), have hn2' : (n : ℕ) - n / 2 = n / 2 + 1, { conv {to_lhs, congr, rw [← nat.succ_sub_one n, nat.succ_sub npos]}, rw [← nat.two_mul_odd_div_two hn, two_mul, ← nat.succ_add, nat.add_sub_cancel], }, have hxn : (n : ℕ) - x.val < n, { rw [nat.sub_lt_iff (le_of_lt x.val_lt) (le_refl _), nat.sub_self], rw ← zmod.cast_val x at hx0, exact nat.pos_of_ne_zero (λ h, by simpa [h] using hx0) }, by conv {to_rhs, rw [← nat.succ_le_iff, nat.succ_eq_add_one, ← hn2', ← zero_add (- x), ← zmod.cast_self, ← sub_eq_add_neg, ← zmod.cast_val x, ← nat.cast_sub (le_of_lt x.val_lt), zmod.val_cast_nat, nat.mod_eq_of_lt hxn, nat.sub_le_sub_left_iff (le_of_lt x.val_lt)] } end lemma ne_neg_self (n : ℕ) [hn : fact ((n : ℕ) % 2 = 1)] {a : zmod n} (ha : a ≠ 0) : a ≠ -a := λ h, have a.val ≤ n / 2 ↔ (n : ℕ) / 2 < (-a).val := le_div_two_iff_lt_neg n ha, by rwa [← h, ← not_lt, not_iff_self] at this lemma neg_one_ne_one {n : ℕ} [fact (2 < n)] : (-1 : zmod n) ≠ 1 := char_p.neg_one_ne_one (zmod n) n @[simp] lemma neg_eq_self_mod_two : ∀ (a : zmod 2), -a = a := dec_trivial @[simp] lemma nat_abs_mod_two (a : ℤ) : (a.nat_abs : zmod 2) = a := begin cases a, { simp only [int.nat_abs_of_nat, int.cast_coe_nat, int.of_nat_eq_coe] }, { simp only [neg_eq_self_mod_two, nat.cast_succ, int.nat_abs, int.cast_neg_succ_of_nat] } end @[simp] lemma val_eq_zero : ∀ {n : ℕ} (a : zmod n), a.val = 0 ↔ a = 0 | 0 a := int.nat_abs_eq_zero | (n+1) a := by { rw fin.ext_iff, exact iff.rfl } lemma val_cast_of_lt {n : ℕ} {a : ℕ} (h : a < n) : (a : zmod n).val = a := by rw [val_cast_nat, nat.mod_eq_of_lt h] lemma neg_val' {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = (n - a.val) % n := begin have : ((-a).val + a.val) % n = (n - a.val + a.val) % n, { rw [←val_add, add_left_neg, nat.sub_add_cancel (le_of_lt a.val_lt), nat.mod_self, val_zero], }, calc (-a).val = val (-a) % n : by rw nat.mod_eq_of_lt ((-a).val_lt) ... = (n - val a) % n : nat.modeq.modeq_add_cancel_right rfl this end lemma neg_val {n : ℕ} [fact (0 < n)] (a : zmod n) : (-a).val = if a = 0 then 0 else n - a.val := begin rw neg_val', by_cases h : a = 0, { rw [if_pos h, h, val_zero, nat.sub_zero, nat.mod_self] }, rw if_neg h, apply nat.mod_eq_of_lt, apply nat.sub_lt ‹0 < n›, contrapose! h, rwa [nat.le_zero_iff, val_eq_zero] at h, end /-- `val_min_abs x` returns the integer in the same equivalence class as `x` that is closest to `0`, The result will be in the interval `(-n/2, n/2]`. -/ def val_min_abs : Π {n : ℕ}, zmod n → ℤ | 0 x := x | n@(_+1) x := if x.val ≤ n / 2 then x.val else (x.val : ℤ) - n @[simp] lemma val_min_abs_def_zero (x : zmod 0) : val_min_abs x = x := rfl lemma val_min_abs_def_pos {n : ℕ} [fact (0 < n)] (x : zmod n) : val_min_abs x = if x.val ≤ n / 2 then x.val else x.val - n := begin unfreezeI, cases n, { exfalso, exact nat.not_lt_zero 0 ‹0 < 0› }, { refl } end @[simp] lemma coe_val_min_abs : ∀ {n : ℕ} (x : zmod n), (x.val_min_abs : zmod n) = x | 0 x := int.cast_id x | k@(n+1) x := begin rw val_min_abs_def_pos, split_ifs, { rw [int.cast_coe_nat, cast_val] }, { rw [int.cast_sub, int.cast_coe_nat, cast_val, int.cast_coe_nat, cast_self, sub_zero], } end lemma nat_abs_val_min_abs_le {n : ℕ} [fact (0 < n)] (x : zmod n) : x.val_min_abs.nat_abs ≤ n / 2 := begin rw zmod.val_min_abs_def_pos, split_ifs with h, { exact h }, have : (x.val - n : ℤ) ≤ 0, { rw [sub_nonpos, int.coe_nat_le], exact le_of_lt x.val_lt, }, rw [← int.coe_nat_le, int.of_nat_nat_abs_of_nonpos this, neg_sub], conv_lhs { congr, rw [← nat.mod_add_div n 2, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one] }, suffices : ((n % 2 : ℕ) + (n / 2) : ℤ) ≤ (val x), { rw ← sub_nonneg at this ⊢, apply le_trans this (le_of_eq _), ring }, norm_cast, calc (n : ℕ) % 2 + n / 2 ≤ 1 + n / 2 : nat.add_le_add_right (nat.le_of_lt_succ (nat.mod_lt _ dec_trivial)) _ ... ≤ x.val : by { rw add_comm, exact nat.succ_le_of_lt (lt_of_not_ge h) } end @[simp] lemma val_min_abs_zero : ∀ n, (0 : zmod n).val_min_abs = 0 | 0 := by simp only [val_min_abs_def_zero] | (n+1) := by simp only [val_min_abs_def_pos, if_true, int.coe_nat_zero, zero_le, val_zero] @[simp] lemma val_min_abs_eq_zero {n : ℕ} (x : zmod n) : x.val_min_abs = 0 ↔ x = 0 := begin cases n, { simp }, split, { simp only [val_min_abs_def_pos, int.coe_nat_succ], split_ifs with h h; assume h0, { apply val_injective, rwa [int.coe_nat_eq_zero] at h0, }, { apply absurd h0, rw sub_eq_zero, apply ne_of_lt, exact_mod_cast x.val_lt } }, { rintro rfl, rw val_min_abs_zero } end lemma cast_nat_abs_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val_min_abs.nat_abs : zmod n) = if a.val ≤ (n : ℕ) / 2 then a else -a := begin have : (a.val : ℤ) - n ≤ 0, by { erw [sub_nonpos, int.coe_nat_le], exact le_of_lt a.val_lt, }, rw [zmod.val_min_abs_def_pos], split_ifs, { rw [int.nat_abs_of_nat, cast_val] }, { rw [← int.cast_coe_nat, int.of_nat_nat_abs_of_nonpos this, int.cast_neg, int.cast_sub], rw [int.cast_coe_nat, int.cast_coe_nat, cast_self, sub_zero, cast_val], } end @[simp] lemma nat_abs_val_min_abs_neg {n : ℕ} (a : zmod n) : (-a).val_min_abs.nat_abs = a.val_min_abs.nat_abs := begin cases n, { simp only [int.nat_abs_neg, val_min_abs_def_zero], }, by_cases ha0 : a = 0, { rw [ha0, neg_zero] }, by_cases haa : -a = a, { rw [haa] }, suffices hpa : (n+1 : ℕ) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, { rw [val_min_abs_def_pos, val_min_abs_def_pos], rw ← not_le at hpa, simp only [if_neg ha0, neg_val, hpa, int.coe_nat_sub (le_of_lt a.val_lt)], split_ifs, all_goals { rw [← int.nat_abs_neg], congr' 1, ring } }, suffices : (((n+1 : ℕ) % 2) + 2 * ((n + 1) / 2)) - a.val ≤ (n+1) / 2 ↔ (n+1 : ℕ) / 2 < a.val, by rwa [nat.mod_add_div] at this, suffices : (n + 1) % 2 + (n + 1) / 2 ≤ val a ↔ (n + 1) / 2 < val a, by rw [nat.sub_le_iff, two_mul, ← add_assoc, nat.add_sub_cancel, this], cases (n + 1 : ℕ).mod_two_eq_zero_or_one with hn0 hn1, { split, { assume h, apply lt_of_le_of_ne (le_trans (nat.le_add_left _ _) h), contrapose! haa, rw [← zmod.cast_val a, ← haa, neg_eq_iff_add_eq_zero, ← nat.cast_add], rw [char_p.cast_eq_zero_iff (zmod (n+1)) (n+1)], rw [← two_mul, ← zero_add (2 * _), ← hn0, nat.mod_add_div] }, { rw [hn0, zero_add], exact le_of_lt } }, { rw [hn1, add_comm, nat.succ_le_iff] } end lemma val_eq_ite_val_min_abs {n : ℕ} [fact (0 < n)] (a : zmod n) : (a.val : ℤ) = a.val_min_abs + if a.val ≤ n / 2 then 0 else n := by { rw [zmod.val_min_abs_def_pos], split_ifs; simp only [add_zero, sub_add_cancel] } lemma prime_ne_zero (p q : ℕ) [hp : fact p.prime] [hq : fact q.prime] (hpq : p ≠ q) : (q : zmod p) ≠ 0 := by rwa [← nat.cast_zero, ne.def, eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, nat.coprime_primes hp hq] end zmod namespace zmod variables (p : ℕ) [fact p.prime] private lemma mul_inv_cancel_aux (a : zmod p) (h : a ≠ 0) : a * a⁻¹ = 1 := begin obtain ⟨k, rfl⟩ := nat_cast_surjective a, apply coe_mul_inv_eq_one, apply nat.coprime.symm, rwa [nat.prime.coprime_iff_not_dvd ‹p.prime›, ← char_p.cast_eq_zero_iff (zmod p)] end /-- Field structure on `zmod p` if `p` is prime. -/ instance : field (zmod p) := { mul_inv_cancel := mul_inv_cancel_aux p, inv_zero := inv_zero p, .. zmod.comm_ring p, .. zmod.nonzero p, .. zmod.has_inv p } end zmod
54dff09930a3a0c12b04e07735c108f9f87540a6
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Meta/SynthInstance.lean
03675e0a9d8235371f554e3827c0eb34e96c321f
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
28,346
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Leonardo de Moura Type class instance synthesizer using tabled resolution. -/ import Lean.Meta.Basic import Lean.Meta.Instances import Lean.Meta.LevelDefEq import Lean.Meta.AbstractMVars import Lean.Meta.WHNF import Lean.Util.Profile namespace Lean.Meta register_builtin_option synthInstance.maxHeartbeats : Nat := { defValue := 500 descr := "maximum amount of heartbeats per typeclass resolution problem. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit" } register_builtin_option synthInstance.maxSize : Nat := { defValue := 128 descr := "maximum number of instances used to construct a solution in the type class instance synthesis procedure" } namespace SynthInstance def getMaxHeartbeats (opts : Options) : Nat := synthInstance.maxHeartbeats.get opts * 1000 open Std (HashMap) builtin_initialize inferTCGoalsRLAttr : TagAttribute ← registerTagAttribute `inferTCGoalsRL "instruct type class resolution procedure to solve goals from right to left for this instance" def hasInferTCGoalsRLAttribute (env : Environment) (constName : Name) : Bool := inferTCGoalsRLAttr.hasTag env constName structure GeneratorNode where mvar : Expr key : Expr mctx : MetavarContext instances : Array Expr currInstanceIdx : Nat deriving Inhabited structure ConsumerNode where mvar : Expr key : Expr mctx : MetavarContext subgoals : List Expr size : Nat -- instance size so far deriving Inhabited inductive Waiter where | consumerNode : ConsumerNode → Waiter | root : Waiter def Waiter.isRoot : Waiter → Bool | Waiter.consumerNode _ => false | Waiter.root => true /- In tabled resolution, we creating a mapping from goals (e.g., `Coe Nat ?x`) to answers and waiters. Waiters are consumer nodes that are waiting for answers for a particular node. We implement this mapping using a `HashMap` where the keys are normalized expressions. That is, we replace assignable metavariables with auxiliary free variables of the form `_tc.<idx>`. We do not declare these free variables in any local context, and we should view them as "normalized names" for metavariables. For example, the term `f ?m ?m ?n` is normalized as `f _tc.0 _tc.0 _tc.1`. This approach is structural, and we may visit the same goal more than once if the different occurrences are just definitionally equal, but not structurally equal. Remark: a metavariable is assignable only if its depth is equal to the metavar context depth. -/ namespace MkTableKey structure State where nextIdx : Nat := 0 lmap : HashMap MVarId Level := {} emap : HashMap MVarId Expr := {} abbrev M := ReaderT MetavarContext (StateM State) partial def normLevel (u : Level) : M Level := do if !u.hasMVar then pure u else match u with | Level.succ v _ => return u.updateSucc! (← normLevel v) | Level.max v w _ => return u.updateMax! (← normLevel v) (← normLevel w) | Level.imax v w _ => return u.updateIMax! (← normLevel v) (← normLevel w) | Level.mvar mvarId _ => let mctx ← read if !mctx.isLevelAssignable mvarId then pure u else let s ← get match s.lmap.find? mvarId with | some u' => pure u' | none => let u' := mkLevelParam $ Name.mkNum `_tc s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u' } pure u' | u => pure u partial def normExpr (e : Expr) : M Expr := do if !e.hasMVar then pure e else match e with | Expr.const _ us _ => return e.updateConst! (← us.mapM normLevel) | Expr.sort u _ => return e.updateSort! (← normLevel u) | Expr.app f a _ => return e.updateApp! (← normExpr f) (← normExpr a) | Expr.letE _ t v b _ => return e.updateLet! (← normExpr t) (← normExpr v) (← normExpr b) | Expr.forallE _ d b _ => return e.updateForallE! (← normExpr d) (← normExpr b) | Expr.lam _ d b _ => return e.updateLambdaE! (← normExpr d) (← normExpr b) | Expr.mdata _ b _ => return e.updateMData! (← normExpr b) | Expr.proj _ _ b _ => return e.updateProj! (← normExpr b) | Expr.mvar mvarId _ => let mctx ← read if !mctx.isExprAssignable mvarId then pure e else let s ← get match s.emap.find? mvarId with | some e' => pure e' | none => do let e' := mkFVar { name := Name.mkNum `_tc s.nextIdx } modify fun s => { s with nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e' } pure e' | _ => pure e end MkTableKey /- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/ def mkTableKey (mctx : MetavarContext) (e : Expr) : Expr := MkTableKey.normExpr e mctx |>.run' {} structure Answer where result : AbstractMVarsResult resultType : Expr size : Nat instance : Inhabited Answer where default := { result := arbitrary, resultType := arbitrary, size := 0 } structure TableEntry where waiters : Array Waiter answers : Array Answer := #[] structure Context where maxResultSize : Nat maxHeartbeats : Nat /- Remark: the SynthInstance.State is not really an extension of `Meta.State`. The field `postponed` is not needed, and the field `mctx` is misleading since `synthInstance` methods operate over different `MetavarContext`s simultaneously. That being said, we still use `extends` because it makes it simpler to move from `M` to `MetaM`. -/ structure State where result? : Option AbstractMVarsResult := none generatorStack : Array GeneratorNode := #[] resumeStack : Array (ConsumerNode × Answer) := #[] tableEntries : HashMap Expr TableEntry := {} abbrev SynthM := ReaderT Context $ StateRefT State MetaM def checkMaxHeartbeats : SynthM Unit := do Core.checkMaxHeartbeatsCore "typeclass" `synthInstance.maxHeartbeats (← read).maxHeartbeats @[inline] def mapMetaM (f : forall {α}, MetaM α → MetaM α) {α} : SynthM α → SynthM α := monadMap @f instance : Inhabited (SynthM α) where default := fun _ _ => arbitrary /-- Return globals and locals instances that may unify with `type` -/ def getInstances (type : Expr) : MetaM (Array Expr) := do -- We must retrieve `localInstances` before we use `forallTelescopeReducing` because it will update the set of local instances let localInstances ← getLocalInstances forallTelescopeReducing type fun _ type => do let className? ← isClass? type match className? with | none => throwError "type class instance expected{indentExpr type}" | some className => let globalInstances ← getGlobalInstancesIndex let result ← globalInstances.getUnify type -- Using insertion sort because it is stable and the array `result` should be mostly sorted. -- Most instances have default priority. let result := result.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority let erasedInstances ← getErasedInstances let result ← result.filterMapM fun e => match e.val with | Expr.const constName us _ => if erasedInstances.contains constName then return none else return some <| e.val.updateConst! (← us.mapM (fun _ => mkFreshLevelMVar)) | _ => panic! "global instance is not a constant" trace[Meta.synthInstance.globalInstances] "{type}, {result}" let result := localInstances.foldl (init := result) fun (result : Array Expr) linst => if linst.className == className then result.push linst.fvar else result pure result def mkGeneratorNode? (key mvar : Expr) : MetaM (Option GeneratorNode) := do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType let instances ← getInstances mvarType if instances.isEmpty then pure none else let mctx ← getMCtx pure $ some { mvar := mvar, key := key, mctx := mctx, instances := instances, currInstanceIdx := instances.size } /-- Create a new generator node for `mvar` and add `waiter` as its waiter. `key` must be `mkTableKey mctx mvarType`. -/ def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit := withMCtx mctx do trace[Meta.synthInstance.newSubgoal] key match (← mkGeneratorNode? key mvar) with | none => pure () | some node => let entry : TableEntry := { waiters := #[waiter] } modify fun s => { s with generatorStack := s.generatorStack.push node, tableEntries := s.tableEntries.insert key entry } def findEntry? (key : Expr) : SynthM (Option TableEntry) := do return (← get).tableEntries.find? key def getEntry (key : Expr) : SynthM TableEntry := do match (← findEntry? key) with | none => panic! "invalid key at synthInstance" | some entry => pure entry /-- Create a `key` for the goal associated with the given metavariable. That is, we create a key for the type of the metavariable. We must instantiate assigned metavariables before we invoke `mkTableKey`. -/ def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr := withMCtx mctx do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType return mkTableKey mctx mvarType /- See `getSubgoals` and `getSubgoalsAux` We use the parameter `j` to reduce the number of `instantiate*` invocations. It is the same approach we use at `forallTelescope` and `lambdaTelescope`. Given `getSubgoalsAux args j subgoals instVal type`, we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/ structure SubgoalsResult where subgoals : List Expr instVal : Expr instTypeBody : Expr private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) : Array Expr → Nat → List Expr → Expr → Expr → MetaM SubgoalsResult | args, j, subgoals, instVal, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args let mvarType ← mkForallFVars xs d let mvar ← mkFreshExprMVarAt lctx localInsts mvarType let arg := mkAppN mvar xs let instVal := mkApp instVal arg let subgoals := if c.binderInfo.isInstImplicit then mvar::subgoals else subgoals let args := args.push (mkAppN mvar xs) getSubgoalsAux lctx localInsts xs args j subgoals instVal b | args, j, subgoals, instVal, type => do let type := type.instantiateRevRange j args.size args let type ← whnf type if type.isForall then getSubgoalsAux lctx localInsts xs args args.size subgoals instVal type else pure ⟨subgoals, instVal, type⟩ /-- `getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`. The subgoals are in the context of the free variables `xs`, and `(lctx, localInsts)` is the local context and instances before we added the free variables to it. This extra complication is required because 1- We want all metavariables created by `synthInstance` to share the same local context. 2- We want to ensure that applications such as `mvar xs` are higher order patterns. The method `getGoals` create a new metavariable for each parameter of `inst`. For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`. Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these metavariables that are instance implicit arguments, and the expressions: - `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`) - `B (?m_1 xs) ... (?m_n xs)` -/ def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do let instType ← inferType inst let result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType match inst.getAppFn with | Expr.const constName _ _ => let env ← getEnv if hasInferTCGoalsRLAttribute env constName then pure result else pure { result with subgoals := result.subgoals.reverse } | _ => pure result def tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do let mvar ← instantiateMVars mvar if !(← hasAssignableMVar mvar) then /- The metavariable `mvar` may have been assinged when solving typing constraints. This may happen when a local instance type depends on other local instances. For example, in Mathlib, we have ``` @Submodule.setLike : {R : Type u_1} → {M : Type u_2} → [_inst_1 : Semiring R] → [_inst_2 : AddCommMonoid M] → [_inst_3 : @ModuleS R M _inst_1 _inst_2] → SetLike (@Submodule R M _inst_1 _inst_2 _inst_3) M ``` TODO: discuss what is the correct behavior here. There are other possibilities. 1) We could try to synthesize the instances `_inst_1` and `_inst_2` and check whether it is defeq to the one inferred by typing constraints. That is, we remove this `if`-statement. We discarded this one because some Mathlib theorems failed to be elaborated using it. 2) Generate an error/warning message when instances such as `Submodule.setLike` are declared, and instruct user to use `{}` binder annotation for `_inst_1` `_inst_2`. -/ return some ((← getMCtx), []) let mvarType ← inferType mvar let lctx ← getLCtx let localInsts ← getLocalInstances forallTelescopeReducing mvarType fun xs mvarTypeBody => do let ⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst trace[Meta.synthInstance.tryResolve] "{mvarTypeBody} =?= {instTypeBody}" if (← isDefEq mvarTypeBody instTypeBody) then let instVal ← mkLambdaFVars xs instVal if (← isDefEq mvar instVal) then trace[Meta.synthInstance.tryResolve] "success" pure (some ((← getMCtx), subgoals)) else trace[Meta.synthInstance.tryResolve] "failure assigning" pure none else trace[Meta.synthInstance.tryResolve] "failure" pure none /-- Try to synthesize metavariable `mvar` using the instance `inst`. Remark: `mctx` contains `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. A subgoal is created for each instance implicit parameter of `inst`. -/ def tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext × List Expr)) := traceCtx `Meta.synthInstance.tryResolve <| withMCtx mctx <| tryResolveCore mvar inst /-- Assign a precomputed answer to `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/ def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) := withMCtx mctx do let (_, _, val) ← openAbstractMVarsResult answer.result if (← isDefEq mvar val) then pure (some (← getMCtx)) else pure none /-- Move waiters that are waiting for the given answer to the resume stack. -/ def wakeUp (answer : Answer) : Waiter → SynthM Unit | Waiter.root => do /- Recall that we now use `ignoreLevelMVarDepth := true`. Thus, we should allow solutions containing universe metavariables, and not check `answer.result.paramNames.isEmpty`. We use `openAbstractMVarsResult` to construct the universe metavariables at the correct depth. -/ if answer.result.numMVars == 0 then modify fun s => { s with result? := answer.result } else let (_, _, answerExpr) ← openAbstractMVarsResult answer.result trace[Meta.synthInstance] "skip answer containing metavariables {answerExpr}" pure () | Waiter.consumerNode cNode => modify fun s => { s with resumeStack := s.resumeStack.push (cNode, answer) } def isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool := oldAnswers.all fun oldAnswer => do -- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer` -- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq) oldAnswer.resultType != answer.resultType private def mkAnswer (cNode : ConsumerNode) : MetaM Answer := withMCtx cNode.mctx do traceM `Meta.synthInstance.newAnswer do m!"size: {cNode.size}, {← inferType cNode.mvar}" let val ← instantiateMVars cNode.mvar trace[Meta.synthInstance.newAnswer] "val: {val}" let result ← abstractMVars val -- assignable metavariables become parameters let resultType ← inferType result.expr pure { result := result, resultType := resultType, size := cNode.size + 1 } /-- Create a new answer after `cNode` resolved all subgoals. That is, `cNode.subgoals == []`. And then, store it in the tabled entries map, and wakeup waiters. -/ def addAnswer (cNode : ConsumerNode) : SynthM Unit := do if cNode.size ≥ (← read).maxResultSize then traceM `Meta.synthInstance.discarded do m!"size: {cNode.size} ≥ {(← read).maxResultSize}, {← inferType cNode.mvar}" return () else let answer ← mkAnswer cNode -- Remark: `answer` does not contain assignable or assigned metavariables. let key := cNode.key let entry ← getEntry key if isNewAnswer entry.answers answer then let newEntry := { entry with answers := entry.answers.push answer } modify fun s => { s with tableEntries := s.tableEntries.insert key newEntry } entry.waiters.forM (wakeUp answer) /-- Process the next subgoal in the given consumer node. -/ def consume (cNode : ConsumerNode) : SynthM Unit := match cNode.subgoals with | [] => addAnswer cNode | mvar::_ => do let waiter := Waiter.consumerNode cNode let key ← mkTableKeyFor cNode.mctx mvar let entry? ← findEntry? key match entry? with | none => newSubgoal cNode.mctx key mvar waiter | some entry => modify fun s => { s with resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack, tableEntries := s.tableEntries.insert key { entry with waiters := entry.waiters.push waiter } } def getTop : SynthM GeneratorNode := do pure (← get).generatorStack.back @[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit := modify fun s => { s with generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f } /-- Try the next instance in the node on the top of the generator stack. -/ def generate : SynthM Unit := do let gNode ← getTop if gNode.currInstanceIdx == 0 then modify fun s => { s with generatorStack := s.generatorStack.pop } else do let key := gNode.key let idx := gNode.currInstanceIdx - 1 let inst := gNode.instances.get! idx let mctx := gNode.mctx let mvar := gNode.mvar trace[Meta.synthInstance.generate] "instance {inst}" modifyTop fun gNode => { gNode with currInstanceIdx := idx } match (← tryResolve mctx mvar inst) with | none => pure () | some (mctx, subgoals) => consume { key := key, mvar := mvar, subgoals := subgoals, mctx := mctx, size := 0 } def getNextToResume : SynthM (ConsumerNode × Answer) := do let s ← get let r := s.resumeStack.back modify fun s => { s with resumeStack := s.resumeStack.pop } pure r /-- Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the next subgoal. -/ def resume : SynthM Unit := do let (cNode, answer) ← getNextToResume match cNode.subgoals with | [] => panic! "resume found no remaining subgoals" | mvar::rest => match (← tryAnswer cNode.mctx mvar answer) with | none => pure () | some mctx => withMCtx mctx <| traceM `Meta.synthInstance.resume do let goal ← inferType cNode.mvar let subgoal ← inferType mvar pure m!"size: {cNode.size + answer.size}, {goal} <== {subgoal}" consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx := mctx, size := cNode.size + answer.size } def step : SynthM Bool := do checkMaxHeartbeats let s ← get if !s.resumeStack.isEmpty then resume pure true else if !s.generatorStack.isEmpty then generate pure true else pure false def getResult : SynthM (Option AbstractMVarsResult) := do pure (← get).result? partial def synth : SynthM (Option AbstractMVarsResult) := do if (← step) then match (← getResult) with | none => synth | some result => pure result else trace[Meta.synthInstance] "failed" pure none def main (type : Expr) (maxResultSize : Nat) : MetaM (Option AbstractMVarsResult) := withCurrHeartbeats <| traceCtx `Meta.synthInstance do trace[Meta.synthInstance] "main goal {type}" let mvar ← mkFreshExprMVar type let mctx ← getMCtx let key := mkTableKey mctx type let action : SynthM (Option AbstractMVarsResult) := do newSubgoal mctx key mvar Waiter.root synth action.run { maxResultSize := maxResultSize, maxHeartbeats := getMaxHeartbeats (← getOptions) } |>.run' {} end SynthInstance /- Type class parameters can be annotated with `outParam` annotations. Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF `a_i` is an `outParam`. The result is type correct because we reject type class declarations IF it contains a regular parameter X that depends on an `out` parameter Y. Then, we execute type class resolution as usual. If it succeeds, and metavariables ?m_i have been assigned, we try to unify the original type `C a_1 ... a_n` witht the normalized one. -/ private def preprocess (type : Expr) : MetaM Expr := forallTelescopeReducing type fun xs type => do let type ← whnf type mkForallFVars xs type private def preprocessLevels (us : List Level) : MetaM (List Level × Bool) := do let mut r := #[] let mut modified := false for u in us do let u ← instantiateLevelMVars u if u.hasMVar then r := r.push (← mkFreshLevelMVar) modified := true else r := r.push u return (r.toList, modified) private partial def preprocessArgs (type : Expr) (i : Nat) (args : Array Expr) : MetaM (Array Expr) := do if h : i < args.size then let type ← whnf type match type with | Expr.forallE _ d b _ => do let arg := args.get ⟨i, h⟩ let arg ← if isOutParam d then mkFreshExprMVar d else pure arg let args := args.set ⟨i, h⟩ arg preprocessArgs (b.instantiate1 arg) (i+1) args | _ => throwError "type class resolution failed, insufficient number of arguments" -- TODO improve error message else return args private def preprocessOutParam (type : Expr) : MetaM Expr := forallTelescope type fun xs typeBody => do match typeBody.getAppFn with | c@(Expr.const constName us _) => let env ← getEnv if !hasOutParams env constName then return type else let args := typeBody.getAppArgs let cType ← inferType c let args ← preprocessArgs cType 0 args mkForallFVars xs (mkAppN c args) | _ => return type /- Remark: when `maxResultSize? == none`, the configuration option `synthInstance.maxResultSize` is used. Remark: we use a different option for controlling the maximum result size for coercions. -/ def synthInstance? (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (Option Expr) := do profileitM Exception "typeclass inference" (← getOptions) do let opts ← getOptions let maxResultSize := maxResultSize?.getD (synthInstance.maxSize.get opts) let inputConfig ← getConfig withConfig (fun config => { config with isDefEqStuckEx := true, transparency := TransparencyMode.instances, foApprox := true, ctxApprox := true, constApprox := false, ignoreLevelMVarDepth := true }) do let type ← instantiateMVars type let type ← preprocess type let s ← get match s.cache.synthInstance.find? type with | some result => pure result | none => let result? ← withNewMCtxDepth do let normType ← preprocessOutParam type trace[Meta.synthInstance] "preprocess: {type} ==> {normType}" SynthInstance.main normType maxResultSize let resultHasUnivMVars := if let some result := result? then !result.paramNames.isEmpty else false let result? ← match result? with | none => pure none | some result => do let (_, _, result) ← openAbstractMVarsResult result trace[Meta.synthInstance] "result {result}" let resultType ← inferType result if (← withConfig (fun _ => inputConfig) <| isDefEq type resultType) then let result ← instantiateMVars result pure (some result) else trace[Meta.synthInstance] "result type{indentExpr resultType}\nis not definitionally equal to{indentExpr type}" pure none if type.hasMVar || resultHasUnivMVars then pure result? else do modify fun s => { s with cache := { s.cache with synthInstance := s.cache.synthInstance.insert type result? } } pure result? /-- Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if instance cannot be synthesized right now because `type` contains metavariables. -/ def trySynthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (LOption Expr) := do catchInternalId isDefEqStuckExceptionId (toLOptionM <| synthInstance? type maxResultSize?) (fun _ => pure LOption.undef) def synthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM Expr := catchInternalId isDefEqStuckExceptionId (do let result? ← synthInstance? type maxResultSize? match result? with | some result => pure result | none => throwError "failed to synthesize{indentExpr type}") (fun _ => throwError "failed to synthesize{indentExpr type}") @[export lean_synth_pending] private def synthPendingImp (mvarId : MVarId) : MetaM Bool := withIncRecDepth <| withMVarContext mvarId do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.syntheticOpaque => return false | _ => /- Check whether the type of the given metavariable is a class or not. If yes, then try to synthesize it using type class resolution. We only do it for `synthetic` and `natural` metavariables. -/ match (← isClass? mvarDecl.type) with | none => return false | some _ => /- TODO: use a configuration option instead of the hard-coded limit `1`. -/ if (← read).synthPendingDepth > 1 then trace[Meta.synthPending] "too many nested synthPending invocations" return false else withReader (fun ctx => { ctx with synthPendingDepth := ctx.synthPendingDepth + 1 }) do trace[Meta.synthPending] "synthPending {mkMVar mvarId}" let val? ← catchInternalId isDefEqStuckExceptionId (synthInstance? mvarDecl.type (maxResultSize? := none)) (fun _ => pure none) match val? with | none => return false | some val => if (← isExprMVarAssigned mvarId) then return false else assignExprMVar mvarId val return true builtin_initialize registerTraceClass `Meta.synthInstance registerTraceClass `Meta.synthInstance.globalInstances registerTraceClass `Meta.synthInstance.newSubgoal registerTraceClass `Meta.synthInstance.tryResolve registerTraceClass `Meta.synthInstance.resume registerTraceClass `Meta.synthInstance.generate registerTraceClass `Meta.synthPending end Lean.Meta
504b311fcbfeef11ef0ad68136362dfa6b4e4049
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/group_action/defs_auto.lean
a170ba99f616d90bff0a690c75ab85e517946d3f
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,801
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.basic import Mathlib.algebra.group.defs import Mathlib.algebra.group.hom import Mathlib.logic.embedding import Mathlib.PostPort universes u v l u_1 u_2 u_3 w namespace Mathlib /-! # Definitions of group actions This file defines a hierarchy of group action type-classes: * `has_scalar α β` * `mul_action α β` * `distrib_mul_action α β` The hierarchy is extended further by `semimodule`, defined elsewhere. Also provided are type-classes regarding the interaction of different group actions, * `smul_comm_class M N α` * `is_scalar_tower M N α` ## Notation `a • b` is used as notation for `smul a b`. ## Implementation details This file should avoid depending on other parts of `group_theory`, to avoid import cycles. More sophisticated lemmas belong in `group_theory.group_action`. -/ /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : Type u) (γ : Type v) where smul : α → γ → γ infixr:73 " • " => Mathlib.has_scalar.smul /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ class mul_action (α : Type u) (β : Type v) [monoid α] extends has_scalar α β where one_smul : ∀ (b : β), 1 • b = b mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b /-- A typeclass mixin saying that two actions on the same space commute. -/ class smul_comm_class (M : Type u_1) (N : Type u_2) (α : Type u_3) [has_scalar M α] [has_scalar N α] where smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a /-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ theorem smul_comm_class.symm (M : Type u_1) (N : Type u_2) (α : Type u_3) [has_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class N M α := smul_comm_class.mk fun (a' : N) (a : M) (b : α) => Eq.symm (smul_comm a a' b) protected instance smul_comm_class_self (M : Type u_1) (α : Type u_2) [comm_monoid M] [mul_action M α] : smul_comm_class M M α := smul_comm_class.mk fun (a a' : M) (b : α) => eq.mpr (id (Eq._oldrec (Eq.refl (a • a' • b = a' • a • b)) (Eq.symm (mul_smul a a' b)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a * a') • b = a' • a • b)) (mul_comm a a'))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a' * a) • b = a' • a • b)) (mul_smul a' a b))) (Eq.refl (a' • a • b)))) /-- An instance of `is_scalar_tower M N α` states that the multiplicative action of `M` on `α` is determined by the multiplicative actions of `M` on `N` and `N` on `α`. -/ class is_scalar_tower (M : Type u_1) (N : Type u_2) (α : Type u_3) [has_scalar M N] [has_scalar N α] [has_scalar M α] where smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • y • z @[simp] theorem smul_assoc {α : Type u} {M : Type u_1} {N : Type u_2} [has_scalar M N] [has_scalar N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z theorem smul_smul {α : Type u} {β : Type v} [monoid α] [mul_action α β] (a₁ : α) (a₂ : α) (b : β) : a₁ • a₂ • b = (a₁ * a₂) • b := Eq.symm (mul_smul a₁ a₂ b) @[simp] theorem one_smul (α : Type u) {β : Type v} [monoid α] [mul_action α β] (b : β) : 1 • b = b := mul_action.one_smul b /-- Pullback a multiplicative action along an injective map respecting `•`. -/ protected def function.injective.mul_action {α : Type u} {β : Type v} {γ : Type w} [monoid α] [mul_action α β] [has_scalar α γ] (f : γ → β) (hf : function.injective f) (smul : ∀ (c : α) (x : γ), f (c • x) = c • f x) : mul_action α γ := mul_action.mk sorry sorry /-- Pushforward a multiplicative action along a surjective map respecting `•`. -/ protected def function.surjective.mul_action {α : Type u} {β : Type v} {γ : Type w} [monoid α] [mul_action α β] [has_scalar α γ] (f : β → γ) (hf : function.surjective f) (smul : ∀ (c : α) (x : β), f (c • x) = c • f x) : mul_action α γ := mul_action.mk sorry sorry theorem ite_smul {α : Type u} {β : Type v} [monoid α] [mul_action α β] (p : Prop) [Decidable p] (a₁ : α) (a₂ : α) (b : β) : ite p a₁ a₂ • b = ite p (a₁ • b) (a₂ • b) := sorry theorem smul_ite {α : Type u} {β : Type v} [monoid α] [mul_action α β] (p : Prop) [Decidable p] (a : α) (b₁ : β) (b₂ : β) : a • ite p b₁ b₂ = ite p (a • b₁) (a • b₂) := sorry namespace mul_action /-- The regular action of a monoid on itself by left multiplication. -/ def regular (α : Type u) [monoid α] : mul_action α α := mk sorry sorry protected instance is_scalar_tower.left (α : Type u) {β : Type v} [monoid α] [mul_action α β] : is_scalar_tower α α β := is_scalar_tower.mk fun (x y : α) (z : β) => mul_smul x y z /-- Embedding induced by action. -/ def to_fun (α : Type u) (β : Type v) [monoid α] [mul_action α β] : β ↪ α → β := function.embedding.mk (fun (y : β) (x : α) => x • y) sorry @[simp] theorem to_fun_apply {α : Type u} {β : Type v} [monoid α] [mul_action α β] (x : α) (y : β) : coe_fn (to_fun α β) y x = x • y := rfl /-- An action of `α` on `β` and a monoid homomorphism `γ → α` induce an action of `γ` on `β`. -/ def comp_hom {α : Type u} (β : Type v) {γ : Type w} [monoid α] [mul_action α β] [monoid γ] (g : γ →* α) : mul_action γ β := mk sorry sorry end mul_action @[simp] theorem smul_one_smul {α : Type u} {M : Type u_1} (N : Type u_2) [monoid N] [has_scalar M N] [mul_action N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • 1) • y = x • y := eq.mpr (id (Eq._oldrec (Eq.refl ((x • 1) • y = x • y)) (smul_assoc x 1 y))) (eq.mpr (id (Eq._oldrec (Eq.refl (x • 1 • y = x • y)) (one_smul N y))) (Eq.refl (x • y))) /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β] extends mul_action α β where smul_add : ∀ (r : α) (x y : β), r • (x + y) = r • x + r • y smul_zero : ∀ (r : α), r • 0 = 0 theorem smul_add {α : Type u} {β : Type v} [monoid α] [add_monoid β] [distrib_mul_action α β] (a : α) (b₁ : β) (b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add a b₁ b₂ @[simp] theorem smul_zero {α : Type u} {β : Type v} [monoid α] [add_monoid β] [distrib_mul_action α β] (a : α) : a • 0 = 0 := distrib_mul_action.smul_zero a /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. -/ protected def function.injective.distrib_mul_action {α : Type u} {β : Type v} {γ : Type w} [monoid α] [add_monoid β] [distrib_mul_action α β] [add_monoid γ] [has_scalar α γ] (f : γ →+ β) (hf : function.injective ⇑f) (smul : ∀ (c : α) (x : γ), coe_fn f (c • x) = c • coe_fn f x) : distrib_mul_action α γ := distrib_mul_action.mk sorry sorry /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism.-/ protected def function.surjective.distrib_mul_action {α : Type u} {β : Type v} {γ : Type w} [monoid α] [add_monoid β] [distrib_mul_action α β] [add_monoid γ] [has_scalar α γ] (f : β →+ γ) (hf : function.surjective ⇑f) (smul : ∀ (c : α) (x : β), coe_fn f (c • x) = c • coe_fn f x) : distrib_mul_action α γ := distrib_mul_action.mk sorry sorry /-- Scalar multiplication by `r` as an `add_monoid_hom`. -/ def const_smul_hom {α : Type u} (β : Type v) [monoid α] [add_monoid β] [distrib_mul_action α β] (r : α) : β →+ β := add_monoid_hom.mk (has_scalar.smul r) (smul_zero r) (smul_add r) @[simp] theorem const_smul_hom_apply {α : Type u} {β : Type v} [monoid α] [add_monoid β] [distrib_mul_action α β] (r : α) (x : β) : coe_fn (const_smul_hom β r) x = r • x := rfl @[simp] theorem smul_neg {α : Type u} {β : Type v} [monoid α] [add_group β] [distrib_mul_action α β] (r : α) (x : β) : r • -x = -(r • x) := sorry theorem smul_sub {α : Type u} {β : Type v} [monoid α] [add_group β] [distrib_mul_action α β] (r : α) (x : β) (y : β) : r • (x - y) = r • x - r • y := sorry end Mathlib
ad25eddc259930b30a1b28736eb5183428b7321f
130c49f47783503e462c16b2eff31933442be6ff
/src/Init/Data/List/Basic.lean
caaeac15a0875ee558650ada3eaf4e9a8e9f44ad
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,706
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.SimpLemmas import Init.Data.Nat.Basic open Decidable List universe u v w variable {α : Type u} {β : Type v} {γ : Type w} namespace List theorem length_add_eq_lengthTRAux (as : List α) (n : Nat) : as.length + n = as.lengthTRAux n := by induction as generalizing n with | nil => simp [length, lengthTRAux] | cons a as ih => simp [length, lengthTRAux, ← ih, Nat.succ_add] rfl @[csimp] theorem length_eq_lenghtTR : @List.length = @List.lengthTR := by apply funext; intro α; apply funext; intro as simp [lengthTR, ← length_add_eq_lengthTRAux] @[simp] theorem length_nil : length ([] : List α) = 0 := rfl def reverseAux : List α → List α → List α | [], r => r | a::l, r => reverseAux l (a::r) def reverse (as : List α) :List α := reverseAux as [] theorem reverseAux_reverseAux_nil (as bs : List α) : reverseAux (reverseAux as bs) [] = reverseAux bs as := by induction as generalizing bs with | nil => rfl | cons a as ih => simp [reverseAux, ih] theorem reverseAux_reverseAux (as bs cs : List α) : reverseAux (reverseAux as bs) cs = reverseAux bs (reverseAux (reverseAux as []) cs) := by induction as generalizing bs cs with | nil => rfl | cons a as ih => simp [reverseAux, ih (a::bs), ih [a]] protected def append : List α → List α → List α | [], bs => bs | a::as, bs => a :: List.append as bs def appendTR (as bs : List α) : List α := reverseAux as.reverse bs @[csimp] theorem append_eq_appendTR : @List.append = @appendTR := by apply funext; intro α; apply funext; intro as; apply funext; intro bs simp [appendTR, reverse] induction as with | nil => rfl | cons a as ih => simp [reverseAux, List.append, ih, reverseAux_reverseAux] instance : Append (List α) := ⟨List.append⟩ @[simp] theorem nil_append (as : List α) : [] ++ as = as := rfl @[simp] theorem append_nil (as : List α) : as ++ [] = as := by induction as with | nil => rfl | cons a as ih => simp_all [HAppend.hAppend, Append.append, List.append] @[simp] theorem cons_append (a : α) (as bs : List α) : (a::as) ++ bs = a::(as ++ bs) := rfl theorem append_assoc (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs) := by induction as with | nil => rfl | cons a as ih => simp [ih] instance : EmptyCollection (List α) := ⟨List.nil⟩ protected def erase {α} [BEq α] : List α → α → List α | [], b => [] | a::as, b => match a == b with | true => as | false => a :: List.erase as b def eraseIdx : List α → Nat → List α | [], _ => [] | a::as, 0 => as | a::as, n+1 => a :: eraseIdx as n def isEmpty : List α → Bool | [] => true | _ :: _ => false @[specialize] def map (f : α → β) : List α → List β | [] => [] | a::as => f a :: map f as def mapTRAux (f : α → β) : List α → List β → List β | [], bs => bs.reverse | a::as, bs => mapTRAux f as (f a :: bs) def mapTR (f : α → β) (as : List α) : List β := mapTRAux f as [] theorem reverseAux_eq_append (as bs : List α) : reverseAux as bs = reverseAux as [] ++ bs := by induction as generalizing bs with | nil => simp [reverseAux] | cons a as ih => simp [reverseAux] rw [ih (a :: bs), ih [a], append_assoc] rfl theorem reverse_cons (a : α) (as : List α) : reverse (a :: as) = reverse as ++ [a] := by simp [reverse, reverseAux] rw [← reverseAux_eq_append] theorem mapTRAux_eq (f : α → β) (as : List α) (bs : List β) : mapTRAux f as bs = bs.reverse ++ map f as := by induction as generalizing bs with | nil => simp [mapTRAux, map] | cons a as ih => simp [mapTRAux, map] rw [ih (f a :: bs), reverse_cons, append_assoc] rfl @[csimp] theorem map_eq_mapTR : @map = @mapTR := by apply funext; intro α; apply funext; intro β; apply funext; intro f; apply funext; intro as simp [mapTR, mapTRAux_eq] rfl @[specialize] def map₂ (f : α → β → γ) : List α → List β → List γ | [], _ => [] | _, [] => [] | a::as, b::bs => f a b :: map₂ f as bs def join : List (List α) → List α | [] => [] | a :: as => a ++ join as @[specialize] def filterMap (f : α → Option β) : List α → List β | [] => [] | a::as => match f a with | none => filterMap f as | some b => b :: filterMap f as @[specialize] def filterAux (p : α → Bool) : List α → List α → List α | [], rs => rs.reverse | a::as, rs => match p a with | true => filterAux p as (a::rs) | false => filterAux p as rs @[inline] def filter (p : α → Bool) (as : List α) : List α := filterAux p as [] @[specialize] def partitionAux (p : α → Bool) : List α → List α × List α → List α × List α | [], (bs, cs) => (bs.reverse, cs.reverse) | a::as, (bs, cs) => match p a with | true => partitionAux p as (a::bs, cs) | false => partitionAux p as (bs, a::cs) @[inline] def partition (p : α → Bool) (as : List α) : List α × List α := partitionAux p as ([], []) def dropWhile (p : α → Bool) : List α → List α | [] => [] | a::l => match p a with | true => dropWhile p l | false => a::l def find? (p : α → Bool) : List α → Option α | [] => none | a::as => match p a with | true => some a | false => find? p as def findSome? (f : α → Option β) : List α → Option β | [] => none | a::as => match f a with | some b => some b | none => findSome? f as def replace [BEq α] : List α → α → α → List α | [], _, _ => [] | a::as, b, c => match a == b with | true => c::as | false => a :: (replace as b c) def elem [BEq α] (a : α) : List α → Bool | [] => false | b::bs => match a == b with | true => true | false => elem a bs def notElem [BEq α] (a : α) (as : List α) : Bool := !(as.elem a) abbrev contains [BEq α] (as : List α) (a : α) : Bool := elem a as def eraseDupsAux {α} [BEq α] : List α → List α → List α | [], bs => bs.reverse | a::as, bs => match bs.elem a with | true => eraseDupsAux as bs | false => eraseDupsAux as (a::bs) def eraseDups {α} [BEq α] (as : List α) : List α := eraseDupsAux as [] def eraseRepsAux {α} [BEq α] : α → List α → List α → List α | a, [], rs => (a::rs).reverse | a, a'::as, rs => match a == a' with | true => eraseRepsAux a as rs | false => eraseRepsAux a' as (a::rs) /-- Erase repeated adjacent elements. -/ def eraseReps {α} [BEq α] : List α → List α | [] => [] | a::as => eraseRepsAux a as [] @[specialize] def spanAux (p : α → Bool) : List α → List α → List α × List α | [], rs => (rs.reverse, []) | a::as, rs => match p a with | true => spanAux p as (a::rs) | false => (rs.reverse, a::as) @[inline] def span (p : α → Bool) (as : List α) : List α × List α := spanAux p as [] @[specialize] def groupByAux (eq : α → α → Bool) : List α → List (List α) → List (List α) | a::as, (ag::g)::gs => match eq a ag with | true => groupByAux eq as ((a::ag::g)::gs) | false => groupByAux eq as ([a]::(ag::g).reverse::gs) | _, gs => gs.reverse @[specialize] def groupBy (p : α → α → Bool) : List α → List (List α) | [] => [] | a::as => groupByAux p as [[a]] def lookup [BEq α] : α → List (α × β) → Option β | _, [] => none | a, (k,b)::es => match a == k with | true => some b | false => lookup a es def removeAll [BEq α] (xs ys : List α) : List α := xs.filter (fun x => ys.notElem x) def drop : Nat → List α → List α | 0, a => a | n+1, [] => [] | n+1, a::as => drop n as def take : Nat → List α → List α | 0, a => [] | n+1, [] => [] | n+1, a::as => a :: take n as def takeWhile (p : α → Bool) : List α → List α | [] => [] | hd :: tl => match p hd with | true => hd :: takeWhile p tl | false => [] @[specialize] def foldr (f : α → β → β) (init : β) : List α → β | [] => init | a :: l => f a (foldr f init l) @[inline] def any (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a || r) false l @[inline] def all (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a && r) true l def or (bs : List Bool) : Bool := bs.any id def and (bs : List Bool) : Bool := bs.all id def zipWith (f : α → β → γ) : List α → List β → List γ | x::xs, y::ys => f x y :: zipWith f xs ys | _, _ => [] def zip : List α → List β → List (Prod α β) := zipWith Prod.mk def unzip : List (α × β) → List α × List β | [] => ([], []) | (a, b) :: t => match unzip t with | (al, bl) => (a::al, b::bl) def rangeAux : Nat → List Nat → List Nat | 0, ns => ns | n+1, ns => rangeAux n (n::ns) def range (n : Nat) : List Nat := rangeAux n [] def iota : Nat → List Nat | 0 => [] | m@(n+1) => m :: iota n def enumFrom : Nat → List α → List (Nat × α) | n, [] => nil | n, x :: xs => (n, x) :: enumFrom (n + 1) xs def enum : List α → List (Nat × α) := enumFrom 0 def init : List α → List α | [] => [] | [a] => [] | a::l => a::init l def intersperse (sep : α) : List α → List α | [] => [] | [x] => [x] | x::xs => x :: sep :: intersperse sep xs def intercalate (sep : List α) (xs : List (List α)) : List α := join (intersperse sep xs) @[inline] protected def bind {α : Type u} {β : Type v} (a : List α) (b : α → List β) : List β := join (map b a) @[inline] protected def pure {α : Type u} (a : α) : List α := [a] inductive lt [LT α] : List α → List α → Prop where | nil (b : α) (bs : List α) : lt [] (b::bs) | head {a : α} (as : List α) {b : α} (bs : List α) : a < b → lt (a::as) (b::bs) | tail {a : α} {as : List α} {b : α} {bs : List α} : ¬ a < b → ¬ b < a → lt as bs → lt (a::as) (b::bs) instance [LT α] : LT (List α) := ⟨List.lt⟩ instance hasDecidableLt [LT α] [h : DecidableRel (α:=α) (·<·)] : (l₁ l₂ : List α) → Decidable (l₁ < l₂) | [], [] => isFalse (fun h => nomatch h) | [], b::bs => isTrue (List.lt.nil _ _) | a::as, [] => isFalse (fun h => nomatch h) | a::as, b::bs => match h a b with | isTrue h₁ => isTrue (List.lt.head _ _ h₁) | isFalse h₁ => match h b a with | isTrue h₂ => isFalse (fun h => match h with | List.lt.head _ _ h₁' => absurd h₁' h₁ | List.lt.tail _ h₂' _ => absurd h₂ h₂') | isFalse h₂ => match hasDecidableLt as bs with | isTrue h₃ => isTrue (List.lt.tail h₁ h₂ h₃) | isFalse h₃ => isFalse (fun h => match h with | List.lt.head _ _ h₁' => absurd h₁' h₁ | List.lt.tail _ _ h₃' => absurd h₃' h₃) @[reducible] protected def le [LT α] (a b : List α) : Prop := ¬ b < a instance [LT α] : LE (List α) := ⟨List.le⟩ instance [LT α] [h : DecidableRel ((· < ·) : α → α → Prop)] : (l₁ l₂ : List α) → Decidable (l₁ ≤ l₂) := fun a b => inferInstanceAs (Decidable (Not _)) /-- `isPrefixOf l₁ l₂` returns `true` Iff `l₁` is a prefix of `l₂`. -/ def isPrefixOf [BEq α] : List α → List α → Bool | [], _ => true | _, [] => false | a::as, b::bs => a == b && isPrefixOf as bs /-- `isSuffixOf l₁ l₂` returns `true` Iff `l₁` is a suffix of `l₂`. -/ def isSuffixOf [BEq α] (l₁ l₂ : List α) : Bool := isPrefixOf l₁.reverse l₂.reverse @[specialize] def isEqv : List α → List α → (α → α → Bool) → Bool | [], [], _ => true | a::as, b::bs, eqv => eqv a b && isEqv as bs eqv | _, _, eqv => false protected def beq [BEq α] : List α → List α → Bool | [], [] => true | a::as, b::bs => a == b && List.beq as bs | _, _ => false instance [BEq α] : BEq (List α) := ⟨List.beq⟩ def replicate {α : Type u} (n : Nat) (a : α) : List α := let rec loop : Nat → List α → List α | 0, as => as | n+1, as => loop n (a::as) loop n [] def dropLast {α} : List α → List α | [] => [] | [a] => [] | a::as => a :: dropLast as @[simp] theorem length_replicate (n : Nat) (a : α) : (replicate n a).length = n := let rec aux (n : Nat) (as : List α) : (replicate.loop a n as).length = n + as.length := by induction n generalizing as with | zero => simp [replicate.loop] | succ n ih => simp [replicate.loop, ih, Nat.succ_add, Nat.add_succ] aux n [] @[simp] theorem length_concat (as : List α) (a : α) : (concat as a).length = as.length + 1 := by induction as with | nil => rfl | cons x xs ih => simp [concat, ih] @[simp] theorem length_set (as : List α) (i : Nat) (a : α) : (as.set i a).length = as.length := by induction as generalizing i with | nil => rfl | cons x xs ih => cases i with | zero => rfl | succ i => simp [set, ih] @[simp] theorem length_dropLast (as : List α) : as.dropLast.length = as.length - 1 := by match as with | [] => rfl | [a] => rfl | a::b::as => have ih := length_dropLast (b::as) simp[dropLast, ih] rfl def maximum? [LT α] [DecidableRel (@LT.lt α _)] : List α → Option α | [] => none | a::as => some <| as.foldl max a def minimum? [LE α] [DecidableRel (@LE.le α _)] : List α → Option α | [] => none | a::as => some <| as.foldl min a end List
ddee81535f0180305ed7066b68dbf7486de3da4a
f7315930643edc12e76c229a742d5446dad77097
/tests/lean/run/tactic14.lean
1567b7e84a515a1d72d2a9b43fdc5f2caa53fb0f
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
391
lean
import logic open tactic definition basic_tac : tactic := repeat (apply @and.intro | assumption) set_begin_end_tactic basic_tac -- basic_tac is automatically applied to each element of a proof-qed block theorem tst (a b : Prop) (H : ¬ a ∨ ¬ b) (Hb : b) : ¬ a ∧ b := begin assume Ha, or.elim H (assume Hna, @absurd _ false Ha Hna) (assume Hnb, @absurd _ false Hb Hnb) end
dc2d4ee5d293032563a1a8cb6c2a7fd8ed3d7ae9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/group/fundamental_domain.lean
a7ef2ec2fb7d8ced7b130f3764f3c36d992a0739
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
17,360
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import measure_theory.group.action import measure_theory.group.pointwise import measure_theory.integral.set_integral /-! # Fundamental domain of a group action A set `s` is said to be a *fundamental domain* of an action of a group `G` on a measurable space `α` with respect to a measure `μ` if * `s` is a measurable set; * the sets `g • s` over all `g : G` cover almost all points of the whole space; * the sets `g • s`, are pairwise a.e. disjoint, i.e., `μ (g₁ • s ∩ g₂ • s) = 0` whenever `g₁ ≠ g₂`; we require this for `g₂ = 1` in the definition, then deduce it for any two `g₁ ≠ g₂`. In this file we prove that in case of a countable group `G` and a measure preserving action, any two fundamental domains have the same measure, and for a `G`-invariant function, its integrals over any two fundamental domains are equal to each other. We also generate additive versions of all theorems in this file using the `to_additive` attribute. -/ open_locale ennreal pointwise topological_space nnreal ennreal measure_theory open measure_theory measure_theory.measure set function topological_space filter namespace measure_theory /-- A measurable set `s` is a *fundamental domain* for an additive action of an additive group `G` on a measurable space `α` with respect to a measure `α` if the sets `g +ᵥ s`, `g : G`, are pairwise a.e. disjoint and cover the whole space. -/ @[protect_proj] structure is_add_fundamental_domain (G : Type*) {α : Type*} [has_zero G] [has_vadd G α] [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := (null_measurable_set : null_measurable_set s μ) (ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g +ᵥ x ∈ s) (ae_disjoint : ∀ g ≠ (0 : G), ae_disjoint μ (g +ᵥ s) s) /-- A measurable set `s` is a *fundamental domain* for an action of a group `G` on a measurable space `α` with respect to a measure `α` if the sets `g • s`, `g : G`, are pairwise a.e. disjoint and cover the whole space. -/ @[protect_proj, to_additive is_add_fundamental_domain] structure is_fundamental_domain (G : Type*) {α : Type*} [has_one G] [has_smul G α] [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := (null_measurable_set : null_measurable_set s μ) (ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g • x ∈ s) (ae_disjoint : ∀ g ≠ (1 : G), ae_disjoint μ (g • s) s) namespace is_fundamental_domain variables {G α E : Type*} [group G] [mul_action G α] [measurable_space α] [normed_add_comm_group E] {s t : set α} {μ : measure α} /-- If for each `x : α`, exactly one of `g • x`, `g : G`, belongs to a measurable set `s`, then `s` is a fundamental domain for the action of `G` on `α`. -/ @[to_additive "If for each `x : α`, exactly one of `g +ᵥ x`, `g : G`, belongs to a measurable set `s`, then `s` is a fundamental domain for the additive action of `G` on `α`."] lemma mk' (h_meas : null_measurable_set s μ) (h_exists : ∀ x : α, ∃! g : G, g • x ∈ s) : is_fundamental_domain G s μ := { null_measurable_set := h_meas, ae_covers := eventually_of_forall $ λ x, (h_exists x).exists, ae_disjoint := λ g hne, disjoint.ae_disjoint $ disjoint_left.2 begin rintro _ ⟨x, hx, rfl⟩ hgx, rw ← one_smul G x at hx, exact hne ((h_exists x).unique hgx hx) end } @[to_additive] lemma Union_smul_ae_eq (h : is_fundamental_domain G s μ) : (⋃ g : G, g • s) =ᵐ[μ] univ := eventually_eq_univ.2 $ h.ae_covers.mono $ λ x ⟨g, hg⟩, mem_Union.2 ⟨g⁻¹, _, hg, inv_smul_smul _ _⟩ @[to_additive] lemma mono (h : is_fundamental_domain G s μ) {ν : measure α} (hle : ν ≪ μ) : is_fundamental_domain G s ν := ⟨h.1.mono_ac hle, hle h.2, λ g hg, hle (h.3 g hg)⟩ variables [measurable_space G] [has_measurable_smul G α] [smul_invariant_measure G α μ] @[to_additive] lemma null_measurable_set_smul (h : is_fundamental_domain G s μ) (g : G) : null_measurable_set (g • s) μ := h.null_measurable_set.smul g @[to_additive] lemma restrict_restrict (h : is_fundamental_domain G s μ) (g : G) (t : set α) : (μ.restrict t).restrict (g • s) = μ.restrict (g • s ∩ t) := restrict_restrict₀ ((h.null_measurable_set_smul g).mono restrict_le_self) @[to_additive] lemma pairwise_ae_disjoint (h : is_fundamental_domain G s μ) : pairwise (λ g₁ g₂ : G, ae_disjoint μ (g₁ • s) (g₂ • s)) := λ g₁ g₂ hne, calc μ (g₁ • s ∩ g₂ • s) = μ (g₂ • ((g₂⁻¹ * g₁) • s ∩ s)) : by rw [smul_set_inter, smul_smul, mul_inv_cancel_left] ... = μ ((g₂⁻¹ * g₁) • s ∩ s) : measure_smul_set _ _ _ ... = 0 : h.ae_disjoint _ $ mt inv_mul_eq_one.1 hne.symm @[to_additive] lemma pairwise_ae_disjoint_of_ac {ν} (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) : pairwise (λ g₁ g₂ : G, ae_disjoint ν (g₁ • s) (g₂ • s)) := h.pairwise_ae_disjoint.mono $ λ g₁ g₂ H, hν H @[to_additive] lemma preimage_of_equiv (h : is_fundamental_domain G s μ) {f : α → α} (hf : quasi_measure_preserving f μ μ) {e : G → G} (he : bijective e) (hef : ∀ g, semiconj f ((•) (e g)) ((•) g)) : is_fundamental_domain G (f ⁻¹' s) μ := { null_measurable_set := h.null_measurable_set.preimage hf, ae_covers := (hf.ae h.ae_covers).mono $ λ x ⟨g, hg⟩, ⟨e g, by rwa [mem_preimage, hef g x]⟩, ae_disjoint := λ g hg, begin lift e to G ≃ G using he, have : (e.symm g⁻¹)⁻¹ ≠ (e.symm 1)⁻¹, by simp [hg], convert (h.pairwise_ae_disjoint _ _ this).preimage hf using 1, { simp only [← preimage_smul_inv, preimage_preimage, ← hef _ _, e.apply_symm_apply, inv_inv] }, { ext1 x, simp only [mem_preimage, ← preimage_smul, ← hef _ _, e.apply_symm_apply, one_smul] } end } @[to_additive] lemma image_of_equiv (h : is_fundamental_domain G s μ) (f : α ≃ᵐ α) (hfμ : measure_preserving f μ μ) (e : equiv.perm G) (hef : ∀ g, semiconj f ((•) (e g)) ((•) g)) : is_fundamental_domain G (f '' s) μ := begin rw f.image_eq_preimage, refine h.preimage_of_equiv (hfμ.symm f).quasi_measure_preserving e.symm.bijective (λ g x, _), rcases f.surjective x with ⟨x, rfl⟩, rw [← hef _ _, f.symm_apply_apply, f.symm_apply_apply, e.apply_symm_apply] end @[to_additive] lemma smul (h : is_fundamental_domain G s μ) (g : G) : is_fundamental_domain G (g • s) μ := h.image_of_equiv (measurable_equiv.smul g) (measure_preserving_smul _ _) ⟨λ g', g⁻¹ * g' * g, λ g', g * g' * g⁻¹, λ g', by simp [mul_assoc], λ g', by simp [mul_assoc]⟩ $ λ g' x, by simp [smul_smul, mul_assoc] @[to_additive] lemma smul_of_comm {G' : Type*} [group G'] [mul_action G' α] [measurable_space G'] [has_measurable_smul G' α] [smul_invariant_measure G' α μ] [smul_comm_class G' G α] (h : is_fundamental_domain G s μ) (g : G') : is_fundamental_domain G (g • s) μ := h.image_of_equiv (measurable_equiv.smul g) (measure_preserving_smul _ _) (equiv.refl _) $ smul_comm g variables [countable G] {ν : measure α} @[to_additive] lemma sum_restrict_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) : sum (λ g : G, ν.restrict (g • s)) = ν := by rw [← restrict_Union_ae (h.pairwise_ae_disjoint.mono $ λ i j h, hν h) (λ g, (h.null_measurable_set_smul g).mono_ac hν), restrict_congr_set (hν h.Union_smul_ae_eq), restrict_univ] @[to_additive] lemma lintegral_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂ν = ∑' g : G, ∫⁻ x in g • s, f x ∂ν := by rw [← lintegral_sum_measure, h.sum_restrict_of_ac hν] @[to_additive] lemma sum_restrict (h : is_fundamental_domain G s μ) : sum (λ g : G, μ.restrict (g • s)) = μ := h.sum_restrict_of_ac (refl _) @[to_additive] lemma lintegral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂μ := h.lintegral_eq_tsum_of_ac (refl _) f @[to_additive] lemma set_lintegral_eq_tsum' (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) (t : set α) : ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ := calc ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂(μ.restrict t) : h.lintegral_eq_tsum_of_ac restrict_le_self.absolutely_continuous _ ... = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ : by simp only [h.restrict_restrict, inter_comm] @[to_additive] lemma set_lintegral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) (t : set α) : ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ := calc ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ : h.set_lintegral_eq_tsum' f t ... = ∑' g : G, ∫⁻ x in t ∩ g⁻¹ • s, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫⁻ x in g⁻¹ • (g • t ∩ s), f (x) ∂μ : by simp only [smul_set_inter, inv_smul_smul] ... = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, ((measure_preserving_smul g⁻¹ μ).set_lintegral_comp_emb (measurable_embedding_const_smul _) _ _).symm @[to_additive] lemma measure_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (t : set α) : ν t = ∑' g : G, ν (t ∩ g • s) := have H : ν.restrict t ≪ μ, from measure.restrict_le_self.absolutely_continuous.trans hν, by simpa only [set_lintegral_one, pi.one_def, measure.restrict_apply₀ ((h.null_measurable_set_smul _).mono_ac H), inter_comm] using h.lintegral_eq_tsum_of_ac H 1 @[to_additive] lemma measure_eq_tsum' (h : is_fundamental_domain G s μ) (t : set α) : μ t = ∑' g : G, μ (t ∩ g • s) := h.measure_eq_tsum_of_ac absolutely_continuous.rfl t @[to_additive] lemma measure_eq_tsum (h : is_fundamental_domain G s μ) (t : set α) : μ t = ∑' g : G, μ (g • t ∩ s) := by simpa only [set_lintegral_one] using h.set_lintegral_eq_tsum (λ _, 1) t @[to_additive] lemma measure_zero_of_invariant (h : is_fundamental_domain G s μ) (t : set α) (ht : ∀ g : G, g • t = t) (hts : μ (t ∩ s) = 0) : μ t = 0 := by simp [measure_eq_tsum h, ht, hts] @[to_additive] protected lemma set_lintegral_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) (f : α → ℝ≥0∞) (hf : ∀ (g : G) x, f (g • x) = f x) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := calc ∫⁻ x in s, f x ∂μ = ∑' g : G, ∫⁻ x in s ∩ g • t, f x ∂μ : ht.set_lintegral_eq_tsum' _ _ ... = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : by simp only [hf, inter_comm] ... = ∫⁻ x in t, f x ∂μ : (hs.set_lintegral_eq_tsum _ _).symm @[to_additive] lemma measure_set_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {A : set α} (hA₀ : measurable_set A) (hA : ∀ (g : G), (λ x, g • x) ⁻¹' A = A) : μ (A ∩ s) = μ (A ∩ t) := begin have : ∫⁻ x in s, A.indicator 1 x ∂μ = ∫⁻ x in t, A.indicator 1 x ∂μ, { refine hs.set_lintegral_eq ht (set.indicator A (λ _, 1)) _, intros g x, convert (set.indicator_comp_right (λ x : α, g • x)).symm, rw hA g }, simpa [measure.restrict_apply hA₀, lintegral_indicator _ hA₀] using this end /-- If `s` and `t` are two fundamental domains of the same action, then their measures are equal. -/ @[to_additive "If `s` and `t` are two fundamental domains of the same action, then their measures are equal."] protected lemma measure_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) : μ s = μ t := by simpa only [set_lintegral_one] using hs.set_lintegral_eq ht (λ _, 1) (λ _ _, rfl) @[to_additive] protected lemma ae_strongly_measurable_on_iff {β : Type*} [topological_space β] [pseudo_metrizable_space β] (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → β} (hf : ∀ (g : G) x, f (g • x) = f x) : ae_strongly_measurable f (μ.restrict s) ↔ ae_strongly_measurable f (μ.restrict t) := calc ae_strongly_measurable f (μ.restrict s) ↔ ae_strongly_measurable f (measure.sum $ λ g : G, (μ.restrict (g • t ∩ s))) : by simp only [← ht.restrict_restrict, ht.sum_restrict_of_ac restrict_le_self.absolutely_continuous] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g • (g⁻¹ • s ∩ t))) : by simp only [smul_set_inter, inter_comm, smul_inv_smul, ae_strongly_measurable_sum_measure_iff] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g⁻¹ • (g⁻¹⁻¹ • s ∩ t))) : inv_surjective.forall ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g⁻¹ • (g • s ∩ t))) : by simp only [inv_inv] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g • s ∩ t)) : begin refine forall_congr (λ g, _), have he : measurable_embedding ((•) g⁻¹ : α → α) := measurable_embedding_const_smul _, rw [← image_smul, ← ((measure_preserving_smul g⁻¹ μ).restrict_image_emb he _).ae_strongly_measurable_comp_iff he], simp only [(∘), hf] end ... ↔ ae_strongly_measurable f (μ.restrict t) : by simp only [← ae_strongly_measurable_sum_measure_iff, ← hs.restrict_restrict, hs.sum_restrict_of_ac restrict_le_self.absolutely_continuous] @[to_additive] protected lemma has_finite_integral_on_iff (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : has_finite_integral f (μ.restrict s) ↔ has_finite_integral f (μ.restrict t) := begin dunfold has_finite_integral, rw hs.set_lintegral_eq ht, intros g x, rw hf end @[to_additive] protected lemma integrable_on_iff (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : integrable_on f s μ ↔ integrable_on f t μ := and_congr (hs.ae_strongly_measurable_on_iff ht hf) (hs.has_finite_integral_on_iff ht hf) variables [normed_space ℝ E] [complete_space E] @[to_additive] protected lemma set_integral_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : ∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ := begin by_cases hfs : integrable_on f s μ, { have hft : integrable_on f t μ, by rwa ht.integrable_on_iff hs hf, have hac : ∀ {u}, μ.restrict u ≪ μ := λ u, restrict_le_self.absolutely_continuous, calc ∫ x in s, f x ∂μ = ∫ x in ⋃ g : G, g • t, f x ∂(μ.restrict s) : by rw [restrict_congr_set (hac ht.Union_smul_ae_eq), restrict_univ] ... = ∑' g : G, ∫ x in g • t, f x ∂(μ.restrict s) : integral_Union_ae (λ g, (ht.null_measurable_set_smul g).mono_ac hac) (ht.pairwise_ae_disjoint_of_ac hac) hfs.integrable.integrable_on ... = ∑' g : G, ∫ x in s ∩ g • t, f x ∂μ : by simp only [ht.restrict_restrict, inter_comm] ... = ∑' g : G, ∫ x in s ∩ g⁻¹ • t, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫ x in g⁻¹ • (g • s ∩ t), f x ∂μ : by simp only [smul_set_inter, inv_smul_smul] ... = ∑' g : G, ∫ x in g • s ∩ t, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, (measure_preserving_smul g⁻¹ μ).set_integral_image_emb (measurable_embedding_const_smul _) _ _ ... = ∑' g : G, ∫ x in g • s, f x ∂(μ.restrict t) : by simp only [hf, hs.restrict_restrict] ... = ∫ x in ⋃ g : G, g • s, f x ∂(μ.restrict t) : (integral_Union_ae (λ g, (hs.null_measurable_set_smul g).mono_ac hac) (hs.pairwise_ae_disjoint.mono $ λ i j h, hac h) hft.integrable.integrable_on).symm ... = ∫ x in t, f x ∂μ : by rw [restrict_congr_set (hac hs.Union_smul_ae_eq), restrict_univ] }, { rw [integral_undef hfs, integral_undef], rwa [hs.integrable_on_iff ht hf] at hfs } end /-- If `f` is invariant under the action of a countable group `G`, and `μ` is a `G`-invariant measure with a fundamental domain `s`, then the `ess_sup` of `f` restricted to `s` is the same as that of `f` on all of its domain. -/ @[to_additive "If `f` is invariant under the action of a countable additive group `G`, and `μ` is a `G`-invariant measure with a fundamental domain `s`, then the `ess_sup` of `f` restricted to `s` is the same as that of `f` on all of its domain."] lemma ess_sup_measure_restrict (hs : is_fundamental_domain G s μ) {f : α → ℝ≥0∞} (hf : ∀ γ : G, ∀ x: α, f (γ • x) = f x) : ess_sup f (μ.restrict s) = ess_sup f μ := begin refine le_antisymm (ess_sup_mono_measure' measure.restrict_le_self) _, rw [ess_sup_eq_Inf (μ.restrict s) f, ess_sup_eq_Inf μ f], refine Inf_le_Inf _, rintro a (ha : (μ.restrict s) {x : α | a < f x} = 0), rw measure.restrict_apply₀' hs.null_measurable_set at ha, refine measure_zero_of_invariant hs _ _ ha, intros γ, ext x, rw mem_smul_set_iff_inv_smul_mem, simp only [mem_set_of_eq, hf (γ⁻¹) x], end end is_fundamental_domain end measure_theory
f292898f223a4401dd84ec62fd8c11447d1532ff
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/FileSource.lean
d0024073e98b6c2d86dca0947bffa347fe94453a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,780
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga -/ import Lean.Data.Lsp namespace Lean.Lsp class FileSource (α : Type) where fileSource : α → DocumentUri export FileSource (fileSource) instance : FileSource Location := ⟨fun l => l.uri⟩ instance : FileSource TextDocumentIdentifier := ⟨fun i => i.uri⟩ instance : FileSource VersionedTextDocumentIdentifier := ⟨fun i => i.uri⟩ instance : FileSource TextDocumentEdit := ⟨fun e => fileSource e.textDocument⟩ instance : FileSource TextDocumentItem := ⟨fun i => i.uri⟩ instance : FileSource TextDocumentPositionParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidOpenTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidChangeTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidCloseTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource CompletionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource HoverParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DeclarationParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DefinitionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource TypeDefinitionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource ReferenceParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource WaitForDiagnosticsParams := ⟨fun p => p.uri⟩ instance : FileSource DocumentHighlightParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DocumentSymbolParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource SemanticTokensParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource SemanticTokensRangeParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource FoldingRangeParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource PlainGoalParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource PlainTermGoalParams where fileSource p := fileSource p.textDocument instance : FileSource RpcConnectParams where fileSource p := p.uri instance : FileSource RpcCallParams where fileSource p := fileSource p.textDocument instance : FileSource RpcReleaseParams where fileSource p := p.uri instance : FileSource RpcKeepAliveParams where fileSource p := p.uri instance : FileSource CodeActionParams where fileSource p := fileSource p.textDocument end Lean.Lsp
eb3a3e758501866165ce84163b2110ccd71636bb
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/orientation.lean
a17ec1101eba471b4030ddb0547c6eeadaf6bc8c
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
15,525
lean
/- Copyright (c) 2021 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.ray import linear_algebra.determinant /-! # Orientations of modules > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines orientations of modules. ## Main definitions * `orientation` is a type synonym for `module.ray` for the case where the module is that of alternating maps from a module to its underlying ring. An orientation may be associated with an alternating map or with a basis. * `module.oriented` is a type class for a choice of orientation of a module that is considered the positive orientation. ## Implementation notes `orientation` is defined for an arbitrary index type, but the main intended use case is when that index type is a `fintype` and there exists a basis of the same cardinality. ## References * https://en.wikipedia.org/wiki/Orientation_(vector_space) -/ noncomputable theory open_locale big_operators section ordered_comm_semiring variables (R : Type*) [strict_ordered_comm_semiring R] variables (M : Type*) [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] variables (ι : Type*) /-- An orientation of a module, intended to be used when `ι` is a `fintype` with the same cardinality as a basis. -/ abbreviation orientation := module.ray R (alternating_map R M R ι) /-- A type class fixing an orientation of a module. -/ class module.oriented := (positive_orientation : orientation R M ι) export module.oriented (positive_orientation) variables {R M} /-- An equivalence between modules implies an equivalence between orientations. -/ def orientation.map (e : M ≃ₗ[R] N) : orientation R M ι ≃ orientation R N ι := module.ray.map $ alternating_map.dom_lcongr R R ι R e @[simp] lemma orientation.map_apply (e : M ≃ₗ[R] N) (v : alternating_map R M R ι) (hv : v ≠ 0) : orientation.map ι e (ray_of_ne_zero _ v hv) = ray_of_ne_zero _ (v.comp_linear_map e.symm) (mt (v.comp_linear_equiv_eq_zero_iff e.symm).mp hv) := rfl @[simp] lemma orientation.map_refl : (orientation.map ι $ linear_equiv.refl R M) = equiv.refl _ := by rw [orientation.map, alternating_map.dom_lcongr_refl, module.ray.map_refl] @[simp] lemma orientation.map_symm (e : M ≃ₗ[R] N) : (orientation.map ι e).symm = orientation.map ι e.symm := rfl /-- A module is canonically oriented with respect to an empty index type. -/ @[priority 100] instance is_empty.oriented [nontrivial R] [is_empty ι] : module.oriented R M ι := { positive_orientation := ray_of_ne_zero R (alternating_map.const_linear_equiv_of_is_empty 1) $ alternating_map.const_linear_equiv_of_is_empty.injective.ne (by simp) } @[simp] lemma orientation.map_positive_orientation_of_is_empty [nontrivial R] [is_empty ι] (f : M ≃ₗ[R] N) : orientation.map ι f positive_orientation = positive_orientation := rfl @[simp] lemma orientation.map_of_is_empty [is_empty ι] (x : orientation R M ι) (f : M ≃ₗ[R] M) : orientation.map ι f x = x := begin induction x using module.ray.ind with g hg, rw orientation.map_apply, congr, ext i, rw alternating_map.comp_linear_map_apply, congr, end end ordered_comm_semiring section ordered_comm_ring variables {R : Type*} [strict_ordered_comm_ring R] variables {M N : Type*} [add_comm_group M] [add_comm_group N] [module R M] [module R N] @[simp] protected lemma orientation.map_neg {ι : Type*} (f : M ≃ₗ[R] N) (x : orientation R M ι) : orientation.map ι f (-x) = - orientation.map ι f x := module.ray.map_neg _ x namespace basis variables {ι : Type*} /-- The value of `orientation.map` when the index type has the cardinality of a basis, in terms of `f.det`. -/ lemma map_orientation_eq_det_inv_smul [finite ι] (e : basis ι R M) (x : orientation R M ι) (f : M ≃ₗ[R] M) : orientation.map ι f x = (f.det)⁻¹ • x := begin casesI nonempty_fintype ι, letI := classical.dec_eq ι, induction x using module.ray.ind with g hg, rw [orientation.map_apply, smul_ray_of_ne_zero, ray_eq_iff, units.smul_def, (g.comp_linear_map ↑f.symm).eq_smul_basis_det e, g.eq_smul_basis_det e, alternating_map.comp_linear_map_apply, alternating_map.smul_apply, basis.det_comp, basis.det_self, mul_one, smul_eq_mul, mul_comm, mul_smul, linear_equiv.coe_inv_det], end variables [fintype ι] [decidable_eq ι] /-- The orientation given by a basis. -/ protected def orientation [nontrivial R] (e : basis ι R M) : orientation R M ι := ray_of_ne_zero R _ e.det_ne_zero lemma orientation_map [nontrivial R] (e : basis ι R M) (f : M ≃ₗ[R] N) : (e.map f).orientation = orientation.map ι f e.orientation := by simp_rw [basis.orientation, orientation.map_apply, basis.det_map'] /-- The orientation given by a basis derived using `units_smul`, in terms of the product of those units. -/ lemma orientation_units_smul [nontrivial R] (e : basis ι R M) (w : ι → units R) : (e.units_smul w).orientation = (∏ i, w i)⁻¹ • e.orientation := begin rw [basis.orientation, basis.orientation, smul_ray_of_ne_zero, ray_eq_iff, e.det.eq_smul_basis_det (e.units_smul w), det_units_smul_self, units.smul_def, smul_smul], norm_cast, simp end @[simp] lemma orientation_is_empty [nontrivial R] [is_empty ι] (b : basis ι R M) : b.orientation = positive_orientation := begin congrm ray_of_ne_zero _ _ _, convert b.det_is_empty, end end basis end ordered_comm_ring section linear_ordered_comm_ring variables {R : Type*} [linear_ordered_comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {ι : Type*} namespace orientation /-- A module `M` over a linearly ordered commutative ring has precisely two "orientations" with respect to an empty index type. (Note that these are only orientations of `M` of in the conventional mathematical sense if `M` is zero-dimensional.) -/ lemma eq_or_eq_neg_of_is_empty [nontrivial R] [is_empty ι] (o : orientation R M ι) : o = positive_orientation ∨ o = - positive_orientation := begin induction o using module.ray.ind with x hx, dsimp [positive_orientation], simp only [ray_eq_iff, same_ray_neg_swap], rw same_ray_or_same_ray_neg_iff_not_linear_independent, intros h, let a : R := alternating_map.const_linear_equiv_of_is_empty.symm x, have H : linear_independent R ![a, 1], { convert h.map' ↑alternating_map.const_linear_equiv_of_is_empty.symm (linear_equiv.ker _), ext i, fin_cases i; simp [a] }, rw linear_independent_iff' at H, simpa using H finset.univ ![1, -a] (by simp [fin.sum_univ_succ]) 0 (by simp), end end orientation namespace basis variables [fintype ι] [decidable_eq ι] /-- The orientations given by two bases are equal if and only if the determinant of one basis with respect to the other is positive. -/ lemma orientation_eq_iff_det_pos (e₁ e₂ : basis ι R M) : e₁.orientation = e₂.orientation ↔ 0 < e₁.det e₂ := calc e₁.orientation = e₂.orientation ↔ same_ray R e₁.det e₂.det : ray_eq_iff _ _ ... ↔ same_ray R (e₁.det e₂ • e₂.det) e₂.det : by rw [← e₁.det.eq_smul_basis_det e₂] ... ↔ 0 < e₁.det e₂ : same_ray_smul_left_iff_of_ne e₂.det_ne_zero (e₁.is_unit_det e₂).ne_zero /-- Given a basis, any orientation equals the orientation given by that basis or its negation. -/ lemma orientation_eq_or_eq_neg (e : basis ι R M) (x : orientation R M ι) : x = e.orientation ∨ x = -e.orientation := begin induction x using module.ray.ind with x hx, rw ← x.map_basis_ne_zero_iff e at hx, rwa [basis.orientation, ray_eq_iff, neg_ray_of_ne_zero, ray_eq_iff, x.eq_smul_basis_det e, same_ray_neg_smul_left_iff_of_ne e.det_ne_zero hx, same_ray_smul_left_iff_of_ne e.det_ne_zero hx, lt_or_lt_iff_ne, ne_comm] end /-- Given a basis, an orientation equals the negation of that given by that basis if and only if it does not equal that given by that basis. -/ lemma orientation_ne_iff_eq_neg (e : basis ι R M) (x : orientation R M ι) : x ≠ e.orientation ↔ x = -e.orientation := ⟨λ h, (e.orientation_eq_or_eq_neg x).resolve_left h, λ h, h.symm ▸ (module.ray.ne_neg_self e.orientation).symm⟩ /-- Composing a basis with a linear equiv gives the same orientation if and only if the determinant is positive. -/ lemma orientation_comp_linear_equiv_eq_iff_det_pos (e : basis ι R M) (f : M ≃ₗ[R] M) : (e.map f).orientation = e.orientation ↔ 0 < (f : M →ₗ[R] M).det := by rw [orientation_map, e.map_orientation_eq_det_inv_smul, units_inv_smul, units_smul_eq_self_iff, linear_equiv.coe_det] /-- Composing a basis with a linear equiv gives the negation of that orientation if and only if the determinant is negative. -/ lemma orientation_comp_linear_equiv_eq_neg_iff_det_neg (e : basis ι R M) (f : M ≃ₗ[R] M) : (e.map f).orientation = -e.orientation ↔ (f : M →ₗ[R] M).det < 0 := by rw [orientation_map, e.map_orientation_eq_det_inv_smul, units_inv_smul, units_smul_eq_neg_iff, linear_equiv.coe_det] /-- Negating a single basis vector (represented using `units_smul`) negates the corresponding orientation. -/ @[simp] lemma orientation_neg_single [nontrivial R] (e : basis ι R M) (i : ι) : (e.units_smul (function.update 1 i (-1))).orientation = -e.orientation := begin rw [orientation_units_smul, finset.prod_update_of_mem (finset.mem_univ _)], simp end /-- Given a basis and an orientation, return a basis giving that orientation: either the original basis, or one constructed by negating a single (arbitrary) basis vector. -/ def adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : basis ι R M := by haveI := classical.dec_eq (orientation R M ι); exact if e.orientation = x then e else (e.units_smul (function.update 1 (classical.arbitrary ι) (-1))) /-- `adjust_to_orientation` gives a basis with the required orientation. -/ @[simp] lemma orientation_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : (e.adjust_to_orientation x).orientation = x := begin rw adjust_to_orientation, split_ifs with h, { exact h }, { rw [orientation_neg_single, eq_comm, ←orientation_ne_iff_eq_neg, ne_comm], exact h } end /-- Every basis vector from `adjust_to_orientation` is either that from the original basis or its negation. -/ lemma adjust_to_orientation_apply_eq_or_eq_neg [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) (i : ι) : e.adjust_to_orientation x i = e i ∨ e.adjust_to_orientation x i = -(e i) := begin rw adjust_to_orientation, split_ifs with h, { simp }, { by_cases hi : i = classical.arbitrary ι; simp [units_smul_apply, hi] } end lemma det_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : (e.adjust_to_orientation x).det = e.det ∨ (e.adjust_to_orientation x).det = - e.det := begin dsimp [basis.adjust_to_orientation], split_ifs, { left, refl }, { right, simp [e.det_units_smul, ← units.coe_prod, finset.prod_update_of_mem] } end @[simp] lemma abs_det_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) (v : ι → M) : |(e.adjust_to_orientation x).det v| = |e.det v| := begin cases e.det_adjust_to_orientation x with h h; simp [h] end end basis end linear_ordered_comm_ring section linear_ordered_field variables {R : Type*} [linear_ordered_field R] variables {M : Type*} [add_comm_group M] [module R M] variables {ι : Type*} namespace orientation variables [fintype ι] [_i : finite_dimensional R M] open finite_dimensional include _i /-- If the index type has cardinality equal to the finite dimension, any two orientations are equal or negations. -/ lemma eq_or_eq_neg (x₁ x₂ : orientation R M ι) (h : fintype.card ι = finrank R M) : x₁ = x₂ ∨ x₁ = -x₂ := begin have e := (fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm, letI := classical.dec_eq ι, rcases e.orientation_eq_or_eq_neg x₁ with h₁|h₁; rcases e.orientation_eq_or_eq_neg x₂ with h₂|h₂; simp [h₁, h₂] end /-- If the index type has cardinality equal to the finite dimension, an orientation equals the negation of another orientation if and only if they are not equal. -/ lemma ne_iff_eq_neg (x₁ x₂ : orientation R M ι) (h : fintype.card ι = finrank R M) : x₁ ≠ x₂ ↔ x₁ = -x₂ := ⟨λ hn, (eq_or_eq_neg x₁ x₂ h).resolve_left hn, λ he, he.symm ▸ (module.ray.ne_neg_self x₂).symm⟩ /-- The value of `orientation.map` when the index type has cardinality equal to the finite dimension, in terms of `f.det`. -/ lemma map_eq_det_inv_smul (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = (f.det)⁻¹ • x := begin have e := (fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm, exact e.map_orientation_eq_det_inv_smul x f end omit _i /-- If the index type has cardinality equal to the finite dimension, composing an alternating map with the same linear equiv on each argument gives the same orientation if and only if the determinant is positive. -/ lemma map_eq_iff_det_pos (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = x ↔ 0 < (f : M →ₗ[R] M).det := begin casesI is_empty_or_nonempty ι, { have H : finrank R M = 0, { refine h.symm.trans _, convert fintype.card_of_is_empty, apply_instance }, simp [linear_map.det_eq_one_of_finrank_eq_zero H] }, have H : 0 < finrank R M, { rw ← h, exact fintype.card_pos }, haveI : finite_dimensional R M := finite_dimensional_of_finrank H, rw [map_eq_det_inv_smul _ _ h, units_inv_smul, units_smul_eq_self_iff, linear_equiv.coe_det] end /-- If the index type has cardinality equal to the finite dimension, composing an alternating map with the same linear equiv on each argument gives the negation of that orientation if and only if the determinant is negative. -/ lemma map_eq_neg_iff_det_neg (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = -x ↔ (f : M →ₗ[R] M).det < 0 := begin casesI is_empty_or_nonempty ι, { have H : finrank R M = 0, { refine h.symm.trans _, convert fintype.card_of_is_empty, apply_instance }, simp [linear_map.det_eq_one_of_finrank_eq_zero H, module.ray.ne_neg_self x] }, have H : 0 < finrank R M, { rw ← h, exact fintype.card_pos }, haveI : finite_dimensional R M := finite_dimensional_of_finrank H, rw [map_eq_det_inv_smul _ _ h, units_inv_smul, units_smul_eq_neg_iff, linear_equiv.coe_det] end include _i /-- If the index type has cardinality equal to the finite dimension, a basis with the given orientation. -/ def some_basis [nonempty ι] [decidable_eq ι] (x : orientation R M ι) (h : fintype.card ι = finrank R M) : basis ι R M := ((fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm).adjust_to_orientation x /-- `some_basis` gives a basis with the required orientation. -/ @[simp] lemma some_basis_orientation [nonempty ι] [decidable_eq ι] (x : orientation R M ι) (h : fintype.card ι = finrank R M) : (x.some_basis h).orientation = x := basis.orientation_adjust_to_orientation _ _ end orientation end linear_ordered_field
95ef42f3b5fe4c3a9319c954f1b5a855329b3bd2
4727251e0cd73359b15b664c3170e5d754078599
/src/data/multiset/locally_finite.lean
26e077299a60e8e9f791a898715b7f010d31b8dc
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,440
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite /-! # Intervals as multisets This file provides basic results about all the `multiset.Ixx`, which are defined in `order.locally_finite`. -/ variables {α : Type*} namespace multiset section preorder variables [preorder α] [locally_finite_order α] {a b c : α} lemma nodup_Icc : (Icc a b).nodup := finset.nodup _ lemma nodup_Ico : (Ico a b).nodup := finset.nodup _ lemma nodup_Ioc : (Ioc a b).nodup := finset.nodup _ lemma nodup_Ioo : (Ioo a b).nodup := finset.nodup _ @[simp] lemma Icc_eq_zero_iff : Icc a b = 0 ↔ ¬a ≤ b := by rw [Icc, finset.val_eq_zero, finset.Icc_eq_empty_iff] @[simp] lemma Ico_eq_zero_iff : Ico a b = 0 ↔ ¬a < b := by rw [Ico, finset.val_eq_zero, finset.Ico_eq_empty_iff] @[simp] lemma Ioc_eq_zero_iff : Ioc a b = 0 ↔ ¬a < b := by rw [Ioc, finset.val_eq_zero, finset.Ioc_eq_empty_iff] @[simp] lemma Ioo_eq_zero_iff [densely_ordered α] : Ioo a b = 0 ↔ ¬a < b := by rw [Ioo, finset.val_eq_zero, finset.Ioo_eq_empty_iff] alias Icc_eq_zero_iff ↔ _ multiset.Icc_eq_zero alias Ico_eq_zero_iff ↔ _ multiset.Ico_eq_zero alias Ioc_eq_zero_iff ↔ _ multiset.Ioc_eq_zero @[simp] lemma Ioo_eq_zero (h : ¬a < b) : Ioo a b = 0 := eq_zero_iff_forall_not_mem.2 $ λ x hx, h ((mem_Ioo.1 hx).1.trans (mem_Ioo.1 hx).2) @[simp] lemma Icc_eq_zero_of_lt (h : b < a) : Icc a b = 0 := Icc_eq_zero h.not_le @[simp] lemma Ico_eq_zero_of_le (h : b ≤ a) : Ico a b = 0 := Ico_eq_zero h.not_lt @[simp] lemma Ioc_eq_zero_of_le (h : b ≤ a) : Ioc a b = 0 := Ioc_eq_zero h.not_lt @[simp] lemma Ioo_eq_zero_of_le (h : b ≤ a) : Ioo a b = 0 := Ioo_eq_zero h.not_lt variables (a) @[simp] lemma Ico_self : Ico a a = 0 := by rw [Ico, finset.Ico_self, finset.empty_val] @[simp] lemma Ioc_self : Ioc a a = 0 := by rw [Ioc, finset.Ioc_self, finset.empty_val] @[simp] lemma Ioo_self : Ioo a a = 0 := by rw [Ioo, finset.Ioo_self, finset.empty_val] variables {a b c} lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := finset.left_mem_Icc lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := finset.left_mem_Ico lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := finset.right_mem_Icc lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := finset.right_mem_Ioc @[simp] lemma left_not_mem_Ioc : a ∉ Ioc a b := finset.left_not_mem_Ioc @[simp] lemma left_not_mem_Ioo : a ∉ Ioo a b := finset.left_not_mem_Ioo @[simp] lemma right_not_mem_Ico : b ∉ Ico a b := finset.right_not_mem_Ico @[simp] lemma right_not_mem_Ioo : b ∉ Ioo a b := finset.right_not_mem_Ioo lemma Ico_filter_lt_of_le_left [decidable_pred (< c)] (hca : c ≤ a) : (Ico a b).filter (λ x, x < c) = ∅ := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_le_left hca], refl } lemma Ico_filter_lt_of_right_le [decidable_pred (< c)] (hbc : b ≤ c) : (Ico a b).filter (λ x, x < c) = Ico a b := by rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_right_le hbc] lemma Ico_filter_lt_of_le_right [decidable_pred (< c)] (hcb : c ≤ b) : (Ico a b).filter (λ x, x < c) = Ico a c := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_lt_of_le_right hcb], refl } lemma Ico_filter_le_of_le_left [decidable_pred ((≤) c)] (hca : c ≤ a) : (Ico a b).filter (λ x, c ≤ x) = Ico a b := by rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_le_left hca] lemma Ico_filter_le_of_right_le [decidable_pred ((≤) b)] : (Ico a b).filter (λ x, b ≤ x) = ∅ := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_right_le], refl } lemma Ico_filter_le_of_left_le [decidable_pred ((≤) c)] (hac : a ≤ c) : (Ico a b).filter (λ x, c ≤ x) = Ico c b := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_of_left_le hac], refl } end preorder section partial_order variables [partial_order α] [locally_finite_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := by rw [Icc, finset.Icc_self, finset.singleton_val] lemma Ico_cons_right (h : a ≤ b) : b ::ₘ (Ico a b) = Icc a b := by { classical, rw [Ico, ←finset.insert_val_of_not_mem right_not_mem_Ico, finset.Ico_insert_right h], refl } lemma Ioo_cons_left (h : a < b) : a ::ₘ (Ioo a b) = Ico a b := by { classical, rw [Ioo, ←finset.insert_val_of_not_mem left_not_mem_Ioo, finset.Ioo_insert_left h], refl } lemma Ico_disjoint_Ico {a b c d : α} (h : b ≤ c) : (Ico a b).disjoint (Ico c d) := λ x hab hbc, by { rw mem_Ico at hab hbc, exact hab.2.not_le (h.trans hbc.1) } @[simp] lemma Ico_inter_Ico_of_le [decidable_eq α] {a b c d : α} (h : b ≤ c) : Ico a b ∩ Ico c d = 0 := multiset.inter_eq_zero_iff_disjoint.2 $ Ico_disjoint_Ico h lemma Ico_filter_le_left {a b : α} [decidable_pred (≤ a)] (hab : a < b) : (Ico a b).filter (λ x, x ≤ a) = {a} := by { rw [Ico, ←finset.filter_val, finset.Ico_filter_le_left hab], refl } lemma card_Ico_eq_card_Icc_sub_one (a b : α) : (Ico a b).card = (Icc a b).card - 1 := finset.card_Ico_eq_card_Icc_sub_one _ _ lemma card_Ioc_eq_card_Icc_sub_one (a b : α) : (Ioc a b).card = (Icc a b).card - 1 := finset.card_Ioc_eq_card_Icc_sub_one _ _ lemma card_Ioo_eq_card_Ico_sub_one (a b : α) : (Ioo a b).card = (Ico a b).card - 1 := finset.card_Ioo_eq_card_Ico_sub_one _ _ lemma card_Ioo_eq_card_Icc_sub_two (a b : α) : (Ioo a b).card = (Icc a b).card - 2 := finset.card_Ioo_eq_card_Icc_sub_two _ _ end partial_order section linear_order variables [linear_order α] [locally_finite_order α] {a b c d : α} lemma Ico_subset_Ico_iff {a₁ b₁ a₂ b₂ : α} (h : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := finset.Ico_subset_Ico_iff h lemma Ico_add_Ico_eq_Ico {a b c : α} (hab : a ≤ b) (hbc : b ≤ c) : Ico a b + Ico b c = Ico a c := by rw [add_eq_union_iff_disjoint.2 (Ico_disjoint_Ico le_rfl), Ico, Ico, Ico, ←finset.union_val, finset.Ico_union_Ico_eq_Ico hab hbc] lemma Ico_inter_Ico : Ico a b ∩ Ico c d = Ico (max a c) (min b d) := by rw [Ico, Ico, Ico, ←finset.inter_val, finset.Ico_inter_Ico] @[simp] lemma Ico_filter_lt (a b c : α) : (Ico a b).filter (λ x, x < c) = Ico a (min b c) := by rw [Ico, Ico, ←finset.filter_val, finset.Ico_filter_lt] @[simp] lemma Ico_filter_le (a b c : α) : (Ico a b).filter (λ x, c ≤ x) = Ico (max a c) b := by rw [Ico, Ico, ←finset.filter_val, finset.Ico_filter_le] @[simp] lemma Ico_sub_Ico_left (a b c : α) : Ico a b - Ico a c = Ico (max a c) b := by rw [Ico, Ico, Ico, ←finset.sdiff_val, finset.Ico_diff_Ico_left] @[simp] lemma Ico_sub_Ico_right (a b c : α) : Ico a b - Ico c b = Ico a (min b c) := by rw [Ico, Ico, Ico, ←finset.sdiff_val, finset.Ico_diff_Ico_right] end linear_order section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] [locally_finite_order α] lemma map_add_left_Icc (a b c : α) : (Icc a b).map ((+) c) = Icc (c + a) (c + b) := by { classical, rw [Icc, Icc, ←finset.image_add_left_Icc, finset.image_val, ((finset.nodup _).map $ add_right_injective c).dedup] } lemma map_add_left_Ico (a b c : α) : (Ico a b).map ((+) c) = Ico (c + a) (c + b) := by { classical, rw [Ico, Ico, ←finset.image_add_left_Ico, finset.image_val, ((finset.nodup _).map $ add_right_injective c).dedup] } lemma map_add_left_Ioc (a b c : α) : (Ioc a b).map ((+) c) = Ioc (c + a) (c + b) := by { classical, rw [Ioc, Ioc, ←finset.image_add_left_Ioc, finset.image_val, ((finset.nodup _).map $ add_right_injective c).dedup] } lemma map_add_left_Ioo (a b c : α) : (Ioo a b).map ((+) c) = Ioo (c + a) (c + b) := by { classical, rw [Ioo, Ioo, ←finset.image_add_left_Ioo, finset.image_val, ((finset.nodup _).map $ add_right_injective c).dedup] } lemma map_add_right_Icc (a b c : α) : (Icc a b).map (λ x, x + c) = Icc (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Icc _ _ _ } lemma map_add_right_Ico (a b c : α) : (Ico a b).map (λ x, x + c) = Ico (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ico _ _ _ } lemma map_add_right_Ioc (a b c : α) : (Ioc a b).map (λ x, x + c) = Ioc (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ioc _ _ _ } lemma map_add_right_Ioo (a b c : α) : (Ioo a b).map (λ x, x + c) = Ioo (a + c) (b + c) := by { simp_rw add_comm _ c, exact map_add_left_Ioo _ _ _ } end ordered_cancel_add_comm_monoid end multiset
d389256d1da139394d0c787e254379f91d53c51a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/real/hyperreal.lean
5f8f7ae1e1aced3d653cae6d4a2cdc60f5c90ea8
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
37,924
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir -/ import order.filter.filter_product import analysis.specific_limits.basic /-! # Construction of the hyperreal numbers as an ultraproduct of real sequences. -/ open filter filter.germ open_locale topological_space classical /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ @[derive [linear_ordered_field, inhabited]] def hyperreal : Type := germ (hyperfilter ℕ : filter ℕ) ℝ namespace hyperreal notation `ℝ*` := hyperreal noncomputable instance : has_coe_t ℝ ℝ* := ⟨λ x, (↑x : germ _ _)⟩ @[simp, norm_cast] lemma coe_eq_coe {x y : ℝ} : (x : ℝ*) = y ↔ x = y := germ.const_inj lemma coe_ne_coe {x y : ℝ} : (x : ℝ*) ≠ y ↔ x ≠ y := coe_eq_coe.not @[simp, norm_cast] lemma coe_eq_zero {x : ℝ} : (x : ℝ*) = 0 ↔ x = 0 := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one {x : ℝ} : (x : ℝ*) = 1 ↔ x = 1 := coe_eq_coe @[norm_cast] lemma coe_ne_zero {x : ℝ} : (x : ℝ*) ≠ 0 ↔ x ≠ 0 := coe_ne_coe @[norm_cast] lemma coe_ne_one {x : ℝ} : (x : ℝ*) ≠ 1 ↔ x ≠ 1 := coe_ne_coe @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ) = (1 : ℝ*) := rfl @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ) = (0 : ℝ*) := rfl @[simp, norm_cast] lemma coe_inv (x : ℝ) : ↑(x⁻¹) = (x⁻¹ : ℝ*) := rfl @[simp, norm_cast] lemma coe_neg (x : ℝ) : ↑(-x) = (-x : ℝ*) := rfl @[simp, norm_cast] lemma coe_add (x y : ℝ) : ↑(x + y) = (x + y : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit0 (x : ℝ) : ↑(bit0 x) = (bit0 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_bit1 (x : ℝ) : ↑(bit1 x) = (bit1 x : ℝ*) := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝ) : ↑(x * y) = (x * y : ℝ*) := rfl @[simp, norm_cast] lemma coe_div (x y : ℝ) : ↑(x / y) = (x / y : ℝ*) := rfl @[simp, norm_cast] lemma coe_sub (x y : ℝ) : ↑(x - y) = (x - y : ℝ*) := rfl @[simp, norm_cast] lemma coe_le_coe {x y : ℝ} : (x : ℝ*) ≤ y ↔ x ≤ y := germ.const_le_iff @[simp, norm_cast] lemma coe_lt_coe {x y : ℝ} : (x : ℝ*) < y ↔ x < y := germ.const_lt_iff @[simp, norm_cast] lemma coe_nonneg {x : ℝ} : 0 ≤ (x : ℝ*) ↔ 0 ≤ x := coe_le_coe @[simp, norm_cast] lemma coe_pos {x : ℝ} : 0 < (x : ℝ*) ↔ 0 < x := coe_lt_coe @[simp, norm_cast] lemma coe_abs (x : ℝ) : ((|x| : ℝ) : ℝ*) = |x| := const_abs x @[simp, norm_cast] lemma coe_max (x y : ℝ) : ((max x y : ℝ) : ℝ*) = max x y := germ.const_max _ _ @[simp, norm_cast] lemma coe_min (x y : ℝ) : ((min x y : ℝ) : ℝ*) = min x y := germ.const_min _ _ /-- Construct a hyperreal number from a sequence of real numbers. -/ noncomputable def of_seq (f : ℕ → ℝ) : ℝ* := (↑f : germ (hyperfilter ℕ : filter ℕ) ℝ) /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := of_seq $ λ n, n⁻¹ /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := of_seq coe localized "notation (name := hyperreal.epsilon) `ε` := hyperreal.epsilon" in hyperreal localized "notation (name := hyperreal.omega) `ω` := hyperreal.omega" in hyperreal @[simp] lemma inv_omega : ω⁻¹ = ε := rfl @[simp] lemma inv_epsilon : ε⁻¹ = ω := @inv_inv _ _ ω lemma omega_pos : 0 < ω := germ.coe_pos.2 $ mem_hyperfilter_of_finite_compl $ begin convert set.finite_singleton 0, simp [set.eq_singleton_iff_unique_mem], end lemma epsilon_pos : 0 < ε := inv_pos_of_pos omega_pos lemma epsilon_ne_zero : ε ≠ 0 := epsilon_pos.ne' lemma omega_ne_zero : ω ≠ 0 := omega_pos.ne' theorem epsilon_mul_omega : ε * ω = 1 := @inv_mul_cancel _ _ ω omega_ne_zero lemma lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → of_seq f < (r : ℝ*) := begin simp only [metric.tendsto_at_top, real.dist_eq, sub_zero, lt_def] at hf ⊢, intros r hr, cases hf r hr with N hf', have hs : {i : ℕ | f i < r}ᶜ ⊆ {i : ℕ | i ≤ N} := λ i hi1, le_of_lt (by simp only [lt_iff_not_ge]; exact λ hi2, hi1 (lt_of_le_of_lt (le_abs_self _) (hf' i hi2)) : i < N), exact mem_hyperfilter_of_finite_compl ((set.finite_le_nat N).subset hs) end lemma neg_lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, 0 < r → (-r : ℝ*) < of_seq f := λ r hr, have hg : _ := hf.neg, neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr) lemma gt_of_tendsto_zero_of_neg {f : ℕ → ℝ} (hf : tendsto f at_top (𝓝 0)) : ∀ {r : ℝ}, r < 0 → (r : ℝ*) < of_seq f := λ r hr, by rw [←neg_neg r, coe_neg]; exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) lemma epsilon_lt_pos (x : ℝ) : 0 < x → ε < x := lt_of_tendsto_zero_of_pos tendsto_inverse_at_top_nhds_0_nat /-- Standard part predicate -/ def is_st (x : ℝ*) (r : ℝ) := ∀ δ : ℝ, 0 < δ → (r - δ : ℝ*) < x ∧ x < r + δ /-- Standard part function: like a "round" to ℝ instead of ℤ -/ noncomputable def st : ℝ* → ℝ := λ x, if h : ∃ r, is_st x r then classical.some h else 0 /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def infinitesimal (x : ℝ*) := is_st x 0 /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def infinite_pos (x : ℝ*) := ∀ r : ℝ, ↑r < x /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def infinite_neg (x : ℝ*) := ∀ r : ℝ, x < r /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def infinite (x : ℝ*) := infinite_pos x ∨ infinite_neg x /-! ### Some facts about `st` -/ private lemma is_st_unique' (x : ℝ*) (r s : ℝ) (hr : is_st x r) (hs : is_st x s) (hrs : r < s) : false := have hrs' : _ := half_pos $ sub_pos_of_lt hrs, have hr' : _ := (hr _ hrs').2, have hs' : _ := (hs _ hrs').1, have h : s - ((s - r) / 2) = r + (s - r) / 2 := by linarith, begin norm_cast at *, rw h at hs', exact not_lt_of_lt hs' hr' end theorem is_st_unique {x : ℝ*} {r s : ℝ} (hr : is_st x r) (hs : is_st x s) : r = s := begin rcases lt_trichotomy r s with h | h | h, { exact false.elim (is_st_unique' x r s hr hs h) }, { exact h }, { exact false.elim (is_st_unique' x s r hs hr h) } end theorem not_infinite_of_exists_st {x : ℝ*} : (∃ r : ℝ, is_st x r) → ¬ infinite x := λ he hi, Exists.dcases_on he $ λ r hr, hi.elim (λ hip, not_lt_of_lt (hr 2 zero_lt_two).2 (hip $ r + 2)) (λ hin, not_lt_of_lt (hr 2 zero_lt_two).1 (hin $ r - 2)) theorem is_st_Sup {x : ℝ*} (hni : ¬ infinite x) : is_st x (Sup {y : ℝ | (y : ℝ*) < x}) := let S : set ℝ := {y : ℝ | (y : ℝ*) < x} in let R : _ := Sup S in have hnile : _ := not_forall.mp (not_or_distrib.mp hni).1, have hnige : _ := not_forall.mp (not_or_distrib.mp hni).2, Exists.dcases_on hnile $ Exists.dcases_on hnige $ λ r₁ hr₁ r₂ hr₂, have HR₁ : S.nonempty := ⟨r₁ - 1, lt_of_lt_of_le (coe_lt_coe.2 $ sub_one_lt _) (not_lt.mp hr₁) ⟩, have HR₂ : bdd_above S := ⟨ r₂, λ y hy, le_of_lt (coe_lt_coe.1 (lt_of_lt_of_le hy (not_lt.mp hr₂))) ⟩, λ δ hδ, ⟨ lt_of_not_le $ λ c, have hc : ∀ y ∈ S, y ≤ R - δ := λ y hy, coe_le_coe.1 $ le_of_lt $ lt_of_lt_of_le hy c, not_lt_of_le (cSup_le HR₁ hc) $ sub_lt_self R hδ, lt_of_not_le $ λ c, have hc : ↑(R + δ / 2) < x := lt_of_lt_of_le (add_lt_add_left (coe_lt_coe.2 (half_lt_self hδ)) R) c, not_lt_of_le (le_cSup HR₂ hc) $ (lt_add_iff_pos_right _).mpr $ half_pos hδ⟩ theorem exists_st_of_not_infinite {x : ℝ*} (hni : ¬ infinite x) : ∃ r : ℝ, is_st x r := ⟨Sup {y : ℝ | (y : ℝ*) < x}, is_st_Sup hni⟩ theorem st_eq_Sup {x : ℝ*} : st x = Sup {y : ℝ | (y : ℝ*) < x} := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) (is_st_Sup (not_infinite_of_exists_st h)) }, { cases not_imp_comm.mp exists_st_of_not_infinite h with H H, { rw (set.ext (λ i, ⟨λ hi, set.mem_univ i, λ hi, H i⟩) : {y : ℝ | (y : ℝ*) < x} = set.univ), exact real.Sup_univ.symm }, { rw (set.ext (λ i, ⟨λ hi, false.elim (not_lt_of_lt (H i) hi), λ hi, false.elim (set.not_mem_empty i hi)⟩) : {y : ℝ | (y : ℝ*) < x} = ∅), exact real.Sup_empty.symm } } end theorem exists_st_iff_not_infinite {x : ℝ*} : (∃ r : ℝ, is_st x r) ↔ ¬ infinite x := ⟨ not_infinite_of_exists_st, exists_st_of_not_infinite ⟩ theorem infinite_iff_not_exists_st {x : ℝ*} : infinite x ↔ ¬ ∃ r : ℝ, is_st x r := iff_not_comm.mp exists_st_iff_not_infinite theorem st_infinite {x : ℝ*} (hi : infinite x) : st x = 0 := begin unfold st, split_ifs, { exact false.elim ((infinite_iff_not_exists_st.mp hi) h) }, { refl } end lemma st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : st x = r := begin unfold st, split_ifs, { exact is_st_unique (classical.some_spec h) hxr }, { exact false.elim (h ⟨r, hxr⟩) } end lemma is_st_st_of_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st x (st x) := by rwa [st_of_is_st hxr] lemma is_st_st_of_exists_st {x : ℝ*} (hx : ∃ r : ℝ, is_st x r) : is_st x (st x) := Exists.dcases_on hx (λ r, is_st_st_of_is_st) lemma is_st_st {x : ℝ*} (hx : st x ≠ 0) : is_st x (st x) := begin unfold st, split_ifs, { exact classical.some_spec h }, { exact false.elim (hx (by unfold st; split_ifs; refl)) } end lemma is_st_st' {x : ℝ*} (hx : ¬ infinite x) : is_st x (st x) := is_st_st_of_exists_st $ exists_st_of_not_infinite hx lemma is_st_refl_real (r : ℝ) : is_st r r := λ δ hδ, ⟨ sub_lt_self _ (coe_lt_coe.2 hδ), (lt_add_of_pos_right _ (coe_lt_coe.2 hδ)) ⟩ lemma st_id_real (r : ℝ) : st r = r := st_of_is_st (is_st_refl_real r) lemma eq_of_is_st_real {r s : ℝ} : is_st r s → r = s := is_st_unique (is_st_refl_real r) lemma is_st_real_iff_eq {r s : ℝ} : is_st r s ↔ r = s := ⟨eq_of_is_st_real, λ hrs, by rw [hrs]; exact is_st_refl_real s⟩ lemma is_st_symm_real {r s : ℝ} : is_st r s ↔ is_st s r := by rw [is_st_real_iff_eq, is_st_real_iff_eq, eq_comm] lemma is_st_trans_real {r s t : ℝ} : is_st r s → is_st s t → is_st r t := by rw [is_st_real_iff_eq, is_st_real_iff_eq, is_st_real_iff_eq]; exact eq.trans lemma is_st_inj_real {r₁ r₂ s : ℝ} (h1 : is_st r₁ s) (h2 : is_st r₂ s) : r₁ = r₂ := eq.trans (eq_of_is_st_real h1) (eq_of_is_st_real h2).symm lemma is_st_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : is_st x r ↔ ∀ (δ : ℝ), 0 < δ → |x - r| < δ := by simp only [abs_sub_lt_iff, sub_lt_iff_lt_add, is_st, and_comm, add_comm] lemma is_st_add {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x + y) (r + s) := λ hxr hys d hd, have hxr' : _ := hxr (d / 2) (half_pos hd), have hys' : _ := hys (d / 2) (half_pos hd), ⟨by convert add_lt_add hxr'.1 hys'.1 using 1; norm_cast; linarith, by convert add_lt_add hxr'.2 hys'.2 using 1; norm_cast; linarith⟩ lemma is_st_neg {x : ℝ*} {r : ℝ} (hxr : is_st x r) : is_st (-x) (-r) := λ d hd, show -(r : ℝ*) - d < -x ∧ -x < -r + d, by cases (hxr d hd); split; linarith lemma is_st_sub {x y : ℝ*} {r s : ℝ} : is_st x r → is_st y s → is_st (x - y) (r - s) := λ hxr hys, by rw [sub_eq_add_neg, sub_eq_add_neg]; exact is_st_add hxr (is_st_neg hys) /- (st x < st y) → (x < y) → (x ≤ y) → (st x ≤ st y) -/ lemma lt_of_is_st_lt {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : r < s → x < y := λ hrs, have hrs' : 0 < (s - r) / 2 := half_pos (sub_pos.mpr hrs), have hxr' : _ := (hxr _ hrs').2, have hys' : _ := (hys _ hrs').1, have H1 : r + ((s - r) / 2) = (r + s) / 2 := by linarith, have H2 : s - ((s - r) / 2) = (r + s) / 2 := by linarith, begin norm_cast at *, rw H1 at hxr', rw H2 at hys', exact lt_trans hxr' hys' end lemma is_st_le_of_le {x y : ℝ*} {r s : ℝ} (hrx : is_st x r) (hsy : is_st y s) : x ≤ y → r ≤ s := by rw [←not_lt, ←not_lt, not_imp_not]; exact lt_of_is_st_lt hsy hrx lemma st_le_of_le {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : x ≤ y → st x ≤ st y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, is_st_le_of_le hx' hy' lemma lt_of_st_lt {x y : ℝ*} (hix : ¬ infinite x) (hiy : ¬ infinite y) : st x < st y → x < y := have hx' : _ := is_st_st' hix, have hy' : _ := is_st_st' hiy, lt_of_is_st_lt hx' hy' /-! ### Basic lemmas about infinite -/ lemma infinite_pos_def {x : ℝ*} : infinite_pos x ↔ ∀ r : ℝ, ↑r < x := by rw iff_eq_eq; refl lemma infinite_neg_def {x : ℝ*} : infinite_neg x ↔ ∀ r : ℝ, x < r := by rw iff_eq_eq; refl lemma ne_zero_of_infinite {x : ℝ*} : infinite x → x ≠ 0 := λ hI h0, or.cases_on hI (λ hip, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_pos 0) 0)) (λ hin, lt_irrefl (0 : ℝ*) ((by rwa ←h0 : infinite_neg 0) 0)) lemma not_infinite_zero : ¬ infinite 0 := λ hI, ne_zero_of_infinite hI rfl lemma pos_of_infinite_pos {x : ℝ*} : infinite_pos x → 0 < x := λ hip, hip 0 lemma neg_of_infinite_neg {x : ℝ*} : infinite_neg x → x < 0 := λ hin, hin 0 lemma not_infinite_pos_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinite_pos x := λ hn hp, not_lt_of_lt (hn 1) (hp 1) lemma not_infinite_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinite_neg x := imp_not_comm.mp not_infinite_pos_of_infinite_neg lemma infinite_neg_neg_of_infinite_pos {x : ℝ*} : infinite_pos x → infinite_neg (-x) := λ hp r, neg_lt.mp (hp (-r)) lemma infinite_pos_neg_of_infinite_neg {x : ℝ*} : infinite_neg x → infinite_pos (-x) := λ hp r, lt_neg.mp (hp (-r)) lemma infinite_pos_iff_infinite_neg_neg {x : ℝ*} : infinite_pos x ↔ infinite_neg (-x) := ⟨ infinite_neg_neg_of_infinite_pos, λ hin, neg_neg x ▸ infinite_pos_neg_of_infinite_neg hin ⟩ lemma infinite_neg_iff_infinite_pos_neg {x : ℝ*} : infinite_neg x ↔ infinite_pos (-x) := ⟨ infinite_pos_neg_of_infinite_neg, λ hin, neg_neg x ▸ infinite_neg_neg_of_infinite_pos hin ⟩ lemma infinite_iff_infinite_neg {x : ℝ*} : infinite x ↔ infinite (-x) := ⟨ λ hi, or.cases_on hi (λ hip, or.inr (infinite_neg_neg_of_infinite_pos hip)) (λ hin, or.inl (infinite_pos_neg_of_infinite_neg hin)), λ hi, or.cases_on hi (λ hipn, or.inr (infinite_neg_iff_infinite_pos_neg.mpr hipn)) (λ hinp, or.inl (infinite_pos_iff_infinite_neg_neg.mpr hinp))⟩ lemma not_infinite_of_infinitesimal {x : ℝ*} : infinitesimal x → ¬ infinite x := λ hi hI, have hi' : _ := (hi 2 zero_lt_two), or.dcases_on hI (λ hip, have hip' : _ := hip 2, not_lt_of_lt hip' (by convert hi'.2; exact (zero_add 2).symm)) (λ hin, have hin' : _ := hin (-2), not_lt_of_lt hin' (by convert hi'.1; exact (zero_sub 2).symm)) lemma not_infinitesimal_of_infinite {x : ℝ*} : infinite x → ¬ infinitesimal x := imp_not_comm.mp not_infinite_of_infinitesimal lemma not_infinitesimal_of_infinite_pos {x : ℝ*} : infinite_pos x → ¬ infinitesimal x := λ hp, not_infinitesimal_of_infinite (or.inl hp) lemma not_infinitesimal_of_infinite_neg {x : ℝ*} : infinite_neg x → ¬ infinitesimal x := λ hn, not_infinitesimal_of_infinite (or.inr hn) lemma infinite_pos_iff_infinite_and_pos {x : ℝ*} : infinite_pos x ↔ (infinite x ∧ 0 < x) := ⟨ λ hip, ⟨or.inl hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hip, hip) (λ hin, false.elim (not_lt_of_lt hp (hin 0))) ⟩ lemma infinite_neg_iff_infinite_and_neg {x : ℝ*} : infinite_neg x ↔ (infinite x ∧ x < 0) := ⟨ λ hip, ⟨or.inr hip, hip 0⟩, λ ⟨hi, hp⟩, hi.cases_on (λ hin, false.elim (not_lt_of_lt hp (hin 0))) (λ hip, hip) ⟩ lemma infinite_pos_iff_infinite_of_pos {x : ℝ*} (hp : 0 < x) : infinite_pos x ↔ infinite x := by rw [infinite_pos_iff_infinite_and_pos]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hp⟩⟩ lemma infinite_pos_iff_infinite_of_nonneg {x : ℝ*} (hp : 0 ≤ x) : infinite_pos x ↔ infinite x := or.cases_on (lt_or_eq_of_le hp) (infinite_pos_iff_infinite_of_pos) (λ h, by rw h.symm; exact ⟨λ hIP, false.elim (not_infinite_zero (or.inl hIP)), λ hI, false.elim (not_infinite_zero hI)⟩) lemma infinite_neg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : infinite_neg x ↔ infinite x := by rw [infinite_neg_iff_infinite_and_neg]; exact ⟨λ hI, hI.1, λ hI, ⟨hI, hn⟩⟩ lemma infinite_pos_abs_iff_infinite_abs {x : ℝ*} : infinite_pos (|x|) ↔ infinite (|x|) := infinite_pos_iff_infinite_of_nonneg (abs_nonneg _) lemma infinite_iff_infinite_pos_abs {x : ℝ*} : infinite x ↔ infinite_pos (|x|) := ⟨ λ hi d, or.cases_on hi (λ hip, by rw [abs_of_pos (hip 0)]; exact hip d) (λ hin, by rw [abs_of_neg (hin 0)]; exact lt_neg.mp (hin (-d))), λ hipa, by { rcases (lt_trichotomy x 0) with h | h | h, { exact or.inr (infinite_neg_iff_infinite_pos_neg.mpr (by rwa abs_of_neg h at hipa)) }, { exact false.elim (ne_zero_of_infinite (or.inl (by rw [h]; rwa [h, abs_zero] at hipa)) h) }, { exact or.inl (by rwa abs_of_pos h at hipa) } } ⟩ lemma infinite_iff_infinite_abs {x : ℝ*} : infinite x ↔ infinite (|x|) := by rw [←infinite_pos_iff_infinite_of_nonneg (abs_nonneg _), infinite_iff_infinite_pos_abs] lemma infinite_iff_abs_lt_abs {x : ℝ*} : infinite x ↔ ∀ r : ℝ, (|r| : ℝ*) < |x| := ⟨ λ hI r, (coe_abs r) ▸ infinite_iff_infinite_pos_abs.mp hI (|r|), λ hR, or.cases_on (max_choice x (-x)) (λ h, or.inl $ λ r, lt_of_le_of_lt (le_abs_self _) (h ▸ (hR r))) (λ h, or.inr $ λ r, neg_lt_neg_iff.mp $ lt_of_le_of_lt (neg_le_abs_self _) (h ▸ (hR r)))⟩ lemma infinite_pos_add_not_infinite_neg {x y : ℝ*} : infinite_pos x → ¬ infinite_neg y → infinite_pos (x + y) := begin intros hip hnin r, cases not_forall.mp hnin with r₂ hr₂, convert add_lt_add_of_lt_of_le (hip (r + -r₂)) (not_lt.mp hr₂) using 1, simp end lemma not_infinite_neg_add_infinite_pos {x y : ℝ*} : ¬ infinite_neg x → infinite_pos y → infinite_pos (x + y) := λ hx hy, by rw [add_comm]; exact infinite_pos_add_not_infinite_neg hy hx lemma infinite_neg_add_not_infinite_pos {x y : ℝ*} : infinite_neg x → ¬ infinite_pos y → infinite_neg (x + y) := by rw [@infinite_neg_iff_infinite_pos_neg x, @infinite_pos_iff_infinite_neg_neg y, @infinite_neg_iff_infinite_pos_neg (x + y), neg_add]; exact infinite_pos_add_not_infinite_neg lemma not_infinite_pos_add_infinite_neg {x y : ℝ*} : ¬ infinite_pos x → infinite_neg y → infinite_neg (x + y) := λ hx hy, by rw [add_comm]; exact infinite_neg_add_not_infinite_pos hy hx lemma infinite_pos_add_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_infinite_neg_of_infinite_pos hy) lemma infinite_neg_add_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_infinite_pos_of_infinite_neg hy) lemma infinite_pos_add_not_infinite {x y : ℝ*} : infinite_pos x → ¬ infinite y → infinite_pos (x + y) := λ hx hy, infinite_pos_add_not_infinite_neg hx (not_or_distrib.mp hy).2 lemma infinite_neg_add_not_infinite {x y : ℝ*} : infinite_neg x → ¬ infinite y → infinite_neg (x + y) := λ hx hy, infinite_neg_add_not_infinite_pos hx (not_or_distrib.mp hy).1 theorem infinite_pos_of_tendsto_top {f : ℕ → ℝ} (hf : tendsto f at_top at_top) : infinite_pos (of_seq f) := λ r, have hf' : _ := tendsto_at_top_at_top.mp hf, Exists.cases_on (hf' (r + 1)) $ λ i hi, have hi' : ∀ (a : ℕ), f a < (r + 1) → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | r < f a}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))), germ.coe_lt.2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS theorem infinite_neg_of_tendsto_bot {f : ℕ → ℝ} (hf : tendsto f at_top at_bot) : infinite_neg (of_seq f) := λ r, have hf' : _ := tendsto_at_top_at_bot.mp hf, Exists.cases_on (hf' (r - 1)) $ λ i hi, have hi' : ∀ (a : ℕ), r - 1 < f a → a < i := λ a, by rw [←not_le, ←not_le]; exact not_imp_not.mpr (hi a), have hS : {a : ℕ | f a < r}ᶜ ⊆ {a : ℕ | a ≤ i} := by simp only [set.compl_set_of, not_lt]; exact λ a har, le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)), germ.coe_lt.2 $ mem_hyperfilter_of_finite_compl $ (set.finite_le_nat _).subset hS lemma not_infinite_neg {x : ℝ*} : ¬ infinite x → ¬ infinite (-x) := not_imp_not.mpr infinite_iff_infinite_neg.mpr lemma not_infinite_add {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x + y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s + r, is_st_add hs hr⟩ theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : ¬ infinite x ↔ ∃ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨ λ hni, Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).1) $ Exists.dcases_on (not_forall.mp (not_or_distrib.mp hni).2) $ λ r hr s hs, by rw [not_lt] at hr hs; exact ⟨r - 1, s + 1, ⟨ lt_of_lt_of_le (by rw sub_eq_add_neg; norm_num) hr, lt_of_le_of_lt hs (by norm_num)⟩ ⟩, λ hrs, Exists.dcases_on hrs $ λ r hr, Exists.dcases_on hr $ λ s hs, not_or_distrib.mpr ⟨not_forall.mpr ⟨s, lt_asymm (hs.2)⟩, not_forall.mpr ⟨r, lt_asymm (hs.1) ⟩⟩⟩ theorem not_infinite_real (r : ℝ) : ¬ infinite r := by rw not_infinite_iff_exist_lt_gt; exact ⟨ r - 1, r + 1, coe_lt_coe.2 $ sub_one_lt r, coe_lt_coe.2 $ lt_add_one r⟩ theorem not_real_of_infinite {x : ℝ*} : infinite x → ∀ r : ℝ, x ≠ r := λ hi r hr, not_infinite_real r $ @eq.subst _ infinite _ _ hr hi /-! ### Facts about `st` that require some infinite machinery -/ private lemma is_st_mul' {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) (hs : s ≠ 0) : is_st (x * y) (r * s) := have hxr' : _ := is_st_iff_abs_sub_lt_delta.mp hxr, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys, have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, is_st_iff_abs_sub_lt_delta.mpr $ λ d hd, calc |x * y - r * s| = |x * (y - s) + (x - r) * s| : by rw [mul_sub, sub_mul, add_sub, sub_add_cancel] ... ≤ |x * (y - s)| + |(x - r) * s| : abs_add _ _ ... ≤ |x| * |y - s| + |x - r| * |s| : by simp only [abs_mul] ... ≤ |x| * ((d / t) / 2 : ℝ) + ((d / |s|) / 2 : ℝ) * |s| : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt $ hys' _ $ half_pos $ div_pos hd $ coe_pos.1 $ lt_of_le_of_lt (abs_nonneg x) ht) $ abs_nonneg _) (mul_le_mul_of_nonneg_right (le_of_lt $ hxr' _ $ half_pos $ div_pos hd $ abs_pos.2 hs) $ abs_nonneg _) ... = (d / 2 * (|x| / t) + d / 2 : ℝ*) : by { push_cast [-filter.germ.const_div], -- TODO: Why wasn't `hyperreal.coe_div` used? have : (|s| : ℝ*) ≠ 0, by simpa, have : (2 : ℝ*) ≠ 0 := two_ne_zero, field_simp [*, add_mul, mul_add, mul_assoc, mul_comm, mul_left_comm] } ... < (d / 2 * 1 + d / 2 : ℝ*) : add_lt_add_right (mul_lt_mul_of_pos_left ((div_lt_one $ lt_of_le_of_lt (abs_nonneg x) ht).mpr ht) $ half_pos $ coe_pos.2 hd) _ ... = (d : ℝ*) : by rw [mul_one, add_halves] lemma is_st_mul {x y : ℝ*} {r s : ℝ} (hxr : is_st x r) (hys : is_st y s) : is_st (x * y) (r * s) := have h : _ := not_infinite_iff_exist_lt_gt.mp $ not_imp_not.mpr infinite_iff_infinite_abs.mpr $ not_infinite_of_exists_st ⟨r, hxr⟩, Exists.cases_on h $ λ u h', Exists.cases_on h' $ λ t ⟨hu, ht⟩, begin by_cases hs : s = 0, { apply is_st_iff_abs_sub_lt_delta.mpr, intros d hd, have hys' : _ := is_st_iff_abs_sub_lt_delta.mp hys (d / t) (div_pos hd (coe_pos.1 (lt_of_le_of_lt (abs_nonneg x) ht))), rw [hs, coe_zero, sub_zero] at hys', rw [hs, mul_zero, coe_zero, sub_zero, abs_mul, mul_comm, ←div_mul_cancel (d : ℝ*) (ne_of_gt (lt_of_le_of_lt (abs_nonneg x) ht)), ←coe_div], exact mul_lt_mul'' hys' ht (abs_nonneg _) (abs_nonneg _) }, exact is_st_mul' hxr hys hs, end --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY lemma not_infinite_mul {x y : ℝ*} (hx : ¬ infinite x) (hy : ¬ infinite y) : ¬ infinite (x * y) := have hx' : _ := exists_st_of_not_infinite hx, have hy' : _ := exists_st_of_not_infinite hy, Exists.cases_on hx' $ Exists.cases_on hy' $ λ r hr s hs, not_infinite_of_exists_st $ ⟨s * r, is_st_mul hs hr⟩ --- lemma st_add {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x + y) = st x + st y := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_add hx hy), have hxy' : _ := is_st_add hx' hy', is_st_unique hxy hxy' lemma st_neg (x : ℝ*) : st (-x) = - st x := if h : infinite x then by rw [st_infinite h, st_infinite (infinite_iff_infinite_neg.mp h), neg_zero] else is_st_unique (is_st_st' (not_infinite_neg h)) (is_st_neg (is_st_st' h)) lemma st_mul {x y : ℝ*} (hx : ¬infinite x) (hy : ¬infinite y) : st (x * y) = (st x) * (st y) := have hx' : _ := is_st_st' hx, have hy' : _ := is_st_st' hy, have hxy : _ := is_st_st' (not_infinite_mul hx hy), have hxy' : _ := is_st_mul hx' hy', is_st_unique hxy hxy' /-! ### Basic lemmas about infinitesimal -/ theorem infinitesimal_def {x : ℝ*} : infinitesimal x ↔ (∀ r : ℝ, 0 < r → -(r : ℝ*) < x ∧ x < r) := ⟨ λ hi r hr, by { convert (hi r hr); simp }, λ hi d hd, by { convert (hi d hd); simp } ⟩ theorem lt_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, 0 < r → x < r := λ hi r hr, ((infinitesimal_def.mp hi) r hr).2 theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, 0 < r → -↑r < x := λ hi r hr, ((infinitesimal_def.mp hi) r hr).1 theorem gt_of_neg_of_infinitesimal {x : ℝ*} : infinitesimal x → ∀ r : ℝ, r < 0 → ↑r < x := λ hi r hr, by convert ((infinitesimal_def.mp hi) (-r) (neg_pos.mpr hr)).1; exact (neg_neg ↑r).symm theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : infinitesimal x ↔ ∀ r : ℝ, r ≠ 0 → |x| < |r| := ⟨ λ hi r hr, abs_lt.mpr (by rw ←coe_abs; exact infinitesimal_def.mp hi (|r|) (abs_pos.2 hr)), λ hR, infinitesimal_def.mpr $ λ r hr, abs_lt.mp $ (abs_of_pos $ coe_pos.2 hr) ▸ hR r $ ne_of_gt hr ⟩ lemma infinitesimal_zero : infinitesimal 0 := is_st_refl_real 0 lemma zero_of_infinitesimal_real {r : ℝ} : infinitesimal r → r = 0 := eq_of_is_st_real lemma zero_iff_infinitesimal_real {r : ℝ} : infinitesimal r ↔ r = 0 := ⟨zero_of_infinitesimal_real, λ hr, by rw hr; exact infinitesimal_zero⟩ lemma infinitesimal_add {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x + y) := by simpa only [add_zero] using is_st_add hx hy lemma infinitesimal_neg {x : ℝ*} (hx : infinitesimal x) : infinitesimal (-x) := by simpa only [neg_zero] using is_st_neg hx lemma infinitesimal_neg_iff {x : ℝ*} : infinitesimal x ↔ infinitesimal (-x) := ⟨infinitesimal_neg, λ h, (neg_neg x) ▸ @infinitesimal_neg (-x) h⟩ lemma infinitesimal_mul {x y : ℝ*} (hx : infinitesimal x) (hy : infinitesimal y) : infinitesimal (x * y) := by simpa only [mul_zero] using is_st_mul hx hy theorem infinitesimal_of_tendsto_zero {f : ℕ → ℝ} : tendsto f at_top (𝓝 0) → infinitesimal (of_seq f) := λ hf d hd, by rw [sub_eq_add_neg, ←coe_neg, ←coe_add, ←coe_add, zero_add, zero_add]; exact ⟨neg_lt_of_tendsto_zero_of_pos hf hd, lt_of_tendsto_zero_of_pos hf hd⟩ theorem infinitesimal_epsilon : infinitesimal ε := infinitesimal_of_tendsto_zero tendsto_inverse_at_top_nhds_0_nat lemma not_real_of_infinitesimal_ne_zero (x : ℝ*) : infinitesimal x → x ≠ 0 → ∀ r : ℝ, x ≠ r := λ hi hx r hr, hx $ hr.trans $ coe_eq_zero.2 $ is_st_unique (hr.symm ▸ is_st_refl_real r : is_st x r) hi theorem infinitesimal_sub_is_st {x : ℝ*} {r : ℝ} (hxr : is_st x r) : infinitesimal (x - r) := show is_st (x - r) 0, by { rw [sub_eq_add_neg, ← add_neg_self r], exact is_st_add hxr (is_st_refl_real (-r)) } theorem infinitesimal_sub_st {x : ℝ*} (hx : ¬infinite x) : infinitesimal (x - st x) := infinitesimal_sub_is_st $ is_st_st' hx lemma infinite_pos_iff_infinitesimal_inv_pos {x : ℝ*} : infinite_pos x ↔ (infinitesimal x⁻¹ ∧ 0 < x⁻¹) := ⟨ λ hip, ⟨ infinitesimal_def.mpr $ λ r hr, ⟨ lt_trans (coe_lt_coe.2 (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)), (inv_lt (coe_lt_coe.2 hr) (hip 0)).mp (by convert hip r⁻¹) ⟩, inv_pos.2 $ hip 0 ⟩, λ ⟨hi, hp⟩ r, @classical.by_cases (r = 0) (↑r < x) (λ h, eq.substr h (inv_pos.mp hp)) $ λ h, lt_of_le_of_lt (coe_le_coe.2 (le_abs_self r)) ((inv_lt_inv (inv_pos.mp hp) (coe_lt_coe.2 (abs_pos.2 h))).mp ((infinitesimal_def.mp hi) ((|r|)⁻¹) (inv_pos.2 (abs_pos.2 h))).2) ⟩ lemma infinite_neg_iff_infinitesimal_inv_neg {x : ℝ*} : infinite_neg x ↔ (infinitesimal x⁻¹ ∧ x⁻¹ < 0) := ⟨ λ hin, have hin' : _ := infinite_pos_iff_infinitesimal_inv_pos.mp (infinite_pos_neg_of_infinite_neg hin), by rwa [infinitesimal_neg_iff, ←neg_pos, neg_inv], λ hin, by rwa [←neg_pos, infinitesimal_neg_iff, neg_inv, ←infinite_pos_iff_infinitesimal_inv_pos, ←infinite_neg_iff_infinite_pos_neg] at hin ⟩ theorem infinitesimal_inv_of_infinite {x : ℝ*} : infinite x → infinitesimal x⁻¹ := λ hi, or.cases_on hi (λ hip, (infinite_pos_iff_infinitesimal_inv_pos.mp hip).1) (λ hin, (infinite_neg_iff_infinitesimal_inv_neg.mp hin).1) theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) (hi : infinitesimal x⁻¹ ) : infinite x := begin cases (lt_or_gt_of_ne h0) with hn hp, { exact or.inr (infinite_neg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_lt_zero.mpr hn⟩) }, { exact or.inl (infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos.mpr hp⟩) } end theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) : infinite x ↔ infinitesimal x⁻¹ := ⟨ infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0 ⟩ lemma infinitesimal_pos_iff_infinite_pos_inv {x : ℝ*} : infinite_pos x⁻¹ ↔ (infinitesimal x ∧ 0 < x) := by convert infinite_pos_iff_infinitesimal_inv_pos; simp only [inv_inv] lemma infinitesimal_neg_iff_infinite_neg_inv {x : ℝ*} : infinite_neg x⁻¹ ↔ (infinitesimal x ∧ x < 0) := by convert infinite_neg_iff_infinitesimal_inv_neg; simp only [inv_inv] theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x ≠ 0) : infinitesimal x ↔ infinite x⁻¹ := by convert (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm; simp only [inv_inv] /-! ### `st` stuff that requires infinitesimal machinery -/ theorem is_st_of_tendsto {f : ℕ → ℝ} {r : ℝ} (hf : tendsto f at_top (𝓝 r)) : is_st (of_seq f) r := have hg : tendsto (λ n, f n - r) at_top (𝓝 0) := (sub_self r) ▸ (hf.sub tendsto_const_nhds), by rw [←(zero_add r), ←(sub_add_cancel f (λ n, r))]; exact is_st_add (infinitesimal_of_tendsto_zero hg) (is_st_refl_real r) lemma is_st_inv {x : ℝ*} {r : ℝ} (hi : ¬ infinitesimal x) : is_st x r → is_st x⁻¹ r⁻¹ := λ hxr, have h : x ≠ 0 := (λ h, hi (h.symm ▸ infinitesimal_zero)), have H : _ := exists_st_of_not_infinite $ not_imp_not.mpr (infinitesimal_iff_infinite_inv h).mpr hi, Exists.cases_on H $ λ s hs, have H' : is_st 1 (r * s) := mul_inv_cancel h ▸ is_st_mul hxr hs, have H'' : s = r⁻¹ := one_div r ▸ eq_one_div_of_mul_eq_one_right (eq_of_is_st_real H').symm, H'' ▸ hs lemma st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := begin by_cases h0 : x = 0, rw [h0, inv_zero, ←coe_zero, st_id_real, inv_zero], by_cases h1 : infinitesimal x, rw [st_infinite ((infinitesimal_iff_infinite_inv h0).mp h1), st_of_is_st h1, inv_zero], by_cases h2 : infinite x, rw [st_of_is_st (infinitesimal_inv_of_infinite h2), st_infinite h2, inv_zero], exact st_of_is_st (is_st_inv h1 (is_st_st' h2)), end /-! ### Infinite stuff that requires infinitesimal machinery -/ lemma infinite_pos_omega : infinite_pos ω := infinite_pos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ lemma infinite_omega : infinite ω := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon lemma infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → 0 < y → infinite_pos (x * y) := λ hx hy₁ hy₂ r, have hy₁' : _ := not_forall.mp (by rw infinitesimal_def at hy₁; exact hy₁), Exists.dcases_on hy₁' $ λ r₁ hy₁'', have hyr : _ := by rw [not_imp, ←abs_lt, not_lt, abs_of_pos hy₂] at hy₁''; exact hy₁'', by rw [←div_mul_cancel r (ne_of_gt hyr.1), coe_mul]; exact mul_lt_mul (hx (r / r₁)) hyr.2 (coe_lt_coe.2 hyr.1) (le_of_lt (hx 0)) lemma infinite_pos_mul_of_not_infinitesimal_pos_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_pos y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → y < 0 → infinite_pos (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, ←neg_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_pos_mul_of_not_infinitesimal_neg_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_neg y → infinite_pos (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg {x y : ℝ*} : infinite_pos x → ¬ infinitesimal y → y < 0 → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, ←neg_pos, neg_mul_eq_mul_neg, infinitesimal_neg_iff]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_neg_infinite_pos {x y : ℝ*} : ¬ infinitesimal x → x < 0 → infinite_pos y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hy hx hp lemma infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos {x y : ℝ*} : infinite_neg x → ¬ infinitesimal y → 0 < y → infinite_neg (x * y) := by rw [infinite_neg_iff_infinite_pos_neg, infinite_neg_iff_infinite_pos_neg, neg_mul_eq_neg_mul]; exact infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos lemma infinite_neg_mul_of_not_infinitesimal_pos_infinite_neg {x y : ℝ*} : ¬ infinitesimal x → 0 < x → infinite_neg y → infinite_neg (x * y) := λ hx hp hy, by rw mul_comm; exact infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hy hx hp lemma infinite_pos_mul_infinite_pos {x y : ℝ*} : infinite_pos x → infinite_pos y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_neg_mul_infinite_neg {x y : ℝ*} : infinite_neg x → infinite_neg y → infinite_pos (x * y) := λ hx hy, infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_pos_mul_infinite_neg {x y : ℝ*} : infinite_pos x → infinite_neg y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg hx (not_infinitesimal_of_infinite_neg hy) (hy 0) lemma infinite_neg_mul_infinite_pos {x y : ℝ*} : infinite_neg x → infinite_pos y → infinite_neg (x * y) := λ hx hy, infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos hx (not_infinitesimal_of_infinite_pos hy) (hy 0) lemma infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : infinite x → ¬ infinitesimal y → infinite (x * y) := λ hx hy, have h0 : y < 0 ∨ 0 < y := lt_or_gt_of_ne (λ H0, hy (eq.substr H0 (is_st_refl_real 0))), or.dcases_on hx (or.dcases_on h0 (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_pos_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_pos_not_infinitesimal_pos Hx hy H0))) (or.dcases_on h0 (λ H0 Hx, or.inl (infinite_pos_mul_of_infinite_neg_not_infinitesimal_neg Hx hy H0)) (λ H0 Hx, or.inr (infinite_neg_mul_of_infinite_neg_not_infinitesimal_pos Hx hy H0))) lemma infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : ¬ infinitesimal x → infinite y → infinite (x * y) := λ hx hy, by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx lemma infinite.mul {x y : ℝ*} : infinite x → infinite y → infinite (x * y) := λ hx hy, infinite_mul_of_infinite_not_infinitesimal hx (not_infinitesimal_of_infinite hy) end hyperreal namespace tactic open positivity private lemma hyperreal_coe_ne_zero {r : ℝ} : r ≠ 0 → (r : ℝ*) ≠ 0 := hyperreal.coe_ne_zero.2 private lemma hyperreal_coe_nonneg {r : ℝ} : 0 ≤ r → 0 ≤ (r : ℝ*) := hyperreal.coe_nonneg.2 private lemma hyperreal_coe_pos {r : ℝ} : 0 < r → 0 < (r : ℝ*) := hyperreal.coe_pos.2 /-- Extension for the `positivity` tactic: cast from `ℝ` to `ℝ*`. -/ @[positivity] meta def positivity_coe_real_hyperreal : expr → tactic strictness | `(@coe _ _ %%inst %%a) := do unify inst `(@coe_to_lift _ _ hyperreal.has_coe_t), strictness_a ← core a, match strictness_a with | positive p := positive <$> mk_app ``hyperreal_coe_pos [p] | nonnegative p := nonnegative <$> mk_app ``hyperreal_coe_nonneg [p] | nonzero p := nonzero <$> mk_app ``hyperreal_coe_ne_zero [p] end | e := pp e >>= fail ∘ format.bracket "The expression " " is not of the form `(r : ℝ*)` for `r : ℝ`" end tactic
6779bbe7e435769828a5f094b1c5d916bb0999fb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/parser2.lean
5809d8ae3a5561978898a46cbd045efaea3d910b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,356
lean
import init.lean.name init.lean.syntax init.lean.parser namespace Lean namespace Parser inductive ParserDescr (k : ParserKind := leading) | ident {} : ParserDescr | numLit {} : ParserDescr | strLit {} : ParserDescr | symbol {} (sym : String) (lbp : Option Nat) : ParserDescr | unicodeSymbol {} (sym ascii : String) (lbp : Option Nat) : ParserDescr | andthen (p q : ParserDescr) : ParserDescr | orelse (p q : ParserDescr) : ParserDescr | sepBy (p q : ParserDescr) : ParserDescr | sepBy1 (p q : ParserDescr) : ParserDescr | many (p : ParserDescr) : ParserDescr | many1 (p : ParserDescr) : ParserDescr | optional (p : ParserDescr) : ParserDescr | nonTerminal (id : Name) : ParserDescr | external (fn : Name) : ParserDescr | node (kind : SyntaxNodeKind) (a : ParserDescr) : ParserDescr abbrev TrailingParserDescr := ParserDescr trailing def toParser {k : ParserKind} : ParserDescr k → ExceptT String Id (Parser k) | ParserDescr.ident := pure ident | ParserDescr.numLit := pure numLit | ParserDescr.strLit := pure strLit | (ParserDescr.andthen p q) := do p ← toParser p, q ← toParser q, pure (andthen p q) | (ParserDescr.orelse p q) := do p ← toParser p, q ← toParser q, pure (orelse p q) | (ParserDescr.symbol sym lbp) := pure (symbol sym lbp) | _ := Except.error "not implemented yet" end Parser end Lean
8c64586aaf073a17f645c5f65e95ce44737982e9
f3849be5d845a1cb97680f0bbbe03b85518312f0
/leanpkg/leanpkg/main.lean
81a7f448b97f89c2f40f92f1f13ca01335d3c17e
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,280
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import leanpkg.resolve variable [io.interface] namespace leanpkg def write_file (fn : string) (cnts : string) (mode := io.mode.write) : io unit := do h ← io.mk_file_handle fn io.mode.write, io.fs.write h cnts.to_char_buffer, io.fs.close h def read_manifest : io manifest := manifest.from_file leanpkg_toml_fn def write_manifest (d : manifest) (fn := leanpkg_toml_fn) : io unit := write_file fn (to_string d) -- TODO(gabriel): implement a cross-platform api def get_dot_lean_dir : io string := do some home ← io.env.get "HOME" | io.fail "environment variable HOME is not set", return $ home ++ "/.lean" -- TODO(gabriel): file existence testing def exists_file (f : string) : io bool := do ch ← io.proc.spawn { cmd := "test", args := ["-f", f] }, ev ← io.proc.wait ch, return $ ev = 0 -- TODO(gabriel): io.env.get_current_directory def get_current_directory : io string := do cwd ← io.cmd { cmd := "pwd" }, return (cwd.dropn 1) -- remove final newline def mk_path_file : ∀ (paths : list string), string | [] := "builtin_path\n" | (x :: xs) := mk_path_file xs ++ "path " ++ x ++ "\n" def configure : io unit := do d ← read_manifest, io.put_str_ln $ "configuring " ++ d.name ++ " " ++ d.version, assg ← solve_deps d, path_file_cnts ← mk_path_file <$> construct_path assg, write_file "leanpkg.path" path_file_cnts def make : io unit := exec_cmd { cmd := "lean", args := ["--make"], env := [("LEAN_PATH", none)] } def build := configure >> make def init_gitignore_contents := "*.olean /_target /leanpkg.path " def init_pkg (n : string) (dir : string) : io unit := do write_manifest { name := n, version := "0.1", path := none, dependencies := [] } (dir ++ "/" ++ leanpkg_toml_fn), write_file (dir ++ "/.gitignore") init_gitignore_contents io.mode.append, exec_cmd {cmd := "leanpkg", args := ["configure"], cwd := dir} def init (n : string) := init_pkg n "." -- TODO(gabriel): windows def basename : ∀ (fn : string), string | [] := [] | (c :: rest) := if c = '/' then [] else c :: basename rest def add_dep_to_manifest (dep : dependency) : io unit := do d ← read_manifest, let d' := { d with dependencies := d.dependencies.filter (λ old_dep, old_dep.name ≠ dep.name) ++ [dep] }, write_manifest d' def strip_dot_git (url : string) : string := if url.taken 4 = ".git" then url.dropn 4 else url def looks_like_git_url (dep : string) : bool := ':' ∈ show list char, from dep def absolutize_add_dep (dep : string) : io string := if looks_like_git_url dep then return dep else resolve_dir dep <$> get_current_directory def parse_add_dep (dep : string) : dependency := if looks_like_git_url dep then { name := basename (strip_dot_git dep), src := source.git dep "master" } else { name := basename dep, src := source.path dep } def git_head_revision (git_repo_dir : string) : io string := do rev ← io.cmd {cmd := "git", args := ["rev-parse", "HEAD"], cwd := git_repo_dir}, return (rev.dropn 1) -- remove newline at end def fixup_git_version (dir : string) : ∀ (src : source), io source | (source.git url _) := source.git url <$> git_head_revision dir | src := return src def add (dep : string) : io unit := do let dep := parse_add_dep dep, (_, assg) ← materialize "." dep assignment.empty, some downloaded_path ← return (assg.find dep.name), manif ← manifest.from_file (downloaded_path ++ "/" ++ leanpkg_toml_fn), src ← fixup_git_version downloaded_path dep.src, let dep := { dep with name := manif.name, src := src }, add_dep_to_manifest dep, configure def new (dir : string) := do ex ← dir_exists dir, when ex $ io.fail $ "directory already exists: " ++ dir, exec_cmd {cmd := "mkdir", args := ["-p", dir]}, init_pkg (basename dir) dir def usage := " Usage: leanpkg <command> configure download dependencies build download dependencies and build *.olean files new <dir> creates a lean package in the specified directory init <name> adds a leanpkg.toml file to the current directory, and sets up .gitignore add <url> adds a dependency from a git repository (uses current master revision) add <dir> adds a local dependency install <url> installs a user-wide package from git install <dir> installs a user-wide package from a local directory dump prints the parsed leanpkg.toml file (for debugging) " def main : ∀ (args : list string), io unit | ["configure"] := configure | ["build"] := build | ["new", dir] := new dir | ["init", name] := init name | ["add", dep] := add dep | ["install", dep] := do dep ← absolutize_add_dep dep, dot_lean_dir ← get_dot_lean_dir, exec_cmd {cmd := "mkdir", args := ["-p", dot_lean_dir]}, let user_toml_fn := dot_lean_dir ++ "/" ++ leanpkg_toml_fn, ex ← exists_file user_toml_fn, when (¬ ex) $ write_manifest { name := "_user_local_packages", version := "1", path := none, dependencies := [] } user_toml_fn, exec_cmd {cmd := "leanpkg", args := ["add", dep], cwd := dot_lean_dir} | ["dump"] := read_manifest >>= io.print_ln | _ := io.fail usage end leanpkg def main : io unit := io.cmdline_args >>= leanpkg.main
68dc1a87b222b79b3b4196ed2769b4266d4fd4c2
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/measure_theory/ess_sup.lean
935fa072aaae518c93258fc20ab5be68e9b817c7
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,451
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.measure_space import order.filter.ennreal /-! # Essential supremum and infimum We define the essential supremum and infimum of a function `f : α → β` with respect to a measure `μ` on `α`. The essential supremum is the infimum of the constants `c : β` such that `f x ≤ c` almost everywhere. TODO: The essential supremum of functions `α → ennreal` is used in particular to define the norm in the `L∞` space (see measure_theory/lp_space.lean). There is a different quantity which is sometimes also called essential supremum: the least upper-bound among measurable functions of a family of measurable functions (in an almost-everywhere sense). We do not define that quantity here, which is simply the supremum of a map with values in `α →ₘ[μ] β` (see measure_theory/ae_eq_fun.lean). ## Main definitions * `ess_sup f μ := μ.ae.limsup f` * `ess_inf f μ := μ.ae.liminf f` -/ open measure_theory variables {α β : Type*} [measurable_space α] {μ : measure α} section conditionally_complete_lattice variable [conditionally_complete_lattice β] /-- Essential supremum of `f` with respect to measure `μ`: the smallest `c : β` such that `f x ≤ c` a.e. -/ def ess_sup (f : α → β) (μ : measure α) := μ.ae.limsup f /-- Essential infimum of `f` with respect to measure `μ`: the greatest `c : β` such that `c ≤ f x` a.e. -/ def ess_inf (f : α → β) (μ : measure α) := μ.ae.liminf f lemma ess_sup_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_sup f μ = ess_sup g μ := filter.limsup_congr hfg lemma ess_inf_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_inf f μ = ess_inf g μ := @ess_sup_congr_ae α (order_dual β) _ _ _ _ _ hfg end conditionally_complete_lattice section complete_lattice variable [complete_lattice β] @[simp] lemma ess_sup_measure_zero {f : α → β} : ess_sup f 0 = ⊥ := le_bot_iff.mp (Inf_le (by simp [set.mem_set_of_eq, filter.eventually_le, ae_iff])) @[simp] lemma ess_inf_measure_zero {f : α → β} : ess_inf f 0 = ⊤ := @ess_sup_measure_zero α (order_dual β) _ _ _ lemma ess_sup_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_sup f μ ≤ ess_sup g μ := filter.limsup_le_limsup hfg lemma ess_inf_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_inf f μ ≤ ess_inf g μ := filter.liminf_le_liminf hfg lemma ess_sup_const (c : β) (hμ : μ ≠ 0) : ess_sup (λ x : α, c) μ = c := begin haveI hμ_ne_bot : μ.ae.ne_bot := by rwa [filter.ne_bot, ne.def, ae_eq_bot], exact filter.limsup_const c, end lemma ess_inf_const (c : β) (hμ : μ ≠ 0) : ess_inf (λ x : α, c) μ = c := @ess_sup_const α (order_dual β) _ _ _ _ hμ lemma ess_sup_const_bot : ess_sup (λ x : α, (⊥ : β)) μ = (⊥ : β) := filter.limsup_const_bot lemma ess_inf_const_top : ess_inf (λ x : α, (⊤ : β)) μ = (⊤ : β) := filter.liminf_const_top lemma order_iso.ess_sup_apply {γ} [complete_lattice γ] (f : α → β) (μ : measure α) (g : β ≃o γ) : g (ess_sup f μ) = ess_sup (λ x, g (f x)) μ := begin refine order_iso.limsup_apply g _ _ _ _, all_goals { by filter.is_bounded_default}, end lemma order_iso.ess_inf_apply {γ} [complete_lattice γ] (f : α → β) (μ : measure α) (g : β ≃o γ) : g (ess_inf f μ) = ess_inf (λ x, g (f x)) μ := @order_iso.ess_sup_apply α (order_dual β) _ _ (order_dual γ) _ _ _ g.dual end complete_lattice section complete_linear_order variable [complete_linear_order β] lemma ae_lt_of_ess_sup_lt {f : α → β} {x : β} (hf : ess_sup f μ < x) : ∀ᵐ y ∂μ, f y < x := filter.eventually_lt_of_limsup_lt hf lemma ae_lt_of_lt_ess_inf {f : α → β} {x : β} (hf : x < ess_inf f μ) : ∀ᵐ y ∂μ, x < f y := @ae_lt_of_ess_sup_lt α (order_dual β) _ _ _ _ _ hf end complete_linear_order namespace ennreal lemma ae_le_ess_sup (f : α → ennreal) : ∀ᵐ y ∂μ, f y ≤ ess_sup f μ := eventually_le_limsup f lemma ess_sup_eq_zero_iff {f : α → ennreal} : ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 := limsup_eq_zero_iff lemma ess_sup_const_mul {f : α → ennreal} {a : ennreal} : ess_sup (λ (x : α), a * (f x)) μ = a * ess_sup f μ := limsup_const_mul lemma ess_sup_add_le (f g : α → ennreal) : ess_sup (f + g) μ ≤ ess_sup f μ + ess_sup g μ := limsup_add_le f g end ennreal
1f46ba7633eeafae10348e4e38ff38b6f6d0d198
8be24982c807641260370bd09243eac768750811
/src/algebraic_countable_over_Q.lean
4b86efee79de0fc1aeb4232d96d3a8dc9d0b4285
[]
no_license
jjaassoonn/transcendental
8008813253af3aa80b5a5c56551317e7ab4246ab
99bc6ea6089f04ed90a0f55f0533ebb7f47b22ff
refs/heads/master
1,607,869,957,944
1,599,659,687,000
1,599,659,687,000
234,444,826
9
1
null
1,598,218,307,000
1,579,224,232,000
HTML
UTF-8
Lean
false
false
35,256
lean
-- import data.set.basic set_theory.schroeder_bernstein -- import data.set.countable -- import ring_theory.algebraic -- import data.polynomial -- import data.rat.default -- import data.real.basic data.real.cardinality -- import tactic -- noncomputable theory -- open_locale classical -- namespace project -- def algebraic_set : set real := {x | is_algebraic rat x } -- def roots_real (p : polynomial rat) : set real := {x | polynomial.aeval rat real x p = 0} -- def poly_rat_to_poly_real (p : polynomial rat) : polynomial real := -- begin -- constructor, -- swap, -- { -- exact p.1, -- }, -- swap, -- { -- intro n, -- exact real.of_rat (p.2 n), -- }, -- { -- intro n, -- split, -- intro hn, -- rw real.of_rat_eq_cast, -- norm_cast, -- exact (p.3 n).mp hn, -- rw real.of_rat_eq_cast, -- norm_cast, -- exact (p.3 n).mpr, -- }, -- done -- end -- def poly_rat_to_poly_real_wd (p : polynomial rat) : Prop := ∀ x : real, polynomial.aeval rat real x p = (poly_rat_to_poly_real p).eval x -- theorem poly_rat_to_poly_real_preserve_deg (p : polynomial rat) : p.degree = (poly_rat_to_poly_real p).degree := -- begin -- rw [poly_rat_to_poly_real, polynomial.degree, polynomial.degree], done -- end -- theorem poly_rat_to_poly_real_C_wd' (a : rat) : polynomial.C (real.of_rat a) = poly_rat_to_poly_real (polynomial.C a) := -- begin -- ext, -- unfold poly_rat_to_poly_real, -- rw polynomial.coeff_C, -- split_ifs, -- simp only [rat.cast_inj, polynomial.coeff_mk, real.of_rat_eq_cast], rw h, rw <-polynomial.coeff, rw polynomial.coeff_C_zero, -- simp only [polynomial.coeff_mk, real.of_rat_eq_cast], rw <-polynomial.coeff, rw polynomial.coeff_C, split_ifs, norm_cast, -- done -- end -- theorem poly_rat_to_poly_real_C_wd : ∀ a : rat, poly_rat_to_poly_real_wd (polynomial.C a) := -- begin -- intros r x, -- rw <-poly_rat_to_poly_real_C_wd', -- simp only [polynomial.eval_C, polynomial.aeval_C, real.of_rat_eq_cast], -- exact rfl, -- done -- end -- theorem poly_rat_to_poly_real_add (p1 p2 : polynomial rat) : poly_rat_to_poly_real (p1 + p2) = poly_rat_to_poly_real p1 + poly_rat_to_poly_real p2 := -- begin -- ext, -- rw [poly_rat_to_poly_real, poly_rat_to_poly_real, poly_rat_to_poly_real], -- simp only [polynomial.coeff_add, polynomial.coeff_mk, real.of_rat_eq_cast], -- norm_cast, -- done -- end -- theorem poly_rat_to_poly_real_add_wd (p1 p2 : polynomial rat) -- (h1 : poly_rat_to_poly_real_wd p1) -- (h2 : poly_rat_to_poly_real_wd p2) : poly_rat_to_poly_real_wd (p1 + p2) := -- begin -- intro x, -- simp only [alg_hom.map_add], -- rw h1, rw h2, -- rw <-polynomial.eval_add, -- rw poly_rat_to_poly_real_add, -- done -- end -- theorem poly_rat_to_poly_real_pow1 (n : nat) : poly_rat_to_poly_real (polynomial.X ^ n) = polynomial.X ^ n := -- begin -- ext, rename n_1 m, -- rw poly_rat_to_poly_real, simp only [polynomial.coeff_X_pow, polynomial.coeff_mk, real.of_rat_eq_cast], -- split_ifs; -- norm_cast; rw [<-polynomial.coeff, polynomial.coeff_X_pow]; split_ifs; refl, -- done -- end -- theorem poly_rat_to_poly_real_pow2 (n : nat) (a : rat) : poly_rat_to_poly_real ((polynomial.C a) * polynomial.X ^ n) = (polynomial.C (real.of_rat a)) * polynomial.X ^ n := -- begin -- ext, rename n_1 m, -- rw poly_rat_to_poly_real, simp only [mul_boole, polynomial.coeff_X_pow, polynomial.coeff_C_mul, polynomial.coeff_mk, real.of_rat_eq_cast], -- norm_cast, rw [<-polynomial.coeff, polynomial.coeff_C_mul_X], -- done -- end -- theorem poly_rat_to_poly_real_pow_wd (n : nat) (a : rat) (h : poly_rat_to_poly_real_wd ((polynomial.C a) * polynomial.X ^ n)) : poly_rat_to_poly_real_wd ((polynomial.C a) * polynomial.X ^ n.succ) := -- begin -- intro x, -- rw poly_rat_to_poly_real_pow2, -- simp only [polynomial.aeval_def, polynomial.eval_X, polynomial.eval₂_C, polynomial.eval_C, polynomial.eval_pow, -- polynomial.eval₂_mul, polynomial.eval_mul, real.of_rat_eq_cast], -- rw polynomial.eval₂_pow, -- rw <-polynomial.aeval_def, -- rw polynomial.aeval_X, -- exact rfl, -- done -- end -- theorem poly_rat_to_poly_real_ne_zero (p : polynomial rat) : p ≠ 0 ↔ (poly_rat_to_poly_real p) ≠ 0 := -- begin -- split, -- intros h hp, -- rw poly_rat_to_poly_real at hp, -- rw polynomial.ext_iff at hp, -- simp only [polynomial.coeff_zero, rat.cast_eq_zero, polynomial.coeff_mk, real.of_rat_eq_cast] at hp, -- rw <-polynomial.coeff at hp, -- have h' : p = 0, -- exact finsupp.ext hp, -- exact h h', -- intros h hp, -- have h' : poly_rat_to_poly_real p = 0, -- unfold poly_rat_to_poly_real, -- simp only [real.of_rat_eq_cast], ext, simp only [polynomial.coeff_zero, rat.cast_eq_zero, polynomial.coeff_mk], rw <-polynomial.coeff, rw hp, simp only [polynomial.coeff_zero], -- exact h h', -- done, -- end -- theorem poly_rat_to_poly_real_well_defined (x : real) (p : polynomial rat) : -- poly_rat_to_poly_real_wd p := -- polynomial.induction_on -- p -- poly_rat_to_poly_real_C_wd -- poly_rat_to_poly_real_add_wd -- poly_rat_to_poly_real_pow_wd -- def roots_real' (p : polynomial rat) : set real := {x | (poly_rat_to_poly_real p).eval x = 0} -- theorem roots_real_eq_roots_real' (p : polynomial rat) : roots_real p = roots_real' p := -- begin -- ext, split; intro hx, -- unfold roots_real at hx, -- rw set.mem_set_of_eq at hx, -- unfold roots_real', -- rw set.mem_set_of_eq, -- have g := poly_rat_to_poly_real_well_defined x p, -- unfold poly_rat_to_poly_real_wd at g, -- have g' := g x, -- rw hx at g', -- exact eq.symm g', -- unfold roots_real' at hx, -- rw set.mem_set_of_eq at hx, -- rw roots_real, -- rw set.mem_set_of_eq, -- have g := poly_rat_to_poly_real_well_defined x p, -- unfold poly_rat_to_poly_real_wd at g, -- have g' := g x, -- rw hx at g', -- exact g', -- done -- end -- theorem roots_real'_eq_roots (p : polynomial rat) (hp : p ≠ 0) : roots_real' p = ↑((poly_rat_to_poly_real p).roots) := -- begin -- ext, -- have g := @polynomial.mem_roots real x _ (poly_rat_to_poly_real p) ((poly_rat_to_poly_real_ne_zero p).mp hp), -- split, -- intro hx, rw roots_real' at hx, rw set.mem_set_of_eq at hx, -- simp only [finset.mem_coe], apply g.mpr, exact hx, -- intro hx, simp only [finset.mem_coe] at hx, unfold roots_real', rw set.mem_set_of_eq, -- exact g.mp hx, -- done -- end -- theorem roots_real_eq_roots (p : polynomial rat) (hp : p ≠ 0) : roots_real p = ↑((poly_rat_to_poly_real p).roots) := -- begin -- rw [roots_real_eq_roots_real', roots_real'_eq_roots], assumption, done -- end -- theorem roots_finite (p : polynomial rat) (hp : p ≠ 0) : set.finite (roots_real p) := -- begin -- rw roots_real_eq_roots, -- split, exact additive.fintype, assumption, done -- end -- -- Part I of project -- def nat_set : set nat := @set.univ nat -- def rat_n (n : nat) := fin n -> rat -- def nat_n (n : nat) := fin n -> nat -- def poly_n (n : nat) := {x : polynomial rat // x.nat_degree < n} -- def poly_n' (n : nat) := {p : polynomial rat // p ≠ 0 ∧ p.nat_degree < n} -- def rat_n' (n : nat) := {f : fin n -> rat // f ≠ 0} -- def rat' := {r : rat // r ≠ 0} -- theorem strange_fun_aux (q : rat) (hq : ¬(q.2 = 1 ∨ q.1 = 0)) : q ≠ 0 := -- begin -- intro absurd, rw rat.zero_iff_num_zero at absurd, -- exact (not_or_distrib.mp hq).2 absurd -- end -- def strange_fun (q : rat) : rat' := -- begin -- by_cases (q.2 = 1 ∨ q.1 = 0); rename h is_q_int, -- { -- by_cases (q < 0), exact ⟨q, ne_of_lt h⟩, -- exact ⟨q + 1, by linarith⟩, -- }, -- { -- exact ⟨q, strange_fun_aux q is_q_int⟩, -- } -- end -- theorem strange_fun_inj : function.injective strange_fun := -- begin -- { -- intros q1 q2 hq, -- by_cases (q1.2 = 1 ∨ q1.1 = 0); rename h q1_int; -- by_cases (q2.2 = 1 ∨ q2.1 = 0); rename h q2_int, -- { -- simp only [strange_fun, q1_int, q2_int, dif_pos] at hq, -- by_cases (q1 < 0); rename h q1_neg; by_cases (q2 < 0); rename h q2_neg, -- simp only [q1_neg, q2_neg, dif_pos, subtype.mk_eq_mk] at hq, exact hq, -- simp only [q1_neg, q2_neg, dif_pos, subtype.mk_eq_mk, dif_neg, not_false_iff] at hq, linarith, -- simp only [q1_neg, q2_neg, dif_pos, subtype.mk_eq_mk, dif_neg, not_false_iff] at hq, linarith, -- simp only [q1_neg, q2_neg, add_left_inj, subtype.mk_eq_mk, dif_neg, not_false_iff] at hq, exact hq, -- }, -- { -- simp only [strange_fun, strange_fun, q1_int, q2_int, dif_pos, dif_neg, not_false_iff] at hq, -- by_cases (q1 < 0); rename h q1_neg; by_cases (q2 < 0); rename h q2_neg, -- simp only [q1_neg, dif_pos, subtype.mk_eq_mk] at hq, assumption, -- simp only [q1_neg, dif_pos, subtype.mk_eq_mk] at hq, assumption, -- simp only [q1_neg, subtype.mk_eq_mk, dif_neg, not_false_iff] at hq, linarith, -- simp only [q1_neg, subtype.mk_eq_mk, dif_neg, not_false_iff] at hq, cases q1_int, -- { -- simp only [rat.add_num_denom, q1_int, mul_one, rat.num_one, int.coe_nat_zero, int.coe_nat_succ, zero_add, rat.denom_one] at hq, -- simp only [not_lt] at q1_neg, -- have g := @rat.num_denom' (q1.num + 1) 1 (by linarith) (nat.coprime_one_right (int.nat_abs (q1.num + 1))), -- norm_cast at g, -- rw <-g at hq, -- have h : ({ num := q1.num + 1, denom := 1, pos := (by linarith), cop := (nat.coprime_one_right (int.nat_abs (q1.num + 1))) } : rat).denom = q2.denom := by rw hq, -- have h' : ({ num := q1.num + 1, denom := 1, pos := (by linarith), cop := (nat.coprime_one_right (int.nat_abs (q1.num + 1))) } : rat).denom = 1 := rfl, -- rw h at h', rw not_or_distrib at q2_int, cases q2_int with q21 q22, exfalso, exact q21 h', -- }, -- { -- rw <-rat.zero_iff_num_zero at q1_int, -- rw q1_int at hq, simp only [zero_add] at hq, -- have h : q2.denom = 1, -- exact calc q2.denom = (1 : rat).denom : by rw hq -- ... = 1 : rfl, -- rw not_or_distrib at q2_int, cases q2_int with q21 q22, exfalso, exact q21 h, -- }, -- }, -- { -- simp only [strange_fun, strange_fun, q1_int, q2_int, dif_pos, dif_neg, not_false_iff] at hq, -- by_cases (q1 < 0); rename h q1_neg; by_cases (q2 < 0); rename h q2_neg, -- simp only [q2_neg, dif_pos, subtype.mk_eq_mk] at hq, exact hq, simp only [q2_neg, subtype.mk_eq_mk, dif_neg, not_false_iff] at hq, -- linarith, split_ifs at hq, simp only [subtype.mk_eq_mk] at hq, exact hq, split_ifs at hq, simp only [subtype.mk_eq_mk] at hq, -- cases q2_int with q22 q21, -- have h : q1.denom = (q2 + 1).denom := by rw hq, -- simp only [rat.add_num_denom, q22, mul_one, rat.num_one, int.coe_nat_zero, int.coe_nat_succ, zero_add, rat.denom_one] at h, -- have g := @rat.num_denom' (q2.num + 1) 1 (by linarith) (nat.coprime_one_right (int.nat_abs (q2.num + 1))), -- norm_cast at g, -- rw <-g at h, -- have h' : ({ num := q2.num + 1, denom := 1, pos := (by linarith), cop := (nat.coprime_one_right (int.nat_abs (q2.num + 1))) } : rat).denom = 1 := rfl, -- rw h' at h, exfalso, exact (not_or_distrib.mp q1_int).1 h, -- rw <-rat.zero_iff_num_zero at q21, simp only [q21, zero_add] at hq, -- have h : q1.denom = 1, -- exact calc q1.denom = (1 : rat).denom : by rw hq -- ... = 1 : rfl, -- exfalso, exact (not_or_distrib.mp q1_int).1 h, -- }, -- { -- simp only [strange_fun, q1_int, q2_int, subtype.mk_eq_mk, dif_neg, not_false_iff] at hq, -- by_cases (q1 < 0); rename h q1_neg; by_cases (q2 < 0); rename h q2_neg; assumption, -- }, -- }, -- end -- theorem strange_fun_sur : function.surjective strange_fun := -- begin -- { -- intro q, -- by_cases (q.1.2 = 1 ∨ q.1.1 = 0); rename h q_int, -- { -- by_cases (q.1 < 0); rename h q_pos, -- use q.1, simp only [strange_fun, q_int, q_pos, dif_pos, subtype.eta], -- generalize h' : q.1-1 = q', -- have q'_int : q'.2 = 1 ∨ q'.1 = 0, -- { -- cases q_int, left, -- have h'' : q.1 + (-1 : rat) = q', linarith, rw rat.add_num_denom at h'', simp only [q_int, rat.num_neg_eq_neg_num, mul_one, rat.num_one, int.coe_nat_zero, int.coe_nat_succ, zero_add, -- rat.denom_neg_eq_denom, rat.denom_one, int.mul_neg_eq_neg_mul_symm] at h'', -- have h''' : ({ num := -1 + q.1.1, denom := 1, pos := (by linarith), cop := (nat.coprime_one_right (int.nat_abs (-1 + q.1.1))) } : rat) = rat.mk (-1 + q.1.1) 1, -- rw rat.num_denom', norm_cast, -- -- rw <-h''' at h'', -- have H : q' = ({ num := -1 + q.1.1, denom := 1, pos := (by linarith), cop := (nat.coprime_one_right (int.nat_abs (-1 + q.1.1))) } : rat), -- { -- rw <-h'', rw add_comm, rw <-h''', -- }, -- rw H, -- left, rw <-rat.zero_iff_num_zero at q_int, simp only [q_int, zero_sub] at h', rw <-h', exact rfl, -- }, -- have q_ne_0 := q.2, rw [not_lt] at q_pos, -- have q_ge_1 : q.1 ≥ 1, -- { -- cases q_int, -- have H : q.1 = q.1.1, -- { -- rw rat.coe_int_eq_mk, -- have H : q.1 = { num := q.1.1, denom := q.1.2, pos := q.1.3, cop := q.1.4 }, {induction q.1, refl}, -- conv_lhs { rw H }, rw rat.num_denom', rw q_int, norm_cast, -- }, -- have H2 : q.1 > 0 := lt_of_le_of_ne q_pos (ne.symm q_ne_0), rw H at H2, norm_cast at H2, -- suffices H3 : q.1.1 ≥ 1, have H4 : (q.1.1 : rat) ≥ 1, norm_cast, assumption, rw <-H at H4, assumption, linarith, -- exfalso, rw <-rat.zero_iff_num_zero at q_int, exact q_ne_0 q_int, -- }, -- have H2 : q' ≥ 0, linarith, -- have H2' : ¬ q' < 0, linarith, use q', simp only [strange_fun, q'_int, H2', dif_pos, dif_neg, not_false_iff], -- apply subtype.eq, simp only [], linarith, -- }, -- { -- use q.1, simp only [strange_fun, q_int, subtype.eta, dif_neg, not_false_iff], -- }, -- }, -- done -- end -- theorem rat_equiv_rat' : rat ≃ rat' := -- begin -- suffices H : ∃ f : rat -> rat', function.bijective f, -- choose f Hf using H, exact equiv.of_bijective f Hf, -- use strange_fun, -- split, -- exact strange_fun_inj, -- exact strange_fun_sur, -- end -- def zero_rat_n {n : nat} : rat_n n.succ := (fun m, 0) -- def zero_poly_n {n : nat} : poly_n n.succ := ⟨0, nat.succ_pos n⟩ -- def identify (n : nat) : (poly_n n) -> (rat_n n) := -- begin -- intro p, -- intro m, -- exact p.val.coeff m.val, -- done -- end -- @[simp] theorem identify_0_eq_0 (n : nat) : (identify n.succ zero_poly_n) = zero_rat_n := -- begin -- rw [identify, zero_rat_n, zero_poly_n], ext, simp only [id.def, polynomial.coeff_zero], done -- end -- lemma m_mod_n_lt_n : ∀ n : nat, n ≠ 0 -> ∀ m : nat, m % n < n := -- begin -- intros n hn m, -- have hn' : 0 < n := zero_lt_iff_ne_zero.mpr hn, -- exact @nat.mod_lt m n hn', -- end -- theorem inj_identify_n : ∀ n : nat, (n ≠ 0) -> function.injective (identify n) := -- begin -- intros n hn, -- unfold function.injective, -- intros p1 p2 h, -- unfold identify at h, -- simp only [id.def] at h, -- rw subtype.ext_iff_val, -- ext, rename n_1 m, -- rw function.funext_iff at h, -- have p1_deg := p1.property, -- have p2_deg := p2.property, -- -- consider m = n, m < n, m > n seprately, -- cases (nat.lt_trichotomy m n) with ineq, -- -- m < n -- { -- let m' := (⟨m, ineq⟩ : fin n), -- have h_m := h m', -- have g : m'.val = m, -- { -- exact rfl, -- }, -- rw [<-g, h_m], -- }, -- rename h_1 ineq, -- cases ineq, -- -- m = n -- { -- rw ineq, -- rw [(@polynomial.coeff_eq_zero_of_nat_degree_lt rat _ p1.val n p1_deg), -- (@polynomial.coeff_eq_zero_of_nat_degree_lt rat _ p2.val n p2_deg)], -- }, -- -- n < m -- { -- rw @polynomial.coeff_eq_zero_of_nat_degree_lt rat _ p1.val m (lt.trans p1_deg ineq), -- rw @polynomial.coeff_eq_zero_of_nat_degree_lt rat _ p2.val m (lt.trans p2_deg ineq), -- } -- end -- theorem identify_nzero_to_nzero (n : nat) (p : poly_n n.succ) (hp : p ≠ zero_poly_n) : (identify n.succ p) ≠ zero_rat_n := -- begin -- have g := inj_identify_n n.succ (nat.succ_ne_zero n), -- have g' := @g p zero_poly_n, simp only [identify_0_eq_0] at g', -- intro absurd, exact hp (g' absurd), -- end -- theorem sur_identify_n : ∀ n : nat, (n ≠ 0) -> function.surjective (identify n) := -- begin -- intros n hn, -- unfold function.surjective, -- intro q, -- let support : finset nat := finset.filter (λ m : nat, (q (⟨m % n, m_mod_n_lt_n n hn m⟩ : fin n)) ≠ 0) (finset.range n), -- have hsupport : support = finset.filter (λ m : nat, (q (⟨m % n, m_mod_n_lt_n n hn m⟩ : fin n)) ≠ 0) (finset.range n) := rfl, -- let to_fun : nat -> rat := (λ m : nat, ite (m ∈ support) (q (⟨m % n, m_mod_n_lt_n n hn m⟩ : fin n)) 0), -- have hto_fun : to_fun = (λ m : nat, ite (m ∈ support) (q (⟨m % n, m_mod_n_lt_n n hn m⟩ : fin n)) 0) := rfl, -- let mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0, -- { -- intro m, -- split, -- intro hm, -- have hm'' := hm, -- rw hsupport at hm, -- have hm' := hm, -- rw finset.mem_filter at hm', -- cases hm', -- rename hm'_right qm_ne_0, -- rw hto_fun, -- have g : (λ (m : ℕ), ite (m ∈ support) (q ⟨m % n, m_mod_n_lt_n n hn m⟩) 0) m = ite (m ∈ support) (q ⟨m % n, m_mod_n_lt_n n hn m⟩) 0 := rfl, -- rw g, -- split_ifs, -- exact qm_ne_0, -- intro hm, -- have hm' := hm, -- rw hto_fun at hm', -- have g : (λ (m : ℕ), ite (m ∈ support) (q ⟨m % n, m_mod_n_lt_n n hn m⟩) 0) m = ite (m ∈ support) (q ⟨m % n, m_mod_n_lt_n n hn m⟩) 0 := rfl, -- rw g at hm', -- have g : ite (m ∈ support) (q ⟨m % n, m_mod_n_lt_n n hn m⟩) 0 ≠ 0 -> (m ∈ support), -- { -- intro h, -- by_contra, -- split_ifs at h, -- have h' : (0 : rat) = 0 := rfl, -- exact h h', -- }, -- exact g hm', -- }, -- let p : polynomial rat := ⟨support, to_fun, mem_support_to_fun⟩, -- have hp_support : p.support = finset.filter (λ (m : ℕ), q ⟨m % n, m_mod_n_lt_n n hn m⟩ ≠ 0) (finset.range n) := rfl, -- have hp_support2 : ∀ m ∈ p.support, m < n, -- { -- rw hp_support, -- intro m, -- rw finset.mem_filter, -- intro hm, -- cases hm, -- exact list.mem_range.mp hm_left, -- }, -- have hp_deg : (p.degree ≠ ⊥) -> p.degree < n, -- { -- intro hp_deg_not_bot, -- rw polynomial.degree, -- rw finset.sup_lt_iff, -- intros m hm, -- have hmn := hp_support2 m hm, -- swap, -- exact @with_bot.bot_lt_coe nat _ n, -- have g := @with_bot.some_eq_coe nat n, -- rw <-g, -- rw with_bot.some_lt_some, -- exact hmn, -- }, -- have hp_nat_deg : p.nat_degree < n, -- { -- by_cases (p = 0), -- rename h hp_eq_0, -- have g := polynomial.nat_degree_zero, -- rw <-hp_eq_0 at g, -- rw g, -- rw zero_lt_iff_ne_zero, -- exact hn, -- rename h hp_ne_0, -- have p_deg_ne_bot : p.degree ≠ ⊥, -- { -- intro gg, -- rw polynomial.degree_eq_bot at gg, -- exact hp_ne_0 gg, -- }, -- have hp_deg' := hp_deg p_deg_ne_bot, -- have g := polynomial.degree_eq_nat_degree hp_ne_0, -- rw g at hp_deg', -- rw <-with_bot.coe_lt_coe, -- exact hp_deg', -- }, -- use ⟨p, hp_nat_deg⟩, -- { -- ext, -- rename x m, -- unfold identify, -- simp only [id.def, polynomial.coeff_mk], -- rw hto_fun, -- have g : (λ (m : ℕ), ite (m ∈ support) (q ⟨m % n, m_mod_n_lt_n n hn m⟩) 0) (m.val) = ite (m.val ∈ support) (q ⟨m.val % n, m_mod_n_lt_n n hn m.val⟩) 0 := rfl, -- rw g, -- split_ifs, -- -- m.val ∈ support -- { -- simp only [ne.def, finset.mem_filter, finset.mem_range] at h, -- cases h, -- have important : m = ⟨m.1 % n, _⟩, -- { -- rw fin.ext_iff, -- simp only [], -- rw nat.mod_eq_of_lt, -- exact h_left, -- }, -- rw <-important, -- }, -- -- m.val ∉ support -- { -- simp only [not_and, finset.mem_filter, finset.mem_range, classical.not_not] at h, -- have h' := h m.2, -- have important : m = ⟨m.1 % n, _⟩, -- { -- rw fin.ext_iff, -- simp only [], -- rw nat.mod_eq_of_lt, -- exact m.2, -- }, -- rw <-important at h', -- exact eq.symm h', -- }, -- }, -- end -- theorem poly_n'_equiv_rat_n' (n : nat) : poly_n' n.succ ≃ rat_n' n.succ := -- begin -- let f : (poly_n' n.succ) -> (rat_n' n.succ), -- { -- intro p, -- generalize hx : (identify n.succ) ⟨p.1, p.2.2⟩ = x, -- split, swap, exact x, -- have g := identify_nzero_to_nzero n ⟨p.1, p.2.2⟩ _, -- rw hx at g, exact g, rw [zero_poly_n], simp only [subtype.mk_eq_mk, ne.def], exact p.2.1, -- }, -- suffices f_bij : function.bijective f, -- exact equiv.of_bijective f f_bij, -- split, -- { -- intros x1 x2 hx, simp only [subtype.mk_eq_mk] at hx, rw [identify, function.funext_iff] at hx, simp only [id.def] at hx, -- suffices h : x1.val = x2.val, exact subtype.eq h, -- ext, -- have h1 := x1.2.2, have h2 := x2.2.2, rename n_1 m, -- by_cases (m ≥ n.succ), -- rw [polynomial.coeff_eq_zero_of_nat_degree_lt, polynomial.coeff_eq_zero_of_nat_degree_lt], -- exact lt_of_lt_of_le h2 h, exact lt_of_lt_of_le h1 h, -- simp only [not_lt] at h, rw hx ⟨m, _⟩, exact nat.lt_succ_iff.mpr h, -- }, -- { -- intro q, -- have h := sur_identify_n n.succ (nat.succ_ne_zero n) q.1, -- choose p hp using h, -- have p_ne_0' : p ≠ zero_poly_n, -- { -- by_contra absurd, rw [ne.def, not_not] at absurd, -- have absurd' := identify_0_eq_0 n, -- rw <-absurd at absurd', rw hp at absurd', exact q.2 absurd', -- }, -- have p_ne_0 : p.1 ≠ 0, -- { -- intro hp, -- have h : 0 = zero_poly_n.1 := rfl, rw h at hp, -- exact p_ne_0' (@subtype.eq _ _ p zero_poly_n hp), -- }, -- use ⟨p.1, ⟨p_ne_0, p.2⟩⟩, -- rw [subtype.ext_iff_val], simp only [subtype.eta], assumption, -- }, -- done -- end -- def f : rat_n 1 -> rat_n' 1 := -- begin -- intro r, split, swap, exact (fun m, (strange_fun (r m)).1), -- intro a, rw function.funext_iff at a, replace a := a 0, simp only [pi.zero_apply] at a, -- generalize hx : (strange_fun (r 0)) = x, rw hx at a, exact x.2 a, -- end -- def g : rat_n' 1 -> rat_n 1 := -- begin -- intros g n, exact g.1 n, -- end -- theorem rat_1_equiv_rat_1' : rat_n 1 ≃ rat_n' 1 := -- begin -- suffices H1 : ∃ f : rat_n 1 -> rat_n' 1, function.bijective f, -- choose h hh using H1, -- exact equiv.of_bijective h hh, -- suffices H2 : ∃ f : rat_n 1 -> rat_n' 1, ∃ g : rat_n' 1 -> rat_n 1, function.injective f ∧ function.injective g, -- choose f g h using H2, exact function.embedding.schroeder_bernstein h.1 h.2, -- use f, use g, split, -- { -- intros x1 x2 hx, simp only [f, subtype.mk_eq_mk] at hx, rw function.funext_iff at hx, replace hx := hx 0, -- replace hx := subtype.eq hx, replace hx := strange_fun_inj hx, ext, fin_cases x, exact hx, -- }, -- { -- intros x1 x2 hx, simp only [g, id.def] at hx, replace hx := subtype.eq hx, exact hx, -- } -- end -- def fn {n : nat} : rat_n (nat.succ (nat.succ n)) -> rat_n (nat.succ n) × rat := -- begin -- intro r, split, intro m, exact r (⟨m.1, nat.lt_trans m.2 (nat.lt_succ_self n.succ)⟩ : fin n.succ.succ), -- exact r (⟨n.succ, nat.lt_succ_self n.succ⟩ : fin n.succ.succ), -- end -- def gn {n : nat} : rat_n (nat.succ n) × rat -> rat_n (nat.succ (nat.succ n)) := -- begin -- intros r m, cases r with p r, -- by_cases (m.1 = n.succ), exact r, -- have hm' := m.2, -- have hm : m.1 < n.succ, -- replace hm : m.1 ≤ n.succ, exact fin.le_last m, exact lt_of_le_of_ne hm h, -- exact p (⟨m.1, hm⟩ : fin n.succ), -- end -- theorem aux_rat_n (n : nat) : rat_n (nat.succ (nat.succ n)) ≃ rat_n (nat.succ n) × rat := -- begin -- suffices H1 : ∃ f : rat_n n.succ.succ -> rat_n n.succ × rat, function.bijective f, -- choose h hh using H1, -- exact equiv.of_bijective h hh, -- suffices H2 : ∃ f : rat_n n.succ.succ -> rat_n n.succ × rat, ∃ g : rat_n n.succ × rat -> rat_n n.succ.succ, function.injective f ∧ function.injective g, -- choose f g h using H2, exact function.embedding.schroeder_bernstein h.1 h.2, -- use fn, use gn, split, -- { -- intros x1 x2 hx, simp only [fn, id.def, prod.mk.inj_iff] at hx, cases hx with h1 h2, rw function.funext_iff at h1, ext, -- by_cases (x = ⟨n.succ, nat.lt_succ_self n.succ⟩), rw <-h at h2, assumption, -- simp only [fin.eq_iff_veq] at h, have h2 := x.2, replace h2 : x.1 ≤ n.succ := fin.le_last x, -- have h3 : x.1 < n.succ := lt_of_le_of_ne h2 h, -- have H := h1 ⟨x.1, h3⟩, simp only [fin.eta] at H, exact H, -- }, -- { -- intros x1 x2 hx, cases x1 with p1 x1, cases x2 with p2 x2, -- ext, swap, simp only [], simp only [gn, id.def] at hx, rw function.funext_iff at hx, -- generalize hm : (⟨n.succ, nat.lt_succ_self n.succ⟩ : fin n.succ.succ) = m, -- have hm' : m.val = n.succ, rw <-hm, replace hx := hx m, simp only [hm', dif_pos] at hx, assumption, -- simp only [], simp only [gn, id.def] at hx, rw function.funext_iff at hx, -- generalize hm : (⟨x.1, nat.lt_trans x.2 (nat.lt_succ_self n.succ)⟩ : fin n.succ.succ) = m, -- replace hx := hx m, have hm' : m.1 ≠ n.succ, -- intro a, rw <-hm at a, simp only [] at a, have hx' := x.2, linarith, -- simp only [hm', dif_neg, not_false_iff] at hx, have hm2 := m.2, replace hm2 : m.1 ≤ n.succ, exact fin.le_last m, -- have hm3 : m.1 < n.succ, exact lt_of_le_of_ne hm2 hm', -- have H : x = ⟨m.1, hm3⟩, rw fin.ext_iff at hm ⊢, simp only [] at hm ⊢, exact hm, -- rw H, exact hx, -- }, -- end -- def fn' {n : nat} : rat_n' (nat.succ (nat.succ n)) -> rat_n (nat.succ n) × rat := -- begin -- intro p, split, intro m, -- exact p.1 (⟨m.1, nat.lt_trans m.2 (nat.lt_succ_self n.succ)⟩ : fin n.succ.succ), -- exact p.1 (⟨n.succ, nat.lt_succ_self n.succ⟩ : fin n.succ.succ), -- end -- def gn' {n : nat} : rat_n (nat.succ n) × rat -> rat_n' (nat.succ (nat.succ n)) := -- begin -- intro x, -- split, swap 2, intro m, -- by_cases (m.1 = n.succ), exact (strange_fun x.2).1, -- have H2 : m.1 < n.succ, have H2' := fin.le_last m, exact lt_of_le_of_ne H2' h, -- exact (strange_fun (x.1 ⟨m.1, H2⟩)).1, -- intro a, rw function.funext_iff at a, simp only [pi.zero_apply, subtype.val_eq_coe] at a, -- generalize hm : (⟨n.succ, nat.lt_succ_self n.succ⟩ : fin n.succ.succ) = m, -- have a' := a m, have h : m.1 = n.succ, rw <-hm, simp only [h, dif_pos] at a', exact (strange_fun x.2).2 a', -- end -- theorem aux_rat_n' (n : nat) : rat_n' (nat.succ (nat.succ n)) ≃ rat_n (nat.succ n) × rat := -- begin -- suffices H1 : ∃ f : rat_n' n.succ.succ -> rat_n n.succ × rat, function.bijective f, -- choose h hh using H1, -- exact equiv.of_bijective h hh, -- suffices H2 : ∃ f : rat_n' n.succ.succ -> rat_n n.succ × rat, ∃ g : rat_n n.succ × rat -> rat_n' n.succ.succ, function.injective f ∧ function.injective g, -- choose f g h using H2, exact function.embedding.schroeder_bernstein h.1 h.2, -- use fn', use gn', split, -- { -- intros x1 x2 hx, simp only [fn', id.def, prod.mk.inj_iff, subtype.val_eq_coe] at hx, cases hx with h1 h2, rw function.funext_iff at h1, -- apply subtype.eq, ext m, -- by_cases (m.val = n.succ), -- have H1 : m = (⟨n.succ, (nat.lt_succ_self n.succ)⟩ : fin n.succ.succ), -- rw fin.ext_iff, simp only [], exact h, -- rw H1, assumption, -- have H2 : m.1 < n.succ, have H2' := fin.le_last m, exact lt_of_le_of_ne H2' h, -- have h1m := h1 ⟨m.1, H2⟩, simp only [fin.eta] at h1m, exact h1m, -- }, -- { -- intros x1 x2 hx, simp only [gn', subtype.mk_eq_mk, subtype.val_eq_coe] at hx, ext, rename x m, -- generalize hm' : (⟨m.1, nat.lt_trans m.2 (nat.lt_succ_self n.succ)⟩ : fin n.succ.succ) = m', -- have hm'' : m'.val = m.1, rw <-hm', -- have Hm' : m'.val ≠ n.succ, have Hm'' := ne_of_lt m.2, rw <-hm'' at Hm'', assumption, -- rw function.funext_iff at hx, have H := hx m', simp only [hm'', Hm', dif_neg, not_false_iff, fin.eta] at H, -- split_ifs at H, -- replace H := subtype.eq H, -- exact congr_fun (false.rec (x1.fst = λ (m : fin n.succ), x2.fst m) (Hm' h)) m, replace H := subtype.eq H, exact strange_fun_inj H, -- generalize hm : (⟨n.succ, nat.lt_succ_self n.succ⟩ : fin n.succ.succ) = m, -- have Hm : m.val = n.succ, rw <-hm, rw function.funext_iff at hx, -- have H := hx m, simp only [Hm, dif_pos] at H, replace H := subtype.eq H, -- exact strange_fun_inj H, -- } -- end -- theorem rat_n_equiv_rat_n' (n : nat) : rat_n n.succ ≃ rat_n' n.succ := -- begin -- induction n with n hn, -- exact rat_1_equiv_rat_1', -- suffices H1 : rat_n n.succ.succ ≃ rat_n n.succ × rat, -- suffices H2 : rat_n' n.succ.succ ≃ rat_n' n.succ × rat', -- have e1 : rat_n n.succ × rat ≃ rat_n' n.succ × rat', apply equiv.prod_congr, -- exact hn, exact rat_equiv_rat', -- exact equiv.trans (equiv.trans H1 e1) H2.symm, swap, exact aux_rat_n n, -- have e2 := aux_rat_n' n, suffices H3 : rat_n (nat.succ n) × rat ≃ rat_n' (nat.succ n) × rat', exact equiv.trans e2 H3, -- apply equiv.prod_congr, exact hn, exact rat_equiv_rat', -- end -- def algebraic_set'_n (n : nat) : set real := ⋃ p : (poly_n' n.succ), roots_real p.1 -- def algebraic_set' : set real := ⋃ n : nat, algebraic_set'_n n.succ -- theorem algebraic_set'_eq_algebraic_set : algebraic_set' = algebraic_set := -- begin -- ext, split; intro hx, -- { -- rw [algebraic_set', set.mem_Union] at hx, -- choose n hx using hx, -- rw [algebraic_set'_n, set.mem_Union] at hx, -- choose p hp using hx, rw [roots_real, set.mem_set_of_eq] at hp, -- rw [algebraic_set, set.mem_set_of_eq, is_algebraic], -- use p.val, split, exact p.2.1,assumption -- }, -- { -- rw [algebraic_set, set.mem_set_of_eq] at hx, -- choose p hp using hx, -- cases hp with p_ne_0 p_x_0, -- rw [algebraic_set', set.mem_Union], -- use p.nat_degree.succ, rw [algebraic_set'_n, set.mem_Union], -- use p, split, exact p_ne_0, -- { -- suffices h1 : p.nat_degree < p.nat_degree.succ, -- suffices h2 : p.nat_degree.succ < p.nat_degree.succ.succ, -- suffices h3 : p.nat_degree.succ.succ < p.nat_degree.succ.succ.succ, -- exact lt.trans (lt.trans h1 h2) h3, -- exact lt_add_one p.nat_degree.succ.succ, exact lt_add_one (nat.succ (polynomial.nat_degree p)), -- exact lt_add_one (polynomial.nat_degree p), -- }, -- simpa only [], -- }, -- done -- end -- theorem poly_n'_1_coeff_ne_0 (q : poly_n' 1) : q.1.coeff 0 ≠ 0 := -- begin -- have h := q.2, -- cases h with h1 h2, -- have h : q.1 = polynomial.C (q.1.coeff 0), ext, -- by_cases (n = 0), rw h, simp only [polynomial.coeff_C_zero], -- rw polynomial.coeff_C, simp only [h, if_false], rw polynomial.coeff_eq_zero_of_nat_degree_lt, -- suffices H : 1 ≤ n, linarith, replace h : n ≠ 0 := h, rw <-nat.lt_one_add_iff, norm_num, exact zero_lt_iff_ne_zero.mpr h, -- rw h, simp only [polynomial.coeff_C_zero, ne.def], intro absurd, conv_rhs at h {rw absurd}, suffices H2 : polynomial.C (0 : rat) = 0, conv_rhs at h {rw H2}, exact h1 h, -- ext, simp only [ring_hom.map_zero], -- end -- def identify'_1 : (poly_n' 1) -> rat' := -- begin -- intro q, split, swap, exact q.1.coeff 0, exact poly_n'_1_coeff_ne_0 q, -- end -- theorem rat_1_equiv_rat : rat_n 1 ≃ rat := -- begin -- constructor, swap 3, { -- intro f, exact f ⟨0, by linarith⟩, -- }, swap 3, { -- intros r m, exact r, -- }, { -- intros x, simp only [id.def], ext, rename x_1 m, -- have hm' : m.1 = 0, have hm1 := m.2, linarith, -- have hm : m = ⟨0, by linarith⟩, rw fin.ext_iff, simp only [], exact hm', rw hm, -- }, { -- intros x, simp only [id.def], -- } -- end -- theorem rat_n_denumerable {n : nat} : denumerable (rat_n n.succ) := -- begin -- induction n with n hn, -- apply denumerable.mk', suffices H : rat_n 1 ≃ rat, apply equiv.trans H, exact denumerable.eqv rat, -- exact rat_1_equiv_rat, -- apply denumerable.mk', -- have Hn := @denumerable.eqv (rat_n (nat.succ n)) hn, -- have e1 := aux_rat_n n, suffices H : rat_n (nat.succ n) × ℚ ≃ nat, exact equiv.trans e1 H, -- have e2 : rat_n (nat.succ n) × ℚ ≃ nat × rat, apply equiv.prod_congr, exact Hn, refl, -- suffices H : ℕ × ℚ ≃ nat, exact equiv.trans e2 H, exact denumerable.eqv (ℕ × ℚ), -- end -- theorem poly_n'_denumerable (n : nat) : denumerable (poly_n' n.succ) := -- begin -- apply denumerable.mk', -- suffices e1 : rat_n' n.succ ≃ nat, exact equiv.trans (poly_n'_equiv_rat_n' n) e1, -- suffices e2 : rat_n n.succ ≃ nat, exact equiv.trans (rat_n_equiv_rat_n' n).symm e2, -- exact @denumerable.eqv _ (rat_n_denumerable), -- done -- end -- theorem algebraic_set'_n_countable (n : nat) : set.countable $ algebraic_set'_n n := -- begin -- rw algebraic_set'_n, -- have h := @set.countable_Union (poly_n' n.succ) real (fun p, roots_real p.1) (poly_n'_denumerable n).1, -- simp only [subtype.val_eq_coe] at h, apply h, -- intro q, apply set.finite.countable, exact roots_finite q.1 q.2.1, -- done -- end -- theorem algebraic_set'_countable : set.countable algebraic_set' := -- begin -- apply set.countable_Union, -- intro n, exact algebraic_set'_n_countable n.succ, -- end -- theorem countable_algebraic_set : set.countable algebraic_set := -- begin -- rw <-algebraic_set'_eq_algebraic_set, exact algebraic_set'_countable, done -- end -- def real_set : set real := @set.univ real -- theorem transcendental_number_exists : ∃ x : real, ¬ (is_algebraic rat x) := -- begin -- have H : algebraic_set ≠ real_set, -- { -- intro h1, -- have h2 : set.countable real_set, -- { -- rw <-h1, exact countable_algebraic_set, -- }, -- have h3 : ¬ set.countable real_set := cardinal.not_countable_real, -- exact h3 h2, -- }, -- rw [ne.def, set.ext_iff, not_forall] at H, -- choose x Hx using H, -- rw not_iff at Hx, -- replace Hx := Hx.mpr, -- use x, -- exact Hx trivial, -- done -- end -- end project
b371e6741173570f6b7c3e5912169860f055e0cf
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/simp32.lean
d146ef5d24094058ed3a8c268c0205527f2407e6
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
1,678
lean
variable vec : Nat → Type variable concat {n m : Nat} (v : vec n) (w : vec m) : vec (n + m) infixl 65 ; : concat axiom concat_assoc {n1 n2 n3 : Nat} (v1 : vec n1) (v2 : vec n2) (v3 : vec n3) : (v1 ; v2) ; v3 = cast (to_heq (congr2 vec (symm (Nat::add_assoc n1 n2 n3)))) (v1 ; (v2 ; v3)) variable empty : vec 0 axiom concat_empty {n : Nat} (v : vec n) : v ; empty = cast (to_heq (congr2 vec (symm (Nat::add_zeror n)))) v rewrite_set simple add_rewrite Nat::add_assoc Nat::add_zeror eq_id : simple add_rewrite concat_assoc concat_empty Nat::add_assoc Nat::add_zeror : simple variable f {A : Type} : A → A (* local opts = options({"simplifier", "heq"}, true) local m = simplifier_monitor(nil, nil, nil, function (s, e, i, k) print("App simplification failure, argument #" .. i) print("Kind: " .. k) print("-----------") end, function (s, e, ceq, ceq_id, i, k) print("Rewrite failure: " .. tostring(e)) end, function (s, e, k) print("Abst failure: " .. tostring(e)) end ) local s = simplifier("simple", opts, m) local t = parse_lean('λ val : Nat, (λ n : Nat, λ v : vec (n + 0), (f v) ; empty) val == (λ n : Nat, λ v : vec (n + 0), v) val') print(t) print("=====>") local t2, pr = s(t) print(t2) -- print(pr) get_environment():type_check(pr) *)
88b6850637be1e5d26720955becd3d6ceac01491
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/arity.hlean
1c69dc0476f3f4d4e9902201b4f36d8b6a647031
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
12,680
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Theorems about functions with multiple arguments -/ variables {A U V W X Y Z : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {E : Πa b c, D a b c → Type} {F : Πa b c d, E a b c d → Type} {G : Πa b c d e, F a b c d e → Type} {H : Πa b c d e f, G a b c d e f → Type} variables {a a' : A} {u u' : U} {v v' : V} {w w' : W} {x x' x'' : X} {y y' : Y} {z z' : Z} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} {d : D a b c} {d' : D a' b' c'} {e : E a b c d} {e' : E a' b' c' d'} {ff : F a b c d e} {f' : F a' b' c' d' e'} {g : G a b c d e ff} {g' : G a' b' c' d' e' f'} {h : H a b c d e ff g} {h' : H a' b' c' d' e' f' g'} namespace eq /- Naming convention: The theorem which states how to construct an path between two function applications is api₀i₁...iₙ. Here i₀, ... iₙ are digits, n is the arity of the function(s), and iⱼ specifies the dimension of the path between the jᵗʰ argument (i₀ specifies the dimension of the path between the functions). A value iⱼ ≡ 0 means that the jᵗʰ arguments are definitionally equal The functions are non-dependent, except when the theorem name contains trailing zeroes (where the function is dependent only in the arguments where it doesn't result in any transports in the theorem statement). For the fully-dependent versions (except that the conclusion doesn't contain a transport) we write apdi₀i₁...iₙ. For versions where only some arguments depend on some other arguments, or for versions with transport in the conclusion (like apdt), we don't have a consistent naming scheme (yet). We don't prove each theorem systematically, but prove only the ones which we actually need. -/ definition homotopy2 [reducible] (f g : Πa b, C a b) : Type := Πa b, f a b = g a b definition homotopy3 [reducible] (f g : Πa b c, D a b c) : Type := Πa b c, f a b c = g a b c definition homotopy4 [reducible] (f g : Πa b c d, E a b c d) : Type := Πa b c d, f a b c d = g a b c d infix ` ~2 `:50 := homotopy2 infix ` ~3 `:50 := homotopy3 definition homotopy2.refl {A} {B : A → Type} {C : Π⦃a⦄, B a → Type} (f : Πa (b : B a), C b) : f ~2 f := λa b, idp definition homotopy2.rfl [refl] {A} {B : A → Type} {C : Π⦃a⦄, B a → Type} {f : Πa (b : B a), C b} : f ~2 f := λa b, idp definition homotopy3.refl {A} {B : A → Type} {C : Πa, B a → Type} {D : Π⦃a⦄ ⦃b : B a⦄, C a b → Type} (f : Πa b (c : C a b), D c) : f ~3 f := λa b c, idp definition homotopy3.rfl {A} {B : A → Type} {C : Πa, B a → Type} {D : Π⦃a⦄ ⦃b : B a⦄, C a b → Type} {f : Πa b (c : C a b), D c} : f ~3 f := λa b c, idp definition ap0111 (f : U → V → W → X) (Hu : u = u') (Hv : v = v') (Hw : w = w') : f u v w = f u' v' w' := by cases Hu; congruence; repeat assumption definition ap01111 (f : U → V → W → X → Y) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') : f u v w x = f u' v' w' x' := by cases Hu; congruence; repeat assumption definition ap011111 (f : U → V → W → X → Y → Z) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') : f u v w x y = f u' v' w' x' y' := by cases Hu; congruence; repeat assumption definition ap0111111 (f : U → V → W → X → Y → Z → A) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') (Hz : z = z') : f u v w x y z = f u' v' w' x' y' z' := by cases Hu; congruence; repeat assumption definition ap010 [unfold 7] (f : X → Πa, B a) (Hx : x = x') : f x ~ f x' := by intros; cases Hx; reflexivity definition ap0100 [unfold 8] (f : X → Πa b, C a b) (Hx : x = x') : f x ~2 f x' := by intros; cases Hx; reflexivity definition ap01000 [unfold 9] (f : X → Πa b c, D a b c) (Hx : x = x') : f x ~3 f x' := by intros; cases Hx; reflexivity definition apdt011 (f : Πa, B a → Z) (Ha : a = a') (Hb : transport B Ha b = b') : f a b = f a' b' := by cases Ha; cases Hb; reflexivity definition apdt0111 (f : Πa b, C a b → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apdt011 C Ha Hb) c = c') : f a b c = f a' b' c' := by cases Ha; cases Hb; cases Hc; reflexivity definition apdt01111 (f : Πa b c, D a b c → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d') : f a b c d = f a' b' c' d' := by cases Ha; cases Hb; cases Hc; cases Hd; reflexivity definition apdt011111 (f : Πa b c d, E a b c d → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d') (He : cast (apdt01111 E Ha Hb Hc Hd) e = e') : f a b c d e = f a' b' c' d' e' := by cases Ha; cases Hb; cases Hc; cases Hd; cases He; reflexivity definition apdt0111111 (f : Πa b c d e, F a b c d e → Z) (Ha : a = a') (Hb : transport B Ha b = b') (Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d') (He : cast (apdt01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apdt011111 F Ha Hb Hc Hd He) ff = f') : f a b c d e ff = f a' b' c' d' e' f' := begin cases Ha, cases Hb, cases Hc, cases Hd, cases He, cases Hf, reflexivity end -- definition apd0111111 (f : Πa b c d e ff, G a b c d e ff → Z) (Ha : a = a') (Hb : transport B Ha b = b') -- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') -- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') -- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') -- : f a b c d e ff g = f a' b' c' d' e' f' g' := -- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; reflexivity -- definition apd01111111 (f : Πa b c d e ff g, G a b c d e ff g → Z) (Ha : a = a') (Hb : transport B Ha b = b') -- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d') -- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f') -- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') (Hh : cast (apd01111111 H Ha Hb Hc Hd He Hf Hg) h = h') -- : f a b c d e ff g h = f a' b' c' d' e' f' g' h' := -- by cases Ha; cases Hb; cases Hc; cases Hd; cases He; cases Hf; cases Hg; cases Hh; reflexivity definition apd100 [unfold 6] {f g : Πa b, C a b} (p : f = g) : f ~2 g := λa b, apd10 (apd10 p a) b definition apd1000 [unfold 7] {f g : Πa b c, D a b c} (p : f = g) : f ~3 g := λa b c, apd100 (apd10 p a) b c /- some properties of these variants of ap -/ -- we only prove what we currently need definition ap010_con (f : X → Πa, B a) (p : x = x') (q : x' = x'') : ap010 f (p ⬝ q) a = ap010 f p a ⬝ ap010 f q a := eq.rec_on q (eq.rec_on p idp) definition ap010_ap (f : X → Πa, B a) (g : Y → X) (p : y = y') : ap010 f (ap g p) a = ap010 (λy, f (g y)) p a := eq.rec_on p idp definition ap_eq_ap010 {A B C : Type} (f : A → B → C) {a a' : A} (p : a = a') (b : B) : ap (λa, f a b) p = ap010 f p b := by reflexivity definition ap011_idp {A B C : Type} (f : A → B → C) {a a' : A} (p : a = a') (b : B) : ap011 f p idp = ap010 f p b := by reflexivity definition ap011_flip {A B C : Type} (f : A → B → C) {a a' : A} {b b' : B} (p : a = a') (q : b = b') : ap011 f p q = ap011 (λb a, f a b) q p := by induction q; induction p; reflexivity /- the following theorems are function extentionality for functions with multiple arguments -/ definition eq_of_homotopy2 {f g : Πa b, C a b} (H : f ~2 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy (H a)) definition eq_of_homotopy3 {f g : Πa b c, D a b c} (H : f ~3 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy2 (H a)) definition eq_of_homotopy2_id (f : Πa b, C a b) : eq_of_homotopy2 (λa b, idpath (f a b)) = idpath f := begin transitivity eq_of_homotopy (λ a, idpath (f a)), {apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy_idp}, apply eq_of_homotopy_idp end definition eq_of_homotopy3_id (f : Πa b c, D a b c) : eq_of_homotopy3 (λa b c, idpath (f a b c)) = idpath f := begin transitivity _, {apply (ap eq_of_homotopy), apply eq_of_homotopy, intros, apply eq_of_homotopy2_id}, apply eq_of_homotopy_idp end definition eq_of_homotopy2_inv {f g : Πa b, C a b} (H : f ~2 g) : eq_of_homotopy2 (λa b, (H a b)⁻¹) = (eq_of_homotopy2 H)⁻¹ := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_inv)) ⬝ !eq_of_homotopy_inv definition eq_of_homotopy3_inv {f g : Πa b c, D a b c} (H : f ~3 g) : eq_of_homotopy3 (λa b c, (H a b c)⁻¹) = (eq_of_homotopy3 H)⁻¹ := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_inv)) ⬝ !eq_of_homotopy_inv definition eq_of_homotopy2_con {f g h : Πa b, C a b} (H1 : f ~2 g) (H2 : g ~2 h) : eq_of_homotopy2 (λa b, H1 a b ⬝ H2 a b) = eq_of_homotopy2 H1 ⬝ eq_of_homotopy2 H2 := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy_con)) ⬝ !eq_of_homotopy_con definition eq_of_homotopy3_con {f g h : Πa b c, D a b c} (H1 : f ~3 g) (H2 : g ~3 h) : eq_of_homotopy3 (λa b c, H1 a b c ⬝ H2 a b c) = eq_of_homotopy3 H1 ⬝ eq_of_homotopy3 H2 := ap eq_of_homotopy (eq_of_homotopy (λa, !eq_of_homotopy2_con)) ⬝ !eq_of_homotopy_con definition ap_apd0111 {A₁ A₂ A₃ : Type} {B : A₁ → Type} {C : Π⦃a⦄, B a → Type} {a a₂ : A₁} {b : B a} {b₂ : B a₂} {c : C b} {c₂ : C b₂} (g : A₂ → A₃) (f : Πa b, C b → A₂) (Ha : a = a₂) (Hb : b =[Ha] b₂) (Hc : c =[apd011 C Ha Hb] c₂) : ap g (apd0111 f Ha Hb Hc) = apd0111 (λa b c, (g (f a b c))) Ha Hb Hc := by induction Hb; induction Hc using idp_rec_on; reflexivity end eq open eq equiv is_equiv namespace funext definition is_equiv_apd100 [instance] (f g : Πa b, C a b) : is_equiv (@apd100 A B C f g) := adjointify _ eq_of_homotopy2 begin intro H, esimp [apd100, eq_of_homotopy2], apply eq_of_homotopy, intro a, apply concat, apply (ap (λx, apd10 (x a))), apply (right_inv apd10), apply (right_inv apd10) end begin intro p, cases p, apply eq_of_homotopy2_id end definition is_equiv_apd1000 [instance] (f g : Πa b c, D a b c) : is_equiv (@apd1000 A B C D f g) := adjointify _ eq_of_homotopy3 begin intro H, esimp, apply eq_of_homotopy, intro a, transitivity apd100 (eq_of_homotopy2 (H a)), {apply ap (λx, apd100 (x a)), apply right_inv apd10}, apply right_inv apd100 end begin intro p, cases p, apply eq_of_homotopy3_id end end funext attribute funext.is_equiv_apd100 funext.is_equiv_apd1000 [constructor] namespace eq open funext local attribute funext.is_equiv_apd100 [instance] protected definition homotopy2.rec_on {f g : Πa b, C a b} {P : (f ~2 g) → Type} (p : f ~2 g) (H : Π(q : f = g), P (apd100 q)) : P p := right_inv apd100 p ▸ H (eq_of_homotopy2 p) protected definition homotopy3.rec_on {f g : Πa b c, D a b c} {P : (f ~3 g) → Type} (p : f ~3 g) (H : Π(q : f = g), P (apd1000 q)) : P p := right_inv apd1000 p ▸ H (eq_of_homotopy3 p) definition eq_equiv_homotopy2 [constructor] (f g : Πa b, C a b) : (f = g) ≃ (f ~2 g) := equiv.mk apd100 _ definition eq_equiv_homotopy3 [constructor] (f g : Πa b c, D a b c) : (f = g) ≃ (f ~3 g) := equiv.mk apd1000 _ definition apd10_ap (f : X → Πa, B a) (p : x = x') : apd10 (ap f p) = ap010 f p := eq.rec_on p idp definition eq_of_homotopy_ap010 (f : X → Πa, B a) (p : x = x') : eq_of_homotopy (ap010 f p) = ap f p := inv_eq_of_eq !apd10_ap⁻¹ definition ap_eq_ap_of_homotopy {f : X → Πa, B a} {p q : x = x'} (H : ap010 f p ~ ap010 f q) : ap f p = ap f q := calc ap f p = eq_of_homotopy (ap010 f p) : eq_of_homotopy_ap010 ... = eq_of_homotopy (ap010 f q) : eq_of_homotopy H ... = ap f q : eq_of_homotopy_ap010 end eq
ebdb574e70f07e8b9d372671a089c1355aff4f26
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/inner_product_space/euclidean_dist.lean
3fbd0fbeb4f4da2c7242f322528cb530ba5f5d9a
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,651
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.inner_product_space.calculus import analysis.inner_product_space.pi_L2 /-! # Euclidean distance on a finite dimensional space When we define a smooth bump function on a normed space, it is useful to have a smooth distance on the space. Since the default distance is not guaranteed to be smooth, we define `to_euclidean` to be an equivalence between a finite dimensional normed space and the standard Euclidean space of the same dimension. Then we define `euclidean.dist x y = dist (to_euclidean x) (to_euclidean y)` and provide some definitions (`euclidean.ball`, `euclidean.closed_ball`) and simple lemmas about this distance. This way we hide the usage of `to_euclidean` behind an API. -/ open_locale topological_space open set variables {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] noncomputable theory /-- If `E` is a finite dimensional space over `ℝ`, then `to_euclidean` is a continuous `ℝ`-linear equivalence between `E` and the Euclidean space of the same dimension. -/ def to_euclidean : E ≃L[ℝ] euclidean_space ℝ (fin $ finite_dimensional.finrank ℝ E) := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm namespace euclidean /-- If `x` and `y` are two points in a finite dimensional space over `ℝ`, then `euclidean.dist x y` is the distance between these points in the metric defined by some inner product space structure on `E`. -/ def dist (x y : E) : ℝ := dist (to_euclidean x) (to_euclidean y) /-- Closed ball w.r.t. the euclidean distance. -/ def closed_ball (x : E) (r : ℝ) : set E := {y | dist y x ≤ r} /-- Open ball w.r.t. the euclidean distance. -/ def ball (x : E) (r : ℝ) : set E := {y | dist y x < r} lemma ball_eq_preimage (x : E) (r : ℝ) : ball x r = to_euclidean ⁻¹' (metric.ball (to_euclidean x) r) := rfl lemma closed_ball_eq_preimage (x : E) (r : ℝ) : closed_ball x r = to_euclidean ⁻¹' (metric.closed_ball (to_euclidean x) r) := rfl lemma ball_subset_closed_ball {x : E} {r : ℝ} : ball x r ⊆ closed_ball x r := λ y (hy : _ < _), le_of_lt hy lemma is_open_ball {x : E} {r : ℝ} : is_open (ball x r) := metric.is_open_ball.preimage to_euclidean.continuous lemma mem_ball_self {x : E} {r : ℝ} (hr : 0 < r) : x ∈ ball x r := metric.mem_ball_self hr lemma closed_ball_eq_image (x : E) (r : ℝ) : closed_ball x r = to_euclidean.symm '' metric.closed_ball (to_euclidean x) r := by rw [to_euclidean.image_symm_eq_preimage, closed_ball_eq_preimage] lemma is_compact_closed_ball {x : E} {r : ℝ} : is_compact (closed_ball x r) := begin rw closed_ball_eq_image, exact (is_compact_closed_ball _ _).image to_euclidean.symm.continuous end lemma is_closed_closed_ball {x : E} {r : ℝ} : is_closed (closed_ball x r) := is_compact_closed_ball.is_closed lemma closure_ball (x : E) {r : ℝ} (h : r ≠ 0) : closure (ball x r) = closed_ball x r := by rw [ball_eq_preimage, ← to_euclidean.preimage_closure, closure_ball (to_euclidean x) h, closed_ball_eq_preimage] lemma exists_pos_lt_subset_ball {R : ℝ} {s : set E} {x : E} (hR : 0 < R) (hs : is_closed s) (h : s ⊆ ball x R) : ∃ r ∈ Ioo 0 R, s ⊆ ball x r := begin rw [ball_eq_preimage, ← image_subset_iff] at h, rcases exists_pos_lt_subset_ball hR (to_euclidean.is_closed_image.2 hs) h with ⟨r, hr, hsr⟩, exact ⟨r, hr, image_subset_iff.1 hsr⟩ end lemma nhds_basis_closed_ball {x : E} : (𝓝 x).has_basis (λ r : ℝ, 0 < r) (closed_ball x) := begin rw [to_euclidean.to_homeomorph.nhds_eq_comap], exact metric.nhds_basis_closed_ball.comap _ end lemma closed_ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : closed_ball x r ∈ 𝓝 x := nhds_basis_closed_ball.mem_of_mem hr lemma nhds_basis_ball {x : E} : (𝓝 x).has_basis (λ r : ℝ, 0 < r) (ball x) := begin rw [to_euclidean.to_homeomorph.nhds_eq_comap], exact metric.nhds_basis_ball.comap _ end lemma ball_mem_nhds {x : E} {r : ℝ} (hr : 0 < r) : ball x r ∈ 𝓝 x := nhds_basis_ball.mem_of_mem hr end euclidean variables {F : Type*} [normed_group F] [normed_space ℝ F] {f g : F → E} {n : with_top ℕ} lemma cont_diff.euclidean_dist (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g) (h : ∀ x, f x ≠ g x) : cont_diff ℝ n (λ x, euclidean.dist (f x) (g x)) := begin simp only [euclidean.dist], apply @cont_diff.dist ℝ, exacts [(@to_euclidean E _ _ _).cont_diff.comp hf, (@to_euclidean E _ _ _).cont_diff.comp hg, λ x, to_euclidean.injective.ne (h x)] end
2aedec20b597e5f117fc34eaecf0c6509970b09a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/playground/deriving.lean
5fd55065e24637c4d42234ac6b90765c1d8ec3ef
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
11,295
lean
import Lean mutual inductive Vect (α : Type u) (β : Type v) : Nat → Nat → Type max u v where | nil : Vect α β 0 0 | lst : List (Array (Vect α β 0 0)) → Vect α β 0 0 | cons1 : {n m : Nat} → TreeV α β n → Vect α β n m → Vect α β (n+1) m | cons2 : {n m : Nat} → TreeV α β m → Vect α β n m → Vect α β n (m+1) inductive TreeV (α : Type u) (β : Type v) : Nat → Type max u v where | diag : {n : Nat} → Vect α β n n → TreeV α β n | lower : {n m : Nat} → n < m → Vect α β n m → TreeV α β m end mutual partial def aux1 {α β m n} [ToString α] [ToString β] (s : Vect α β m n) : String := let inst1 {m' n' : Nat} : ToString (Vect α β m' n') := ⟨aux1⟩ let inst1 {n' : Nat} : ToString (TreeV α β n') := ⟨aux2⟩ match m, n, s with | _, _, Vect.nil => "nil" | _, _, Vect.lst xs => "lst " ++ toString xs | _, _, Vect.cons1 t v => "cons1 " ++ toString t ++ " " ++ toString v | _, _, Vect.cons2 t v => "cons2 " ++ toString t ++ " " ++ toString v partial def aux2 {α β n} [ToString α] [ToString β] (s : TreeV α β n) : String := let inst1 {m' n' : Nat} : ToString (Vect α β m' n') := ⟨aux1⟩ let inst1 {n' : Nat} : ToString (TreeV α β n') := ⟨aux2⟩ match n, s with | _, TreeV.diag v => "diag " ++ toString v | _, TreeV.lower _ v => "lower " ++ "<proof>" ++ " " ++ toString v end instance {α β m n} [ToString α] [ToString β] : ToString (Vect α β m n) where toString := aux1 instance {α β n} [ToString α] [ToString β] : ToString (TreeV α β n) where toString := aux2 namespace Test mutual inductive Foo (α : Type) where | mk : List (Bla α) → Foo α | leaf : α → Foo α inductive Bla (α : Type) where | nil : Bla α | cons : Foo α → Bla α → Bla α end open Lean open Lean.Meta def tst : MetaM Unit := do let info ← getConstInfoInduct `Test.Bla trace[Meta.debug] "nested: {info.isNested}" pure () #eval tst mutual partial def fooToString {α : Type} [ToString α] (s : Foo α) : String := let inst1 : ToString (Bla α) := ⟨blaToString⟩ match s with | Foo.mk bs => "Foo.mk " ++ toString bs | Foo.leaf a => "Foo.leaf " ++ toString a partial def blaToString {α : Type} [ToString α] (s : Bla α) : String := let inst1 : ToString (Bla α) := ⟨blaToString⟩ let inst2 : ToString (Foo α) := ⟨fooToString⟩ match s with | Bla.nil => "Bla.nil" | Bla.cons h t => "Bla.cons (" ++ toString h ++ ") " ++ toString t end instance [ToString α] : ToString (Foo α) where toString := fooToString instance [ToString α] : ToString (Bla α) where toString := blaToString #eval Foo.mk [Bla.cons (Foo.leaf 10) Bla.nil] end Test namespace Lean.Elab open Meta namespace Deriving /- For type classes such as BEq, ToString, Format -/ namespace Default structure ContextCore where classInfo : ConstantInfo typeInfos : Array InductiveVal auxFunNames : Array Name usePartial : Bool resultType : Syntax structure Header where binders : Array Syntax argNames : Array Name targetName : Name abbrev MkAltRhs := ContextCore → (ctorName : Name) → (ctorArgs : Array (Syntax × Expr)) → TermElabM Syntax structure Context extends ContextCore where mkAltRhs : MkAltRhs def mkContext (className : Name) (typeName : Name) (resultType : Syntax) (mkAltRhs : MkAltRhs) : TermElabM Context := do let indVal ← getConstInfoInduct typeName let mut typeInfos := #[] for typeName in indVal.all do typeInfos ← typeInfos.push (← getConstInfoInduct typeName) let classInfo ← getConstInfo className let mut auxFunNames := #[] for typeName in indVal.all do match className.eraseMacroScopes, typeName.eraseMacroScopes with | Name.str _ c _, Name.str _ t _ => auxFunNames := auxFunNames.push (← mkFreshUserName <| Name.mkSimple <| c.decapitalize ++ t) | _, _ => auxFunNames := auxFunNames.push (← mkFreshUserName `instFn) trace[Meta.debug] "{auxFunNames}" let usePartial := indVal.isNested || typeInfos.size > 1 return { classInfo := classInfo typeInfos := typeInfos auxFunNames := auxFunNames usePartial := usePartial resultType := resultType mkAltRhs := mkAltRhs } def mkInductArgNames (indVal : InductiveVal) : TermElabM (Array Name) := do forallTelescopeReducing indVal.type fun xs _ => do let mut argNames := #[] for x in xs do let localDecl ← getLocalDecl x.fvarId! let paramName ← mkFreshUserName localDecl.userName.eraseMacroScopes argNames := argNames.push paramName pure argNames def mkInductiveApp (indVal : InductiveVal) (argNames : Array Name) : TermElabM Syntax := let f := mkIdent indVal.name let args := argNames.map mkIdent `(@$f $args*) def implicitBinderF := Parser.Term.implicitBinder def instBinderF := Parser.Term.instBinder def explicitBinderF := Parser.Term.explicitBinder def mkImplicitBinders (argNames : Array Name) : TermElabM (Array Syntax) := argNames.mapM fun argName => `(implicitBinderF| { $(mkIdent argName) }) def mkInstImplicitBinders (ctx : Context) (indVal : InductiveVal) (argNames : Array Name) : TermElabM (Array Syntax) := forallBoundedTelescope indVal.type indVal.nparams fun xs _ => do let mut binders := #[] for i in [:xs.size] do try let x := xs[i] let clsName := ctx.classInfo.name let c ← mkAppM clsName #[x] if (← isTypeCorrect c) then let argName := argNames[i] let binder ← `(instBinderF| [ $(mkIdent clsName):ident $(mkIdent argName):ident ]) binders := binders.push binder catch _ => pure () return binders def mkHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do let argNames ← mkInductArgNames indVal let binders ← mkImplicitBinders argNames let targetType ← mkInductiveApp indVal argNames let targetName ← mkFreshUserName `x let targetBinder ← `(explicitBinderF| ($(mkIdent targetName) : $targetType)) let binders := binders ++ (← mkInstImplicitBinders ctx indVal argNames) let binders := binders.push targetBinder return { binders := binders argNames := argNames targetName := targetName } def mkLocalInstanceLetDecls (ctx : Context) (argNames : Array Name) : TermElabM (Array Syntax) := do let mut letDecls := #[] for i in [:ctx.typeInfos.size] do let indVal := ctx.typeInfos[i] let auxFunName := ctx.auxFunNames[i] let currArgNames ← mkInductArgNames indVal let numParams := indVal.nparams let currIndices := currArgNames[numParams:] let binders ← mkImplicitBinders currIndices let argNamesNew := argNames[:numParams] ++ currIndices let indType ← mkInductiveApp indVal argNamesNew let type ← `($(mkIdent ctx.classInfo.name) $indType) let val ← `(⟨$(mkIdent auxFunName)⟩) let instName ← mkFreshUserName `localinst let letDecl ← `(Parser.Term.letDecl| $(mkIdent instName):ident $binders:implicitBinder* : $type := $val) letDecls := letDecls.push letDecl return letDecls def mkLet (letDecls : Array Syntax) (body : Syntax) : TermElabM Syntax := letDecls.foldrM (init := body) fun letDecl body => `(let $letDecl:letDecl; $body) def matchAltExpr := Parser.Term.matchAlt def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (argNames : Array Name) : TermElabM Syntax := do let discrs ← mkDiscrs let alts ← mkAlts `(match $[$discrs],* with | $[$alts:matchAlt]|*) where mkDiscr (varName : Name) : TermElabM Syntax := `(Parser.Term.matchDiscr| $(mkIdent varName):term) mkDiscrs : TermElabM (Array Syntax) := do let mut discrs := #[] -- add indices for argName in argNames[indVal.nparams:] do discrs := discrs.push (← mkDiscr argName) return discrs.push (← mkDiscr header.targetName) mkAlts : TermElabM (Array Syntax) := do let mut alts := #[] for ctorName in indVal.ctors do let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.nindices] do patterns := patterns.push (← `(_)) let ctorInfo ← getConstInfoCtor ctorName let mut ctorArgs := #[] -- add `_` for inductive parameters, they are inaccessible for i in [:indVal.nparams] do ctorArgs := ctorArgs.push (← `(_)) for i in [:ctorInfo.nfields] do ctorArgs := ctorArgs.push (mkIdent (← mkFreshUserName `y)) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*)) let altRhs ← forallTelescopeReducing ctorInfo.type fun xs _ => ctx.mkAltRhs ctx.toContextCore ctorName (Array.zip ctorArgs xs) let alt ← `(matchAltExpr| $[$patterns:term],* => $altRhs:term) alts := alts.push alt return alts def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do let auxFunName ← ctx.auxFunNames[i] let indVal ← ctx.typeInfos[i] let header ← mkHeader ctx indVal let mut body ← mkMatch ctx header indVal header.argNames if ctx.usePartial then let letDecls ← mkLocalInstanceLetDecls ctx header.argNames body ← mkLet letDecls body let binders := header.binders if ctx.usePartial then `(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : $ctx.resultType:term := $body:term) else `(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : $ctx.resultType:term := $body:term) def mkMutualBlock (ctx : Context) : TermElabM Syntax := do let mut auxDefs := #[] for i in [:ctx.typeInfos.size] do auxDefs := auxDefs.push (← mkAuxFunction ctx i) `(mutual $auxDefs:command* end) def mkInstanceCmds (ctx : Context) : TermElabM (Array Syntax) := do let mut instances := #[] for i in [:ctx.typeInfos.size] do let indVal := ctx.typeInfos[i] let auxFunName := ctx.auxFunNames[i] let argNames ← mkInductArgNames indVal let binders ← mkImplicitBinders argNames let binders := binders ++ (← mkInstImplicitBinders ctx indVal argNames) let indType ← mkInductiveApp indVal argNames let type ← `($(mkIdent ctx.classInfo.name) $indType) let val ← `(⟨$(mkIdent auxFunName)⟩) let instCmd ← `(instance $binders:implicitBinder* : $type := $val) trace[Meta.debug] "\n{instCmd}" instances := instances.push instCmd return instances open Command def mkDeriving (className : Name) (typeName : Name) (resultType : Syntax) (mkAltRhs : MkAltRhs) : CommandElabM Unit := do let cmds ← liftTermElabM none do let ctx ← mkContext className typeName resultType mkAltRhs let block ← mkMutualBlock ctx trace[Meta.debug] "\n{block}" return #[block] ++ (← mkInstanceCmds ctx) cmds.forM elabCommand def mkDerivingToString (typeName : Name) : CommandElabM Unit := do mkDeriving `ToString typeName (← `(String)) fun ctx ctorName ctorArgs => quote (toString ctorName) -- TODO syntax[runTstKind] "runTst" : command @[commandElab runTstKind] def elabTst : CommandElab := fun stx => mkDerivingToString `Test.Foo set_option trace.Meta.debug true runTst
75b12154725cda41440e4e05f7511d8595a4e8dc
00d2363f9655e2a7618f6b94dda7e2c4e5cf8d19
/lean_modifications/conv_interactive_modifications.lean
4985b22d85de954226e16b7364d1fe8442031817
[ "Apache-2.0" ]
permissive
devjuice1/lean_proof_recording
927e276e2ab8fb1288f51d9146dcfbf0d6444a87
bf7c527315deccd35363fa7ca89d97d7b9cb6ac1
refs/heads/master
1,692,914,925,585
1,633,018,872,000
1,633,018,872,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
951
lean
/- This is a staging area for code which will be inserted into a Lean file. The code to be inserted is between the line comments `PR BEGIN MODIFICATION` and `PR END MODIFICATION` It will be inserted by `insert_proof_recording_code.py`. Insert info: - file: `_target/lean/library/init/meta/converter/interactive.lean` - location: after the itactic definition Most of this code is carefully written, but any code labeled "BEGIN/END CUSTOMIZABLE CODE" encourages customization to change what is being recorded -/ prelude import init.meta.interactive init.meta.converter.conv import .interactive_base_modifications namespace conv namespace interactive --PR BEGIN MODIFICATION @[reducible] meta def pr.recorded_itactic /-(tactic_name: string) (arg_num : nat)-/ : lean.parser (conv unit) := lean.parser.val $ interactive.pr.record /-tactic_name arg_num "itactic"-/ lean.parser.itactic_reflected --PR END MODIFICATION end interactive end conv
07be2428e4cfde2c68191c71185dafd560ffcbd0
1446f520c1db37e157b631385707cc28a17a595e
/stage0/src/Init/Lean/Message.lean
264440e025f52588eed0b97cab91f5862f48ab56
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,301
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura Message Type used by the Lean frontend -/ prelude import Init.Data.ToString import Init.Lean.Data.Position import Init.Lean.Syntax import Init.Lean.MetavarContext import Init.Lean.Environment import Init.Lean.Util.PPExt import Init.Lean.Util.PPGoal namespace Lean def mkErrorStringWithPos (fileName : String) (line col : Nat) (msg : String) : String := fileName ++ ":" ++ toString line ++ ":" ++ toString col ++ " " ++ toString msg inductive MessageSeverity | information | warning | error structure MessageDataContext := (env : Environment) (mctx : MetavarContext) (lctx : LocalContext) (opts : Options) /- Structure message data. We use it for reporting errors, trace messages, etc. -/ inductive MessageData | ofFormat : Format → MessageData | ofSyntax : Syntax → MessageData | ofExpr : Expr → MessageData | ofLevel : Level → MessageData | ofName : Name → MessageData | ofGoal : MVarId → MessageData /- `withContext ctx d` specifies the pretty printing context `(env, mctx, lctx, opts)` for the nested expressions in `d`. -/ | withContext : MessageDataContext → MessageData → MessageData /- Lifted `Format.nest` -/ | nest : Nat → MessageData → MessageData /- Lifted `Format.group` -/ | group : MessageData → MessageData /- Lifted `Format.compose` -/ | compose : MessageData → MessageData → MessageData /- Tagged sections. `Name` should be viewed as a "kind", and is used by `MessageData` inspector functions. Example: an inspector that tries to find "definitional equality failures" may look for the tag "DefEqFailure". -/ | tagged : Name → MessageData → MessageData | node : Array MessageData → MessageData namespace MessageData instance : Inhabited MessageData := ⟨MessageData.ofFormat (arbitrary _)⟩ @[init] def stxMaxDepthOption : IO Unit := registerOption `syntaxMaxDepth { defValue := (2 : Nat), group := "", descr := "maximum depth when displaying syntax objects in messages" } def getSyntaxMaxDepth (opts : Options) : Nat := opts.getNat `syntaxMaxDepth 2 partial def formatAux : Option MessageDataContext → MessageData → Format | _, ofFormat fmt => fmt | _, ofLevel u => fmt u | _, ofName n => fmt n | some ctx, ofSyntax s => s.formatStx (getSyntaxMaxDepth ctx.opts) | none, ofSyntax s => s.formatStx | none, ofExpr e => format (toString e) | some ctx, ofExpr e => ppExpr ctx.env ctx.mctx ctx.lctx ctx.opts e | none, ofGoal mvarId => "goal " ++ format (mkMVar mvarId) | some ctx, ofGoal mvarId => ppGoal ctx.env ctx.mctx ctx.opts mvarId | _, withContext ctx d => formatAux (some ctx) d | ctx, tagged cls d => Format.sbracket (format cls) ++ " " ++ formatAux ctx d | ctx, nest n d => Format.nest n (formatAux ctx d) | ctx, compose d₁ d₂ => formatAux ctx d₁ ++ formatAux ctx d₂ | ctx, group d => Format.group (formatAux ctx d) | ctx, node ds => Format.nest 2 $ ds.foldl (fun r d => r ++ Format.line ++ formatAux ctx d) Format.nil instance : HasAppend MessageData := ⟨compose⟩ instance : HasFormat MessageData := ⟨fun d => formatAux none d⟩ instance coeOfFormat : HasCoe Format MessageData := ⟨ofFormat⟩ instance coeOfLevel : HasCoe Level MessageData := ⟨ofLevel⟩ instance coeOfExpr : HasCoe Expr MessageData := ⟨ofExpr⟩ instance coeOfName : HasCoe Name MessageData := ⟨ofName⟩ instance coeOfSyntax : HasCoe Syntax MessageData := ⟨ofSyntax⟩ instance coeOfOptExpr : HasCoe (Option Expr) MessageData := ⟨fun o => match o with | none => "none" | some e => ofExpr e⟩ partial def arrayExpr.toMessageData (es : Array Expr) : Nat → MessageData → MessageData | i, acc => if h : i < es.size then let e := es.get ⟨i, h⟩; let acc := if i == 0 then acc ++ ofExpr e else acc ++ ", " ++ ofExpr e; arrayExpr.toMessageData (i+1) acc else acc ++ "]" instance coeOfArrayExpr : HasCoe (Array Expr) MessageData := ⟨fun es => arrayExpr.toMessageData es 0 "#["⟩ def bracket (l : String) (f : MessageData) (r : String) : MessageData := group (nest l.length $ l ++ f ++ r) def paren (f : MessageData) : MessageData := bracket "(" f ")" def sbracket (f : MessageData) : MessageData := bracket "[" f "]" def joinSep : List MessageData → MessageData → MessageData | [], sep => Format.nil | [a], sep => a | a::as, sep => a ++ sep ++ joinSep as sep def ofList: List MessageData → MessageData | [] => "[]" | xs => sbracket $ joinSep xs ("," ++ Format.line) def ofArray (msgs : Array MessageData) : MessageData := ofList msgs.toList end MessageData structure Message := (fileName : String) (pos : Position) (endPos : Option Position := none) (severity : MessageSeverity := MessageSeverity.error) (caption : String := "") (data : MessageData) @[export lean_mk_message] def mkMessageEx (fileName : String) (pos : Position) (endPos : Option Position) (severity : MessageSeverity) (caption : String) (text : String) : Message := { fileName := fileName, pos := pos, endPos := endPos, severity := severity, caption := caption, data := text } namespace Message protected def toString (msg : Message) : String := mkErrorStringWithPos msg.fileName msg.pos.line msg.pos.column ((match msg.severity with | MessageSeverity.information => "" | MessageSeverity.warning => "warning: " | MessageSeverity.error => "error: ") ++ (if msg.caption == "" then "" else msg.caption ++ ":\n") ++ toString (fmt msg.data)) instance : Inhabited Message := ⟨{ fileName := "", pos := ⟨0, 1⟩, data := arbitrary _}⟩ instance : HasToString Message := ⟨Message.toString⟩ @[export lean_message_pos] def getPostEx (msg : Message) : Position := msg.pos @[export lean_message_severity] def getSeverityEx (msg : Message) : MessageSeverity := msg.severity @[export lean_message_string] def getMessageStringEx (msg : Message) : String := toString (fmt msg.data) end Message structure MessageLog := (msgs : PersistentArray Message := {}) namespace MessageLog def empty : MessageLog := ⟨{}⟩ def isEmpty (log : MessageLog) : Bool := log.msgs.isEmpty instance : Inhabited MessageLog := ⟨{}⟩ def add (msg : Message) (log : MessageLog) : MessageLog := ⟨log.msgs.push msg⟩ protected def append (l₁ l₂ : MessageLog) : MessageLog := ⟨l₁.msgs ++ l₂.msgs⟩ instance : HasAppend MessageLog := ⟨MessageLog.append⟩ def hasErrors (log : MessageLog) : Bool := log.msgs.any $ fun m => match m.severity with | MessageSeverity.error => true | _ => false def errorsToWarnings (log : MessageLog) : MessageLog := { msgs := log.msgs.map (fun m => match m.severity with | MessageSeverity.error => { severity := MessageSeverity.warning, .. m} | _ => m) } def forM {m : Type → Type} [Monad m] (log : MessageLog) (f : Message → m Unit) : m Unit := log.msgs.forM f def toList (log : MessageLog) : List Message := (log.msgs.foldl (fun acc msg => msg :: acc) []).reverse end MessageLog end Lean
9fa5eb586eb97e6b7d83894167516c1c203caf53
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc4.lean
1d024b87782c69f05c21adabbb56698713a00fbf
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
235
lean
open nat set_option blast.strategy "cc" definition tst (a₁ a₂ b₁ b₂ c d : nat) : a₁ = c → a₂ = c → b₁ = d → d = b₂ → a₁ + b₁ + a₁ = a₂ + b₂ + c := by blast print tst
dc0f37645dbb8cc28086f35f580d3c7b4d75b6c3
0f5090f82d527e0df5bf3adac9f9e2e1d81d71e2
/src/apurva/matrix_extension.lean
34a7a5fffe410ccf34f9d079b83f7e14f93a174e
[]
no_license
apurvanakade/mc2020-lean-projects
36eb42c4baccc37183635c36f8e1b3afa4ec1230
02466225aa629ab1232043bcc0a053a099fdb939
refs/heads/master
1,688,791,717,534
1,597,874,092,000
1,597,874,092,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,322
lean
import data.complex.basic import data.fintype.basic import data.fin import data.matrix.basic import linear_algebra.basis import linear_algebra.determinant import linear_algebra.nonsingular_inverse import .complex_transpose import tactic noncomputable theory open_locale classical open_locale matrix universes u u' variables {n : ℕ} variables {S : Type u} [semiring S] -- need a better name def matrix.extension (A : matrix (fin n) (fin n) S) (a : S) : matrix (fin (n+1)) (fin (n+1)) S := λ i j, match i, j with | ⟨0, _⟩, ⟨0, _⟩ := a | ⟨0, _⟩, _ := 0 | _, ⟨0, _⟩ := 0 | ⟨x+1, hx⟩, ⟨y+1, hy⟩ := A ⟨x, nat.lt_of_succ_lt_succ hx⟩ ⟨y, nat.lt_of_succ_lt_succ hy⟩ end def vector.extension (v : (fin n) → S) (a : S) : fin (n+1) → S := λ i, match i with | ⟨0, _⟩ := a | ⟨x+1, hx⟩ := v ⟨x, nat.lt_of_succ_lt_succ hx⟩ end -- set_option pp.notation false lemma matrix.extension_mul (A B : matrix (fin n) (fin n) S) (a b : S) : (A.extension a) • (B.extension b) = (A • B).extension (a * b):= begin ext, cases i, cases i_val, cases j, cases j_val, sorry, repeat{sorry,} end lemma matrix.extension_conj (A : matrix (fin n) (fin n) ℂ) (a : ℂ) : (A.extension a).conj = A.conj.extension a.conj := begin sorry, end
f26eb8fc2d46fa97327be90adfbd2bda1059e8cd
7cdf3413c097e5d36492d12cdd07030eb991d394
/world_experiments/world7/level16.lean
6d141ce568c1104dadf790e265afdcdaa7f371a9
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
489
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level15 -- hide namespace mynat -- hide /- # World 2 -- Addition World ## Level 16/16 -- `ne_succ_self` This isn't too hard. -/ /- Lemma For any natural number $n$, we have $$ n \neq \operatorname{succ}(n). $$ -/ lemma ne_succ_self (n : mynat) : n ≠ succ n := begin [less_leaky] induction n with d hd, apply zero_ne_succ, intro hs, apply hd, apply succ_inj, assumption end end mynat -- hide
1ca48a6734b04d6a023abf400540a970d8212a86
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/tactic/ext.lean
f99d4f37ad0338fd81eaee3f0fe500acc4b84703
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
1,842
lean
import tactic.basic universes u₁ u₂ /-- Tag lemmas of the form: ``` lemma my_collection.ext (a b : my_collection) (h : ∀ x, a.lookup x = b.lookup y) : a = b := ... ``` -/ @[user_attribute] meta def extensional_attribute : user_attribute := { name := `extensionality, descr := "lemmas usable by `ext` tactic" } attribute [extensionality] _root_.funext array.ext namespace ulift @[extensionality] lemma ext {α : Type u₁} (X Y : ulift.{u₂} α) (w : X.down = Y.down) : X = Y := begin cases X, cases Y, dsimp at w, rw w, end end ulift namespace tactic open interactive interactive.types open lean.parser nat local postfix `?`:9001 := optional local postfix *:9001 := many /-- `ext1 id` selects and apply one extensionality lemma (with attribute `extensionality`), using `id`, if provided, to name a local constant introduced by the lemma. If `id` is omitted, the local constant is named automatically, as per `intro`. -/ meta def interactive.ext1 (xs : parse ident_*) : tactic unit := ext1 xs $> () /-- - `ext` applies as many extensionality lemmas as possible; - `ext ids`, with `ids` a list of identifiers, finds extentionality and applies them until it runs out of identifiers in `ids` to name the local constants. When trying to prove: ``` α β : Type, f g : α → set β ⊢ f = g ``` applying `ext x y` yields: ``` α β : Type, f g : α → set β, x : α, y : β ⊢ y ∈ f x ↔ y ∈ f x ``` by applying functional extensionality and set extensionality. A maximum depth can be provided with `ext x y z : 3`. -/ meta def interactive.ext : parse ident_* → parse (tk ":" *> small_nat)? → tactic unit | [] (some n) := iterate_range 1 n (ext1 [] $> ()) | [] none := repeat1 (ext1 [] $> ()) | xs n := tactic.ext xs n end tactic
ca43a35641b0da9a111d7b3523e9e7e56cdd6c86
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/algebra/functions.lean
ab142964a010f0bc635cc1b555641ec7832ecea1
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
4,527
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.order init.meta universe u export linear_order (min max) section open decidable tactic variables {α : Type u} [linear_order α] lemma min_def (a b : α) : min a b = if a ≤ b then a else b := by rw [congr_fun linear_order.min_def a, min_default] lemma max_def (a b : α) : max a b = if a ≤ b then b else a := by rw [congr_fun linear_order.max_def a, max_default] private meta def min_tac_step : tactic unit := solve1 $ intros >> `[simp only [min_def, max_def]] >> try `[simp [*, if_pos, if_neg]] >> try `[apply le_refl] >> try `[apply le_of_not_le, assumption] meta def tactic.interactive.min_tac (a b : interactive.parse lean.parser.pexpr) : tactic unit := interactive.by_cases (none, ``(%%a ≤ %%b)); min_tac_step lemma min_le_left (a b : α) : min a b ≤ a := by min_tac a b lemma min_le_right (a b : α) : min a b ≤ b := by min_tac a b lemma le_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) : c ≤ min a b := by min_tac a b lemma le_max_left (a b : α) : a ≤ max a b := by min_tac a b lemma le_max_right (a b : α) : b ≤ max a b := by min_tac a b lemma max_le {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) : max a b ≤ c := by min_tac a b lemma eq_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) (h₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) : c = min a b := le_antisymm (le_min h₁ h₂) (h₃ (min_le_left a b) (min_le_right a b)) lemma min_comm (a b : α) : min a b = min b a := eq_min (min_le_right a b) (min_le_left a b) (λ c h₁ h₂, le_min h₂ h₁) lemma min_assoc (a b c : α) : min (min a b) c = min a (min b c) := begin apply eq_min, { apply le_trans, apply min_le_left, apply min_le_left }, { apply le_min, apply le_trans, apply min_le_left, apply min_le_right, apply min_le_right }, { intros d h₁ h₂, apply le_min, apply le_min h₁, apply le_trans h₂, apply min_le_left, apply le_trans h₂, apply min_le_right } end lemma min_left_comm : ∀ (a b c : α), min a (min b c) = min b (min a c) := left_comm (@min α _) (@min_comm α _) (@min_assoc α _) @[simp] lemma min_self (a : α) : min a a = a := by min_tac a a @[ematch] lemma min_eq_left {a b : α} (h : a ≤ b) : min a b = a := begin apply eq.symm, apply eq_min (le_refl _) h, intros, assumption end @[ematch] lemma min_eq_right {a b : α} (h : b ≤ a) : min a b = b := eq.subst (min_comm b a) (min_eq_left h) lemma eq_max {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) (h₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = max a b := le_antisymm (h₃ (le_max_left a b) (le_max_right a b)) (max_le h₁ h₂) lemma max_comm (a b : α) : max a b = max b a := eq_max (le_max_right a b) (le_max_left a b) (λ c h₁ h₂, max_le h₂ h₁) lemma max_assoc (a b c : α) : max (max a b) c = max a (max b c) := begin apply eq_max, { apply le_trans, apply le_max_left a b, apply le_max_left }, { apply max_le, apply le_trans, apply le_max_right a b, apply le_max_left, apply le_max_right }, { intros d h₁ h₂, apply max_le, apply max_le h₁, apply le_trans (le_max_left _ _) h₂, apply le_trans (le_max_right _ _) h₂} end lemma max_left_comm : ∀ (a b c : α), max a (max b c) = max b (max a c) := left_comm (@max α _) (@max_comm α _) (@max_assoc α _) @[simp] lemma max_self (a : α) : max a a = a := by min_tac a a lemma max_eq_left {a b : α} (h : b ≤ a) : max a b = a := begin apply eq.symm, apply eq_max (le_refl _) h, intros, assumption end lemma max_eq_right {a b : α} (h : a ≤ b) : max a b = b := eq.subst (max_comm b a) (max_eq_left h) /- these rely on lt_of_lt -/ lemma min_eq_left_of_lt {a b : α} (h : a < b) : min a b = a := min_eq_left (le_of_lt h) lemma min_eq_right_of_lt {a b : α} (h : b < a) : min a b = b := min_eq_right (le_of_lt h) lemma max_eq_left_of_lt {a b : α} (h : b < a) : max a b = a := max_eq_left (le_of_lt h) lemma max_eq_right_of_lt {a b : α} (h : a < b) : max a b = b := max_eq_right (le_of_lt h) /- these use the fact that it is a linear ordering -/ lemma lt_min {a b c : α} (h₁ : a < b) (h₂ : a < c) : a < min b c := or.elim (le_or_gt b c) (assume h : b ≤ c, by min_tac b c) (assume h : b > c, by min_tac b c) lemma max_lt {a b c : α} (h₁ : a < c) (h₂ : b < c) : max a b < c := or.elim (le_or_gt a b) (assume h : a ≤ b, by min_tac b a) (assume h : a > b, by min_tac a b) end
59e8700ad394130c04390307beab69dbaaad483c
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/core/data.lean
ad188e434310844e6d401107dc2c344fe5fca072
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
687
lean
import tactic.rewrite_all universe u @[derive decidable_eq] structure sided_pair (α : Type u) := (l r : α) namespace sided_pair variables {α β : Type} (p : sided_pair α) def get : side → α | side.L := p.l | side.R := p.r def set : side → α → sided_pair α | side.L v := ⟨v, p.r⟩ | side.R v := ⟨p.l, v⟩ def flip : sided_pair α := ⟨p.r, p.l⟩ def map (f : α → β) : sided_pair β := ⟨f p.l, f p.r⟩ def to_list : list α := [p.l, p.r] def to_string [has_to_string α] (p : sided_pair α) : string := to_string p.l ++ "-" ++ to_string p.r instance has_to_string [has_to_string α] : has_to_string (sided_pair α) := ⟨to_string⟩ end sided_pair
08ceae319a72204fff464af27368324c8f30e247
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/bits.lean
984ffb50a06f75245cadf10fe2c9a6ab1a76314f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,231
lean
/- Copyright (c) 2022 Praneeth Kolichala. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Praneeth Kolichala -/ import data.nat.basic /-! # Additional properties of binary recursion on `nat` This file documents additional properties of binary recursion, which allows us to more easily work with operations which do depend on the number of leading zeros in the binary representation of `n`. For example, we can more easily work with `nat.bits` and `nat.size`. See also: `nat.bitwise`, `nat.pow` (for various lemmas about `size` and `shiftl`/`shiftr`), and `nat.digits`. -/ namespace nat universe u variables {n : ℕ} /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ -- There is no need to prove `bit0_eq_zero : bit0 n = 0 ↔ n = 0` -- as this is true for any `[semiring R] [no_zero_divisors R] [char_zero R]` -- However the lemmas `bit0_eq_bit0`, `bit1_eq_bit1`, `bit1_eq_one`, `one_eq_bit1` -- need `[ring R] [no_zero_divisors R] [char_zero R]` in general, -- so we prove `ℕ` specialized versions here. @[simp] lemma bit0_eq_bit0 {m n : ℕ} : bit0 m = bit0 n ↔ m = n := ⟨nat.bit0_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_bit1 {m n : ℕ} : bit1 m = bit1 n ↔ m = n := ⟨nat.bit1_inj, λ h, by subst h⟩ @[simp] lemma bit1_eq_one {n : ℕ} : bit1 n = 1 ↔ n = 0 := ⟨@nat.bit1_inj n 0, λ h, by subst h⟩ @[simp] lemma one_eq_bit1 {n : ℕ} : 1 = bit1 n ↔ n = 0 := ⟨λ h, (@nat.bit1_inj 0 n h).symm, λ h, by subst h⟩ theorem bit_add : ∀ (b : bool) (n m : ℕ), bit b (n + m) = bit ff n + bit b m | tt := bit1_add | ff := bit0_add theorem bit_add' : ∀ (b : bool) (n m : ℕ), bit b (n + m) = bit b n + bit ff m | tt := bit1_add' | ff := bit0_add theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] lemma bit0_mod_two : bit0 n % 2 = 0 := by { rw nat.mod_two_of_bodd, simp } lemma bit1_mod_two : bit1 n % 2 = 1 := by { rw nat.mod_two_of_bodd, simp } lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } @[simp] lemma bit_cases_on_bit {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (b : bool) (n : ℕ) : bit_cases_on (bit b n) H = H b n := eq_of_heq $ (eq_rec_heq _ _).trans $ by rw [bodd_bit, div2_bit] @[simp] lemma bit_cases_on_bit0 {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : bit_cases_on (bit0 n) H = H ff n := bit_cases_on_bit H ff n @[simp] lemma bit_cases_on_bit1 {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : bit_cases_on (bit1 n) H = H tt n := bit_cases_on_bit H tt n lemma bit_cases_on_injective {C : ℕ → Sort u} : function.injective (λ H : Π b n, C (bit b n), λ n, bit_cases_on n H) := begin intros H₁ H₂ h, ext b n, simpa only [bit_cases_on_bit] using congr_fun h (bit b n) end @[simp] lemma bit_cases_on_inj {C : ℕ → Sort u} (H₁ H₂ : Π b n, C (bit b n)) : (λ n, bit_cases_on n H₁) = (λ n, bit_cases_on n H₂) ↔ H₁ = H₂ := bit_cases_on_injective.eq_iff protected lemma bit0_eq_zero {n : ℕ} : bit0 n = 0 ↔ n = 0 := ⟨nat.eq_zero_of_add_eq_zero_left, λ h, by simp [h]⟩ lemma bit_eq_zero_iff {n : ℕ} {b : bool} : bit b n = 0 ↔ n = 0 ∧ b = ff := by { split, { cases b; simp [nat.bit, nat.bit0_eq_zero], }, rintro ⟨rfl, rfl⟩, refl, } /-- The same as binary_rec_eq, but that one unfortunately requires `f` to be the identity when appending `ff` to `0`. Here, we allow you to explicitly say that that case is not happening, i.e. supplying `n = 0 → b = tt`. -/ lemma binary_rec_eq' {C : ℕ → Sort*} {z : C 0} {f : ∀ b n, C n → C (bit b n)} (b n) (h : f ff 0 z = z ∨ (n = 0 → b = tt)) : binary_rec z f (bit b n) = f b n (binary_rec z f n) := begin rw [binary_rec], split_ifs with h', { rcases bit_eq_zero_iff.mp h' with ⟨rfl, rfl⟩, rw binary_rec_zero, simp only [imp_false, or_false, eq_self_iff_true, not_true] at h, exact h.symm }, { generalize_proofs e, revert e, rw [bodd_bit, div2_bit], intros, refl, } end /-- The same as `binary_rec`, but the induction step can assume that if `n=0`, the bit being appended is `tt`-/ @[elab_as_eliminator] def binary_rec' {C : ℕ → Sort*} (z : C 0) (f : ∀ b n, (n = 0 → b = tt) → C n → C (bit b n)) : ∀ n, C n := binary_rec z (λ b n ih, if h : n = 0 → b = tt then f b n h ih else by { convert z, rw bit_eq_zero_iff, simpa using h, }) /-- The same as `binary_rec`, but special casing both 0 and 1 as base cases -/ @[elab_as_eliminator] def binary_rec_from_one {C : ℕ → Sort*} (z₀ : C 0) (z₁ : C 1) (f : ∀ b n, n ≠ 0 → C n → C (bit b n)) : ∀ n, C n := binary_rec' z₀ (λ b n h ih, if h' : n = 0 then by { rw [h', h h'], exact z₁ } else f b n h' ih) @[simp] lemma zero_bits : bits 0 = [] := by simp [nat.bits] @[simp] lemma bits_append_bit (n : ℕ) (b : bool) (hn : n = 0 → b = tt) : (bit b n).bits = b :: n.bits := by { rw [nat.bits, binary_rec_eq'], simpa, } @[simp] lemma bit0_bits (n : ℕ) (hn : n ≠ 0) : (bit0 n).bits = ff :: n.bits := bits_append_bit n ff (λ hn', absurd hn' hn) @[simp] lemma bit1_bits (n : ℕ) : (bit1 n).bits = tt :: n.bits := bits_append_bit n tt (λ _, rfl) @[simp] lemma one_bits : nat.bits 1 = [tt] := by { convert bit1_bits 0, simp, } -- TODO Find somewhere this can live. -- example : bits 3423 = [tt, tt, tt, tt, tt, ff, tt, ff, tt, ff, tt, tt] := by norm_num lemma bodd_eq_bits_head (n : ℕ) : n.bodd = n.bits.head := begin induction n using nat.binary_rec' with b n h ih, { simp, }, simp [bodd_bit, bits_append_bit _ _ h], end lemma div2_bits_eq_tail (n : ℕ) : n.div2.bits = n.bits.tail := begin induction n using nat.binary_rec' with b n h ih, { simp, }, simp [div2_bit, bits_append_bit _ _ h], end end nat
ed319cda1c9c79f8914ea3f369c88593eb348a90
e38d5e91d30731bef617cc9b6de7f79c34cdce9a
/src/examples/face.lean
1292971826aafd72d2e63e37fa29c6d25e7b40f3
[ "Apache-2.0" ]
permissive
bbentzen/cubicalean
55e979c303fbf55a81ac46b1000c944b2498be7a
3b94cd2aefdfc2163c263bd3fc6f2086fef814b5
refs/heads/master
1,588,314,875,258
1,554,412,699,000
1,554,412,699,000
177,333,390
0
0
null
null
null
null
UTF-8
Lean
false
false
461
lean
/- Copyright (c) 2019 Bruno Bentzen. All rights reserved. Released under the Apache License 2.0 (see "License"); Author: Bruno Bentzen -/ import ..core.interval open interval -- the ε face maps of type lines example {A : I → Type} : Type := A i0 example {A : I → Type} : Type := A i1 -- the ε face maps of lines example {A : I → Type} (a : Π i, A i) : A i1 := a i1 example {A : I → Type} (a : Π i, A i) : A i0 := a i0