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
e15dc8bab7b9f06641717a2cadb8907c9962ebe0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/hom/complete_lattice.lean
fb0163c8fe28f5ad46f1658b396494999f62e399
[ "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
26,955
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.lattice import order.hom.lattice /-! # Complete lattice homomorphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines frame homorphisms and complete lattice homomorphisms. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `Sup_hom`: Maps which preserve `⨆`. * `Inf_hom`: Maps which preserve `⨅`. * `frame_hom`: Frame homomorphisms. Maps which preserve `⨆`, `⊓` and `⊤`. * `complete_lattice_hom`: Complete lattice homomorphisms. Maps which preserve `⨆` and `⨅`. ## Typeclasses * `Sup_hom_class` * `Inf_hom_class` * `frame_hom_class` * `complete_lattice_hom_class` ## Concrete homs * `complete_lattice.set_preimage`: `set.preimage` as a complete lattice homomorphism. ## TODO Frame homs are Heyting homs. -/ open function order_dual set variables {F α β γ δ : Type*} {ι : Sort*} {κ : ι → Sort*} /-- The type of `⨆`-preserving functions from `α` to `β`. -/ structure Sup_hom (α β : Type*) [has_Sup α] [has_Sup β] := (to_fun : α → β) (map_Sup' (s : set α) : to_fun (Sup s) = Sup (to_fun '' s)) /-- The type of `⨅`-preserving functions from `α` to `β`. -/ structure Inf_hom (α β : Type*) [has_Inf α] [has_Inf β] := (to_fun : α → β) (map_Inf' (s : set α) : to_fun (Inf s) = Inf (to_fun '' s)) /-- The type of frame homomorphisms from `α` to `β`. They preserve finite meets and arbitrary joins. -/ structure frame_hom (α β : Type*) [complete_lattice α] [complete_lattice β] extends inf_top_hom α β := (map_Sup' (s : set α) : to_fun (Sup s) = Sup (to_fun '' s)) /-- The type of complete lattice homomorphisms from `α` to `β`. -/ structure complete_lattice_hom (α β : Type*) [complete_lattice α] [complete_lattice β] extends Inf_hom α β := (map_Sup' (s : set α) : to_fun (Sup s) = Sup (to_fun '' s)) section set_option old_structure_cmd true /-- `Sup_hom_class F α β` states that `F` is a type of `⨆`-preserving morphisms. You should extend this class when you extend `Sup_hom`. -/ class Sup_hom_class (F : Type*) (α β : out_param $ Type*) [has_Sup α] [has_Sup β] extends fun_like F α (λ _, β) := (map_Sup (f : F) (s : set α) : f (Sup s) = Sup (f '' s)) /-- `Inf_hom_class F α β` states that `F` is a type of `⨅`-preserving morphisms. You should extend this class when you extend `Inf_hom`. -/ class Inf_hom_class (F : Type*) (α β : out_param $ Type*) [has_Inf α] [has_Inf β] extends fun_like F α (λ _, β) := (map_Inf (f : F) (s : set α) : f (Inf s) = Inf (f '' s)) /-- `frame_hom_class F α β` states that `F` is a type of frame morphisms. They preserve `⊓` and `⨆`. You should extend this class when you extend `frame_hom`. -/ class frame_hom_class (F : Type*) (α β : out_param $ Type*) [complete_lattice α] [complete_lattice β] extends inf_top_hom_class F α β := (map_Sup (f : F) (s : set α) : f (Sup s) = Sup (f '' s)) /-- `complete_lattice_hom_class F α β` states that `F` is a type of complete lattice morphisms. You should extend this class when you extend `complete_lattice_hom`. -/ class complete_lattice_hom_class (F : Type*) (α β : out_param $ Type*) [complete_lattice α] [complete_lattice β] extends Inf_hom_class F α β := (map_Sup (f : F) (s : set α) : f (Sup s) = Sup (f '' s)) end export Sup_hom_class (map_Sup) export Inf_hom_class (map_Inf) attribute [simp] map_Sup map_Inf lemma map_supr [has_Sup α] [has_Sup β] [Sup_hom_class F α β] (f : F) (g : ι → α) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, supr, map_Sup, set.range_comp] lemma map_supr₂ [has_Sup α] [has_Sup β] [Sup_hom_class F α β] (f : F) (g : Π i, κ i → α) : f (⨆ i j, g i j) = ⨆ i j, f (g i j) := by simp_rw map_supr lemma map_infi [has_Inf α] [has_Inf β] [Inf_hom_class F α β] (f : F) (g : ι → α) : f (⨅ i, g i) = ⨅ i, f (g i) := by rw [infi, infi, map_Inf, set.range_comp] lemma map_infi₂ [has_Inf α] [has_Inf β] [Inf_hom_class F α β] (f : F) (g : Π i, κ i → α) : f (⨅ i j, g i j) = ⨅ i j, f (g i j) := by simp_rw map_infi @[priority 100] -- See note [lower instance priority] instance Sup_hom_class.to_sup_bot_hom_class [complete_lattice α] [complete_lattice β] [Sup_hom_class F α β] : sup_bot_hom_class F α β := { map_sup := λ f a b, by rw [←Sup_pair, map_Sup, set.image_pair, Sup_pair], map_bot := λ f, by rw [←Sup_empty, map_Sup, set.image_empty, Sup_empty], ..‹Sup_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance Inf_hom_class.to_inf_top_hom_class [complete_lattice α] [complete_lattice β] [Inf_hom_class F α β] : inf_top_hom_class F α β := { map_inf := λ f a b, by rw [←Inf_pair, map_Inf, set.image_pair, Inf_pair], map_top := λ f, by rw [←Inf_empty, map_Inf, set.image_empty, Inf_empty], ..‹Inf_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance frame_hom_class.to_Sup_hom_class [complete_lattice α] [complete_lattice β] [frame_hom_class F α β] : Sup_hom_class F α β := { .. ‹frame_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance frame_hom_class.to_bounded_lattice_hom_class [complete_lattice α] [complete_lattice β] [frame_hom_class F α β] : bounded_lattice_hom_class F α β := { .. ‹frame_hom_class F α β›, ..Sup_hom_class.to_sup_bot_hom_class } @[priority 100] -- See note [lower instance priority] instance complete_lattice_hom_class.to_frame_hom_class [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : frame_hom_class F α β := { .. ‹complete_lattice_hom_class F α β›, ..Inf_hom_class.to_inf_top_hom_class } @[priority 100] -- See note [lower instance priority] instance complete_lattice_hom_class.to_bounded_lattice_hom_class [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : bounded_lattice_hom_class F α β := { ..Sup_hom_class.to_sup_bot_hom_class, ..Inf_hom_class.to_inf_top_hom_class } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_Sup_hom_class [complete_lattice α] [complete_lattice β] [order_iso_class F α β] : Sup_hom_class F α β := { map_Sup := λ f s, eq_of_forall_ge_iff $ λ c, by simp only [←le_map_inv_iff, Sup_le_iff, set.ball_image_iff], .. show order_hom_class F α β, from infer_instance } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_Inf_hom_class [complete_lattice α] [complete_lattice β] [order_iso_class F α β] : Inf_hom_class F α β := { map_Inf := λ f s, eq_of_forall_le_iff $ λ c, by simp only [←map_inv_le_iff, le_Inf_iff, set.ball_image_iff], .. show order_hom_class F α β, from infer_instance } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_complete_lattice_hom_class [complete_lattice α] [complete_lattice β] [order_iso_class F α β] : complete_lattice_hom_class F α β := { ..order_iso_class.to_Sup_hom_class, ..order_iso_class.to_lattice_hom_class, .. show Inf_hom_class F α β, from infer_instance } instance [has_Sup α] [has_Sup β] [Sup_hom_class F α β] : has_coe_t F (Sup_hom α β) := ⟨λ f, ⟨f, map_Sup f⟩⟩ instance [has_Inf α] [has_Inf β] [Inf_hom_class F α β] : has_coe_t F (Inf_hom α β) := ⟨λ f, ⟨f, map_Inf f⟩⟩ instance [complete_lattice α] [complete_lattice β] [frame_hom_class F α β] : has_coe_t F (frame_hom α β) := ⟨λ f, ⟨f, map_Sup f⟩⟩ instance [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : has_coe_t F (complete_lattice_hom α β) := ⟨λ f, ⟨f, map_Sup f⟩⟩ /-! ### Supremum homomorphisms -/ namespace Sup_hom variables [has_Sup α] section has_Sup variables [has_Sup β] [has_Sup γ] [has_Sup δ] instance : Sup_hom_class (Sup_hom α β) α β := { coe := Sup_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_Sup := Sup_hom.map_Sup' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (Sup_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : Sup_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : Sup_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `Sup_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : Sup_hom α β) (f' : α → β) (h : f' = f) : Sup_hom α β := { to_fun := f', map_Sup' := h.symm ▸ f.map_Sup' } @[simp] lemma coe_copy (f : Sup_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : Sup_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `Sup_hom`. -/ protected def id : Sup_hom α α := ⟨id, λ s, by rw [id, set.image_id]⟩ instance : inhabited (Sup_hom α α) := ⟨Sup_hom.id α⟩ @[simp] lemma coe_id : ⇑(Sup_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : Sup_hom.id α a = a := rfl /-- Composition of `Sup_hom`s as a `Sup_hom`. -/ def comp (f : Sup_hom β γ) (g : Sup_hom α β) : Sup_hom α γ := { to_fun := f ∘ g, map_Sup' := λ s, by rw [comp_apply, map_Sup, map_Sup, set.image_image] } @[simp] lemma coe_comp (f : Sup_hom β γ) (g : Sup_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : Sup_hom β γ) (g : Sup_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : Sup_hom γ δ) (g : Sup_hom β γ) (h : Sup_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : Sup_hom α β) : f.comp (Sup_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : Sup_hom α β) : (Sup_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : Sup_hom β γ} {f : Sup_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : Sup_hom β γ} {f₁ f₂ : Sup_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_Sup variables [complete_lattice β] instance : partial_order (Sup_hom α β) := partial_order.lift _ fun_like.coe_injective instance : has_bot (Sup_hom α β) := ⟨⟨λ _, ⊥, λ s, begin obtain rfl | hs := s.eq_empty_or_nonempty, { rw [set.image_empty, Sup_empty] }, { rw [hs.image_const, Sup_singleton] } end⟩⟩ instance : order_bot (Sup_hom α β) := ⟨⊥, λ f a, bot_le⟩ @[simp] lemma coe_bot : ⇑(⊥ : Sup_hom α β) = ⊥ := rfl @[simp] lemma bot_apply (a : α) : (⊥ : Sup_hom α β) a = ⊥ := rfl end Sup_hom /-! ### Infimum homomorphisms -/ namespace Inf_hom variables [has_Inf α] section has_Inf variables [has_Inf β] [has_Inf γ] [has_Inf δ] instance : Inf_hom_class (Inf_hom α β) α β := { coe := Inf_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_Inf := Inf_hom.map_Inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (Inf_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : Inf_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : Inf_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `Inf_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : Inf_hom α β) (f' : α → β) (h : f' = f) : Inf_hom α β := { to_fun := f', map_Inf' := h.symm ▸ f.map_Inf' } @[simp] lemma coe_copy (f : Inf_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : Inf_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as an `Inf_hom`. -/ protected def id : Inf_hom α α := ⟨id, λ s, by rw [id, set.image_id]⟩ instance : inhabited (Inf_hom α α) := ⟨Inf_hom.id α⟩ @[simp] lemma coe_id : ⇑(Inf_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : Inf_hom.id α a = a := rfl /-- Composition of `Inf_hom`s as a `Inf_hom`. -/ def comp (f : Inf_hom β γ) (g : Inf_hom α β) : Inf_hom α γ := { to_fun := f ∘ g, map_Inf' := λ s, by rw [comp_apply, map_Inf, map_Inf, set.image_image] } @[simp] lemma coe_comp (f : Inf_hom β γ) (g : Inf_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : Inf_hom β γ) (g : Inf_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : Inf_hom γ δ) (g : Inf_hom β γ) (h : Inf_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : Inf_hom α β) : f.comp (Inf_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : Inf_hom α β) : (Inf_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : Inf_hom β γ} {f : Inf_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : Inf_hom β γ} {f₁ f₂ : Inf_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_Inf variables [complete_lattice β] instance : partial_order (Inf_hom α β) := partial_order.lift _ fun_like.coe_injective instance : has_top (Inf_hom α β) := ⟨⟨λ _, ⊤, λ s, begin obtain rfl | hs := s.eq_empty_or_nonempty, { rw [set.image_empty, Inf_empty] }, { rw [hs.image_const, Inf_singleton] } end⟩⟩ instance : order_top (Inf_hom α β) := ⟨⊤, λ f a, le_top⟩ @[simp] lemma coe_top : ⇑(⊤ : Inf_hom α β) = ⊤ := rfl @[simp] lemma top_apply (a : α) : (⊤ : Inf_hom α β) a = ⊤ := rfl end Inf_hom /-! ### Frame homomorphisms -/ namespace frame_hom variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] [complete_lattice δ] instance : frame_hom_class (frame_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := f, obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := g, congr' }, map_Sup := λ f, f.map_Sup', map_inf := λ f, f.map_inf', map_top := λ f, f.map_top' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (frame_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun /-- Reinterpret a `frame_hom` as a `lattice_hom`. -/ def to_lattice_hom (f : frame_hom α β) : lattice_hom α β := f @[simp] lemma to_fun_eq_coe {f : frame_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : frame_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `frame_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : frame_hom α β) (f' : α → β) (h : f' = f) : frame_hom α β := { to_inf_top_hom := f.to_inf_top_hom.copy f' h, ..(f : Sup_hom α β).copy f' h } @[simp] lemma coe_copy (f : frame_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : frame_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `frame_hom`. -/ protected def id : frame_hom α α := { to_inf_top_hom := inf_top_hom.id α, ..Sup_hom.id α } instance : inhabited (frame_hom α α) := ⟨frame_hom.id α⟩ @[simp] lemma coe_id : ⇑(frame_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : frame_hom.id α a = a := rfl /-- Composition of `frame_hom`s as a `frame_hom`. -/ def comp (f : frame_hom β γ) (g : frame_hom α β) : frame_hom α γ := { to_inf_top_hom := f.to_inf_top_hom.comp g.to_inf_top_hom, ..(f : Sup_hom β γ).comp (g : Sup_hom α β) } @[simp] lemma coe_comp (f : frame_hom β γ) (g : frame_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : frame_hom β γ) (g : frame_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : frame_hom γ δ) (g : frame_hom β γ) (h : frame_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : frame_hom α β) : f.comp (frame_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : frame_hom α β) : (frame_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : frame_hom β γ} {f : frame_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : frame_hom β γ} {f₁ f₂ : frame_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ instance : partial_order (frame_hom α β) := partial_order.lift _ fun_like.coe_injective end frame_hom /-! ### Complete lattice homomorphisms -/ namespace complete_lattice_hom variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] [complete_lattice δ] instance : complete_lattice_hom_class (complete_lattice_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_Sup := λ f, f.map_Sup', map_Inf := λ f, f.map_Inf' } /-- Reinterpret a `complete_lattice_hom` as a `Sup_hom`. -/ def to_Sup_hom (f : complete_lattice_hom α β) : Sup_hom α β := f /-- Reinterpret a `complete_lattice_hom` as a `bounded_lattice_hom`. -/ def to_bounded_lattice_hom (f : complete_lattice_hom α β) : bounded_lattice_hom α β := f /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (complete_lattice_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : complete_lattice_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : complete_lattice_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `complete_lattice_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : complete_lattice_hom α β) (f' : α → β) (h : f' = f) : complete_lattice_hom α β := { to_Inf_hom := f.to_Inf_hom.copy f' h, .. f.to_Sup_hom.copy f' h } @[simp] lemma coe_copy (f : complete_lattice_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : complete_lattice_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `complete_lattice_hom`. -/ protected def id : complete_lattice_hom α α := { to_fun := id, ..Sup_hom.id α, ..Inf_hom.id α } instance : inhabited (complete_lattice_hom α α) := ⟨complete_lattice_hom.id α⟩ @[simp] lemma coe_id : ⇑(complete_lattice_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : complete_lattice_hom.id α a = a := rfl /-- Composition of `complete_lattice_hom`s as a `complete_lattice_hom`. -/ def comp (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) : complete_lattice_hom α γ := { to_Inf_hom := f.to_Inf_hom.comp g.to_Inf_hom, ..f.to_Sup_hom.comp g.to_Sup_hom } @[simp] lemma coe_comp (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : complete_lattice_hom γ δ) (g : complete_lattice_hom β γ) (h : complete_lattice_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : complete_lattice_hom α β) : f.comp (complete_lattice_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : complete_lattice_hom α β) : (complete_lattice_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : complete_lattice_hom β γ} {f : complete_lattice_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : complete_lattice_hom β γ} {f₁ f₂ : complete_lattice_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end complete_lattice_hom /-! ### Dual homs -/ namespace Sup_hom variables [has_Sup α] [has_Sup β] [has_Sup γ] /-- Reinterpret a `⨆`-homomorphism as an `⨅`-homomorphism between the dual orders. -/ @[simps] protected def dual : Sup_hom α β ≃ Inf_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨to_dual ∘ f ∘ of_dual, f.map_Sup'⟩, inv_fun := λ f, ⟨of_dual ∘ f ∘ to_dual, f.map_Inf'⟩, left_inv := λ f, Sup_hom.ext $ λ a, rfl, right_inv := λ f, Inf_hom.ext $ λ a, rfl } @[simp] lemma dual_id : (Sup_hom.id α).dual = Inf_hom.id _ := rfl @[simp] lemma dual_comp (g : Sup_hom β γ) (f : Sup_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : Sup_hom.dual.symm (Inf_hom.id _) = Sup_hom.id α := rfl @[simp] lemma symm_dual_comp (g : Inf_hom βᵒᵈ γᵒᵈ) (f : Inf_hom αᵒᵈ βᵒᵈ) : Sup_hom.dual.symm (g.comp f) = (Sup_hom.dual.symm g).comp (Sup_hom.dual.symm f) := rfl end Sup_hom namespace Inf_hom variables [has_Inf α] [has_Inf β] [has_Inf γ] /-- Reinterpret an `⨅`-homomorphism as a `⨆`-homomorphism between the dual orders. -/ @[simps] protected def dual : Inf_hom α β ≃ Sup_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, { to_fun := to_dual ∘ f ∘ of_dual, map_Sup' := λ _, congr_arg to_dual (map_Inf f _) }, inv_fun := λ f, { to_fun := of_dual ∘ f ∘ to_dual, map_Inf' := λ _, congr_arg of_dual (map_Sup f _) }, left_inv := λ f, Inf_hom.ext $ λ a, rfl, right_inv := λ f, Sup_hom.ext $ λ a, rfl } @[simp] lemma dual_id : (Inf_hom.id α).dual = Sup_hom.id _ := rfl @[simp] lemma dual_comp (g : Inf_hom β γ) (f : Inf_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : Inf_hom.dual.symm (Sup_hom.id _) = Inf_hom.id α := rfl @[simp] lemma symm_dual_comp (g : Sup_hom βᵒᵈ γᵒᵈ) (f : Sup_hom αᵒᵈ βᵒᵈ) : Inf_hom.dual.symm (g.comp f) = (Inf_hom.dual.symm g).comp (Inf_hom.dual.symm f) := rfl end Inf_hom namespace complete_lattice_hom variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] /-- Reinterpret a complete lattice homomorphism as a complete lattice homomorphism between the dual lattices. -/ @[simps] protected def dual : complete_lattice_hom α β ≃ complete_lattice_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_Sup_hom.dual, f.map_Inf'⟩, inv_fun := λ f, ⟨f.to_Sup_hom.dual, f.map_Inf'⟩, left_inv := λ f, ext $ λ a, rfl, right_inv := λ f, ext $ λ a, rfl } @[simp] lemma dual_id : (complete_lattice_hom.id α).dual = complete_lattice_hom.id _ := rfl @[simp] lemma dual_comp (g : complete_lattice_hom β γ) (f : complete_lattice_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : complete_lattice_hom.dual.symm (complete_lattice_hom.id _) = complete_lattice_hom.id α := rfl @[simp] lemma symm_dual_comp (g : complete_lattice_hom βᵒᵈ γᵒᵈ) (f : complete_lattice_hom αᵒᵈ βᵒᵈ) : complete_lattice_hom.dual.symm (g.comp f) = (complete_lattice_hom.dual.symm g).comp (complete_lattice_hom.dual.symm f) := rfl end complete_lattice_hom /-! ### Concrete homs -/ namespace complete_lattice_hom /-- `set.preimage` as a complete lattice homomorphism. See also `Sup_hom.set_image`. -/ def set_preimage (f : α → β) : complete_lattice_hom (set β) (set α) := { to_fun := preimage f, map_Sup' := λ s, preimage_sUnion.trans $ by simp only [set.Sup_eq_sUnion, set.sUnion_image], map_Inf' := λ s, preimage_sInter.trans $ by simp only [set.Inf_eq_sInter, set.sInter_image] } @[simp] lemma coe_set_preimage (f : α → β) : ⇑(set_preimage f) = preimage f := rfl @[simp] lemma set_preimage_apply (f : α → β) (s : set β) : set_preimage f s = s.preimage f := rfl @[simp] lemma set_preimage_id : set_preimage (id : α → α) = complete_lattice_hom.id _ := rfl -- This lemma can't be `simp` because `g ∘ f` matches anything (`id ∘ f = f` synctatically) lemma set_preimage_comp (g : β → γ) (f : α → β) : set_preimage (g ∘ f) = (set_preimage f).comp (set_preimage g) := rfl end complete_lattice_hom lemma set.image_Sup {f : α → β} (s : set (set α)) : f '' Sup s = Sup (image f '' s) := begin ext b, simp only [Sup_eq_sUnion, mem_image, mem_sUnion, exists_prop, sUnion_image, mem_Union], split, { rintros ⟨a, ⟨t, ht₁, ht₂⟩, rfl⟩, exact ⟨t, ht₁, a, ht₂, rfl⟩, }, { rintros ⟨t, ht₁, a, ht₂, rfl⟩, exact ⟨a, ⟨t, ht₁, ht₂⟩, rfl⟩, }, end /-- Using `set.image`, a function between types yields a `Sup_hom` between their lattices of subsets. See also `complete_lattice_hom.set_preimage`. -/ @[simps] def Sup_hom.set_image (f : α → β) : Sup_hom (set α) (set β) := { to_fun := image f, map_Sup' := set.image_Sup } /-- An equivalence of types yields an order isomorphism between their lattices of subsets. -/ @[simps] def equiv.to_order_iso_set (e : α ≃ β) : set α ≃o set β := { to_fun := image e, inv_fun := image e.symm, left_inv := λ s, by simp only [← image_comp, equiv.symm_comp_self, id.def, image_id'], right_inv := λ s, by simp only [← image_comp, equiv.self_comp_symm, id.def, image_id'], map_rel_iff' := λ s t, ⟨λ h, by simpa using @monotone_image _ _ e.symm _ _ h, λ h, monotone_image h⟩ } variables [complete_lattice α] (x : α × α) /-- The map `(a, b) ↦ a ⊔ b` as a `Sup_hom`. -/ def sup_Sup_hom : Sup_hom (α × α) α := { to_fun := λ x, x.1 ⊔ x.2, map_Sup' := λ s, by simp_rw [prod.fst_Sup, prod.snd_Sup, Sup_image, supr_sup_eq] } /-- The map `(a, b) ↦ a ⊓ b` as an `Inf_hom`. -/ def inf_Inf_hom : Inf_hom (α × α) α := { to_fun := λ x, x.1 ⊓ x.2, map_Inf' := λ s, by simp_rw [prod.fst_Inf, prod.snd_Inf, Inf_image, infi_inf_eq] } @[simp, norm_cast] lemma sup_Sup_hom_apply : sup_Sup_hom x = x.1 ⊔ x.2 := rfl @[simp, norm_cast] lemma inf_Inf_hom_apply : inf_Inf_hom x = x.1 ⊓ x.2 := rfl
c97f8f3a4d3dbe0af9d515d5cd2cca74858623ae
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/module/submodule.lean
5bf48ebf4adf698bdfdd20080e59a909f338ef5a
[ "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
13,492
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.module.linear_map import group_theory.group_action.sub_mul_action /-! # Submodules of a module In this file we define * `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to addition and scalar multiplication. * `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`. ## Tags submodule, subspace, linear map -/ open function open_locale big_operators universes u' u v w variables {S : Type u'} {R : Type u} {M : Type v} {ι : Type w} set_option old_structure_cmd true /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] extends add_submonoid M, sub_mul_action R M : Type v. /-- Reinterpret a `submodule` as an `add_submonoid`. -/ add_decl_doc submodule.to_add_submonoid /-- Reinterpret a `submodule` as an `sub_mul_action`. -/ add_decl_doc submodule.to_sub_mul_action namespace submodule variables [semiring R] [add_comm_monoid M] [module R M] instance : set_like (submodule R M) M := ⟨submodule.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] theorem mem_to_add_submonoid (p : submodule R M) (x : M) : x ∈ p.to_add_submonoid ↔ x ∈ p := iff.rfl variables {p q : submodule R M} @[simp] lemma mk_coe (S : set M) (h₁ h₂ h₃) : ((⟨S, h₁, h₂, h₃⟩ : submodule R M) : set M) = S := rfl @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (p : submodule R M) (s : set M) (hs : s = ↑p) : submodule R M := { carrier := s, zero_mem' := hs.symm ▸ p.zero_mem', add_mem' := hs.symm ▸ p.add_mem', smul_mem' := hs.symm ▸ p.smul_mem' } theorem to_add_submonoid_injective : injective (to_add_submonoid : submodule R M → add_submonoid M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q := to_add_submonoid_injective.eq_iff @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : submodule R M → add_submonoid M) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : submodule R M → add_submonoid M) := to_add_submonoid_strict_mono.monotone @[simp] theorem coe_to_add_submonoid (p : submodule R M) : (p.to_add_submonoid : set M) = p := rfl theorem to_sub_mul_action_injective : injective (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_sub_mul_action_eq : p.to_sub_mul_action = q.to_sub_mul_action ↔ p = q := to_sub_mul_action_injective.eq_iff @[mono] lemma to_sub_mul_action_strict_mono : strict_mono (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ _ _, id @[mono] lemma to_sub_mul_action_mono : monotone (to_sub_mul_action : submodule R M → sub_mul_action R M) := to_sub_mul_action_strict_mono.monotone @[simp] theorem coe_to_sub_mul_action (p : submodule R M) : (p.to_sub_mul_action : set M) = p := rfl end submodule namespace submodule section add_comm_monoid variables [semiring S] [semiring R] [add_comm_monoid M] -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variables {module_M : module R M} variables {p q : submodule R M} variables {r : R} {x y : M} variables [has_scalar S R] [module S M] [is_scalar_tower S R M] variables (p) @[simp] lemma mem_carrier : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[simp] lemma zero_mem : (0 : M) ∈ p := p.zero_mem' lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add_mem' h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h lemma smul_of_tower_mem (r : S) (h : x ∈ p) : r • x ∈ p := p.to_sub_mul_action.smul_of_tower_mem r h lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p := p.to_add_submonoid.sum_mem lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p := submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (hyp i hi)) @[simp] lemma smul_mem_iff' (u : units S) : (u:S) • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff' u instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance : has_scalar S p := ⟨λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩⟩ protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩ @[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val variables {p} @[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := (set_like.coe_eq_coe : (x : M) = (0 : p) ↔ x = 0) @[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl @[norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_smul_of_tower (r : S) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl @[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2 variables (p) instance : add_comm_monoid p := { add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid } instance module' : module S p := by refine {smul := (•), ..p.to_sub_mul_action.mul_action', ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } instance : module R p := p.module' instance : is_scalar_tower S R p := p.to_sub_mul_action.is_scalar_tower instance no_zero_smul_divisors [no_zero_smul_divisors R M] : no_zero_smul_divisors R p := ⟨λ c x h, have c = 0 ∨ (x : M) = 0, from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h), this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩ /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →ₗ[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((submodule.subtype p) : p → M) = subtype.val := rfl /-- Note the `add_submonoid` version of this lemma is called `add_submonoid.coe_finset_sum`. -/ @[simp] lemma coe_sum (x : ι → p) (s : finset ι) : ↑(∑ i in s, x i) = ∑ i in s, (x i : M) := p.subtype.map_sum section restrict_scalars variables (S) [module R M] [is_scalar_tower S R M] /-- `V.restrict_scalars S` is the `S`-submodule of the `S`-module given by restriction of scalars, corresponding to `V`, an `R`-submodule of the original `R`-module. -/ @[simps] def restrict_scalars (V : submodule R M) : submodule S M := { carrier := V.carrier, zero_mem' := V.zero_mem, smul_mem' := λ c m h, V.smul_of_tower_mem c h, add_mem' := λ x y hx hy, V.add_mem hx hy } @[simp] lemma restrict_scalars_mem (V : submodule R M) (m : M) : m ∈ V.restrict_scalars S ↔ m ∈ V := iff.refl _ variables (R S M) lemma restrict_scalars_injective : function.injective (restrict_scalars S : submodule R M → submodule S M) := λ V₁ V₂ h, ext $ by convert set.ext_iff.1 (set_like.ext'_iff.1 h); refl @[simp] lemma restrict_scalars_inj {V₁ V₂ : submodule R M} : restrict_scalars S V₁ = restrict_scalars S V₂ ↔ V₁ = V₂ := (restrict_scalars_injective S _ _).eq_iff /-- Even though `p.restrict_scalars S` has type `submodule S M`, it is still an `R`-module. -/ instance restrict_scalars.orig_module (p : submodule R M) : module R (p.restrict_scalars S) := (by apply_instance : module R p) instance (p : submodule R M) : is_scalar_tower S R (p.restrict_scalars S) := { smul_assoc := λ r s x, subtype.ext $ smul_assoc r s (x : M) } /-- `restrict_scalars S` is an embedding of the lattice of `R`-submodules into the lattice of `S`-submodules. -/ @[simps] def restrict_scalars_embedding : submodule R M ↪o submodule S M := { to_fun := restrict_scalars S, inj' := restrict_scalars_injective S R M, map_rel_iff' := λ p q, by simp [set_like.le_def] } /-- Turning `p : submodule R M` into an `S`-submodule gives the same module structure as turning it into a type and adding a module structure. -/ @[simps {simp_rhs := tt}] def restrict_scalars_equiv (p : submodule R M) : p.restrict_scalars S ≃ₗ[R] p := { to_fun := id, inv_fun := id, map_smul' := λ c x, rfl, .. add_equiv.refl p } end restrict_scalars end add_comm_monoid section add_comm_group variables [ring R] [add_comm_group M] variables {module_M : module R M} variables (p p' : submodule R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := p.to_sub_mul_action.neg_mem hx /-- Reinterpret a submodule as an additive subgroup. -/ def to_add_subgroup : add_subgroup M := { neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid } @[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl @[simp] lemma mem_to_add_subgroup : x ∈ p.to_add_subgroup ↔ x ∈ p := iff.rfl include module_M theorem to_add_subgroup_injective : injective (to_add_subgroup : submodule R M → add_subgroup M) | p q h := set_like.ext (set_like.ext_iff.1 h : _) @[simp] theorem to_add_subgroup_eq : p.to_add_subgroup = p'.to_add_subgroup ↔ p = p' := to_add_subgroup_injective.eq_iff @[mono] lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : submodule R M → add_subgroup M) := λ _ _, id @[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : submodule R M → add_subgroup M) := to_add_subgroup_strict_mono.monotone omit module_M lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := p.to_add_subgroup.sub_mem @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := p.to_add_subgroup.neg_mem_iff lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := p.to_add_subgroup.add_mem_cancel_right lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := p.to_add_subgroup.add_mem_cancel_left instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl instance : add_comm_group p := { add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := rfl end add_comm_group section ordered_monoid variables [semiring R] /-- A submodule of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`. -/ instance to_ordered_add_comm_monoid {M} [ordered_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_add_comm_monoid S := subtype.coe_injective.ordered_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`. -/ instance to_linear_ordered_add_comm_monoid {M} [linear_ordered_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_add_comm_monoid S := subtype.coe_injective.linear_ordered_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`. -/ instance to_ordered_cancel_add_comm_monoid {M} [ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_cancel_add_comm_monoid S := subtype.coe_injective.ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) /-- A submodule of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`. -/ instance to_linear_ordered_cancel_add_comm_monoid {M} [linear_ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_cancel_add_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) end ordered_monoid section ordered_group variables [ring R] /-- A submodule of an `ordered_add_comm_group` is an `ordered_add_comm_group`. -/ instance to_ordered_add_comm_group {M} [ordered_add_comm_group M] [module R M] (S : submodule R M) : ordered_add_comm_group S := subtype.coe_injective.ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`. -/ instance to_linear_ordered_add_comm_group {M} [linear_ordered_add_comm_group M] [module R M] (S : submodule R M) : linear_ordered_add_comm_group S := subtype.coe_injective.linear_ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) end ordered_group end submodule namespace submodule variables [division_ring S] [semiring R] [add_comm_monoid M] [module R M] variables [has_scalar S R] [module S M] [is_scalar_tower S R M] variables (p : submodule R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff s0 end submodule /-- Subspace of a vector space. Defined to equal `submodule`. -/ abbreviation subspace (R : Type u) (M : Type v) [field R] [add_comm_group M] [module R M] := submodule R M
cbf7b645024ab52eefa4b9c6ca892f7c2a9698e8
82e44445c70db0f03e30d7be725775f122d72f3e
/src/number_theory/quadratic_reciprocity.lean
a9ba7764a71911a26d19faa6486f7a2a2977ec30
[ "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
24,988
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 field_theory.finite.basic import data.zmod.basic import data.nat.parity /-! # Quadratic reciprocity. This file contains results about quadratic residues modulo a prime number. The main results are the law of quadratic reciprocity, `quadratic_reciprocity`, as well as the interpretations in terms of existence of square roots depending on the congruence mod 4, `exists_sq_eq_prime_iff_of_mod_four_eq_one`, and `exists_sq_eq_prime_iff_of_mod_four_eq_three`. Also proven are conditions for `-1` and `2` to be a square modulo a prime, `exists_sq_eq_neg_one_iff_mod_four_ne_three` and `exists_sq_eq_two_iff` ## Implementation notes The proof of quadratic reciprocity implemented uses Gauss' lemma and Eisenstein's lemma -/ open function finset nat finite_field zmod open_locale big_operators nat namespace zmod variables (p q : ℕ) [fact p.prime] [fact q.prime] /-- Euler's Criterion: A unit `x` of `zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion_units (x : units (zmod p)) : (∃ y : units (zmod p), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, refine iff_of_true ⟨1, _⟩ _; apply subsingleton.elim }, obtain ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmod p)), obtain ⟨n, hn⟩ : x ∈ submonoid.powers g, { rw mem_powers_iff_mem_gpowers, apply hg }, split, { rintro ⟨y, rfl⟩, rw [← pow_mul, two_mul_odd_div_two hp_odd, units_pow_card_sub_one_eq_one], }, { subst x, assume h, have key : 2 * (p / 2) ∣ n * (p / 2), { rw [← pow_mul] at h, rw [two_mul_odd_div_two hp_odd, ← card_units, ← order_of_eq_card_of_forall_mem_gpowers hg], apply order_of_dvd_of_pow_eq_one h }, have : 0 < p / 2 := nat.div_pos (fact.out (1 < p)) dec_trivial, obtain ⟨m, rfl⟩ := dvd_of_mul_dvd_mul_right this key, refine ⟨g ^ m, _⟩, rw [mul_comm, pow_mul], }, end /-- Euler's Criterion: a nonzero `a : zmod p` is a square if and only if `x ^ (p / 2) = 1`. -/ lemma euler_criterion {a : zmod p} (ha : a ≠ 0) : (∃ y : zmod p, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := begin apply (iff_congr _ (by simp [units.ext_iff])).mp (euler_criterion_units p (units.mk0 a ha)), simp only [units.ext_iff, sq, units.coe_mk0, units.coe_mul], split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ }, { rintro ⟨y, rfl⟩, have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, }, refine ⟨units.mk0 y hy, _⟩, simp, } end lemma exists_sq_eq_neg_one_iff_mod_four_ne_three : (∃ y : zmod p, y ^ 2 = -1) ↔ p % 4 ≠ 3 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, exact dec_trivial }, haveI := fact.mk hp_odd, have neg_one_ne_zero : (-1 : zmod p) ≠ 0, from mt neg_eq_zero.1 one_ne_zero, rw [euler_criterion p neg_one_ne_zero, neg_one_pow_eq_pow_mod_two], cases mod_two_eq_zero_or_one (p / 2) with p_half_even p_half_odd, { rw [p_half_even, pow_zero, eq_self_iff_true, true_iff], contrapose! p_half_even with hp, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp], exact dec_trivial }, { rw [p_half_odd, pow_one, iff_false_intro (ne_neg_self p one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at p_half_odd, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp_odd, have hp : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp hp_odd p_half_odd, generalize : p % 4 = k, dec_trivial! } end lemma pow_div_two_eq_neg_one_or_one {a : zmod p} (ha : a ≠ 0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := begin cases nat.prime.eq_two_or_odd (fact.out p.prime) with hp2 hp_odd, { substI p, revert a ha, exact dec_trivial }, rw [← mul_self_eq_one_iff, ← pow_add, ← two_mul, two_mul_odd_div_two hp_odd], exact pow_card_sub_one_eq_one ha end /-- **Wilson's Lemma**: the product of `1`, ..., `p-1` is `-1` modulo `p`. -/ @[simp] lemma wilsons_lemma : ((p - 1)! : zmod p) = -1 := begin refine calc ((p - 1)! : zmod p) = (∏ x in Ico 1 (succ (p - 1)), x) : by rw [← finset.prod_Ico_id_eq_factorial, prod_nat_cast] ... = (∏ x : units (zmod p), x) : _ ... = -1 : by simp_rw [← units.coe_hom_apply, ← (units.coe_hom (zmod p)).map_prod, prod_univ_units_id_eq_neg_one, units.coe_hom_apply, units.coe_neg, units.coe_one], have hp : 0 < p := (fact.out p.prime).pos, symmetry, refine prod_bij (λ a _, (a : zmod p).val) _ _ _ _, { intros a ha, rw [Ico.mem, ← nat.succ_sub hp, nat.succ_sub_one], split, { apply nat.pos_of_ne_zero, rw ← @val_zero p, assume h, apply units.ne_zero a (val_injective p h) }, { exact val_lt _ } }, { intros a ha, simp only [cast_id, nat_cast_val], }, { intros _ _ _ _ h, rw units.ext_iff, exact val_injective p h }, { intros b hb, rw [Ico.mem, nat.succ_le_iff, ← succ_sub hp, succ_sub_one, pos_iff_ne_zero] at hb, refine ⟨units.mk0 b _, finset.mem_univ _, _⟩, { assume h, apply hb.1, apply_fun val at h, simpa only [val_cast_of_lt hb.right, val_zero] using h }, { simp only [val_cast_of_lt hb.right, units.coe_mk0], } } end @[simp] lemma prod_Ico_one_prime : (∏ x in Ico 1 p, (x : zmod p)) = -1 := begin conv in (Ico 1 p) { rw [← succ_sub_one p, succ_sub (fact.out p.prime).pos] }, rw [← prod_nat_cast, finset.prod_Ico_id_eq_factorial, wilsons_lemma] end end zmod /-- The image of the map sending a non zero natural number `x ≤ p / 2` to the absolute value of the element of interger in the interval `(-p/2, p/2]` congruent to `a * x` mod p is the set of non zero natural numbers `x` such that `x ≤ p / 2` -/ lemma Ico_map_val_min_abs_nat_abs_eq_Ico_map_id (p : ℕ) [hp : fact p.prime] (a : zmod p) (hap : a ≠ 0) : (Ico 1 (p / 2).succ).1.map (λ x, (a * x).val_min_abs.nat_abs) = (Ico 1 (p / 2).succ).1.map (λ a, a) := begin have he : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x ≠ 0 ∧ x ≤ p / 2, by simp [nat.lt_succ_iff, nat.succ_le_iff, pos_iff_ne_zero] {contextual := tt}, have hep : ∀ {x}, x ∈ Ico 1 (p / 2).succ → x < p, from λ x hx, lt_of_le_of_lt (he hx).2 (nat.div_lt_self hp.1.pos dec_trivial), have hpe : ∀ {x}, x ∈ Ico 1 (p / 2).succ → ¬ p ∣ x, from λ x hx hpx, not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero (he hx).1) hpx) (hep hx), have hmem : ∀ (x : ℕ) (hx : x ∈ Ico 1 (p / 2).succ), (a * x : zmod p).val_min_abs.nat_abs ∈ Ico 1 (p / 2).succ, { assume x hx, simp [hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hx, lt_succ_iff, succ_le_iff, pos_iff_ne_zero, nat_abs_val_min_abs_le _], }, have hsurj : ∀ (b : ℕ) (hb : b ∈ Ico 1 (p / 2).succ), ∃ x ∈ Ico 1 (p / 2).succ, b = (a * x : zmod p).val_min_abs.nat_abs, { assume b hb, refine ⟨(b / a : zmod p).val_min_abs.nat_abs, Ico.mem.mpr ⟨_, _⟩, _⟩, { apply nat.pos_of_ne_zero, simp only [div_eq_mul_inv, hap, char_p.cast_eq_zero_iff (zmod p) p, hpe hb, not_false_iff, val_min_abs_eq_zero, inv_eq_zero, int.nat_abs_eq_zero, ne.def, mul_eq_zero, or_self] }, { apply lt_succ_of_le, apply nat_abs_val_min_abs_le }, { rw nat_cast_nat_abs_val_min_abs, split_ifs, { erw [mul_div_cancel' _ hap, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat], }, { erw [mul_neg_eq_neg_mul_symm, mul_div_cancel' _ hap, nat_abs_val_min_abs_neg, val_min_abs_def_pos, val_cast_of_lt (hep hb), if_pos (le_of_lt_succ (Ico.mem.1 hb).2), int.nat_abs_of_nat] } } }, exact multiset.map_eq_map_of_bij_of_nodup _ _ (finset.nodup _) (finset.nodup _) (λ x _, (a * x : zmod p).val_min_abs.nat_abs) hmem (λ _ _, rfl) (inj_on_of_surj_on_of_card_le _ hmem hsurj (le_refl _)) hsurj end private lemma gauss_lemma_aux₁ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) * (p / 2)! : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! := calc (a ^ (p / 2) * (p / 2)! : zmod p) = (∏ x in Ico 1 (p / 2).succ, a * x) : by rw [prod_mul_distrib, ← prod_nat_cast, ← prod_nat_cast, prod_Ico_id_eq_factorial, prod_const, Ico.card, succ_sub_one]; simp ... = (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val) : by simp ... = (∏ x in Ico 1 (p / 2).succ, (if (a * x : zmod p).val ≤ p / 2 then 1 else -1) * (a * x : zmod p).val_min_abs.nat_abs) : prod_congr rfl $ λ _ _, begin simp only [nat_cast_nat_abs_val_min_abs], split_ifs; simp end ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (∏ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : have (∏ x in Ico 1 (p / 2).succ, if (a * x : zmod p).val ≤ p / 2 then (1 : zmod p) else -1) = (∏ x in (Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2), -1), from prod_bij_ne_one (λ x _ _, x) (λ x, by split_ifs; simp * at * {contextual := tt}) (λ _ _ _ _ _ _, id) (λ b h _, ⟨b, by simp [-not_le, *] at *⟩) (by intros; split_ifs at *; simp * at *), by rw [prod_mul_distrib, this]; simp ... = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, ¬(a * x : zmod p).val ≤ p / 2)).card * (p / 2)! : by rw [← prod_nat_cast, finset.prod_eq_multiset_prod, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.prod_eq_multiset_prod, prod_Ico_id_eq_factorial] private lemma gauss_lemma_aux₂ (p : ℕ) [hp : fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : (a^(p / 2) : zmod p) = (-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := (mul_left_inj' (show ((p / 2)! : zmod p) ≠ 0, by rw [ne.def, char_p.cast_eq_zero_iff (zmod p) p, hp.1.dvd_factorial, not_le]; exact nat.div_lt_self hp.1.pos dec_trivial)).1 $ by simpa using gauss_lemma_aux₁ p hap private lemma eisenstein_lemma_aux₁ (p : ℕ) [fact p.prime] [hp2 : fact (p % 2 = 1)] {a : ℕ} (hap : (a : zmod p) ≠ 0) : ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card + ∑ x in Ico 1 (p / 2).succ, x + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) := have hp2 : (p : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 hp2.1, calc ((∑ x in Ico 1 (p / 2).succ, a * x : ℕ) : zmod 2) = ((∑ x in Ico 1 (p / 2).succ, ((a * x) % p + p * ((a * x) / p)) : ℕ) : zmod 2) : by simp only [mod_add_div] ... = (∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) + (∑ x in Ico 1 (p / 2).succ, (a * x) / p : ℕ) : by simp only [val_nat_cast]; simp [sum_add_distrib, mul_sum.symm, nat.cast_add, nat.cast_mul, nat.cast_sum, hp2] ... = _ : congr_arg2 (+) (calc ((∑ x in Ico 1 (p / 2).succ, ((a * x : ℕ) : zmod p).val : ℕ) : zmod 2) = ∑ x in Ico 1 (p / 2).succ, ((((a * x : zmod p).val_min_abs + (if (a * x : zmod p).val ≤ p / 2 then 0 else p)) : ℤ) : zmod 2) : by simp only [(val_eq_ite_val_min_abs _).symm]; simp [nat.cast_sum] ... = ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card + ((∑ x in Ico 1 (p / 2).succ, (a * x : zmod p).val_min_abs.nat_abs) : ℕ) : by { simp [ite_cast, add_comm, sum_add_distrib, finset.sum_ite, hp2, nat.cast_sum], } ... = _ : by rw [finset.sum_eq_multiset_sum, Ico_map_val_min_abs_nat_abs_eq_Ico_map_id p a hap, ← finset.sum_eq_multiset_sum]; simp [nat.cast_sum]) rfl private lemma eisenstein_lemma_aux₂ (p : ℕ) [fact p.prime] [fact (p % 2 = 1)] {a : ℕ} (ha2 : a % 2 = 1) (hap : (a : zmod p) ≠ 0) : ((Ico 1 (p / 2).succ).filter ((λ x : ℕ, p / 2 < (a * x : zmod p).val))).card ≡ ∑ x in Ico 1 (p / 2).succ, (x * a) / p [MOD 2] := have ha2 : (a : zmod 2) = (1 : ℕ), from (eq_iff_modeq_nat _).2 ha2, (eq_iff_modeq_nat 2).1 $ sub_eq_zero.1 $ by simpa [add_left_comm, sub_eq_add_neg, finset.mul_sum.symm, mul_comm, ha2, nat.cast_sum, add_neg_eq_iff_eq_add.symm, neg_eq_self_mod_two, add_assoc] using eq.symm (eisenstein_lemma_aux₁ p hap) lemma div_eq_filter_card {a b c : ℕ} (hb0 : 0 < b) (hc : a / b ≤ c) : a / b = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card := calc a / b = (Ico 1 (a / b).succ).card : by simp ... = ((Ico 1 c.succ).filter (λ x, x * b ≤ a)).card : congr_arg _ $ finset.ext $ λ x, have x * b ≤ a → x ≤ c, from λ h, le_trans (by rwa [le_div_iff_mul_le _ _ hb0]) hc, by simp [lt_succ_iff, le_div_iff_mul_le _ _ hb0]; tauto /-- The given sum is the number of integer points in the triangle formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)` -/ private lemma sum_Ico_eq_card_lt {p q : ℕ} : ∑ a in Ico 1 (p / 2).succ, (a * q) / p = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)).card := if hp0 : p = 0 then by simp [hp0, finset.ext_iff] else calc ∑ a in Ico 1 (p / 2).succ, (a * q) / p = ∑ a in Ico 1 (p / 2).succ, ((Ico 1 (q / 2).succ).filter (λ x, x * p ≤ a * q)).card : finset.sum_congr rfl $ λ x hx, div_eq_filter_card (nat.pos_of_ne_zero hp0) (calc x * q / p ≤ (p / 2) * q / p : nat.div_le_div_right (mul_le_mul_of_nonneg_right (le_of_lt_succ $ by finish) (nat.zero_le _)) ... ≤ _ : nat.div_mul_div_le_div _ _ _) ... = _ : by rw [← card_sigma]; exact card_congr (λ a _, ⟨a.1, a.2⟩) (by simp only [mem_filter, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, heq_iff_eq, forall_true_iff] {contextual := tt}) (λ ⟨b₁, b₂⟩ h, ⟨⟨b₁, b₂⟩, by revert h; simp only [mem_filter, eq_self_iff_true, exists_prop_of_true, mem_sigma, and_self, forall_true_iff, mem_product] {contextual := tt}⟩) /-- Each of the sums in this lemma is the cardinality of the set integer points in each of the two triangles formed by the diagonal of the rectangle `(0, p/2) × (0, q/2)`. Adding them gives the number of points in the rectangle. -/ private lemma sum_mul_div_add_sum_mul_div_eq_mul (p q : ℕ) [hp : fact p.prime] (hq0 : (q : zmod p) ≠ 0) : ∑ a in Ico 1 (p / 2).succ, (a * q) / p + ∑ a in Ico 1 (q / 2).succ, (a * p) / q = (p / 2) * (q / 2) := begin have hswap : (((Ico 1 (q / 2).succ).product (Ico 1 (p / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * q ≤ x.1 * p)).card = (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)).card := card_congr (λ x _, prod.swap x) (λ ⟨_, _⟩, by simp only [mem_filter, and_self, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}) (λ ⟨_, _⟩ ⟨_, _⟩, by simp only [prod.mk.inj_iff, eq_self_iff_true, and_self, prod.swap_prod_mk, forall_true_iff] {contextual := tt}) (λ ⟨x₁, x₂⟩ h, ⟨⟨x₂, x₁⟩, by revert h; simp only [mem_filter, eq_self_iff_true, and_self, exists_prop_of_true, prod.swap_prod_mk, forall_true_iff, mem_product] {contextual := tt}⟩), have hdisj : disjoint (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q)) (((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p)), { apply disjoint_filter.2 (λ x hx hpq hqp, _), have hxp : x.1 < p, from lt_of_le_of_lt (show x.1 ≤ p / 2, by simp only [*, lt_succ_iff, Ico.mem, mem_product] at *; tauto) (nat.div_lt_self hp.1.pos dec_trivial), have : (x.1 : zmod p) = 0, { simpa [hq0] using congr_arg (coe : ℕ → zmod p) (le_antisymm hpq hqp) }, apply_fun zmod.val at this, rw [val_cast_of_lt hxp, val_zero] at this, simpa only [this, nonpos_iff_eq_zero, Ico.mem, one_ne_zero, false_and, mem_product] using hx }, have hunion : ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.2 * p ≤ x.1 * q) ∪ ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)).filter (λ x : ℕ × ℕ, x.1 * q ≤ x.2 * p) = ((Ico 1 (p / 2).succ).product (Ico 1 (q / 2).succ)), from finset.ext (λ x, by have := le_total (x.2 * p) (x.1 * q); simp only [mem_union, mem_filter, Ico.mem, mem_product]; tauto), rw [sum_Ico_eq_card_lt, sum_Ico_eq_card_lt, hswap, ← card_disjoint_union hdisj, hunion, card_product], simp only [Ico.card, nat.sub_zero, succ_sub_succ_eq_sub] end variables (p q : ℕ) [fact p.prime] [fact q.prime] namespace zmod /-- The Legendre symbol of `a` and `p` is an integer defined as * `0` if `a` is `0` modulo `p`; * `1` if `a ^ (p / 2)` is `1` modulo `p` (by `euler_criterion` this is equivalent to “`a` is a square modulo `p`”); * `-1` otherwise. -/ def legendre_sym (a p : ℕ) : ℤ := if (a : zmod p) = 0 then 0 else if (a : zmod p) ^ (p / 2) = 1 then 1 else -1 lemma legendre_sym_eq_pow (a p : ℕ) [hp : fact p.prime] : (legendre_sym a p : zmod p) = (a ^ (p / 2)) := begin rw legendre_sym, by_cases ha : (a : zmod p) = 0, { simp only [if_pos, ha, zero_pow (nat.div_pos (hp.1.two_le) (succ_pos 1)), int.cast_zero] }, cases hp.1.eq_two_or_odd with hp2 hp_odd, { substI p, generalize : (a : (zmod 2)) = b, revert b, dec_trivial, }, { haveI := fact.mk hp_odd, rw if_neg ha, have : (-1 : zmod p) ≠ 1, from (ne_neg_self p one_ne_zero).symm, cases pow_div_two_eq_neg_one_or_one p ha with h h, { rw [if_pos h, h, int.cast_one], }, { rw [h, if_neg this, int.cast_neg, int.cast_one], } } end lemma legendre_sym_eq_one_or_neg_one (a p : ℕ) (ha : (a : zmod p) ≠ 0) : legendre_sym a p = -1 ∨ legendre_sym a p = 1 := by unfold legendre_sym; split_ifs; simp only [*, eq_self_iff_true, or_true, true_or] at * lemma legendre_sym_eq_zero_iff (a p : ℕ) : legendre_sym a p = 0 ↔ (a : zmod p) = 0 := begin split, { classical, contrapose, assume ha, cases legendre_sym_eq_one_or_neg_one a p ha with h h, all_goals { rw h, norm_num } }, { assume ha, rw [legendre_sym, if_pos ha] } end /-- Gauss' lemma. The legendre symbol can be computed by considering the number of naturals less than `p/2` such that `(a * x) % p > p / 2` -/ lemma gauss_lemma {a : ℕ} [fact (p % 2 = 1)] (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1) ^ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card := have (legendre_sym a p : zmod p) = (((-1)^((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card : ℤ) : zmod p), by rw [legendre_sym_eq_pow, gauss_lemma_aux₂ p ha0]; simp, begin cases legendre_sym_eq_one_or_neg_one a p ha0; cases neg_one_pow_eq_or ℤ ((Ico 1 (p / 2).succ).filter (λ x : ℕ, p / 2 < (a * x : zmod p).val)).card; simp [*, ne_neg_self p one_ne_zero, (ne_neg_self p one_ne_zero).symm] at * end lemma legendre_sym_eq_one_iff {a : ℕ} (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = 1 ↔ (∃ b : zmod p, b ^ 2 = a) := begin rw [euler_criterion p ha0, legendre_sym, if_neg ha0], split_ifs, { simp only [h, eq_self_iff_true] }, finish -- this is quite slow. I'm actually surprised that it can close the goal at all! end lemma eisenstein_lemma [fact (p % 2 = 1)] {a : ℕ} (ha1 : a % 2 = 1) (ha0 : (a : zmod p) ≠ 0) : legendre_sym a p = (-1)^∑ x in Ico 1 (p / 2).succ, (x * a) / p := by rw [neg_one_pow_eq_pow_mod_two, gauss_lemma p ha0, neg_one_pow_eq_pow_mod_two, show _ = _, from eisenstein_lemma_aux₂ p ha1 ha0] /-- **Quadratic reciprocity theorem** -/ theorem quadratic_reciprocity [hp1 : fact (p % 2 = 1)] [hq1 : fact (q % 2 = 1)] (hpq : p ≠ q) : legendre_sym p q * legendre_sym q p = (-1) ^ ((p / 2) * (q / 2)) := have hpq0 : (p : zmod q) ≠ 0, from prime_ne_zero q p hpq.symm, have hqp0 : (q : zmod p) ≠ 0, from prime_ne_zero p q hpq, by rw [eisenstein_lemma q hp1.1 hpq0, eisenstein_lemma p hq1.1 hqp0, ← pow_add, sum_mul_div_add_sum_mul_div_eq_mul q p hpq0, mul_comm] -- move this local attribute [instance] lemma fact_prime_two : fact (nat.prime 2) := ⟨nat.prime_two⟩ lemma legendre_sym_two [hp1 : fact (p % 2 = 1)] : legendre_sym 2 p = (-1) ^ (p / 4 + p / 2) := have hp2 : p ≠ 2, from mt (congr_arg (% 2)) (by simpa using hp1.1), have hp22 : p / 2 / 2 = _ := div_eq_filter_card (show 0 < 2, from dec_trivial) (nat.div_le_self (p / 2) 2), have hcard : (Ico 1 (p / 2).succ).card = p / 2, by simp, have hx2 : ∀ x ∈ Ico 1 (p / 2).succ, (2 * x : zmod p).val = 2 * x, from λ x hx, have h2xp : 2 * x < p, from calc 2 * x ≤ 2 * (p / 2) : mul_le_mul_of_nonneg_left (le_of_lt_succ $ by finish) dec_trivial ... < _ : by conv_rhs {rw [← div_add_mod p 2, hp1.1]}; exact lt_succ_self _, by rw [← nat.cast_two, ← nat.cast_mul, val_cast_of_lt h2xp], have hdisj : disjoint ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)), from disjoint_filter.2 (λ x hx, by simp [hx2 _ hx, mul_comm]), have hunion : ((Ico 1 (p / 2).succ).filter (λ x, p / 2 < ((2 : ℕ) * x : zmod p).val)) ∪ ((Ico 1 (p / 2).succ).filter (λ x, x * 2 ≤ p / 2)) = Ico 1 (p / 2).succ, begin rw [filter_union_right], conv_rhs {rw [← @filter_true _ (Ico 1 (p / 2).succ)]}, exact filter_congr (λ x hx, by simp [hx2 _ hx, lt_or_le, mul_comm]) end, begin rw [gauss_lemma p (prime_ne_zero p 2 hp2), neg_one_pow_eq_pow_mod_two, @neg_one_pow_eq_pow_mod_two _ _ (p / 4 + p / 2)], refine congr_arg2 _ rfl ((eq_iff_modeq_nat 2).1 _), rw [show 4 = 2 * 2, from rfl, ← nat.div_div_eq_div_mul, hp22, nat.cast_add, ← sub_eq_iff_eq_add', sub_eq_add_neg, neg_eq_self_mod_two, ← nat.cast_add, ← card_disjoint_union hdisj, hunion, hcard] end lemma exists_sq_eq_two_iff [hp1 : fact (p % 2 = 1)] : (∃ a : zmod p, a ^ 2 = 2) ↔ p % 8 = 1 ∨ p % 8 = 7 := have hp2 : ((2 : ℕ) : zmod p) ≠ 0, from prime_ne_zero p 2 (λ h, by simpa [h] using hp1.1), have hpm4 : p % 4 = p % 8 % 4, from (nat.mod_mul_left_mod p 2 4).symm, have hpm2 : p % 2 = p % 8 % 2, from (nat.mod_mul_left_mod p 4 2).symm, begin rw [show (2 : zmod p) = (2 : ℕ), by simp, ← legendre_sym_eq_one_iff p hp2, legendre_sym_two p, neg_one_pow_eq_one_iff_even (show (-1 : ℤ) ≠ 1, from dec_trivial), even_add, even_div, even_div], have := nat.mod_lt p (show 0 < 8, from dec_trivial), resetI, rw fact_iff at hp1, revert this hp1, erw [hpm4, hpm2], generalize hm : p % 8 = m, unfreezingI {clear_dependent p}, dec_trivial!, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) [hq1 : fact (q % 2 = 1)] : (∃ a : zmod p, a ^ 2 = q) ↔ ∃ b : zmod q, b ^ 2 = p := if hpq : p = q then by substI hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin haveI hp_odd : fact (p % 2 = 1) := ⟨odd_of_mod_four_eq_one hp1⟩, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hqp0, if_neg hpq0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction, end lemma exists_sq_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p ≠ q) : (∃ a : zmod p, a ^ 2 = q) ↔ ¬∃ b : zmod q, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin haveI hp_odd : fact (p % 2 = 1) := ⟨odd_of_mod_four_eq_three hp3⟩, haveI hq_odd : fact (q % 2 = 1) := ⟨odd_of_mod_four_eq_three hq3⟩, have hpq0 : (p : zmod q) ≠ 0 := prime_ne_zero q p (ne.symm hpq), have hqp0 : (q : zmod p) ≠ 0 := prime_ne_zero p q hpq, have := quadratic_reciprocity p q hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg hpq0, if_neg hqp0] at this, rw [euler_criterion q hpq0, euler_criterion p hqp0], split_ifs at this; simp *; contradiction end end zmod
3e8bb905a65e7d97b0cec95b70e710c830daee5f
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/instances/ennreal.lean
3929f95e8318de25462115c06860137bfbc5c682
[ "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
54,868
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.instances.nnreal import topology.algebra.ordered.liminf_limsup /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical topological_space ennreal nnreal big_operators filter variables {α : Type*} {β : Type*} {γ : Type*} namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} section topological_space open topological_space /-- Topology on `ℝ≥0∞`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ℝ≥0∞ := preorder.topology ℝ≥0∞ instance : order_topology ℝ≥0∞ := ⟨rfl⟩ instance : t2_space ℝ≥0∞ := by apply_instance -- short-circuit type class inference instance : second_countable_topology ℝ≥0∞ := ⟨⟨⋃q ≥ (0:ℚ), {{a : ℝ≥0∞ | a < real.to_nnreal q}, {a : ℝ≥0∞ | ↑(real.to_nnreal q) < a}}, (countable_encodable _).bUnion $ assume a ha, (countable_singleton _).insert _, le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) (le_generate_from $ λ s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < real.to_nnreal q}, {b | ↑(real.to_nnreal q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(real.to_nnreal q) < a}, {b | b < ↑(real.to_nnreal q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end)⟩⟩ lemma embedding_coe : embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ≥0 | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : ℝ≥0 | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ℝ≥0∞ | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma open_embedding_coe : open_embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩ lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ℝ≥0∞) ∈ 𝓝 (r : ℝ≥0∞) := is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _ @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} : tendsto (λa, (m a : ℝ≥0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ≥0∞) := embedding_coe.continuous lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} : continuous (λa, (f a : ℝ≥0∞)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ℝ≥0∞) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma tendsto_nhds_coe_iff {α : Type*} {l : filter α} {x : ℝ≥0} {f : ℝ≥0∞ → α} : tendsto f (𝓝 ↑x) l ↔ tendsto (f ∘ coe : ℝ≥0 → α) (𝓝 x) l := show _ ≤ _ ↔ _ ≤ _, by rw [nhds_coe, filter.map_map] lemma continuous_at_coe_iff {α : Type*} [topological_space α] {x : ℝ≥0} {f : ℝ≥0∞ → α} : continuous_at f (↑x) ↔ continuous_at (f ∘ coe : ℝ≥0 → α) x := tendsto_nhds_coe_iff lemma nhds_coe_coe {r p : ℝ≥0} : 𝓝 ((r : ℝ≥0∞), (p : ℝ≥0∞)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe_iff.2 continuous_id).comp nnreal.continuous_of_real lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) := begin lift a to ℝ≥0 using ha, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := λ a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha) lemma tendsto_to_real {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) := nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_subtype_mk _ continuous_coe, .. ne_top_equiv_nnreal } /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) := nhds_top.trans $ infi_ne_top _ lemma nhds_top_basis : (𝓝 ∞).has_basis (λ a, a < ∞) (λ a, Ioi a) := nhds_top_basis lemma tendsto_nhds_top_iff_nnreal {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi] lemma tendsto_nhds_top_iff_nat {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a := tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n, λ h x, let ⟨n, hn⟩ := exists_nat_gt x in (h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩ lemma tendsto_nhds_top {m : α → ℝ≥0∞} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_top_iff_nat.2 h lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n+1, λ m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ @[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} : tendsto (λ x, (f x : ℝ≥0∞)) l (𝓝 ∞) ↔ tendsto f l at_top := by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff]; [simp, apply_instance, apply_instance] lemma nhds_zero : 𝓝 (0 : ℝ≥0∞) = ⨅a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) (λ a, Iio a) := nhds_bot_basis lemma nhds_zero_basis_Iic : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) Iic := nhds_bot_basis_Iic @[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝ≥0} : (𝓝[Ioi r] (r : ℝ≥0∞)).ne_bot := nhds_within_Ioi_self_ne_bot' ennreal.coe_lt_top @[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[Ioi 0] (0 : ℝ≥0∞)).ne_bot := nhds_within_Ioi_coe_ne_bot -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds : x ≠ ⊤ → 0 < ε → Icc (x - ε) (x + ε) ∈ 𝓝 x := begin assume xt ε0, rw _root_.mem_nhds_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top : x ≠ ⊤ → 𝓝 x = ⨅ε > 0, 𝓟 (Icc (x - ε) (x + ε)) := begin assume xt, refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0, -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩, cases ha, { rw ha at *, rcases exists_between xs with ⟨b, ⟨ab, bx⟩⟩, have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx), refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rw ha at *, rcases exists_between xs with ⟨b, ⟨xb, ba⟩⟩, have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb, have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb), refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ℝ≥0∞` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter α} {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] instance : has_continuous_add ℝ≥0∞ := begin refine ⟨continuous_iff_continuous_at.2 _⟩, rintro ⟨(_|a), b⟩, { exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) }, rcases b with (_|b), { exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) }, simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] end protected lemma tendsto_at_top_zero [hβ : nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} : filter.at_top.tendsto f (𝓝 0) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, f n ≤ ε := begin rw ennreal.tendsto_at_top zero_ne_top, { simp_rw [set.mem_Icc, zero_add, zero_sub, zero_le _, true_and], }, { exact hβ, }, end protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ℝ≥0∞, b ≠ 0 → tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 ((⊤:ℝ≥0∞), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _, rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩, replace hε : 0 < ε, from coe_pos.1 hε, filter_upwards [prod_is_open.mem_nhds (lt_mem_nhds $ @coe_lt_top (n / ε)) (lt_mem_nhds hεb)], rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, dsimp at h₁ h₂ ⊢, rw [← div_mul_cancel n hε.ne', coe_mul], exact mul_lt_mul h₁ h₂ end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ℝ≥0∞) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) protected lemma tendsto.const_mul {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha lemma tendsto_finset_prod_of_ne_top {ι : Type*} {f : ι → α → ℝ≥0∞} {x : filter α} {a : ι → ℝ≥0∞} (s : finset ι) (h : ∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) (h' : ∀ i ∈ s, a i ≠ ∞): tendsto (λ b, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := begin induction s using finset.induction with a s has IH, { simp [tendsto_const_nhds] }, simp only [finset.prod_insert has], apply tendsto.mul (h _ (finset.mem_insert_self _ _)), { right, exact (prod_lt_top (λ i hi, lt_top_iff_ne_top.2 (h' _ (finset.mem_insert_of_mem hi)))).ne }, { exact IH (λ i hi, h _ (finset.mem_insert_of_mem hi)) (λ i hi, h' _ (finset.mem_insert_of_mem hi)) }, { exact or.inr (h' _ (finset.mem_insert_self _ _)) } end protected lemma continuous_at_const_mul {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at ((*) a) b := tendsto.const_mul tendsto_id h.symm protected lemma continuous_at_mul_const {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (λ x, x * a) b := tendsto.mul_const tendsto_id h.symm protected lemma continuous_const_mul {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha) protected lemma continuous_mul_const {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous (λ x, x * a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha) lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0∞} (h : ∀ a < 1, a * x ≤ y) : x ≤ y := begin have : tendsto (* x) (𝓝[Iio 1] 1) (𝓝 (1 * x)) := (ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left, rw one_mul at this, haveI : (𝓝[Iio 1] (1 : ℝ≥0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ennreal.zero_lt_one, exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h) end lemma infi_mul_left' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, a * f i) = a * ⨅ i, f i := begin by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0, { rcases h H.1 H.2 with ⟨i, hi⟩, rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot], exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ }, { rw not_and_distrib at H, casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, mul_top, if_neg], exact mt h0 (not_nonempty_iff.2 ‹_›) }, { exact (map_infi_of_continuous_at_of_monotone' (ennreal.continuous_at_const_mul H) ennreal.mul_left_mono).symm } } end lemma infi_mul_left {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, a * f i) = a * ⨅ i, f i := infi_mul_left' h (λ _, ‹nonempty ι›) lemma infi_mul_right' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, f i * a) = (⨅ i, f i) * a := by simpa only [mul_comm a] using infi_mul_left' h h0 lemma infi_mul_right {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, f i * a) = (⨅ i, f i) * a := infi_mul_right' h (λ _, ‹nonempty ι›) protected lemma continuous_inv : continuous (has_inv.inv : ℝ≥0∞ → ℝ≥0∞) := continuous_iff_continuous_at.2 $ λ a, tendsto_order.2 ⟨begin assume b hb, simp only [@ennreal.lt_inv_iff_lt_inv b], exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb), end, begin assume b hb, simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b], exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb) end⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [function.comp, ennreal.inv_inv] using (ennreal.continuous_inv.tendsto a⁻¹).comp h, (ennreal.continuous_inv.tendsto a).comp⟩ protected lemma tendsto.div {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ℝ≥0∞)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := begin simp only [← Sup_image], symmetry, rw [image_comp (+ a)], refine is_lub.Sup_eq ((is_lub_Sup $ f '' s).is_lub_of_tendsto _ (hs.image _) _), exacts [λ x _ y _ hxy, add_le_add hxy le_rfl, tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds] end lemma Sup_add {s : set ℝ≥0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := by rw [Sup_eq_supr, bsupr_add hs] lemma supr_add {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by rw Sup_range ... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩ ... = _ : supr_range lemma add_supr {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr {ι : Sort*} {f g : ι → ℝ≥0∞} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hι : nonempty ι, { letI := hι, refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : ∀f:ι → ℝ≥0∞, (⨆i, f i) = 0 := λ f, supr_eq_zero.mpr (λ i, (hι ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ℝ≥0∞} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ℝ≥0∞} (hf : ∀a, monotone (f a)) : ∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) := begin refine finset.induction_on s _ _, { simp, }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end lemma mul_Sup {s : set ℝ≥0∞} {a : ℝ≥0∞} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : ∀x∈s, x = (0:ℝ≥0∞), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0), have h₂ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, h₂, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₁ : Sup s ≠ 0 := pos_iff_ne_zero.1 (lt_of_lt_of_le (pos_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((λb, a * b) '' s) = a * Sup s := is_lub.Sup_eq ((is_lub_Sup s).is_lub_of_tendsto (assume x _ y _ h, mul_le_mul_left' h _) ⟨x, hx⟩ (ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end lemma mul_supr {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] lemma supr_div {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f / a = ⨆i, f i / a := supr_mul protected lemma tendsto_coe_sub : ∀{b:ℝ≥0∞}, tendsto (λb:ℝ≥0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine (forall_ennreal.2 $ and.intro (assume a, _) _), { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm], exact tendsto_const_nhds.sub tendsto_id }, simp, exact (tendsto.congr' (mem_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [nonempty ι] {b : ι → ℝ≥0∞} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto (assume x _ y _, sub_le_sub (le_refl _)) (range_nonempty _) (ennreal.tendsto_coe_sub.comp (tendsto_id' inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _ end topological_space section tsum variables {f g : α → ℝ≥0∞} @[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ≥0∞)) ↑r ↔ has_sum f r := have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ℝ≥0∞) ∘ (λs:finset α, ∑ a in s, f a), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ℝ≥0∞) = r := (ennreal.has_sum_coe.2 h).tsum_eq protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ℝ≥0∞) | ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) := tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} : ∑' b, (f b:ℝ≥0∞) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ℝ≥0∞)) to ℝ≥0 using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) := ennreal.has_sum.tsum_eq protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) : ∑' a, f a = ⨆ i, ∑ a in s i, f a := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ℝ≥0∞) : ∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ℝ≥0∞) : ∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ℝ≥0∞} : ∑'p:α×β, f p.1 p.2 = ∑'a, ∑'b, f a b := tsum_prod' ennreal.summable $ λ _, ennreal.summable protected lemma tsum_comm {f : α → β → ℝ≥0∞} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b := tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable) protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma sum_le_tsum {f : α → ℝ≥0∞} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x := sum_le_tsum s (λ x hx, zero_le _) ennreal.summable protected lemma tsum_eq_supr_nat' {f : ℕ → ℝ≥0∞} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) := ennreal.tsum_eq_supr_sum' _ $ λ t, let ⟨n, hn⟩ := t.exists_nat_subset_range, ⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in ⟨k, finset.subset.trans hn (finset.range_mono hk)⟩ protected lemma tsum_eq_supr_nat {f : ℕ → ℝ≥0∞} : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma tsum_eq_liminf_sum_nat {f : ℕ → ℝ≥0∞} : ∑' i, f i = filter.at_top.liminf (λ n, ∑ i in finset.range n, f i) := begin rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat], congr, refine funext (λ n, le_antisymm _ _), { refine le_binfi (λ i hi, finset.sum_le_sum_of_subset_of_nonneg _ (λ _ _ _, zero_le _)), simpa only [finset.range_subset, add_le_add_iff_right] using hi, }, { refine le_trans (infi_le _ n) _, simp [le_refl n, le_refl ((finset.range n).sum f)], }, end protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a := le_tsum' ennreal.summable a protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞ | ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a @[simp] protected lemma tsum_top [nonempty α] : ∑' a : α, ∞ = ∞ := let ⟨a⟩ := ‹nonempty α› in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩ protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ ∑'i, f i : ennreal.le_tsum _, have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)), by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j, from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), has_sum.tsum_eq this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ℝ≥0∞} : ∑'b:α, (⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0∞} (r : ℝ≥0∞) : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end lemma tendsto_nat_tsum (f : ℕ → ℝ≥0∞) : tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 (∑' n, f n)) := by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum } lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) (x : α) : (((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ℝ≥0∞) = f x := coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _ lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) : summable (ennreal.to_nnreal ∘ f) := by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf lemma tendsto_cofinite_zero_of_tsum_lt_top {α} {f : α → ℝ≥0∞} (hf : ∑' x, f x < ∞) : tendsto f cofinite (𝓝 0) := begin have f_ne_top : ∀ n, f n ≠ ∞, from ennreal.ne_top_of_tsum_ne_top hf.ne, have h_f_coe : f = λ n, ((f n).to_nnreal : ennreal), from funext (λ n, (coe_to_nnreal (f_ne_top n)).symm), rw [h_f_coe, ←@coe_zero, tendsto_coe], exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf.ne), end lemma tendsto_at_top_zero_of_tsum_lt_top {f : ℕ → ℝ≥0∞} (hf : ∑' x, f x < ∞) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_lt_top hf } protected lemma tsum_apply {ι α : Type*} {f : ι → α → ℝ≥0∞} {x : α} : (∑' i, f i) x = ∑' i, f i x := tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable lemma tsum_sub {f : ℕ → ℝ≥0∞} {g : ℕ → ℝ≥0∞} (h₁ : ∑' i, g i < ∞) (h₂ : g ≤ f) : ∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) := begin have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i, { rw [ennreal.tsum_add, add_sub_self h₁]}, have h₄:(λ i, (f i - g i) + (g i)) = f, { ext n, rw ennreal.sub_add_cancel_of_le (h₂ n)}, rw h₄ at h₃, apply h₃, end end tsum lemma tendsto_to_real_iff {ι} {fi : filter ι} {f : ι → ℝ≥0∞} (hf : ∀ i, f i ≠ ∞) {x : ℝ≥0∞} (hx : x ≠ ∞) : fi.tendsto (λ n, (f n).to_real) (𝓝 x.to_real) ↔ fi.tendsto f (𝓝 x) := begin refine ⟨λ h, _, λ h, tendsto.comp (ennreal.tendsto_to_real hx) h⟩, have h_eq : f = (λ n, ennreal.of_real (f n).to_real), by { ext1 n, rw ennreal.of_real_to_real (hf n), }, rw [h_eq, ← ennreal.of_real_to_real hx], exact ennreal.tendsto_of_real h, end lemma tsum_coe_ne_top_iff_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) ≠ ∞ ↔ summable (λ a, (f a : ℝ)) := begin rw nnreal.summable_coe, exact tsum_coe_ne_top_iff_summable, end lemma tsum_coe_eq_top_iff_not_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) = ∞ ↔ ¬ summable (λ a, (f a : ℝ)) := begin rw [← @not_not (∑' a, ↑(f a) = ⊤)], exact not_congr tsum_coe_ne_top_iff_summable_coe end lemma summable_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : summable (λ x, (f x).to_real) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hsum, rwa ennreal.tsum_coe_ne_top_iff_summable_coe at hsum, end end ennreal namespace nnreal open_locale nnreal lemma tsum_eq_to_nnreal_tsum {f : β → ℝ≥0} : (∑' b, f b) = (∑' b, (f b : ℝ≥0∞)).to_nnreal := begin by_cases h : summable f, { rw [← ennreal.coe_tsum h, ennreal.to_nnreal_coe] }, { have A := tsum_eq_zero_of_not_summable h, simp only [← ennreal.tsum_coe_ne_top_iff_summable, not_not] at h, simp only [h, ennreal.top_to_nnreal, A] } end /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have ∑'b, (g b : ℝ≥0∞) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin split, { intros h, refine ((tendsto_of_monotone _).resolve_right h).comp _, exacts [finset.sum_mono_set _, tendsto_finset_range] }, { rintros hnat ⟨r, hr⟩, exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) } end lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top] lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_refl _) (summable_comp_injective hf hi) hf lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := begin split, { simp only [← nnreal.summable_coe, nnreal.coe_tsum], exact λ h, ⟨h.sigma_factor, h.sigma⟩ }, { rintro ⟨h₁, h₂⟩, simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁] using h₂ } end lemma indicator_summable {f : α → ℝ≥0} (hf : summable f) (s : set α) : summable (s.indicator f) := begin refine nnreal.summable_of_le (λ a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf, split_ifs, exact le_refl (f a), exact zero_le_coe, end lemma tsum_indicator_ne_zero {f : α → ℝ≥0} (hf : summable f) {s : set α} (h : ∃ a ∈ s, f a ≠ 0) : ∑' x, (s.indicator f) x ≠ 0 := λ h', let ⟨a, ha, hap⟩ := h in hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm (((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a)) open finset /-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin rw ← tendsto_coe, convert tendsto_sum_nat_add (λ i, (f i : ℝ)), norm_cast, end lemma has_sum_lt {f g : α → ℝ≥0} {sf sg : ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hf : has_sum f sf) (hg : has_sum g sg) : sf < sg := begin have A : ∀ (a : α), (f a : ℝ) ≤ g a := λ a, nnreal.coe_le_coe.2 (h a), have : (sf : ℝ) < sg := has_sum_lt A (nnreal.coe_lt_coe.2 hi) (has_sum_coe.2 hf) (has_sum_coe.2 hg), exact nnreal.coe_lt_coe.1 this end @[mono] lemma has_sum_strict_mono {f g : α → ℝ≥0} {sf sg : ℝ≥0} (hf : has_sum f sf) (hg : has_sum g sg) (h : f < g) : sf < sg := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {f g : α → ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi (summable_of_le h hg).has_sum hg.has_sum @[mono] lemma tsum_strict_mono {f g : α → ℝ≥0} (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hg lemma tsum_pos {g : α → ℝ≥0} (hg : summable g) (i : α) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum (λ a, zero_le _) hi hg } end nnreal namespace ennreal lemma tsum_to_real_eq {f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) : (∑' a, f a).to_real = ∑' a, (f a).to_real := begin lift f to α → ℝ≥0 using hf, have : (∑' (a : α), (f a : ℝ≥0∞)).to_real = ((∑' (a : α), (f a : ℝ≥0∞)).to_nnreal : ℝ≥0∞).to_real, { rw [ennreal.coe_to_real], refl }, rw [this, ← nnreal.tsum_eq_to_nnreal_tsum, ennreal.coe_to_real], exact nnreal.coe_tsum end lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0∞) (hf : ∑' i, f i ≠ ∞) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin lift f to ℕ → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf, simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero], exact_mod_cast nnreal.tendsto_sum_nat_add f end end ennreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin lift f to α → ℝ≥0 using hn, rw nnreal.summable_coe at hf, simpa only [(∘), ← nnreal.coe_tsum] using nnreal.tsum_comp_le_tsum_of_inj hf hi end /-- Comparison test of convergence of series of non-negative real numbers. -/ lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := begin lift f to β → ℝ≥0 using λ b, (hg b).trans (hgf b), lift g to β → ℝ≥0 using hg, rw nnreal.summable_coe at hf ⊢, exact nnreal.summable_of_le (λ b, nnreal.coe_le_coe.1 (hgf b)) hf end /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin lift f to ℕ → ℝ≥0 using hf, simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'], exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat) end lemma ennreal.of_real_tsum_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : ennreal.of_real (∑' n, f n) = ∑' n, ennreal.of_real (f n) := by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq (nnreal.has_sum_of_real_of_nonneg hf_nonneg hf)] lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin lift f to ℕ → ℝ≥0 using hf, exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top end lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf] lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma } lemma summable_of_sum_le {ι : Type*} {f : ι → ℝ} {c : ℝ} (hf : 0 ≤ f) (h : ∀ u : finset ι, ∑ x in u, f x ≤ c) : summable f := ⟨ ⨆ u : finset ι, ∑ x in u, f x, tendsto_at_top_csupr (finset.sum_mono_set_of_nonneg hf) ⟨c, λ y ⟨u, hu⟩, hu ▸ h u⟩ ⟩ lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1 (summable_of_sum_range_le hf h).has_sum) h /-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable series and at least one term of `f` is strictly smaller than the corresponding term in `g`, then the series of `f` is strictly smaller than the series of `g`. -/ lemma tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ} (h0 : ∀ (b : ℕ), 0 ≤ f b) (h : ∀ (b : ℕ), f b ≤ g b) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ℝ≥0∞} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ℝ≥0∞) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ℝ≥0∞) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm end section variable [pseudo_emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ℝ≥0∞ β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ℝ≥0∞), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λm n hm hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ℝ≥0∞} (C : ℝ≥0∞) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin refine continuous_iff_continuous_at.2 (λx, tendsto_order.2 ⟨_, _⟩), show ∀e, e < f x → ∀ᶠ y in 𝓝 x, e < f y, { assume e he, let ε := min (f x - e) 1, have : ε ≠ ⊤ := ne_top_of_le_ne_top ennreal.coe_ne_top (min_le_right _ _), have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, { simp [C_zero, ‹0 < ε›] }, { calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε ≠ ⊤›) }}, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y}, { rintros y hy, by_cases htop : f y = ⊤, { simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] }, { simp at hy, have : e + ε < f y + ε := calc e + ε ≤ e + (f x - e) : add_le_add_left (min_le_left _ _) _ ... = f x : by simp [le_of_lt he] ... ≤ f y + C * edist x y : h x y ... = f y + C * edist y x : by simp [edist_comm] ... ≤ f y + C * (C⁻¹ * (ε/2)) : add_le_add_left (mul_le_mul_left' (le_of_lt hy) _) _ ... < f y + ε : (ennreal.add_lt_add_iff_left htop).2 I, show e < f y, from (ennreal.add_lt_add_iff_right ‹ε ≠ ⊤›).1 this }}, apply filter.mem_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, show ∀e, f x < e → ∀ᶠ y in 𝓝 x, f y < e, { assume e he, let ε := min (e - f x) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, simp [C_zero, ‹0 < ε›], calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (‹0 < ε›.ne') (‹ε < ⊤›.ne) }, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e}, { rintros y hy, have htop : f x ≠ ⊤ := ne_top_of_lt he, show f y < e, from calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (C⁻¹ * (ε/2)) : add_le_add_left (mul_le_mul_left' (le_of_lt hy) _) _ ... < f x + ε : (ennreal.add_lt_add_iff_left htop).2 I ... ≤ f x + (e - f x) : add_le_add_left (min_le_left _ _) _ ... = e : by simp [le_of_lt he] }, apply filter.mem_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by norm_num), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg : _) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end lemma emetric.is_closed_ball {a : α} {r : ℝ≥0∞} : is_closed (closed_ball a r) := is_closed_le (continuous_id.edist continuous_const) continuous_const @[simp] lemma emetric.diam_closure (s : set α) : diam (closure s) = diam s := begin refine le_antisymm (diam_le $ λ x hx y hy, _) (diam_mono subset_closure), have : edist x y ∈ closure (Iic (diam s)), from map_mem_closure2 (@continuous_edist α _) hx hy (λ _ _, edist_le_diam_of_mem), rwa closure_Iic at this end @[simp] lemma metric.diam_closure {α : Type*} [pseudo_metric_space α] (s : set α) : metric.diam (closure s) = diam s := by simp only [metric.diam, emetric.diam_closure] namespace real /-- For a bounded set `s : set ℝ`, its `emetric.diam` is equal to `Sup s - Inf s` reinterpreted as `ℝ≥0∞`. -/ lemma ediam_eq {s : set ℝ} (h : bounded s) : emetric.diam s = ennreal.of_real (Sup s - Inf s) := begin rcases eq_empty_or_nonempty s with rfl|hne, { simp }, refine le_antisymm (metric.ediam_le_of_forall_dist_le $ λ x hx y hy, _) _, { have := real.subset_Icc_Inf_Sup_of_bounded h, exact real.dist_le_of_mem_Icc (this hx) (this hy) }, { apply ennreal.of_real_le_of_le_to_real, rw [← metric.diam, ← metric.diam_closure], have h' := real.bounded_iff_bdd_below_bdd_above.1 h, calc Sup s - Inf s ≤ dist (Sup s) (Inf s) : le_abs_self _ ... ≤ diam (closure s) : dist_le_diam_of_mem h.closure (cSup_mem_closure hne h'.2) (cInf_mem_closure hne h'.1) } end /-- For a bounded set `s : set ℝ`, its `metric.diam` is equal to `Sup s - Inf s`. -/ lemma diam_eq {s : set ℝ} (h : bounded s) : metric.diam s = Sup s - Inf s := begin rw [metric.diam, real.ediam_eq h, ennreal.to_real_of_real], rw real.bounded_iff_bdd_below_bdd_above at h, exact sub_nonneg.2 (real.Inf_le_Sup s h.1 h.2) end @[simp] lemma ediam_Ioo (a b : ℝ) : emetric.diam (Ioo a b) = ennreal.of_real (b - a) := begin rcases le_or_lt b a with h|h, { simp [h] }, { rw [real.ediam_eq (bounded_Ioo _ _), cSup_Ioo h, cInf_Ioo h] }, end @[simp] lemma ediam_Icc (a b : ℝ) : emetric.diam (Icc a b) = ennreal.of_real (b - a) := begin rcases le_or_lt a b with h|h, { rw [real.ediam_eq (bounded_Icc _ _), cSup_Icc h, cInf_Icc h] }, { simp [h, h.le] } end @[simp] lemma ediam_Ico (a b : ℝ) : emetric.diam (Ico a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ico_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ico_self) @[simp] lemma ediam_Ioc (a b : ℝ) : emetric.diam (Ioc a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ioc_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ioc_self) end real /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
b797566b0dec853dc7a100b63be82d250219c70f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/basic.lean
0494de6740b60dcde8d8196ed671c9c9684d2d3e
[]
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
58,862
lean
/- Copyright (c) 2014 Floris van Doorn (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group_power.basic import Mathlib.algebra.order_functions import Mathlib.algebra.ordered_monoid import Mathlib.PostPort universes u_1 u namespace Mathlib /-! # Basic operations on the natural numbers This file contains: - instances on the natural numbers - some basic lemmas about natural numbers - extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers * `decreasing_induction`: recursion growing downwards * `strong_rec'`: recursion based on strong inequalities - decidability instances on predicates about the natural numbers -/ /-! ### instances -/ protected instance nat.nontrivial : nontrivial ℕ := nontrivial.mk (Exists.intro 0 (Exists.intro 1 nat.zero_ne_one)) protected instance nat.comm_semiring : comm_semiring ℕ := comm_semiring.mk Nat.add nat.add_assoc 0 nat.zero_add nat.add_zero nat.add_comm Nat.mul nat.mul_assoc 1 nat.one_mul nat.mul_one nat.zero_mul nat.mul_zero nat.left_distrib nat.right_distrib nat.mul_comm protected instance nat.linear_ordered_semiring : linear_ordered_semiring ℕ := linear_ordered_semiring.mk comm_semiring.add comm_semiring.add_assoc comm_semiring.zero comm_semiring.zero_add comm_semiring.add_zero comm_semiring.add_comm comm_semiring.mul comm_semiring.mul_assoc comm_semiring.one comm_semiring.one_mul comm_semiring.mul_one comm_semiring.zero_mul comm_semiring.mul_zero comm_semiring.left_distrib comm_semiring.right_distrib nat.add_left_cancel nat.add_right_cancel linear_order.le nat.lt linear_order.le_refl linear_order.le_trans linear_order.le_antisymm nat.add_le_add_left nat.le_of_add_le_add_left sorry nat.mul_lt_mul_of_pos_left nat.mul_lt_mul_of_pos_right linear_order.le_total linear_order.decidable_le nat.decidable_eq linear_order.decidable_lt sorry -- all the fields are already included in the linear_ordered_semiring instance protected instance nat.linear_ordered_cancel_add_comm_monoid : linear_ordered_cancel_add_comm_monoid ℕ := linear_ordered_cancel_add_comm_monoid.mk linear_ordered_semiring.add linear_ordered_semiring.add_assoc nat.add_left_cancel linear_ordered_semiring.zero linear_ordered_semiring.zero_add linear_ordered_semiring.add_zero linear_ordered_semiring.add_comm linear_ordered_semiring.add_right_cancel linear_ordered_semiring.le linear_ordered_semiring.lt linear_ordered_semiring.le_refl linear_ordered_semiring.le_trans linear_ordered_semiring.le_antisymm linear_ordered_semiring.add_le_add_left linear_ordered_semiring.le_of_add_le_add_left linear_ordered_semiring.le_total linear_ordered_semiring.decidable_le linear_ordered_semiring.decidable_eq linear_ordered_semiring.decidable_lt protected instance nat.linear_ordered_comm_monoid_with_zero : linear_ordered_comm_monoid_with_zero ℕ := linear_ordered_comm_monoid_with_zero.mk linear_ordered_semiring.le linear_ordered_semiring.lt linear_ordered_semiring.le_refl linear_ordered_semiring.le_trans linear_ordered_semiring.le_antisymm linear_ordered_semiring.le_total linear_ordered_semiring.decidable_le linear_ordered_semiring.decidable_eq linear_ordered_semiring.decidable_lt linear_ordered_semiring.mul linear_ordered_semiring.mul_assoc linear_ordered_semiring.one linear_ordered_semiring.one_mul linear_ordered_semiring.mul_one sorry linear_ordered_semiring.zero linear_ordered_semiring.zero_mul linear_ordered_semiring.mul_zero sorry sorry linear_ordered_semiring.zero_le_one /-! Extra instances to short-circuit type class resolution -/ protected instance nat.add_comm_monoid : add_comm_monoid ℕ := ordered_add_comm_monoid.to_add_comm_monoid ℕ protected instance nat.add_monoid : add_monoid ℕ := add_right_cancel_monoid.to_add_monoid ℕ protected instance nat.monoid : monoid ℕ := monoid_with_zero.to_monoid ℕ protected instance nat.comm_monoid : comm_monoid ℕ := ordered_comm_monoid.to_comm_monoid ℕ protected instance nat.comm_semigroup : comm_semigroup ℕ := comm_monoid.to_comm_semigroup ℕ protected instance nat.semigroup : semigroup ℕ := monoid.to_semigroup ℕ protected instance nat.add_comm_semigroup : add_comm_semigroup ℕ := add_comm_monoid.to_add_comm_semigroup ℕ protected instance nat.add_semigroup : add_semigroup ℕ := add_monoid.to_add_semigroup ℕ protected instance nat.distrib : distrib ℕ := semiring.to_distrib ℕ protected instance nat.semiring : semiring ℕ := ordered_semiring.to_semiring ℕ protected instance nat.ordered_semiring : ordered_semiring ℕ := linear_ordered_semiring.to_ordered_semiring ℕ protected instance nat.canonically_ordered_comm_semiring : canonically_ordered_comm_semiring ℕ := canonically_ordered_comm_semiring.mk ordered_add_comm_monoid.add sorry ordered_add_comm_monoid.zero sorry sorry sorry ordered_add_comm_monoid.le ordered_add_comm_monoid.lt sorry sorry sorry sorry sorry 0 nat.zero_le sorry linear_ordered_semiring.mul sorry linear_ordered_semiring.one sorry sorry sorry sorry sorry sorry sorry sorry protected instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : Nonempty ↥s] : semilattice_sup_bot ↥s := semilattice_sup_bot.mk { val := nat.find sorry, property := sorry } linear_order.le linear_order.lt sorry sorry sorry sorry lattice.sup sorry sorry sorry theorem nat.eq_of_mul_eq_mul_right {n : ℕ} {m : ℕ} {k : ℕ} (Hm : 0 < m) (H : n * m = k * m) : n = k := nat.eq_of_mul_eq_mul_left Hm (eq.mp (Eq._oldrec (Eq.refl (m * n = k * m)) (mul_comm k m)) (eq.mp (Eq._oldrec (Eq.refl (n * m = k * m)) (mul_comm n m)) H)) protected instance nat.comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero ℕ := comm_cancel_monoid_with_zero.mk comm_monoid_with_zero.mul sorry comm_monoid_with_zero.one sorry sorry sorry comm_monoid_with_zero.zero sorry sorry sorry sorry /-! Inject some simple facts into the type class system. This `fact` should not be confused with the factorial function `nat.fact`! -/ protected instance succ_pos'' (n : ℕ) : fact (0 < Nat.succ n) := nat.succ_pos n protected instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := lt_trans zero_lt_one h namespace nat /-! ### Recursion and `set.range` -/ theorem zero_union_range_succ : singleton 0 ∪ set.range Nat.succ = set.univ := sorry theorem range_of_succ {α : Type u_1} (f : ℕ → α) : singleton (f 0) ∪ set.range (f ∘ Nat.succ) = set.range f := sorry theorem range_rec {α : Type u_1} (x : α) (f : ℕ → α → α) : (set.range fun (n : ℕ) => Nat.rec x f n) = singleton x ∪ set.range fun (n : ℕ) => Nat.rec (f 0 x) (f ∘ Nat.succ) n := sorry theorem range_cases_on {α : Type u_1} (x : α) (f : ℕ → α) : (set.range fun (n : ℕ) => nat.cases_on n x f) = singleton x ∪ set.range f := Eq.symm (range_of_succ fun (n : ℕ) => nat.cases_on n x f) /-! ### The units of the natural numbers as a `monoid` and `add_monoid` -/ theorem units_eq_one (u : units ℕ) : u = 1 := units.ext (eq_one_of_dvd_one (Exists.intro (units.inv u) (Eq.symm (units.val_inv u)))) theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext (and.left (eq_zero_of_add_eq_zero (add_units.val_neg u))) @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := sorry /-! ### Equalities and inequalities involving zero and one -/ theorem one_lt_iff_ne_zero_and_ne_one {n : ℕ} : 1 < n ↔ n ≠ 0 ∧ n ≠ 1 := sorry protected theorem mul_ne_zero {n : ℕ} {m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 := fun (ᾰ : n * m = 0) => idRhs False (or.elim (eq_zero_of_mul_eq_zero ᾰ) n0 m0) @[simp] protected theorem mul_eq_zero {a : ℕ} {b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := sorry @[simp] protected theorem zero_eq_mul {a : ℕ} {b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (0 = a * b ↔ a = 0 ∨ b = 0)) (propext eq_comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b = 0 ↔ a = 0 ∨ b = 0)) (propext nat.mul_eq_zero))) (iff.refl (a = 0 ∨ b = 0))) theorem eq_zero_of_double_le {a : ℕ} (h : bit0 1 * a ≤ a) : a = 0 := sorry theorem eq_zero_of_mul_le {a : ℕ} {b : ℕ} (hb : bit0 1 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le (le_trans (mul_le_mul_right a hb) h) theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := { mp := eq_zero_of_le_zero, mpr := fun (h : i = 0) => h ▸ le_refl i } theorem zero_max {m : ℕ} : max 0 m = m := max_eq_right (zero_le m) theorem one_le_of_lt {n : ℕ} {m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (zero_le n) h theorem eq_one_of_mul_eq_one_right {m : ℕ} {n : ℕ} (H : m * n = 1) : m = 1 := eq_one_of_dvd_one (Exists.intro n (Eq.symm H)) theorem eq_one_of_mul_eq_one_left {m : ℕ} {n : ℕ} (H : m * n = 1) : n = 1 := eq_one_of_mul_eq_one_right (eq.mpr (id (Eq._oldrec (Eq.refl (n * m = 1)) (mul_comm n m))) H) /-! ### `succ` -/ theorem eq_of_lt_succ_of_not_lt {a : ℕ} {b : ℕ} (h1 : a < b + 1) (h2 : ¬a < b) : a = b := (fun (h3 : a ≤ b) => or.elim (eq_or_lt_of_not_lt h2) (fun (h : a = b) => h) fun (h : b < a) => absurd h (not_lt_of_ge h3)) (le_of_lt_succ h1) theorem one_add (n : ℕ) : 1 + n = Nat.succ n := sorry @[simp] theorem succ_pos' {n : ℕ} : 0 < Nat.succ n := succ_pos n theorem succ_inj' {n : ℕ} {m : ℕ} : Nat.succ n = Nat.succ m ↔ n = m := { mp := succ.inj, mpr := congr_arg fun {n : ℕ} => Nat.succ n } theorem succ_injective : function.injective Nat.succ := fun (x y : ℕ) => succ.inj theorem succ_le_succ_iff {m : ℕ} {n : ℕ} : Nat.succ m ≤ Nat.succ n ↔ m ≤ n := { mp := le_of_succ_le_succ, mpr := succ_le_succ } theorem max_succ_succ {m : ℕ} {n : ℕ} : max (Nat.succ m) (Nat.succ n) = Nat.succ (max m n) := sorry theorem not_succ_lt_self {n : ℕ} : ¬Nat.succ n < n := not_lt_of_ge (le_succ n) theorem lt_succ_iff {m : ℕ} {n : ℕ} : m < Nat.succ n ↔ m ≤ n := succ_le_succ_iff theorem succ_le_iff {m : ℕ} {n : ℕ} : Nat.succ m ≤ n ↔ m < n := { mp := lt_of_succ_le, mpr := succ_le_of_lt } theorem lt_iff_add_one_le {m : ℕ} {n : ℕ} : m < n ↔ m + 1 ≤ n := eq.mpr (id (Eq._oldrec (Eq.refl (m < n ↔ m + 1 ≤ n)) (propext succ_le_iff))) (iff.refl (m < n)) -- Just a restatement of `nat.lt_succ_iff` using `+1`. theorem lt_add_one_iff {a : ℕ} {b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. theorem lt_one_add_iff {a : ℕ} {b : ℕ} : a < 1 + b ↔ a ≤ b := sorry -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. theorem add_one_le_iff {a : ℕ} {b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl (a + 1 ≤ b) theorem one_add_le_iff {a : ℕ} {b : ℕ} : 1 + a ≤ b ↔ a < b := sorry theorem of_le_succ {n : ℕ} {m : ℕ} (H : n ≤ Nat.succ m) : n ≤ m ∨ n = Nat.succ m := or.imp le_of_lt_succ id (lt_or_eq_of_le H) theorem succ_lt_succ_iff {m : ℕ} {n : ℕ} : Nat.succ m < Nat.succ n ↔ m < n := { mp := lt_of_succ_lt_succ, mpr := succ_lt_succ } /-! ### `add` -/ -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a : ℕ} {b : ℕ} : Nat.add a b = a + b := rfl @[simp] theorem mul_def {a : ℕ} {b : ℕ} : Nat.mul a b = a * b := rfl theorem exists_eq_add_of_le {m : ℕ} {n : ℕ} : m ≤ n → ∃ (k : ℕ), n = m + k := sorry theorem exists_eq_add_of_lt {m : ℕ} {n : ℕ} : m < n → ∃ (k : ℕ), n = m + k + 1 := sorry theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := gt_of_gt_of_ge (trans_rel_left gt (nat.add_lt_add_right h n) (nat.zero_add n)) (zero_le n) theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := eq.mpr (id (Eq._oldrec (Eq.refl (0 < m + n)) (add_comm m n))) (add_pos_left h m) theorem add_pos_iff_pos_or_pos (m : ℕ) (n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := sorry theorem add_eq_one_iff {a : ℕ} {b : ℕ} : a + b = 1 ↔ a = 0 ∧ b = 1 ∨ a = 1 ∧ b = 0 := sorry theorem le_add_one_iff {i : ℕ} {j : ℕ} : i ≤ j + 1 ↔ i ≤ j ∨ i = j + 1 := sorry theorem add_succ_lt_add {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (hab : a < b) (hcd : c < d) : a + c + 1 < b + d := eq.mpr (id (Eq._oldrec (Eq.refl (a + c + 1 < b + d)) (add_assoc a c 1))) (add_lt_add_of_lt_of_le hab (iff.mpr succ_le_iff hcd)) /-! ### `pred` -/ @[simp] theorem add_succ_sub_one (n : ℕ) (m : ℕ) : n + Nat.succ m - 1 = n + m := eq.mpr (id (Eq._oldrec (Eq.refl (n + Nat.succ m - 1 = n + m)) (add_succ n m))) (eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ (n + m) - 1 = n + m)) (succ_sub_one (n + m)))) (Eq.refl (n + m))) @[simp] theorem succ_add_sub_one (n : ℕ) (m : ℕ) : Nat.succ n + m - 1 = n + m := eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ n + m - 1 = n + m)) (succ_add n m))) (eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ (n + m) - 1 = n + m)) (succ_sub_one (n + m)))) (Eq.refl (n + m))) theorem pred_eq_sub_one (n : ℕ) : Nat.pred n = n - 1 := rfl theorem pred_eq_of_eq_succ {m : ℕ} {n : ℕ} (H : m = Nat.succ n) : Nat.pred m = n := sorry @[simp] theorem pred_eq_succ_iff {n : ℕ} {m : ℕ} : Nat.pred n = Nat.succ m ↔ n = m + bit0 1 := sorry theorem pred_sub (n : ℕ) (m : ℕ) : Nat.pred n - m = Nat.pred (n - m) := eq.mpr (id (Eq._oldrec (Eq.refl (Nat.pred n - m = Nat.pred (n - m))) (Eq.symm (sub_one n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (n - 1 - m = Nat.pred (n - m))) (nat.sub_sub n 1 m))) (eq.mpr (id (Eq._oldrec (Eq.refl (n - (1 + m) = Nat.pred (n - m))) (one_add m))) (Eq.refl (n - Nat.succ m)))) theorem le_pred_of_lt {n : ℕ} {m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 theorem le_of_pred_lt {m : ℕ} {n : ℕ} : Nat.pred m < n → m ≤ n := sorry /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] theorem pred_one_add (n : ℕ) : Nat.pred (1 + n) = n := eq.mpr (id (Eq._oldrec (Eq.refl (Nat.pred (1 + n) = n)) (add_comm 1 n))) (eq.mpr (id (Eq._oldrec (Eq.refl (Nat.pred (n + 1) = n)) (add_one n))) (eq.mpr (id (Eq._oldrec (Eq.refl (Nat.pred (Nat.succ n) = n)) (pred_succ n))) (Eq.refl n))) /-! ### `sub` -/ protected theorem le_sub_add (n : ℕ) (m : ℕ) : n ≤ n - m + m := sorry theorem sub_add_eq_max (n : ℕ) (m : ℕ) : n - m + m = max n m := sorry theorem add_sub_eq_max (n : ℕ) (m : ℕ) : n + (m - n) = max n m := eq.mpr (id (Eq._oldrec (Eq.refl (n + (m - n) = max n m)) (add_comm n (m - n)))) (eq.mpr (id (Eq._oldrec (Eq.refl (m - n + n = max n m)) (max_comm n m))) (eq.mpr (id (Eq._oldrec (Eq.refl (m - n + n = max m n)) (sub_add_eq_max m n))) (Eq.refl (max m n)))) theorem sub_add_min (n : ℕ) (m : ℕ) : n - m + min n m = n := sorry protected theorem add_sub_cancel' {n : ℕ} {m : ℕ} (h : m ≤ n) : m + (n - m) = n := eq.mpr (id (Eq._oldrec (Eq.refl (m + (n - m) = n)) (add_comm m (n - m)))) (eq.mpr (id (Eq._oldrec (Eq.refl (n - m + m = n)) (nat.sub_add_cancel h))) (Eq.refl n)) protected theorem sub_add_sub_cancel {a : ℕ} {b : ℕ} {c : ℕ} (hab : b ≤ a) (hbc : c ≤ b) : a - b + (b - c) = a - c := eq.mpr (id (Eq._oldrec (Eq.refl (a - b + (b - c) = a - c)) (Eq.symm (nat.add_sub_assoc hbc (a - b))))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - b + b - c = a - c)) (Eq.symm (nat.sub_add_comm hab)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a + b - b - c = a - c)) (nat.add_sub_cancel a b))) (Eq.refl (a - c)))) protected theorem sub_eq_of_eq_add {m : ℕ} {n : ℕ} {k : ℕ} (h : k = m + n) : k - m = n := eq.mpr (id (Eq._oldrec (Eq.refl (k - m = n)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (m + n - m = n)) (nat.add_sub_cancel_left m n))) (Eq.refl n)) theorem sub_cancel {a : ℕ} {b : ℕ} {c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := eq.mpr (id (Eq._oldrec (Eq.refl (b = c)) (Eq.symm (nat.sub_add_cancel h₁)))) (eq.mpr (id (Eq._oldrec (Eq.refl (b - a + a = c)) (Eq.symm (nat.sub_add_cancel h₂)))) (eq.mpr (id (Eq._oldrec (Eq.refl (b - a + a = c - a + a)) w)) (Eq.refl (c - a + a)))) theorem sub_sub_sub_cancel_right {a : ℕ} {b : ℕ} {c : ℕ} (h₂ : c ≤ b) : a - c - (b - c) = a - b := eq.mpr (id (Eq._oldrec (Eq.refl (a - c - (b - c) = a - b)) (nat.sub_sub a c (b - c)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - (c + (b - c)) = a - b)) (Eq.symm (nat.add_sub_assoc h₂ c)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - (c + b - c) = a - b)) (nat.add_sub_cancel_left c b))) (Eq.refl (a - b)))) theorem add_sub_cancel_right (n : ℕ) (m : ℕ) (k : ℕ) : n + (m + k) - k = n + m := eq.mpr (id (Eq._oldrec (Eq.refl (n + (m + k) - k = n + m)) (nat.add_sub_assoc (le_add_left k m) n))) (eq.mpr (id (Eq._oldrec (Eq.refl (n + (m + k - k) = n + m)) (nat.add_sub_cancel m k))) (Eq.refl (n + m))) protected theorem sub_add_eq_add_sub {a : ℕ} {b : ℕ} {c : ℕ} (h : b ≤ a) : a - b + c = a + c - b := eq.mpr (id (Eq._oldrec (Eq.refl (a - b + c = a + c - b)) (add_comm a c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - b + c = c + a - b)) (nat.add_sub_assoc h c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - b + c = c + (a - b))) (add_comm (a - b) c))) (Eq.refl (c + (a - b))))) theorem sub_min (n : ℕ) (m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add (eq.mpr (id (Eq._oldrec (Eq.refl (n = min n m + (n - m))) (add_comm (min n m) (n - m)))) (eq.mpr (id (Eq._oldrec (Eq.refl (n = n - m + min n m)) (sub_add_min n m))) (Eq.refl n))) theorem sub_sub_assoc {a : ℕ} {b : ℕ} {c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := sorry protected theorem lt_of_sub_pos {m : ℕ} {n : ℕ} (h : 0 < n - m) : m < n := lt_of_not_ge fun (this : n ≤ m) => (fun (this : n - m = 0) => lt_irrefl 0 (eq.mp (Eq._oldrec (Eq.refl (0 < n - m)) this) h)) (sub_eq_zero_of_le this) protected theorem lt_of_sub_lt_sub_right {m : ℕ} {n : ℕ} {k : ℕ} : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le fun (h : n ≤ m) => nat.sub_le_sub_right h k protected theorem lt_of_sub_lt_sub_left {m : ℕ} {n : ℕ} {k : ℕ} : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left m) protected theorem sub_lt_self {m : ℕ} {n : ℕ} (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := sorry protected theorem le_sub_right_of_add_le {m : ℕ} {n : ℕ} {k : ℕ} (h : m + k ≤ n) : m ≤ n - k := eq.mpr (id (Eq._oldrec (Eq.refl (m ≤ n - k)) (Eq.symm (nat.add_sub_cancel m k)))) (nat.sub_le_sub_right h k) protected theorem le_sub_left_of_add_le {m : ℕ} {n : ℕ} {k : ℕ} (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (eq.mp (Eq._oldrec (Eq.refl (k + m ≤ n)) (add_comm k m)) h) protected theorem lt_sub_right_of_add_lt {m : ℕ} {n : ℕ} {k : ℕ} (h : m + k < n) : m < n - k := lt_of_succ_le (nat.le_sub_right_of_add_le (eq.mpr (id (Eq._oldrec (Eq.refl (Nat.succ m + k ≤ n)) (succ_add m k))) (succ_le_of_lt h))) protected theorem lt_sub_left_of_add_lt {m : ℕ} {n : ℕ} {k : ℕ} (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (eq.mp (Eq._oldrec (Eq.refl (k + m < n)) (add_comm k m)) h) protected theorem add_lt_of_lt_sub_right {m : ℕ} {n : ℕ} {k : ℕ} (h : m < n - k) : m + k < n := nat.lt_of_sub_lt_sub_right (eq.mpr (id (Eq._oldrec (Eq.refl (m + k - k < n - k)) (nat.add_sub_cancel m k))) h) protected theorem add_lt_of_lt_sub_left {m : ℕ} {n : ℕ} {k : ℕ} (h : m < n - k) : k + m < n := eq.mpr (id (Eq._oldrec (Eq.refl (k + m < n)) (add_comm k m))) (nat.add_lt_of_lt_sub_right h) protected theorem le_add_of_sub_le_right {m : ℕ} {n : ℕ} {k : ℕ} : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left {m : ℕ} {n : ℕ} {k : ℕ} : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right {m : ℕ} {n : ℕ} {k : ℕ} : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left {m : ℕ} {n : ℕ} {k : ℕ} : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add {m : ℕ} {n : ℕ} {k : ℕ} : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add {m : ℕ} {n : ℕ} {k : ℕ} : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add {m : ℕ} {n : ℕ} {k : ℕ} (H : n ≤ k) : k - n < m ↔ k < n + m := sorry protected theorem le_sub_left_iff_add_le {m : ℕ} {n : ℕ} {k : ℕ} (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := iff.mpr le_iff_le_iff_lt_iff_lt (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le {m : ℕ} {n : ℕ} {k : ℕ} (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := eq.mpr (id (Eq._oldrec (Eq.refl (m ≤ k - n ↔ m + n ≤ k)) (propext (nat.le_sub_left_iff_add_le H)))) (eq.mpr (id (Eq._oldrec (Eq.refl (n + m ≤ k ↔ m + n ≤ k)) (add_comm n m))) (iff.refl (m + n ≤ k))) protected theorem lt_sub_left_iff_add_lt {m : ℕ} {n : ℕ} {k : ℕ} : n < k - m ↔ m + n < k := { mp := nat.add_lt_of_lt_sub_left, mpr := nat.lt_sub_left_of_add_lt } protected theorem lt_sub_right_iff_add_lt {m : ℕ} {n : ℕ} {k : ℕ} : m < k - n ↔ m + n < k := eq.mpr (id (Eq._oldrec (Eq.refl (m < k - n ↔ m + n < k)) (propext nat.lt_sub_left_iff_add_lt))) (eq.mpr (id (Eq._oldrec (Eq.refl (n + m < k ↔ m + n < k)) (add_comm n m))) (iff.refl (m + n < k))) theorem sub_le_left_iff_le_add {m : ℕ} {n : ℕ} {k : ℕ} : m - n ≤ k ↔ m ≤ n + k := iff.mpr le_iff_le_iff_lt_iff_lt nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add {m : ℕ} {n : ℕ} {k : ℕ} : m - k ≤ n ↔ m ≤ n + k := eq.mpr (id (Eq._oldrec (Eq.refl (m - k ≤ n ↔ m ≤ n + k)) (propext sub_le_left_iff_le_add))) (eq.mpr (id (Eq._oldrec (Eq.refl (m ≤ k + n ↔ m ≤ n + k)) (add_comm k n))) (iff.refl (m ≤ n + k))) protected theorem sub_lt_right_iff_lt_add {m : ℕ} {n : ℕ} {k : ℕ} (H : k ≤ m) : m - k < n ↔ m < n + k := eq.mpr (id (Eq._oldrec (Eq.refl (m - k < n ↔ m < n + k)) (propext (nat.sub_lt_left_iff_lt_add H)))) (eq.mpr (id (Eq._oldrec (Eq.refl (m < k + n ↔ m < n + k)) (add_comm k n))) (iff.refl (m < n + k))) protected theorem sub_le_sub_left_iff {m : ℕ} {n : ℕ} {k : ℕ} (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := sorry protected theorem sub_lt_sub_right_iff {m : ℕ} {n : ℕ} {k : ℕ} (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff n m k H) protected theorem sub_lt_sub_left_iff {m : ℕ} {n : ℕ} {k : ℕ} (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff {m : ℕ} {n : ℕ} {k : ℕ} : m - n ≤ k ↔ m - k ≤ n := iff.trans sub_le_left_iff_le_add (iff.symm sub_le_right_iff_le_add) protected theorem sub_le_self (n : ℕ) (m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (le_add_left n m) protected theorem sub_lt_iff {m : ℕ} {n : ℕ} {k : ℕ} (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := iff.trans (nat.sub_lt_left_iff_lt_add h₁) (iff.symm (nat.sub_lt_right_iff_lt_add h₂)) theorem pred_le_iff {n : ℕ} {m : ℕ} : Nat.pred n ≤ m ↔ n ≤ Nat.succ m := sub_le_right_iff_le_add theorem lt_pred_iff {n : ℕ} {m : ℕ} : n < Nat.pred m ↔ Nat.succ n < m := nat.lt_sub_right_iff_add_lt theorem lt_of_lt_pred {a : ℕ} {b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (iff.mp lt_pred_iff h) /-! ### `mul` -/ theorem mul_self_le_mul_self {n : ℕ} {m : ℕ} (h : n ≤ m) : n * n ≤ m * m := mul_le_mul h h (zero_le n) (zero_le m) theorem mul_self_lt_mul_self {n : ℕ} {m : ℕ} : n < m → n * n < m * m := sorry theorem mul_self_le_mul_self_iff {n : ℕ} {m : ℕ} : n ≤ m ↔ n * n ≤ m * m := sorry theorem mul_self_lt_mul_self_iff {n : ℕ} {m : ℕ} : n < m ↔ n * n < m * m := iff.trans (lt_iff_not_ge n m) (iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) (iff.symm (lt_iff_not_ge (n * n) (m * m)))) theorem le_mul_self (n : ℕ) : n ≤ n * n := sorry theorem le_mul_of_pos_left {m : ℕ} {n : ℕ} (h : 0 < n) : m ≤ n * m := sorry theorem le_mul_of_pos_right {m : ℕ} {n : ℕ} (h : 0 < n) : m ≤ m * n := sorry theorem two_mul_ne_two_mul_add_one {n : ℕ} {m : ℕ} : bit0 1 * n ≠ bit0 1 * m + 1 := sorry theorem mul_eq_one_iff {a : ℕ} {b : ℕ} : a * b = 1 ↔ a = 1 ∧ b = 1 := sorry protected theorem mul_left_inj {a : ℕ} {b : ℕ} {c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := { mp := eq_of_mul_eq_mul_right ha, mpr := fun (e : b = c) => e ▸ rfl } protected theorem mul_right_inj {a : ℕ} {b : ℕ} {c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := { mp := eq_of_mul_eq_mul_left ha, mpr := fun (e : b = c) => e ▸ rfl } theorem mul_left_injective {a : ℕ} (ha : 0 < a) : function.injective fun (x : ℕ) => x * a := fun (_x _x_1 : ℕ) => eq_of_mul_eq_mul_right ha theorem mul_right_injective {a : ℕ} (ha : 0 < a) : function.injective fun (x : ℕ) => a * x := fun (_x _x_1 : ℕ) => eq_of_mul_eq_mul_left ha theorem mul_right_eq_self_iff {a : ℕ} {b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := (fun (this : a * b = a * 1 ↔ b = 1) => eq.mp (Eq._oldrec (Eq.refl (a * b = a * 1 ↔ b = 1)) (mul_one a)) this) (nat.mul_right_inj ha) theorem mul_left_eq_self_iff {a : ℕ} {b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (a * b = b ↔ a = 1)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = b ↔ a = 1)) (propext (mul_right_eq_self_iff hb)))) (iff.refl (a = 1))) theorem lt_succ_iff_lt_or_eq {n : ℕ} {i : ℕ} : n < Nat.succ i ↔ n < i ∨ n = i := iff.trans lt_succ_iff le_iff_lt_or_eq theorem mul_self_inj {n : ℕ} {m : ℕ} : n * n = m * m ↔ n = m := iff.trans le_antisymm_iff (iff.symm (iff.trans le_antisymm_iff (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff))) /-! ### Recursion and induction principles This section is here due to dependencies -- the lemmas here require some of the lemmas proved above, and some of the results in later sections depend on the definitions in this section. -/ @[simp] theorem rec_zero {C : ℕ → Sort u} (h0 : C 0) (h : (n : ℕ) → C n → C (n + 1)) : Nat.rec h0 h 0 = h0 := rfl @[simp] theorem rec_add_one {C : ℕ → Sort u} (h0 : C 0) (h : (n : ℕ) → C n → C (n + 1)) (n : ℕ) : Nat.rec h0 h (n + 1) = h n (Nat.rec h0 h n) := rfl /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ def le_rec_on {C : ℕ → Sort u} {n : ℕ} {m : ℕ} : n ≤ m → ({k : ℕ} → C k → C (k + 1)) → C n → C m := sorry theorem le_rec_on_self {C : ℕ → Sort u} {n : ℕ} {h : n ≤ n} {next : {k : ℕ} → C k → C (k + 1)} (x : C n) : le_rec_on h next x = x := sorry theorem le_rec_on_succ {C : ℕ → Sort u} {n : ℕ} {m : ℕ} (h1 : n ≤ m) {h2 : n ≤ m + 1} {next : {k : ℕ} → C k → C (k + 1)} (x : C n) : le_rec_on h2 next x = next (le_rec_on h1 next x) := sorry theorem le_rec_on_succ' {C : ℕ → Sort u} {n : ℕ} {h : n ≤ n + 1} {next : {k : ℕ} → C k → C (k + 1)} (x : C n) : le_rec_on h next x = next x := eq.mpr (id (Eq._oldrec (Eq.refl (le_rec_on h next x = next x)) (le_rec_on_succ (le_refl n) x))) (eq.mpr (id (Eq._oldrec (Eq.refl (next (le_rec_on (le_refl n) next x) = next x)) (le_rec_on_self x))) (Eq.refl (next x))) theorem le_rec_on_trans {C : ℕ → Sort u} {n : ℕ} {m : ℕ} {k : ℕ} (hnm : n ≤ m) (hmk : m ≤ k) {next : {k : ℕ} → C k → C (k + 1)} (x : C n) : le_rec_on (le_trans hnm hmk) next x = le_rec_on hmk next (le_rec_on hnm next x) := sorry theorem le_rec_on_succ_left {C : ℕ → Sort u} {n : ℕ} {m : ℕ} (h1 : n ≤ m) (h2 : n + 1 ≤ m) {next : {k : ℕ} → C k → C (k + 1)} (x : C n) : le_rec_on h2 next (next x) = le_rec_on h1 next x := sorry theorem le_rec_on_injective {C : ℕ → Sort u} {n : ℕ} {m : ℕ} (hnm : n ≤ m) (next : (n : ℕ) → C n → C (n + 1)) (Hnext : ∀ (n : ℕ), function.injective (next n)) : function.injective (le_rec_on hnm next) := sorry theorem le_rec_on_surjective {C : ℕ → Sort u} {n : ℕ} {m : ℕ} (hnm : n ≤ m) (next : (n : ℕ) → C n → C (n + 1)) (Hnext : ∀ (n : ℕ), function.surjective (next n)) : function.surjective (le_rec_on hnm next) := sorry /-- Recursion principle based on `<`. -/ protected def strong_rec' {p : ℕ → Sort u} (H : (n : ℕ) → ((m : ℕ) → m < n → p m) → p n) (n : ℕ) : p n := sorry /-- Recursion principle based on `<` applied to some natural number. -/ def strong_rec_on' {P : ℕ → Sort u_1} (n : ℕ) (h : (n : ℕ) → ((m : ℕ) → m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort u_1} {h : (n : ℕ) → ((m : ℕ) → m < n → P m) → P n} {n : ℕ} : strong_rec_on' n h = h n fun (m : ℕ) (hmn : m < n) => strong_rec_on' m h := sorry /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ theorem le_induction {P : ℕ → Prop} {m : ℕ} (h0 : P m) (h1 : ∀ (n : ℕ), m ≤ n → P n → P (n + 1)) (n : ℕ) : m ≤ n → P n := less_than_or_equal._oldrec h0 h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ def decreasing_induction {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ} {n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (fun (k : ℕ) (ih : P k → P m) (hsk : P (k + 1)) => ih (h k hsk)) (fun (h : P m) => h) hP @[simp] theorem decreasing_induction_self {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : decreasing_induction h nn hP = hP := sorry theorem decreasing_induction_succ {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ} {n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n + 1)) : decreasing_induction h msn hP = decreasing_induction h mn (h n hP) := sorry @[simp] theorem decreasing_induction_succ' {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m + 1)) : decreasing_induction h msm hP = h m hP := sorry theorem decreasing_induction_trans {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ} {n : ℕ} {k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : decreasing_induction h (le_trans mn nk) hP = decreasing_induction h mn (decreasing_induction h nk hP) := sorry theorem decreasing_induction_succ_left {P : ℕ → Sort u_1} (h : (n : ℕ) → P (n + 1) → P n) {m : ℕ} {n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : decreasing_induction h mn hP = h m (decreasing_induction h smn hP) := sorry /-! ### `div` -/ protected theorem div_le_of_le_mul' {m : ℕ} {n : ℕ} {k : ℕ} (h : m ≤ k * n) : m / k ≤ n := sorry protected theorem div_le_self' (m : ℕ) (n : ℕ) : m / n ≤ m := sorry /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ theorem div_lt_self' (n : ℕ) (b : ℕ) : (n + 1) / (b + bit0 1) < n + 1 := div_lt_self (succ_pos n) (succ_lt_succ (succ_pos b)) theorem le_div_iff_mul_le' {x : ℕ} {y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := le_div_iff_mul_le x y k0 theorem div_lt_iff_lt_mul' {x : ℕ} {y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le (le_div_iff_mul_le' k0) protected theorem div_le_div_right {n : ℕ} {m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := sorry theorem lt_of_div_lt_div {m : ℕ} {n : ℕ} {k : ℕ} (h : m / k < n / k) : m < n := by_contradiction fun (h₁ : ¬m < n) => absurd h (not_lt_of_ge (nat.div_le_div_right (iff.mp not_lt h₁))) protected theorem div_pos {a : ℕ} {b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := sorry protected theorem div_lt_of_lt_mul {m : ℕ} {n : ℕ} {k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (lt_of_le_of_lt (trans_rel_left LessEq (le_add_left (n * (m / n)) (m % n)) (mod_add_div m n)) h) (zero_le n) theorem lt_mul_of_div_lt {a : ℕ} {b : ℕ} {c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge (not_le_of_gt h ∘ iff.mpr (le_div_iff_mul_le b a w)) protected theorem div_eq_zero_iff {a : ℕ} {b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := sorry protected theorem div_eq_zero {a : ℕ} {b : ℕ} (hb : a < b) : a / b = 0 := iff.mpr (nat.div_eq_zero_iff (has_le.le.trans_lt (zero_le a) hb)) hb theorem eq_zero_of_le_div {a : ℕ} {b : ℕ} (hb : bit0 1 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb (eq.mpr (id (Eq._oldrec (Eq.refl (b * a ≤ a)) (mul_comm b a))) (iff.mp (le_div_iff_mul_le' (lt_of_lt_of_le (of_as_true trivial) hb)) h)) theorem mul_div_le_mul_div_assoc (a : ℕ) (b : ℕ) (c : ℕ) : a * (b / c) ≤ a * b / c := sorry theorem div_mul_div_le_div (a : ℕ) (b : ℕ) (c : ℕ) : a / c * b / a ≤ b / c := sorry theorem eq_zero_of_le_half {a : ℕ} (h : a ≤ a / bit0 1) : a = 0 := eq_zero_of_le_div (le_refl (bit0 1)) h protected theorem eq_mul_of_div_eq_right {a : ℕ} {b : ℕ} {c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := eq.mpr (id (Eq._oldrec (Eq.refl (a = b * c)) (Eq.symm H2))) (eq.mpr (id (Eq._oldrec (Eq.refl (a = b * (a / b))) (nat.mul_div_cancel' H1))) (Eq.refl a)) protected theorem div_eq_iff_eq_mul_right {a : ℕ} {b : ℕ} {c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := { mp := nat.eq_mul_of_div_eq_right H', mpr := nat.div_eq_of_eq_mul_right H } protected theorem div_eq_iff_eq_mul_left {a : ℕ} {b : ℕ} {c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := eq.mpr (id (Eq._oldrec (Eq.refl (a / b = c ↔ a = c * b)) (mul_comm c b))) (nat.div_eq_iff_eq_mul_right H H') protected theorem eq_mul_of_div_eq_left {a : ℕ} {b : ℕ} {c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := eq.mpr (id (Eq._oldrec (Eq.refl (a = c * b)) (mul_comm c b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a = b * c)) (nat.eq_mul_of_div_eq_right H1 H2))) (Eq.refl (b * c))) protected theorem mul_div_cancel_left' {a : ℕ} {b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a * (b / a) = b)) (mul_comm a (b / a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (b / a * a = b)) (nat.div_mul_cancel Hd))) (Eq.refl b)) /-! ### `mod`, `dvd` -/ protected theorem div_mod_unique {n : ℕ} {k : ℕ} {m : ℕ} {d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := sorry theorem two_mul_odd_div_two {n : ℕ} (hn : n % bit0 1 = 1) : bit0 1 * (n / bit0 1) = n - 1 := sorry theorem div_dvd_of_dvd {a : ℕ} {b : ℕ} (h : b ∣ a) : a / b ∣ a := Exists.intro b (Eq.symm (nat.div_mul_cancel h)) protected theorem div_div_self {a : ℕ} {b : ℕ} : b ∣ a → 0 < a → a / (a / b) = b := sorry theorem mod_mul_right_div_self (a : ℕ) (b : ℕ) (c : ℕ) : a % (b * c) / b = a / b % c := sorry theorem mod_mul_left_div_self (a : ℕ) (b : ℕ) (c : ℕ) : a % (c * b) / b = a / b % c := eq.mpr (id (Eq._oldrec (Eq.refl (a % (c * b) / b = a / b % c)) (mul_comm c b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a % (b * c) / b = a / b % c)) (mod_mul_right_div_self a b c))) (Eq.refl (a / b % c))) @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := { mp := eq_one_of_dvd_one, mpr := fun (e : n = 1) => Eq.symm e ▸ dvd_refl 1 } protected theorem dvd_add_left {k : ℕ} {m : ℕ} {n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := iff.symm (nat.dvd_add_iff_left h) protected theorem dvd_add_right {k : ℕ} {m : ℕ} {n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := iff.symm (nat.dvd_add_iff_right h) @[simp] protected theorem not_two_dvd_bit1 (n : ℕ) : ¬bit0 1 ∣ bit1 n := mt (iff.mp (nat.dvd_add_right two_dvd_bit0)) (of_as_true trivial) /-- A natural number `m` divides the sum `m + n` if and only if `m` divides `n`.-/ @[simp] protected theorem dvd_add_self_left {m : ℕ} {n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number `m` divides the sum `n + m` if and only if `m` divides `n`.-/ @[simp] protected theorem dvd_add_self_right {m : ℕ} {n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) theorem not_dvd_of_pos_of_lt {a : ℕ} {b : ℕ} (h1 : 0 < b) (h2 : b < a) : ¬a ∣ b := sorry protected theorem mul_dvd_mul_iff_left {a : ℕ} {b : ℕ} {c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := sorry protected theorem mul_dvd_mul_iff_right {a : ℕ} {b : ℕ} {c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := sorry theorem succ_div (a : ℕ) (b : ℕ) : (a + 1) / b = a / b + ite (b ∣ a + 1) 1 0 := sorry theorem succ_div_of_dvd {a : ℕ} {b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := eq.mpr (id (Eq._oldrec (Eq.refl ((a + 1) / b = a / b + 1)) (succ_div a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b + ite (b ∣ a + 1) 1 0 = a / b + 1)) (if_pos hba))) (Eq.refl (a / b + 1))) theorem succ_div_of_not_dvd {a : ℕ} {b : ℕ} (hba : ¬b ∣ a + 1) : (a + 1) / b = a / b := eq.mpr (id (Eq._oldrec (Eq.refl ((a + 1) / b = a / b)) (succ_div a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b + ite (b ∣ a + 1) 1 0 = a / b)) (if_neg hba))) (eq.mpr (id (Eq._oldrec (Eq.refl (a / b + 0 = a / b)) (add_zero (a / b)))) (Eq.refl (a / b)))) @[simp] theorem mod_mod_of_dvd (n : ℕ) {m : ℕ} {k : ℕ} (h : m ∣ k) : n % k % m = n % m := sorry @[simp] theorem mod_mod (a : ℕ) (n : ℕ) : a % n % n = a % n := sorry /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ theorem sub_mod_eq_zero_of_mod_eq {a : ℕ} {b : ℕ} {c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := sorry @[simp] theorem one_mod (n : ℕ) : 1 % (n + bit0 1) = 1 := mod_eq_of_lt (add_lt_add_right (succ_pos n) 1) theorem dvd_sub_mod {n : ℕ} (k : ℕ) : n ∣ k - k % n := Exists.intro (k / n) (nat.sub_eq_of_eq_add (Eq.symm (mod_add_div k n))) @[simp] theorem mod_add_mod (m : ℕ) (n : ℕ) (k : ℕ) : (m % n + k) % n = (m + k) % n := sorry @[simp] theorem add_mod_mod (m : ℕ) (n : ℕ) (k : ℕ) : (m + n % k) % k = (m + n) % k := eq.mpr (id (Eq._oldrec (Eq.refl ((m + n % k) % k = (m + n) % k)) (add_comm m (n % k)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((n % k + m) % k = (m + n) % k)) (mod_add_mod n k m))) (eq.mpr (id (Eq._oldrec (Eq.refl ((n + m) % k = (m + n) % k)) (add_comm n m))) (Eq.refl ((m + n) % k)))) theorem add_mod (a : ℕ) (b : ℕ) (n : ℕ) : (a + b) % n = (a % n + b % n) % n := eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % n = (a % n + b % n) % n)) (add_mod_mod (a % n) b n))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % n = (a % n + b) % n)) (mod_add_mod a n b))) (Eq.refl ((a + b) % n))) theorem add_mod_eq_add_mod_right {m : ℕ} {n : ℕ} {k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := eq.mpr (id (Eq._oldrec (Eq.refl ((m + i) % n = (k + i) % n)) (Eq.symm (mod_add_mod m n i)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((m % n + i) % n = (k + i) % n)) (Eq.symm (mod_add_mod k n i)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((m % n + i) % n = (k % n + i) % n)) H)) (Eq.refl ((k % n + i) % n)))) theorem add_mod_eq_add_mod_left {m : ℕ} {n : ℕ} {k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := eq.mpr (id (Eq._oldrec (Eq.refl ((i + m) % n = (i + k) % n)) (add_comm i m))) (eq.mpr (id (Eq._oldrec (Eq.refl ((m + i) % n = (i + k) % n)) (add_mod_eq_add_mod_right i H))) (eq.mpr (id (Eq._oldrec (Eq.refl ((k + i) % n = (i + k) % n)) (add_comm k i))) (Eq.refl ((i + k) % n)))) theorem mul_mod (a : ℕ) (b : ℕ) (n : ℕ) : a * b % n = a % n * (b % n) % n := sorry theorem dvd_div_of_mul_dvd {a : ℕ} {b : ℕ} {c : ℕ} (h : a * b ∣ c) : b ∣ c / a := sorry theorem mul_dvd_of_dvd_div {a : ℕ} {b : ℕ} {c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := sorry theorem div_mul_div {a : ℕ} {b : ℕ} {c : ℕ} {d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : a / b * (c / d) = a * c / (b * d) := sorry @[simp] theorem div_div_div_eq_div {a : ℕ} {b : ℕ} {c : ℕ} (dvd : b ∣ a) (dvd2 : a ∣ c) : c / (a / b) / b = c / a := sorry theorem eq_of_dvd_of_div_eq_one {a : ℕ} {b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (Eq.symm (nat.div_mul_cancel w)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a = b / a * a)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (a = 1 * a)) (one_mul a))) (Eq.refl a))) theorem eq_zero_of_dvd_of_div_eq_zero {a : ℕ} {b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (b = 0)) (Eq.symm (nat.div_mul_cancel w)))) (eq.mpr (id (Eq._oldrec (Eq.refl (b / a * a = 0)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (0 * a = 0)) (zero_mul a))) (Eq.refl 0))) /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ theorem eq_zero_of_dvd_of_lt {a : ℕ} {b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := eq_zero_of_dvd_of_div_eq_zero w (iff.elim_right (nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)) h) theorem div_le_div_left {a : ℕ} {b : ℕ} {c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := iff.mpr (le_div_iff_mul_le (a / b) a h₂) (le_trans (mul_le_mul_left (a / b) h₁) (div_mul_le_self a b)) theorem div_eq_self {a : ℕ} {b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := sorry /-! ### `pow` -/ -- This is redundant with `canonically_ordered_semiring.pow_le_pow_of_le_left`, -- but `canonically_ordered_semiring` is not such an obvious abstraction, and also quite long. -- So, we leave a version in the `nat` namespace as well. -- (The global `pow_le_pow_of_le_left` needs an extra hypothesis `0 ≤ x`.) protected theorem pow_le_pow_of_le_left {x : ℕ} {y : ℕ} (H : x ≤ y) (i : ℕ) : x ^ i ≤ y ^ i := canonically_ordered_semiring.pow_le_pow_of_le_left H theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i : ℕ} {j : ℕ} : i ≤ j → x ^ i ≤ x ^ j := sorry theorem pow_lt_pow_of_lt_left {x : ℕ} {y : ℕ} (H : x < y) {i : ℕ} (h : 0 < i) : x ^ i < y ^ i := sorry theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i : ℕ} {j : ℕ} (h : i < j) : x ^ i < x ^ j := sorry -- TODO: Generalize? theorem pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p ^ n < p ^ (n + 1) := sorry theorem lt_pow_self {p : ℕ} (h : 1 < p) (n : ℕ) : n < p ^ n := sorry theorem lt_two_pow (n : ℕ) : n < bit0 1 ^ n := lt_pow_self (of_as_true trivial) n theorem one_le_pow (n : ℕ) (m : ℕ) (h : 0 < m) : 1 ≤ m ^ n := eq.mpr (id (Eq._oldrec (Eq.refl (1 ≤ m ^ n)) (Eq.symm (one_pow n)))) (nat.pow_le_pow_of_le_left h n) theorem one_le_pow' (n : ℕ) (m : ℕ) : 1 ≤ (m + 1) ^ n := one_le_pow n (m + 1) (succ_pos m) theorem one_le_two_pow (n : ℕ) : 1 ≤ bit0 1 ^ n := one_le_pow n (bit0 1) (of_as_true trivial) theorem one_lt_pow (n : ℕ) (m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m ^ n := eq.mpr (id (Eq._oldrec (Eq.refl (1 < m ^ n)) (Eq.symm (one_pow n)))) (pow_lt_pow_of_lt_left h₁ h₀) theorem one_lt_pow' (n : ℕ) (m : ℕ) : 1 < (m + bit0 1) ^ (n + 1) := one_lt_pow (n + 1) (m + bit0 1) (succ_pos n) (nat.lt_of_sub_eq_succ rfl) theorem one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < bit0 1 ^ n := one_lt_pow n (bit0 1) h₀ (of_as_true trivial) theorem one_lt_two_pow' (n : ℕ) : 1 < bit0 1 ^ (n + 1) := one_lt_pow (n + 1) (bit0 1) (succ_pos n) (of_as_true trivial) theorem pow_right_strict_mono {x : ℕ} (k : bit0 1 ≤ x) : strict_mono fun (n : ℕ) => x ^ n := fun (_x _x_1 : ℕ) => pow_lt_pow_of_lt_right k theorem pow_le_iff_le_right {x : ℕ} {m : ℕ} {n : ℕ} (k : bit0 1 ≤ x) : x ^ m ≤ x ^ n ↔ m ≤ n := strict_mono.le_iff_le (pow_right_strict_mono k) theorem pow_lt_iff_lt_right {x : ℕ} {m : ℕ} {n : ℕ} (k : bit0 1 ≤ x) : x ^ m < x ^ n ↔ m < n := strict_mono.lt_iff_lt (pow_right_strict_mono k) theorem pow_right_injective {x : ℕ} (k : bit0 1 ≤ x) : function.injective fun (n : ℕ) => x ^ n := strict_mono.injective (pow_right_strict_mono k) theorem pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono fun (x : ℕ) => x ^ m := fun (_x _x_1 : ℕ) (h : _x < _x_1) => pow_lt_pow_of_lt_left h k end nat theorem strict_mono.nat_pow {n : ℕ} (hn : 1 ≤ n) {f : ℕ → ℕ} (hf : strict_mono f) : strict_mono fun (m : ℕ) => f m ^ n := strict_mono.comp (nat.pow_left_strict_mono hn) hf namespace nat theorem pow_le_iff_le_left {m : ℕ} {x : ℕ} {y : ℕ} (k : 1 ≤ m) : x ^ m ≤ y ^ m ↔ x ≤ y := strict_mono.le_iff_le (pow_left_strict_mono k) theorem pow_lt_iff_lt_left {m : ℕ} {x : ℕ} {y : ℕ} (k : 1 ≤ m) : x ^ m < y ^ m ↔ x < y := strict_mono.lt_iff_lt (pow_left_strict_mono k) theorem pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective fun (x : ℕ) => x ^ m := strict_mono.injective (pow_left_strict_mono k) /-! ### `pow` and `mod` / `dvd` -/ theorem mod_pow_succ {b : ℕ} (b_pos : 0 < b) (w : ℕ) (m : ℕ) : m % b ^ Nat.succ w = b * (m / b % b ^ w) + m % b := sorry theorem pow_dvd_pow_iff_pow_le_pow {k : ℕ} {l : ℕ} {x : ℕ} (w : 0 < x) : x ^ k ∣ x ^ l ↔ x ^ k ≤ x ^ l := sorry /-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/ theorem pow_dvd_pow_iff_le_right {x : ℕ} {k : ℕ} {l : ℕ} (w : 1 < x) : x ^ k ∣ x ^ l ↔ k ≤ l := eq.mpr (id (Eq._oldrec (Eq.refl (x ^ k ∣ x ^ l ↔ k ≤ l)) (propext (pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w))))) (eq.mpr (id (Eq._oldrec (Eq.refl (x ^ k ≤ x ^ l ↔ k ≤ l)) (propext (pow_le_iff_le_right w)))) (iff.refl (k ≤ l))) theorem pow_dvd_pow_iff_le_right' {b : ℕ} {k : ℕ} {l : ℕ} : (b + bit0 1) ^ k ∣ (b + bit0 1) ^ l ↔ k ≤ l := pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl) theorem not_pos_pow_dvd {p : ℕ} {k : ℕ} (hp : 1 < p) (hk : 1 < k) : ¬p ^ k ∣ p := sorry theorem pow_dvd_of_le_of_pow_dvd {p : ℕ} {m : ℕ} {n : ℕ} {k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := (fun (this : p ^ m ∣ p ^ n) => dvd_trans this hdiv) (pow_dvd_pow p hmn) theorem dvd_of_pow_dvd {p : ℕ} {k : ℕ} {m : ℕ} (hk : 1 ≤ k) (hpk : p ^ k ∣ m) : p ∣ m := eq.mpr (id (Eq._oldrec (Eq.refl (p ∣ m)) (Eq.symm (pow_one p)))) (pow_dvd_of_le_of_pow_dvd hk hpk) /-- `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ theorem exists_lt_and_lt_iff_not_dvd (m : ℕ) {n : ℕ} (hn : 0 < n) : (∃ (k : ℕ), n * k < m ∧ m < n * (k + 1)) ↔ ¬n ∣ m := sorry /-! ### `find` -/ theorem find_eq_iff {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) {m : ℕ} : nat.find h = m ↔ p m ∧ ∀ (n : ℕ), n < m → ¬p n := sorry @[simp] theorem find_eq_zero {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) : nat.find h = 0 ↔ p 0 := sorry @[simp] theorem find_pos {p : ℕ → Prop} [decidable_pred p] (h : ∃ (n : ℕ), p n) : 0 < nat.find h ↔ ¬p 0 := eq.mpr (id (Eq._oldrec (Eq.refl (0 < nat.find h ↔ ¬p 0)) (propext pos_iff_ne_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat.find h ≠ 0 ↔ ¬p 0)) (propext not_iff_not))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat.find h = 0 ↔ p 0)) (propext (find_eq_zero h)))) (iff.refl (p 0)))) /-! ### `find_greatest` -/ /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ := sorry @[simp] theorem find_greatest_zero {P : ℕ → Prop} [decidable_pred P] : nat.find_greatest P 0 = 0 := rfl @[simp] theorem find_greatest_eq {P : ℕ → Prop} [decidable_pred P] {b : ℕ} : P b → nat.find_greatest P b = b := sorry @[simp] theorem find_greatest_of_not {P : ℕ → Prop} [decidable_pred P] {b : ℕ} (h : ¬P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := sorry theorem find_greatest_eq_iff {P : ℕ → Prop} [decidable_pred P] {b : ℕ} {m : ℕ} : nat.find_greatest P b = m ↔ m ≤ b ∧ (m ≠ 0 → P m) ∧ ∀ {n : ℕ}, m < n → n ≤ b → ¬P n := sorry theorem find_greatest_eq_zero_iff {P : ℕ → Prop} [decidable_pred P] {b : ℕ} : nat.find_greatest P b = 0 ↔ ∀ {n : ℕ}, 0 < n → n ≤ b → ¬P n := sorry theorem find_greatest_spec {P : ℕ → Prop} [decidable_pred P] {b : ℕ} (h : ∃ (m : ℕ), m ≤ b ∧ P m) : P (nat.find_greatest P b) := sorry theorem find_greatest_le {P : ℕ → Prop} [decidable_pred P] {b : ℕ} : nat.find_greatest P b ≤ b := and.left (iff.mp find_greatest_eq_iff rfl) theorem le_find_greatest {P : ℕ → Prop} [decidable_pred P] {b : ℕ} {m : ℕ} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := le_of_not_lt fun (hlt : nat.find_greatest P b < m) => and.right (and.right (iff.mp find_greatest_eq_iff rfl)) m hlt hmb hm theorem find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b : ℕ} {k : ℕ} (hk : nat.find_greatest P b < k) (hkb : k ≤ b) : ¬P k := and.right (and.right (iff.mp find_greatest_eq_iff rfl)) k hk hkb theorem find_greatest_of_ne_zero {P : ℕ → Prop} [decidable_pred P] {b : ℕ} {m : ℕ} (h : nat.find_greatest P b = m) (h0 : m ≠ 0) : P m := and.left (and.right (iff.mp find_greatest_eq_iff h)) h0 /-! ### `bodd_div2` and `bodd` -/ @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := sorry @[simp] theorem bodd_bit0 (n : ℕ) : bodd (bit0 n) = false := bodd_bit false n @[simp] theorem bodd_bit1 (n : ℕ) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] theorem div2_bit0 (n : ℕ) : div2 (bit0 n) = n := div2_bit false n @[simp] theorem div2_bit1 (n : ℕ) : div2 (bit1 n) = n := div2_bit tt n /-! ### `bit0` and `bit1` -/ protected theorem bit0_le {n : ℕ} {m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n : ℕ} {m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le (b : Bool) {n : ℕ} {m : ℕ} : n ≤ m → bit b n ≤ bit b m := fun (ᾰ : n ≤ m) => bool.cases_on b (idRhs (bit0 n ≤ bit0 m) (nat.bit0_le ᾰ)) (idRhs (bit1 n ≤ bit1 m) (nat.bit1_le ᾰ)) theorem bit_ne_zero (b : Bool) {n : ℕ} (h : n ≠ 0) : bit b n ≠ 0 := bool.cases_on b (nat.bit0_ne_zero h) (nat.bit1_ne_zero n) theorem bit0_le_bit (b : Bool) {m : ℕ} {n : ℕ} : m ≤ n → bit0 m ≤ bit b n := fun (ᾰ : m ≤ n) => bool.cases_on b (idRhs (bit0 m ≤ bit0 n) (nat.bit0_le ᾰ)) (idRhs (bit0 m ≤ bit tt n) (le_of_lt (nat.bit0_lt_bit1 ᾰ))) theorem bit_le_bit1 (b : Bool) {m : ℕ} {n : ℕ} : m ≤ n → bit b m ≤ bit1 n := fun (ᾰ : m ≤ n) => bool.cases_on b (idRhs (bit false m ≤ bit1 n) (le_of_lt (nat.bit0_lt_bit1 ᾰ))) (idRhs (bit1 m ≤ bit1 n) (nat.bit1_le ᾰ)) theorem bit_lt_bit0 (b : Bool) {n : ℕ} {m : ℕ} : n < m → bit b n < bit0 m := fun (ᾰ : n < m) => bool.cases_on b (idRhs (bit0 n < bit0 m) (nat.bit0_lt ᾰ)) (idRhs (bit1 n < bit0 m) (nat.bit1_lt_bit0 ᾰ)) theorem bit_lt_bit (a : Bool) (b : Bool) {n : ℕ} {m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 a h) (bit0_le_bit b (le_refl m)) @[simp] theorem bit0_le_bit1_iff {n : ℕ} {k : ℕ} : bit0 k ≤ bit1 n ↔ k ≤ n := sorry @[simp] theorem bit0_lt_bit1_iff {n : ℕ} {k : ℕ} : bit0 k < bit1 n ↔ k ≤ n := { mp := fun (h : bit0 k < bit1 n) => iff.mp bit0_le_bit1_iff (le_of_lt h), mpr := nat.bit0_lt_bit1 } @[simp] theorem bit1_le_bit0_iff {n : ℕ} {k : ℕ} : bit1 k ≤ bit0 n ↔ k < n := sorry @[simp] theorem bit1_lt_bit0_iff {n : ℕ} {k : ℕ} : bit1 k < bit0 n ↔ k < n := { mp := fun (h : bit1 k < bit0 n) => iff.mp bit1_le_bit0_iff (le_of_lt h), mpr := nat.bit1_lt_bit0 } @[simp] theorem one_le_bit0_iff {n : ℕ} : 1 ≤ bit0 n ↔ 0 < n := sorry @[simp] theorem one_lt_bit0_iff {n : ℕ} : 1 < bit0 n ↔ 1 ≤ n := sorry @[simp] theorem bit_le_bit_iff {n : ℕ} {k : ℕ} {b : Bool} : bit b k ≤ bit b n ↔ k ≤ n := bool.cases_on b (idRhs (bit0 k ≤ bit0 n ↔ k ≤ n) bit0_le_bit0) (idRhs (bit1 k ≤ bit1 n ↔ k ≤ n) bit1_le_bit1) @[simp] theorem bit_lt_bit_iff {n : ℕ} {k : ℕ} {b : Bool} : bit b k < bit b n ↔ k < n := bool.cases_on b (idRhs (bit0 k < bit0 n ↔ k < n) bit0_lt_bit0) (idRhs (bit1 k < bit1 n ↔ k < n) bit1_lt_bit1) @[simp] theorem bit_le_bit1_iff {n : ℕ} {k : ℕ} {b : Bool} : bit b k ≤ bit1 n ↔ k ≤ n := bool.cases_on b (idRhs (bit0 k ≤ bit1 n ↔ k ≤ n) bit0_le_bit1_iff) (idRhs (bit1 k ≤ bit1 n ↔ k ≤ n) bit1_le_bit1) @[simp] theorem bit0_mod_two {n : ℕ} : bit0 n % bit0 1 = 0 := sorry @[simp] theorem bit1_mod_two {n : ℕ} : bit1 n % bit0 1 = 1 := sorry theorem pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := sorry /-- Define a function on `ℕ` depending on parity of the argument. -/ def bit_cases {C : ℕ → Sort u} (H : (b : Bool) → (n : ℕ) → C (bit b n)) (n : ℕ) : C n := eq.rec_on (bit_decomp n) (H (bodd n) (div2 n)) /-! ### `shiftl` and `shiftr` -/ theorem shiftl_eq_mul_pow (m : ℕ) (n : ℕ) : shiftl m n = m * bit0 1 ^ n := sorry theorem shiftl'_tt_eq_mul_pow (m : ℕ) (n : ℕ) : shiftl' tt m n + 1 = (m + 1) * bit0 1 ^ n := sorry theorem one_shiftl (n : ℕ) : shiftl 1 n = bit0 1 ^ n := Eq.trans (shiftl_eq_mul_pow 1 n) (nat.one_mul (bit0 1 ^ n)) @[simp] theorem zero_shiftl (n : ℕ) : shiftl 0 n = 0 := Eq.trans (shiftl_eq_mul_pow 0 n) (nat.zero_mul (bit0 1 ^ n)) theorem shiftr_eq_div_pow (m : ℕ) (n : ℕ) : shiftr m n = m / bit0 1 ^ n := sorry @[simp] theorem zero_shiftr (n : ℕ) : shiftr 0 n = 0 := Eq.trans (shiftr_eq_div_pow 0 n) (nat.zero_div (bit0 1 ^ n)) theorem shiftl'_ne_zero_left (b : Bool) {m : ℕ} (h : m ≠ 0) (n : ℕ) : shiftl' b m n ≠ 0 := sorry theorem shiftl'_tt_ne_zero (m : ℕ) {n : ℕ} (h : n ≠ 0) : shiftl' tt m n ≠ 0 := nat.cases_on n (fun (h : 0 ≠ 0) => idRhs (shiftl' tt m 0 ≠ 0) (absurd rfl h)) (fun (n : ℕ) (h : Nat.succ n ≠ 0) => idRhs (bit1 (shiftl' tt m n) ≠ 0) (nat.bit1_ne_zero (shiftl' tt m n))) h /-! ### `size` -/ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b : Bool} {n : ℕ} (h : bit b n ≠ 0) : size (bit b n) = Nat.succ (size n) := sorry @[simp] theorem size_bit0 {n : ℕ} (h : n ≠ 0) : size (bit0 n) = Nat.succ (size n) := size_bit (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n : ℕ) : size (bit1 n) = Nat.succ (size n) := size_bit (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := size_bit1 0 @[simp] theorem size_shiftl' {b : Bool} {m : ℕ} {n : ℕ} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := sorry @[simp] theorem size_shiftl {m : ℕ} (h : m ≠ 0) (n : ℕ) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left false h n) theorem lt_size_self (n : ℕ) : n < bit0 1 ^ size n := sorry theorem size_le {m : ℕ} {n : ℕ} : size m ≤ n ↔ m < bit0 1 ^ n := sorry theorem lt_size {m : ℕ} {n : ℕ} : m < size n ↔ bit0 1 ^ m ≤ n := sorry theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := eq.mpr (id (Eq._oldrec (Eq.refl (0 < size n ↔ 0 < n)) (propext lt_size))) (iff.refl (bit0 1 ^ 0 ≤ n)) theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := sorry theorem size_pow {n : ℕ} : size (bit0 1 ^ n) = n + 1 := le_antisymm (iff.mpr size_le (pow_lt_pow_of_lt_right (of_as_true trivial) (lt_succ_self n))) (iff.mpr lt_size (le_refl (bit0 1 ^ n))) theorem size_le_size {m : ℕ} {n : ℕ} (h : m ≤ n) : size m ≤ size n := iff.mpr size_le (lt_of_le_of_lt h (lt_size_self n)) /-! ### decidability of predicates -/ protected instance decidable_ball_lt (n : ℕ) (P : (k : ℕ) → k < n → Prop) [H : (n_1 : ℕ) → (h : n_1 < n) → Decidable (P n_1 h)] : Decidable (∀ (n_1 : ℕ) (h : n_1 < n), P n_1 h) := Nat.rec (fun (P : (k : ℕ) → k < 0 → Prop) (H : (n : ℕ) → (h : n < 0) → Decidable (P n h)) => is_true sorry) (fun (n : ℕ) (IH : (P : (k : ℕ) → k < n → Prop) → [H : (n_1 : ℕ) → (h : n_1 < n) → Decidable (P n_1 h)] → Decidable (∀ (n_1 : ℕ) (h : n_1 < n), P n_1 h)) (P : (k : ℕ) → k < Nat.succ n → Prop) (H : (n_1 : ℕ) → (h : n_1 < Nat.succ n) → Decidable (P n_1 h)) => decidable.cases_on (IH fun (k : ℕ) (h : k < n) => P k (lt_succ_of_lt h)) (fun (h : ¬∀ (n_1 : ℕ) (h : n_1 < n), (fun (k : ℕ) (h : k < n) => P k (lt_succ_of_lt h)) n_1 h) => isFalse sorry) fun (h : ∀ (n_1 : ℕ) (h : n_1 < n), (fun (k : ℕ) (h : k < n) => P k (lt_succ_of_lt h)) n_1 h) => dite (P n (lt_succ_self n)) (fun (p : P n (lt_succ_self n)) => is_true sorry) fun (p : ¬P n (lt_succ_self n)) => isFalse sorry) n P protected instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : Decidable (∀ (i : fin n), P i) := decidable_of_iff (∀ (k : ℕ) (h : k < n), P { val := k, property := h }) sorry protected instance decidable_ball_le (n : ℕ) (P : (k : ℕ) → k ≤ n → Prop) [H : (n_1 : ℕ) → (h : n_1 ≤ n) → Decidable (P n_1 h)] : Decidable (∀ (n_1 : ℕ) (h : n_1 ≤ n), P n_1 h) := decidable_of_iff (∀ (k : ℕ) (h : k < Nat.succ n), P k (le_of_lt_succ h)) sorry protected instance decidable_lo_hi (lo : ℕ) (hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : Decidable (∀ (x : ℕ), lo ≤ x → x < hi → P x) := decidable_of_iff (∀ (x : ℕ), x < hi - lo → P (lo + x)) sorry protected instance decidable_lo_hi_le (lo : ℕ) (hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : Decidable (∀ (x : ℕ), lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀ (x : ℕ), lo ≤ x → x < hi + 1 → P x) sorry protected instance decidable_exists_lt {P : ℕ → Prop} [h : decidable_pred P] : decidable_pred fun (n : ℕ) => ∃ (m : ℕ), m < n ∧ P m := sorry /-! ### find -/ theorem find_le {p : ℕ → Prop} {q : ℕ → Prop} [decidable_pred p] [decidable_pred q] (h : ∀ (n : ℕ), q n → p n) (hp : ∃ (n : ℕ), p n) (hq : ∃ (n : ℕ), q n) : nat.find hp ≤ nat.find hq := nat.find_min' hp (h (nat.find hq) (nat.find_spec hq))
1b9ce89e4d7976f991128f7b9b10298fbfb4725b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/category/Top/opens.lean
251221c85dcbea66c8bb6378f576e546734374b4
[ "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
11,665
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.category.preorder import category_theory.eq_to_hom import topology.category.Top.epi_mono import topology.sets.opens /-! # The category of open sets in a topological space. We define `to_Top : opens X ⥤ Top` and `map (f : X ⟶ Y) : opens Y ⥤ opens X`, given by taking preimages of open sets. Unfortunately `opens` isn't (usefully) a functor `Top ⥤ Cat`. (One can in fact define such a functor, but using it results in unresolvable `eq.rec` terms in goals.) Really it's a 2-functor from (spaces, continuous functions, equalities) to (categories, functors, natural isomorphisms). We don't attempt to set up the full theory here, but do provide the natural isomorphisms `map_id : map (𝟙 X) ≅ 𝟭 (opens X)` and `map_comp : map (f ≫ g) ≅ map g ⋙ map f`. Beyond that, there's a collection of simp lemmas for working with these constructions. -/ open category_theory open topological_space open opposite universe u namespace topological_space.opens variables {X Y Z : Top.{u}} /-! Since `opens X` has a partial order, it automatically receives a `category` instance. Unfortunately, because we do not allow morphisms in `Prop`, the morphisms `U ⟶ V` are not just proofs `U ≤ V`, but rather `ulift (plift (U ≤ V))`. -/ instance opens_hom_has_coe_to_fun {U V : opens X} : has_coe_to_fun (U ⟶ V) (λ f, U → V) := ⟨λ f x, ⟨x, f.le x.2⟩⟩ /-! We now construct as morphisms various inclusions of open sets. -/ -- This is tedious, but necessary because we decided not to allow Prop as morphisms in a category... /-- The inclusion `U ⊓ V ⟶ U` as a morphism in the category of open sets. -/ def inf_le_left (U V : opens X) : U ⊓ V ⟶ U := inf_le_left.hom /-- The inclusion `U ⊓ V ⟶ V` as a morphism in the category of open sets. -/ def inf_le_right (U V : opens X) : U ⊓ V ⟶ V := inf_le_right.hom /-- The inclusion `U i ⟶ supr U` as a morphism in the category of open sets. -/ def le_supr {ι : Type*} (U : ι → opens X) (i : ι) : U i ⟶ supr U := (le_supr U i).hom /-- The inclusion `⊥ ⟶ U` as a morphism in the category of open sets. -/ def bot_le (U : opens X) : ⊥ ⟶ U := bot_le.hom /-- The inclusion `U ⟶ ⊤` as a morphism in the category of open sets. -/ def le_top (U : opens X) : U ⟶ ⊤ := le_top.hom -- We do not mark this as a simp lemma because it breaks open `x`. -- Nevertheless, it is useful in `sheaf_of_functions`. lemma inf_le_left_apply (U V : opens X) (x) : (inf_le_left U V) x = ⟨x.1, (@_root_.inf_le_left _ _ U V : _ ≤ _) x.2⟩ := rfl @[simp] lemma inf_le_left_apply_mk (U V : opens X) (x) (m) : (inf_le_left U V) ⟨x, m⟩ = ⟨x, (@_root_.inf_le_left _ _ U V : _ ≤ _) m⟩ := rfl @[simp] lemma le_supr_apply_mk {ι : Type*} (U : ι → opens X) (i : ι) (x) (m) : (le_supr U i) ⟨x, m⟩ = ⟨x, (_root_.le_supr U i : _) m⟩ := rfl /-- The functor from open sets in `X` to `Top`, realising each open set as a topological space itself. -/ def to_Top (X : Top.{u}) : opens X ⥤ Top := { obj := λ U, ⟨U.val, infer_instance⟩, map := λ U V i, ⟨λ x, ⟨x.1, i.le x.2⟩, (embedding.continuous_iff embedding_subtype_coe).2 continuous_induced_dom⟩ } @[simp] lemma to_Top_map (X : Top.{u}) {U V : opens X} {f : U ⟶ V} {x} {h} : ((to_Top X).map f) ⟨x, h⟩ = ⟨x, f.le h⟩ := rfl /-- The inclusion map from an open subset to the whole space, as a morphism in `Top`. -/ @[simps] def inclusion {X : Top.{u}} (U : opens X) : (to_Top X).obj U ⟶ X := { to_fun := _, continuous_to_fun := continuous_subtype_coe } lemma open_embedding {X : Top.{u}} (U : opens X) : open_embedding (inclusion U) := is_open.open_embedding_subtype_coe U.2 /-- The inclusion of the top open subset (i.e. the whole space) is an isomorphism. -/ def inclusion_top_iso (X : Top.{u}) : (to_Top X).obj ⊤ ≅ X := { hom := inclusion ⊤, inv := ⟨λ x, ⟨x, trivial⟩, continuous_def.2 $ λ U ⟨S, hS, hSU⟩, hSU ▸ hS⟩ } /-- `opens.map f` gives the functor from open sets in Y to open set in X, given by taking preimages under f. -/ def map (f : X ⟶ Y) : opens Y ⥤ opens X := { obj := λ U, ⟨ f ⁻¹' U.val, U.property.preimage f.continuous ⟩, map := λ U V i, ⟨ ⟨ λ x h, i.le h ⟩ ⟩ }. lemma map_coe (f : X ⟶ Y) (U : opens Y) : ↑((map f).obj U) = f ⁻¹' U := rfl @[simp] lemma map_obj (f : X ⟶ Y) (U) (p) : (map f).obj ⟨U, p⟩ = ⟨f ⁻¹' U, p.preimage f.continuous⟩ := rfl @[simp] lemma map_id_obj (U : opens X) : (map (𝟙 X)).obj U = U := let ⟨_,_⟩ := U in rfl @[simp] lemma map_id_obj' (U) (p) : (map (𝟙 X)).obj ⟨U, p⟩ = ⟨U, p⟩ := rfl @[simp] lemma map_id_obj_unop (U : (opens X)ᵒᵖ) : (map (𝟙 X)).obj (unop U) = unop U := let ⟨_,_⟩ := U.unop in rfl @[simp] lemma op_map_id_obj (U : (opens X)ᵒᵖ) : (map (𝟙 X)).op.obj U = U := by simp /-- The inclusion `U ⟶ (map f).obj ⊤` as a morphism in the category of open sets. -/ def le_map_top (f : X ⟶ Y) (U : opens X) : U ⟶ (map f).obj ⊤ := le_top U @[simp] lemma map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj U = (map f).obj ((map g).obj U) := rfl @[simp] lemma map_comp_obj' (f : X ⟶ Y) (g : Y ⟶ Z) (U) (p) : (map (f ≫ g)).obj ⟨U, p⟩ = (map f).obj ((map g).obj ⟨U, p⟩) := rfl @[simp] lemma map_comp_map (f : X ⟶ Y) (g : Y ⟶ Z) {U V} (i : U ⟶ V) : (map (f ≫ g)).map i = (map f).map ((map g).map i) := rfl @[simp] lemma map_comp_obj_unop (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).obj (unop U) = (map f).obj ((map g).obj (unop U)) := rfl @[simp] lemma op_map_comp_obj (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (map (f ≫ g)).op.obj U = (map f).op.obj ((map g).op.obj U) := rfl lemma map_supr (f : X ⟶ Y) {ι : Type*} (U : ι → opens Y) : (map f).obj (supr U) = supr ((map f).obj ∘ U) := begin apply subtype.eq, rw [supr_def, supr_def, map_obj], dsimp, rw set.preimage_Union, refl, end section variable (X) /-- The functor `opens X ⥤ opens X` given by taking preimages under the identity function is naturally isomorphic to the identity functor. -/ @[simps] def map_id : map (𝟙 X) ≅ 𝟭 (opens X) := { hom := { app := λ U, eq_to_hom (map_id_obj U) }, inv := { app := λ U, eq_to_hom (map_id_obj U).symm } } lemma map_id_eq : map (𝟙 X) = 𝟭 (opens X) := by { unfold map, congr, ext, refl, ext } end /-- The natural isomorphism between taking preimages under `f ≫ g`, and the composite of taking preimages under `g`, then preimages under `f`. -/ @[simps] def map_comp (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f := { hom := { app := λ U, eq_to_hom (map_comp_obj f g U) }, inv := { app := λ U, eq_to_hom (map_comp_obj f g U).symm } } lemma map_comp_eq (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) = map g ⋙ map f := rfl /-- If two continuous maps `f g : X ⟶ Y` are equal, then the functors `opens Y ⥤ opens X` they induce are isomorphic. -/ -- We could make `f g` implicit here, but it's nice to be able to see when -- they are the identity (often!) def map_iso (f g : X ⟶ Y) (h : f = g) : map f ≅ map g := nat_iso.of_components (λ U, eq_to_iso (congr_fun (congr_arg functor.obj (congr_arg map h)) U) ) (by obviously) lemma map_eq (f g : X ⟶ Y) (h : f = g) : map f = map g := by { unfold map, congr, ext, rw h, rw h, assumption' } @[simp] lemma map_iso_refl (f : X ⟶ Y) (h) : map_iso f f h = iso.refl (map _) := rfl @[simp] lemma map_iso_hom_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) : (map_iso f g h).hom.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h)) U) := rfl @[simp] lemma map_iso_inv_app (f g : X ⟶ Y) (h : f = g) (U : opens Y) : (map_iso f g h).inv.app U = eq_to_hom (congr_fun (congr_arg functor.obj (congr_arg map h.symm)) U) := rfl /-- A homeomorphism of spaces gives an equivalence of categories of open sets. -/ @[simps] def map_map_iso {X Y : Top.{u}} (H : X ≅ Y) : opens Y ≌ opens X := { functor := map H.hom, inverse := map H.inv, unit_iso := nat_iso.of_components (λ U, eq_to_iso (by simp [map, set.preimage_preimage])) (by { intros _ _ _, simp }), counit_iso := nat_iso.of_components (λ U, eq_to_iso (by simp [map, set.preimage_preimage])) (by { intros _ _ _, simp }) } end topological_space.opens /-- An open map `f : X ⟶ Y` induces a functor `opens X ⥤ opens Y`. -/ @[simps] def is_open_map.functor {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) : opens X ⥤ opens Y := { obj := λ U, ⟨f '' U, hf U U.2⟩, map := λ U V h, ⟨⟨set.image_subset _ h.down.down⟩⟩ } /-- An open map `f : X ⟶ Y` induces an adjunction between `opens X` and `opens Y`. -/ def is_open_map.adjunction {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) : adjunction hf.functor (topological_space.opens.map f) := adjunction.mk_of_unit_counit { unit := { app := λ U, hom_of_le $ λ x hxU, ⟨x, hxU, rfl⟩ }, counit := { app := λ V, hom_of_le $ λ y ⟨x, hfxV, hxy⟩, hxy ▸ hfxV } } instance is_open_map.functor_full_of_mono {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) [H : mono f] : full hf.functor := { preimage := λ U V i, hom_of_le (λ x hx, by { obtain ⟨y, hy, eq⟩ := i.le ⟨x, hx, rfl⟩, exact (Top.mono_iff_injective f).mp H eq ▸ hy }) } instance is_open_map.functor_faithful {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) : faithful hf.functor := {} namespace topological_space.opens open topological_space @[simp] lemma open_embedding_obj_top {X : Top} (U : opens X) : U.open_embedding.is_open_map.functor.obj ⊤ = U := by { ext1, exact set.image_univ.trans subtype.range_coe } @[simp] lemma inclusion_map_eq_top {X : Top} (U : opens X) : (opens.map U.inclusion).obj U = ⊤ := by { ext1, exact subtype.coe_preimage_self _ } @[simp] lemma adjunction_counit_app_self {X : Top} (U : opens X) : U.open_embedding.is_open_map.adjunction.counit.app U = eq_to_hom (by simp) := by ext lemma inclusion_top_functor (X : Top) : (@opens.open_embedding X ⊤).is_open_map.functor = map (inclusion_top_iso X).inv := begin apply functor.hext, intro, abstract obj_eq { ext, exact ⟨ λ ⟨⟨_,_⟩,h,rfl⟩, h, λ h, ⟨⟨x,trivial⟩,h,rfl⟩ ⟩ }, intros, apply subsingleton.helim, congr' 1, iterate 2 {apply inclusion_top_functor.obj_eq}, end lemma functor_obj_map_obj {X Y : Top} {f : X ⟶ Y} (hf : is_open_map f) (U : opens Y) : hf.functor.obj ((opens.map f).obj U) = hf.functor.obj ⊤ ⊓ U := begin ext, split, { rintros ⟨x, hx, rfl⟩, exact ⟨⟨x, trivial, rfl⟩, hx⟩ }, { rintros ⟨⟨x, -, rfl⟩, hx⟩, exact ⟨x, hx, rfl⟩ } end @[simp] lemma functor_map_eq_inf {X : Top} (U V : opens X) : U.open_embedding.is_open_map.functor.obj ((opens.map U.inclusion).obj V) = V ⊓ U := by { ext1, refine set.image_preimage_eq_inter_range.trans _, simpa } lemma map_functor_eq' {X U : Top} (f : U ⟶ X) (hf : _root_.open_embedding f) (V) : ((opens.map f).obj $ hf.is_open_map.functor.obj V) = V := opens.ext $ set.preimage_image_eq _ hf.inj @[simp] lemma map_functor_eq {X : Top} {U : opens X} (V : opens U) : ((opens.map U.inclusion).obj $ U.open_embedding.is_open_map.functor.obj V) = V := topological_space.opens.map_functor_eq' _ U.open_embedding V @[simp] lemma adjunction_counit_map_functor {X : Top} {U : opens X} (V : opens U) : U.open_embedding.is_open_map.adjunction.counit.app (U.open_embedding.is_open_map.functor.obj V) = eq_to_hom (by { conv_rhs { rw ← V.map_functor_eq }, refl }) := by ext end topological_space.opens
15ec2a92431cb5d13e175754adc879c8c3e11ac7
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/coe2.lean
b2fbd3fb979fbaf13e73f9792e58ece4de9ed645
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
479
lean
import standard namespace setoid inductive setoid : Type := | mk_setoid: Π (A : Type), (A → A → Prop) → setoid definition carrier (s : setoid) := setoid_rec (λ a eq, a) s definition eqv {s : setoid} : carrier s → carrier s → Prop := setoid_rec (λ a eqv, eqv) s infix `≈`:50 := eqv coercion carrier inductive morphism (s1 s2 : setoid) : Type := | mk_morphism : Π (f : s1 → s2), (∀ x y, x ≈ y → f x ≈ f y) → morphism s1 s2 end
4a39c0245e18bac796a7644a1e4e47d580f32275
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Exception.lean
ab1e2c07def80f67261e6bbe97a2d7d580545a8e
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,585
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.Message import Lean.InternalExceptionId import Lean.Data.Options namespace Lean /- Exception type used in most Lean monads -/ inductive Exception | error (ref : Syntax) (msg : MessageData) | internal (id : InternalExceptionId) def Exception.toMessageData : Exception → MessageData | Exception.error _ msg => msg | Exception.internal id => id.toString def Exception.getRef : Exception → Syntax | Exception.error ref _ => ref | Exception.internal _ => Syntax.missing instance Exception.inhabited : Inhabited Exception := ⟨Exception.error (arbitrary _) (arbitrary _)⟩ class Ref (m : Type → Type) := (getRef : m Syntax) (withRef {α} : Syntax → m α → m α) export Ref (getRef withRef) instance refTrans (m n : Type → Type) [Ref m] [MonadFunctor m m n n] [MonadLift m n] : Ref n := { getRef := liftM (getRef : m _), withRef := fun α ref x => monadMap (fun α => withRef ref : forall {α}, m α → m α) x } def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [Ref m] {α} (ref : Syntax) (x : m α) : m α := do oldRef ← getRef; let ref := replaceRef ref oldRef; Ref.withRef ref x /- Similar to `AddMessageContext`, but for error messages. The default instance just uses `AddMessageContext`. In error messages, we may want to provide additional information (e.g., macro expansion stack), and refine the `(ref : Syntax)`. -/ class AddErrorMessageContext (m : Type → Type) := (add : Syntax → MessageData → m (Syntax × MessageData)) instance addErrorMessageContextDefault (m : Type → Type) [AddMessageContext m] [Monad m] : AddErrorMessageContext m := { add := fun ref msg => do msg ← addMessageContext msg; pure (ref, msg) } section Methods variables {m : Type → Type} [Monad m] [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] def throwError {α} (msg : MessageData) : m α := do ref ← getRef; (ref, msg) ← AddErrorMessageContext.add ref msg; throw $ Exception.error ref msg def throwErrorAt {α} (ref : Syntax) (msg : MessageData) : m α := do withRef ref $ throwError msg def ofExcept {ε α} [HasToString ε] (x : Except ε α) : m α := match x with | Except.ok a => pure a | Except.error e => throwError $ toString e def throwKernelException {α} [MonadOptions m] (ex : KernelException) : m α := do opts ← getOptions; throwError $ ex.toMessageData opts end Methods class MonadRecDepth (m : Type → Type) := (withRecDepth {α} : Nat → m α → m α) (getRecDepth : m Nat) (getMaxRecDepth : m Nat) instance ReaderT.MonadRecDepth {ρ m} [Monad m] [MonadRecDepth m] : MonadRecDepth (ReaderT ρ m) := { withRecDepth := fun α d x ctx => MonadRecDepth.withRecDepth d (x ctx), getRecDepth := fun _ => MonadRecDepth.getRecDepth, getMaxRecDepth := fun _ => MonadRecDepth.getMaxRecDepth } instance StateRefT.monadRecDepth {ω σ m} [Monad m] [MonadRecDepth m] : MonadRecDepth (StateRefT' ω σ m) := inferInstanceAs (MonadRecDepth (ReaderT _ _)) @[inline] def withIncRecDepth {α m} [Monad m] [MonadRecDepth m] [MonadExceptOf Exception m] [Ref m] [AddErrorMessageContext m] (x : m α) : m α := do curr ← MonadRecDepth.getRecDepth; max ← MonadRecDepth.getMaxRecDepth; when (curr == max) $ throwError maxRecDepthErrorMessage; MonadRecDepth.withRecDepth (curr+1) x end Lean
a2415fb7ed2e422cb34487d177918e5b2de883d2
92b50235facfbc08dfe7f334827d47281471333b
/library/theories/number_theory/bezout.lean
152f34c02cffdd86f64e0bbe86518901370875e5
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
3,821
lean
/- Copyright (c) 2015 William Peterson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: William Peterson, Jeremy Avigad Extended gcd, Bezout's theorem, chinese remainder theorem. -/ import data.nat.div data.int .primes /- Bezout's theorem -/ section Bezout open nat int open eq.ops well_founded decidable prod private definition pair_nat.lt : ℕ × ℕ → ℕ × ℕ → Prop := measure pr₂ private definition pair_nat.lt.wf : well_founded pair_nat.lt := intro_k (measure.wf pr₂) 20 local attribute pair_nat.lt.wf [instance] local infixl `≺`:50 := pair_nat.lt private definition gcd.lt.dec (x y₁ : ℕ) : (succ y₁, x mod succ y₁) ≺ (x, succ y₁) := !nat.mod_lt (succ_pos y₁) private definition egcd_rec_f (z : ℤ) : ℤ → ℤ → ℤ × ℤ := λ s t, (t, s - t * z) definition egcd.F : Π (p₁ : ℕ × ℕ), (Π p₂ : ℕ × ℕ, p₂ ≺ p₁ → ℤ × ℤ) → ℤ × ℤ | (x, y) := nat.cases_on y (λ f, (1, 0) ) (λ y₁ (f : Π p₂, p₂ ≺ (x, succ y₁) → ℤ × ℤ), let bz := f (succ y₁, x mod succ y₁) !gcd.lt.dec in prod.cases_on bz (egcd_rec_f (x div succ y₁))) definition egcd (x y : ℕ) := fix egcd.F (pair x y) theorem egcd_zero (x : ℕ) : egcd x 0 = (1, 0) := well_founded.fix_eq egcd.F (x, 0) theorem egcd_succ (x y : ℕ) : egcd x (succ y) = prod.cases_on (egcd (succ y) (x mod succ y)) (egcd_rec_f (x div succ y)) := well_founded.fix_eq egcd.F (x, succ y) theorem egcd_of_pos (x : ℕ) {y : ℕ} (ypos : y > 0) : let erec := egcd y (x mod y), u := pr₁ erec, v := pr₂ erec in egcd x y = (v, u - v * (x div y)) := obtain y' (yeq : y = succ y'), from exists_eq_succ_of_pos ypos, by rewrite [yeq, egcd_succ, -prod.eta (egcd _ _)] theorem egcd_prop (x y : ℕ) : (pr₁ (egcd x y)) * x + (pr₂ (egcd x y)) * y = gcd x y := gcd.induction x y (take m, by rewrite [egcd_zero, ▸*, int.mul_zero, int.one_mul]) (take m n, assume npos : 0 < n, assume IH, begin let H := egcd_of_pos m npos, esimp at H, rewrite [H, ▸*, gcd_rec, -IH, add.comm (#int _ * _), -of_nat_mod, ↑modulo], rewrite [*int.mul_sub_right_distrib, *int.mul_sub_left_distrib, *mul.left_distrib], rewrite [sub_add_eq_add_sub, *sub_eq_add_neg, int.add.assoc, of_nat_div, *int.mul.assoc] end) theorem Bezout_aux (x y : ℕ) : ∃ a b : ℤ, a * x + b * y = gcd x y := exists.intro _ (exists.intro _ (egcd_prop x y)) theorem Bezout (x y : ℤ) : ∃ a b : ℤ, a * x + b * y = gcd x y := obtain a' b' (H : a' * nat_abs x + b' * nat_abs y = gcd x y), from !Bezout_aux, begin existsi (a' * sign x), existsi (b' * sign y), rewrite [*int.mul.assoc, -*abs_eq_sign_mul, -*of_nat_nat_abs], apply H end end Bezout /- A sample application of Bezout's theorem, namely, an alternative proof that irreducible implies prime (dvd_or_dvd_of_prime_of_dvd_mul). -/ namespace nat open int example {p x y : ℕ} (pp : prime p) (H : p ∣ x * y) : p ∣ x ∨ p ∣ y := decidable.by_cases (assume Hpx : p ∣ x, or.inl Hpx) (assume Hnpx : ¬ p ∣ x, have cpx : coprime p x, from coprime_of_prime_of_not_dvd pp Hnpx, obtain (a b : ℤ) (Hab : a * p + b * x = gcd p x), from !Bezout_aux, assert H1 : a * p * y + b * x * y = y, by rewrite [-int.mul.right_distrib, Hab, ↑coprime at cpx, cpx, int.one_mul], have H2 : p ∣ y, begin apply dvd_of_of_nat_dvd_of_nat, rewrite [-H1], apply int.dvd_add, {apply int.dvd_mul_of_dvd_left, apply int.dvd_mul_of_dvd_right, apply int.dvd.refl}, {rewrite int.mul.assoc, apply int.dvd_mul_of_dvd_right, apply of_nat_dvd_of_nat_of_dvd H} end, or.inr H2) end nat
84abe6872019019ad288e30e2909106d956f0304
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/specific_groups/dihedral.lean
5f187ff794f92bef3cec66ee6bf984b432388f08
[ "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
5,498
lean
/- Copyright (c) 2020 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import data.fintype.card import data.zmod.basic import group_theory.order_of_element /-! # Dihedral Groups We define the dihedral groups `dihedral_group n`, with elements `r i` and `sr i` for `i : zmod n`. For `n ≠ 0`, `dihedral_group n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral_group 0` corresponds to the infinite dihedral group. -/ /-- For `n ≠ 0`, `dihedral_group n` represents the symmetry group of the regular `n`-gon. `r i` represents the rotations of the `n`-gon by `2πi/n`, and `sr i` represents the reflections of the `n`-gon. `dihedral_group 0` corresponds to the infinite dihedral group. -/ @[derive decidable_eq] inductive dihedral_group (n : ℕ) : Type | r : zmod n → dihedral_group | sr : zmod n → dihedral_group namespace dihedral_group variables {n : ℕ} /-- Multiplication of the dihedral group. -/ private def mul : dihedral_group n → dihedral_group n → dihedral_group n | (r i) (r j) := r (i + j) | (r i) (sr j) := sr (j - i) | (sr i) (r j) := sr (i + j) | (sr i) (sr j) := r (j - i) /-- The identity `1` is the rotation by `0`. -/ private def one : dihedral_group n := r 0 instance : inhabited (dihedral_group n) := ⟨one⟩ /-- The inverse of a an element of the dihedral group. -/ private def inv : dihedral_group n → dihedral_group n | (r i) := r (-i) | (sr i) := sr i /-- The group structure on `dihedral_group n`. -/ instance : group (dihedral_group n) := { mul := mul, mul_assoc := begin rintros (a | a) (b | b) (c | c); simp only [mul]; ring, end, one := one, one_mul := begin rintros (a | a), exact congr_arg r (zero_add a), exact congr_arg sr (sub_zero a), end, mul_one := begin rintros (a | a), exact congr_arg r (add_zero a), exact congr_arg sr (add_zero a), end, inv := inv, mul_left_inv := begin rintros (a | a), exact congr_arg r (neg_add_self a), exact congr_arg r (sub_self a), end } @[simp] lemma r_mul_r (i j : zmod n) : r i * r j = r (i + j) := rfl @[simp] lemma r_mul_sr (i j : zmod n) : r i * sr j = sr (j - i) := rfl @[simp] lemma sr_mul_r (i j : zmod n) : sr i * r j = sr (i + j) := rfl @[simp] lemma sr_mul_sr (i j : zmod n) : sr i * sr j = r (j - i) := rfl lemma one_def : (1 : dihedral_group n) = r 0 := rfl private def fintype_helper : (zmod n ⊕ zmod n) ≃ dihedral_group n := { inv_fun := λ i, match i with | (r j) := sum.inl j | (sr j) := sum.inr j end, to_fun := λ i, match i with | (sum.inl j) := r j | (sum.inr j) := sr j end, left_inv := by rintro (x | x); refl, right_inv := by rintro (x | x); refl } /-- If `0 < n`, then `dihedral_group n` is a finite group. -/ instance [fact (0 < n)] : fintype (dihedral_group n) := fintype.of_equiv _ fintype_helper instance : nontrivial (dihedral_group n) := ⟨⟨r 0, sr 0, dec_trivial⟩⟩ /-- If `0 < n`, then `dihedral_group n` has `2n` elements. -/ lemma card [fact (0 < n)] : fintype.card (dihedral_group n) = 2 * n := by rw [← fintype.card_eq.mpr ⟨fintype_helper⟩, fintype.card_sum, zmod.card, two_mul] @[simp] lemma r_one_pow (k : ℕ) : (r 1 : dihedral_group n) ^ k = r k := begin induction k with k IH, { refl }, { rw [pow_succ, IH, r_mul_r], congr' 1, norm_cast, rw nat.one_add } end @[simp] lemma r_one_pow_n : (r (1 : zmod n))^n = 1 := begin cases n, { rw pow_zero }, { rw [r_one_pow, one_def], congr' 1, exact zmod.nat_cast_self _, } end @[simp] lemma sr_mul_self (i : zmod n) : sr i * sr i = 1 := by rw [sr_mul_sr, sub_self, one_def] /-- If `0 < n`, then `sr i` has order 2. -/ @[simp] lemma order_of_sr (i : zmod n) : order_of (sr i) = 2 := begin rw order_of_eq_prime _ _, { exact ⟨nat.prime_two⟩ }, rw [sq, sr_mul_self], dec_trivial, end /-- If `0 < n`, then `r 1` has order `n`. -/ @[simp] lemma order_of_r_one : order_of (r 1 : dihedral_group n) = n := begin by_cases hnpos : 0 < n, { haveI : fact (0 < n) := ⟨hnpos⟩, cases lt_or_eq_of_le (nat.le_of_dvd hnpos (order_of_dvd_of_pow_eq_one (@r_one_pow_n n))) with h h, { have h1 : (r 1 : dihedral_group n)^(order_of (r 1)) = 1, { exact pow_order_of_eq_one _ }, rw r_one_pow at h1, injection h1 with h2, rw [← zmod.val_eq_zero, zmod.val_nat_cast, nat.mod_eq_of_lt h] at h2, apply absurd h2.symm, apply ne_of_lt, exact absurd h2.symm (ne_of_lt (order_of_pos _)) }, { exact h } }, { simp only [not_lt, nonpos_iff_eq_zero] at hnpos, rw hnpos, apply order_of_eq_zero, rw is_of_fin_order_iff_pow_eq_one, push_neg, intros m hm, rw [r_one_pow, one_def], by_contradiction h, have h' : (m : zmod 0) = 0, { exact r.inj h, }, have h'' : m = 0, { simp only [int.coe_nat_eq_zero, int.nat_cast_eq_coe_nat] at h', exact h', }, rw h'' at hm, apply nat.lt_irrefl, exact hm }, end /-- If `0 < n`, then `i : zmod n` has order `n / gcd n i`. -/ lemma order_of_r [fact (0 < n)] (i : zmod n) : order_of (r i) = n / nat.gcd n i.val := begin conv_lhs { rw ←zmod.nat_cast_zmod_val i }, rw [←r_one_pow, order_of_pow, order_of_r_one] end end dihedral_group
82f4414febac8347b3db60bf9de6dc42de217804
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/src/tidy/tidy_attributes.lean
98c765eeceeb76ceeaf14528d33688135984edec
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
845
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 .at_least_one open tactic meta def tidy_attribute : user_attribute := { name := `tidy, descr := "A tactic that should be called by tidy." } run_cmd attribute.register `tidy_attribute meta def name_to_tactic ( n : name ) : tactic (tactic string) := do e ← mk_const n, (eval_expr (tactic string) e) <|> (eval_expr (tactic unit) e) >>= (λ t, pure ( t >> pure n.to_string )) meta def names_to_tactics ( n : list name ) : tactic (list (tactic string)) := do n.mmap name_to_tactic meta def run_tidy_tactics : tactic string := do names ← attribute.get_instances `tidy, tactics ← names_to_tactics names, first tactics <|> fail "no @[tidy] tactics succeeded"
0e01fd88a927c8db8044979b93052a92b4fd391f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/action.lean
b54d36e94489854296129891f0f16cec4e24fee3
[ "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
6,655
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import category_theory.elements import category_theory.is_connected import category_theory.single_obj import group_theory.group_action.basic import group_theory.semidirect_product /-! # Actions as functors and as categories From a multiplicative action M ↻ X, we can construct a functor from M to the category of types, mapping the single object of M to X and an element `m : M` to map `X → X` given by multiplication by `m`. This functor induces a category structure on X -- a special case of the category of elements. A morphism `x ⟶ y` in this category is simply a scalar `m : M` such that `m • x = y`. In the case where M is a group, this category is a groupoid -- the `action groupoid'. -/ open mul_action semidirect_product namespace category_theory universes u variables (M : Type*) [monoid M] (X : Type u) [mul_action M X] /-- A multiplicative action M ↻ X viewed as a functor mapping the single object of M to X and an element `m : M` to the map `X → X` given by multiplication by `m`. -/ @[simps] def action_as_functor : single_obj M ⥤ Type u := { obj := λ _, X, map := λ _ _, (•), map_id' := λ _, funext $ mul_action.one_smul, map_comp' := λ _ _ _ f g, funext $ λ x, (smul_smul g f x).symm } /-- A multiplicative action M ↻ X induces a category strucure on X, where a morphism from x to y is a scalar taking x to y. Due to implementation details, the object type of this category is not equal to X, but is in bijection with X. -/ @[derive category] def action_category := (action_as_functor M X).elements namespace action_category /-- The projection from the action category to the monoid, mapping a morphism to its label. -/ def π : action_category M X ⥤ single_obj M := category_of_elements.π _ @[simp] lemma π_map (p q : action_category M X) (f : p ⟶ q) : (π M X).map f = f.val := rfl @[simp] lemma π_obj (p : action_category M X) : (π M X).obj p = single_obj.star M := unit.ext variables {M X} /-- The canonical map `action_category M X → X`. It is given by `λ x, x.snd`, but has a more explicit type. -/ protected def back : action_category M X → X := λ x, x.snd instance : has_coe_t X (action_category M X) := ⟨λ x, ⟨(), x⟩⟩ @[simp] lemma coe_back (x : X) : (↑x : action_category M X).back = x := rfl @[simp] lemma back_coe (x : action_category M X) : ↑(x.back) = x := by ext; refl variables (M X) /-- An object of the action category given by M ↻ X corresponds to an element of X. -/ def obj_equiv : X ≃ action_category M X := { to_fun := coe, inv_fun := λ x, x.back, left_inv := coe_back, right_inv := back_coe } lemma hom_as_subtype (p q : action_category M X) : (p ⟶ q) = { m : M // m • p.back = q.back } := rfl instance [inhabited X] : inhabited (action_category M X) := { default := ↑(default X) } instance [nonempty X] : nonempty (action_category M X) := nonempty.map (obj_equiv M X) infer_instance variables {X} (x : X) /-- The stabilizer of a point is isomorphic to the endomorphism monoid at the corresponding point. In fact they are definitionally equivalent. -/ def stabilizer_iso_End : stabilizer.submonoid M x ≃* End (↑x : action_category M X) := mul_equiv.refl _ @[simp] lemma stabilizer_iso_End_apply (f : stabilizer.submonoid M x) : (stabilizer_iso_End M x).to_fun f = f := rfl @[simp] lemma stabilizer_iso_End_symm_apply (f : End _) : (stabilizer_iso_End M x).inv_fun f = f := rfl variables {M X} @[simp] protected lemma id_val (x : action_category M X) : subtype.val (𝟙 x) = 1 := rfl @[simp] protected lemma comp_val {x y z : action_category M X} (f : x ⟶ y) (g : y ⟶ z) : (f ≫ g).val = g.val * f.val := rfl instance [is_pretransitive M X] [nonempty X] : is_connected (action_category M X) := zigzag_is_connected $ λ x y, relation.refl_trans_gen.single $ or.inl $ nonempty_subtype.mpr (show _, from exists_smul_eq M x.back y.back) section group variables {G : Type*} [group G] [mul_action G X] noncomputable instance : groupoid (action_category G X) := category_theory.groupoid_of_elements _ /-- Any subgroup of `G` is a vertex group in its action groupoid. -/ def End_mul_equiv_subgroup (H : subgroup G) : End (obj_equiv G (quotient_group.quotient H) ↑(1 : G)) ≃* H := mul_equiv.trans (stabilizer_iso_End G ((1 : G) : quotient_group.quotient H)).symm (mul_equiv.subgroup_congr $ stabilizer_quotient H) /-- A target vertex `t` and a scalar `g` determine a morphism in the action groupoid. -/ def hom_of_pair (t : X) (g : G) : ↑(g⁻¹ • t) ⟶ (t : action_category G X) := subtype.mk g (smul_inv_smul g t) @[simp] lemma hom_of_pair.val (t : X) (g : G) : (hom_of_pair t g).val = g := rfl /-- Any morphism in the action groupoid is given by some pair. -/ protected def cases {P : Π ⦃a b : action_category G X⦄, (a ⟶ b) → Sort*} (hyp : ∀ t g, P (hom_of_pair t g)) ⦃a b⦄ (f : a ⟶ b) : P f := begin refine cast _ (hyp b.back f.val), rcases a with ⟨⟨⟩, a : X⟩, rcases b with ⟨⟨⟩, b : X⟩, rcases f with ⟨g : G, h : g • a = b⟩, cases (inv_smul_eq_iff.mpr h.symm), refl end variables {H : Type*} [group H] /-- Given `G` acting on `X`, a functor from the corresponding action groupoid to a group `H` can be curried to a group homomorphism `G →* (X → H) ⋊ G`. -/ @[simps] def curry (F : action_category G X ⥤ single_obj H) : G →* (X → H) ⋊[mul_aut_arrow] G := have F_map_eq : ∀ {a b} {f : a ⟶ b}, F.map f = (F.map (hom_of_pair b.back f.val) : H) := action_category.cases (λ _ _, rfl), { to_fun := λ g, ⟨λ b, F.map (hom_of_pair b g), g⟩, map_one' := by { congr, funext, exact F_map_eq.symm.trans (F.map_id b) }, map_mul' := begin intros g h, congr, funext, exact F_map_eq.symm.trans (F.map_comp (hom_of_pair (g⁻¹ • b) h) (hom_of_pair b g)), end } /-- Given `G` acting on `X`, a group homomorphism `φ : G →* (X → H) ⋊ G` can be uncurried to a functor from the action groupoid to `H`, provided that `φ g = (_, g)` for all `g`. -/ @[simps] def uncurry (F : G →* (X → H) ⋊[mul_aut_arrow] G) (sane : ∀ g, (F g).right = g) : action_category G X ⥤ single_obj H := { obj := λ _, (), map := λ a b f, ((F f.val).left b.back), map_id' := by { intro x, rw [action_category.id_val, F.map_one], refl }, map_comp' := begin intros x y z f g, revert y z g, refine action_category.cases _, simp [single_obj.comp_as_mul, sane], end } end group end action_category end category_theory
e08e192893aadd77ee1b2c52dc01592f9972357f
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/list/indexes.lean
d1db0d604c871f73c9ec34b60b1e342067cf1677
[ "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
5,623
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import data.list.basic import data.list.defs import logic.basic universes u v open function namespace list variables {α : Type u} {β : Type v} section foldr_with_index /-- Specification of `foldr_with_index_aux`. -/ def foldr_with_index_aux_spec (f : ℕ → α → β → β) (start : ℕ) (b : β) (as : list α) : β := foldr (uncurry f) b $ enum_from start as theorem foldr_with_index_aux_spec_cons (f : ℕ → α → β → β) (start b a as) : foldr_with_index_aux_spec f start b (a :: as) = f start a (foldr_with_index_aux_spec f (start + 1) b as) := rfl theorem foldr_with_index_aux_eq_foldr_with_index_aux_spec (f : ℕ → α → β → β) (start b as) : foldr_with_index_aux f start b as = foldr_with_index_aux_spec f start b as := begin induction as generalizing start, { refl }, { simp only [foldr_with_index_aux, foldr_with_index_aux_spec_cons, *] } end theorem foldr_with_index_eq_foldr_enum (f : ℕ → α → β → β) (b : β) (as : list α) : foldr_with_index f b as = foldr (uncurry f) b (enum as) := by simp only [foldr_with_index, foldr_with_index_aux_spec, foldr_with_index_aux_eq_foldr_with_index_aux_spec, enum] end foldr_with_index theorem indexes_values_eq_filter_enum (p : α → Prop) [decidable_pred p] (as : list α) : indexes_values p as = filter (p ∘ prod.snd) (enum as) := by simp [indexes_values, foldr_with_index_eq_foldr_enum, uncurry, filter_eq_foldr] theorem find_indexes_eq_map_indexes_values (p : α → Prop) [decidable_pred p] (as : list α) : find_indexes p as = map prod.fst (indexes_values p as) := by simp only [indexes_values_eq_filter_enum, map_filter_eq_foldr, find_indexes, foldr_with_index_eq_foldr_enum, uncurry] section foldl_with_index /-- Specification of `foldl_with_index_aux`. -/ def foldl_with_index_aux_spec (f : ℕ → α → β → α) (start : ℕ) (a : α) (bs : list β) : α := foldl (λ a (p : ℕ × β), f p.fst a p.snd) a $ enum_from start bs theorem foldl_with_index_aux_spec_cons (f : ℕ → α → β → α) (start a b bs) : foldl_with_index_aux_spec f start a (b :: bs) = foldl_with_index_aux_spec f (start + 1) (f start a b) bs := rfl theorem foldl_with_index_aux_eq_foldl_with_index_aux_spec (f : ℕ → α → β → α) (start a bs) : foldl_with_index_aux f start a bs = foldl_with_index_aux_spec f start a bs := begin induction bs generalizing start a, { refl }, { simp [foldl_with_index_aux, foldl_with_index_aux_spec_cons, *] } end theorem foldl_with_index_eq_foldl_enum (f : ℕ → α → β → α) (a : α) (bs : list β) : foldl_with_index f a bs = foldl (λ a (p : ℕ × β), f p.fst a p.snd) a (enum bs) := by simp only [foldl_with_index, foldl_with_index_aux_spec, foldl_with_index_aux_eq_foldl_with_index_aux_spec, enum] end foldl_with_index section mfold_with_index variables {m : Type u → Type v} [monad m] theorem mfoldr_with_index_eq_mfoldr_enum {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : mfoldr_with_index f b as = mfoldr (uncurry f) b (enum as) := by simp only [mfoldr_with_index, mfoldr_eq_foldr, foldr_with_index_eq_foldr_enum, uncurry] theorem mfoldl_with_index_eq_mfoldl_enum [is_lawful_monad m] {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : mfoldl_with_index f b as = mfoldl (λ b (p : ℕ × α), f p.fst b p.snd) b (enum as) := by rw [mfoldl_with_index, mfoldl_eq_foldl, foldl_with_index_eq_foldl_enum] end mfold_with_index section mmap_with_index variables {m : Type u → Type v} [applicative m] /-- Specification of `mmap_with_index_aux`. -/ def mmap_with_index_aux_spec {α β} (f : ℕ → α → m β) (start : ℕ) (as : list α) : m (list β) := list.traverse (uncurry f) $ enum_from start as -- Note: `traverse` the class method would require a less universe-polymorphic -- `m : Type u → Type u`. theorem mmap_with_index_aux_spec_cons {α β} (f : ℕ → α → m β) (start : ℕ) (a : α) (as : list α) : mmap_with_index_aux_spec f start (a :: as) = list.cons <$> f start a <*> mmap_with_index_aux_spec f (start + 1) as := rfl theorem mmap_with_index_aux_eq_mmap_with_index_aux_spec {α β} (f : ℕ → α → m β) (start : ℕ) (as : list α) : mmap_with_index_aux f start as = mmap_with_index_aux_spec f start as := begin induction as generalizing start, { refl }, { simp [mmap_with_index_aux, mmap_with_index_aux_spec_cons, *] } end theorem mmap_with_index_eq_mmap_enum {α β} (f : ℕ → α → m β) (as : list α) : mmap_with_index f as = list.traverse (uncurry f) (enum as) := by simp only [mmap_with_index, mmap_with_index_aux_spec, mmap_with_index_aux_eq_mmap_with_index_aux_spec, enum ] end mmap_with_index section mmap_with_index' variables {m : Type u → Type v} [applicative m] [is_lawful_applicative m] theorem mmap_with_index'_aux_eq_mmap_with_index_aux {α} (f : ℕ → α → m punit) (start : ℕ) (as : list α) : mmap_with_index'_aux f start as = mmap_with_index_aux f start as *> pure punit.star := by induction as generalizing start; simp [mmap_with_index'_aux, mmap_with_index_aux, *, seq_right_eq, const, -comp_const] with functor_norm theorem mmap_with_index'_eq_mmap_with_index {α} (f : ℕ → α → m punit) (as : list α) : mmap_with_index' f as = mmap_with_index f as *> pure punit.star := by apply mmap_with_index'_aux_eq_mmap_with_index_aux end mmap_with_index' end list
03822604067bfa52a3f025dbb30143ce6164a2a4
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/equivalence.lean
c5fb20d8763d85c8eb1a421345c1e9f751621718
[ "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
23,396
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, Floris van Doorn -/ import category_theory.fully_faithful import category_theory.whiskering import category_theory.essential_image import tactic.slice /-! # Equivalence of categories An equivalence of categories `C` and `D` is a pair of functors `F : C ⥤ D` and `G : D ⥤ C` such that `η : 𝟭 C ≅ F ⋙ G` and `ε : G ⋙ F ≅ 𝟭 D`. In many situations, equivalences are a better notion of "sameness" of categories than the stricter isomorphims of categories. Recall that one way to express that two functors `F : C ⥤ D` and `G : D ⥤ C` are adjoint is using two natural transformations `η : 𝟭 C ⟶ F ⋙ G` and `ε : G ⋙ F ⟶ 𝟭 D`, called the unit and the counit, such that the compositions `F ⟶ FGF ⟶ F` and `G ⟶ GFG ⟶ G` are the identity. Unfortunately, it is not the case that the natural isomorphisms `η` and `ε` in the definition of an equivalence automatically give an adjunction. However, it is true that * if one of the two compositions is the identity, then so is the other, and * given an equivalence of categories, it is always possible to refine `η` in such a way that the identities are satisfied. For this reason, in mathlib we define an equivalence to be a "half-adjoint equivalence", which is a tuple `(F, G, η, ε)` as in the first paragraph such that the composite `F ⟶ FGF ⟶ F` is the identity. By the remark above, this already implies that the tuple is an "adjoint equivalence", i.e., that the composite `G ⟶ GFG ⟶ G` is also the identity. We also define essentially surjective functors and show that a functor is an equivalence if and only if it is full, faithful and essentially surjective. ## Main definitions * `equivalence`: bundled (half-)adjoint equivalences of categories * `is_equivalence`: type class on a functor `F` containing the data of the inverse `G` as well as the natural isomorphisms `η` and `ε`. * `ess_surj`: type class on a functor `F` containing the data of the preimages and the isomorphisms `F.obj (preimage d) ≅ d`. ## Main results * `equivalence.mk`: upgrade an equivalence to a (half-)adjoint equivalence * `equivalence_of_fully_faithfully_ess_surj`: a fully faithful essentially surjective functor is an equivalence. ## Notations We write `C ≌ D` (`\backcong`, not to be confused with `≅`/`\cong`) for a bundled equivalence. -/ namespace category_theory open category_theory.functor nat_iso category -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ u₁ u₂ u₃ /-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other words the composite `F ⟶ FGF ⟶ F` is the identity. In `unit_inverse_comp`, we show that this is actually an adjoint equivalence, i.e., that the composite `G ⟶ GFG ⟶ G` is also the identity. The triangle equation is written as a family of equalities between morphisms, it is more complicated if we write it as an equality of natural transformations, because then we would have to insert natural transformations like `F ⟶ F1`. See https://stacks.math.columbia.edu/tag/001J -/ structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] := mk' :: (functor : C ⥤ D) (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ functor ⋙ inverse) (counit_iso : inverse ⋙ functor ≅ 𝟭 D) (functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫ counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously) restate_axiom equivalence.functor_unit_iso_comp' infixr ` ≌ `:10 := equivalence variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] namespace equivalence /-- The unit of an equivalence of categories. -/ abbreviation unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom /-- The counit of an equivalence of categories. -/ abbreviation counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom /-- The inverse of the unit of an equivalence of categories. -/ abbreviation unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv /-- The inverse of the counit of an equivalence of categories. -/ abbreviation counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv /- While these abbreviations are convenient, they also cause some trouble, preventing structure projections from unfolding. -/ @[simp] lemma equivalence_mk'_unit (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit = unit_iso.hom := rfl @[simp] lemma equivalence_mk'_counit (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit = counit_iso.hom := rfl @[simp] lemma equivalence_mk'_unit_inv (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit_inv = unit_iso.inv := rfl @[simp] lemma equivalence_mk'_counit_inv (functor inverse unit_iso counit_iso f) : (⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit_inv = counit_iso.inv := rfl @[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) : e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) := e.functor_unit_iso_comp X @[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) : e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) := begin erw [iso.inv_eq_inv (e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)], exact e.functor_unit_comp X end lemma counit_inv_app_functor (e : C ≌ D) (X : C) : e.counit_inv.app (e.functor.obj X) = e.functor.map (e.unit.app X) := by { symmetry, erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl } lemma counit_app_functor (e : C ≌ D) (X : C) : e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) := by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl } /-- The other triangle equality. The proof follows the following proof in Globular: http://globular.science/1905.001 -/ @[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) := begin rw [←id_comp (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp, ←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)), app_hom, app_inv], slice_lhs 2 3 { erw [e.unit.naturality] }, slice_lhs 1 2 { erw [e.unit.naturality] }, slice_lhs 4 4 { rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] }, slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality], erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] }, slice_lhs 3 4 { erw [e.unit_inv.naturality] }, slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] }, erw [id_comp], slice_lhs 3 4 { erw [←e.unit_inv.naturality] }, slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality, (e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl end @[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) : e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) := begin erw [iso.inv_eq_inv (e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)], exact e.unit_inverse_comp Y end lemma unit_app_inverse (e : C ≌ D) (Y : D) : e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) := by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl } lemma unit_inv_app_inverse (e : C ≌ D) (Y : D) : e.unit_inv.app (e.inverse.obj Y) = e.inverse.map (e.counit.app Y) := by { symmetry, erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl } @[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y := (nat_iso.naturality_2 (e.counit_iso) f).symm @[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y := (nat_iso.naturality_1 (e.unit_iso) f).symm section -- In this section we convert an arbitrary equivalence to a half-adjoint equivalence. variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) /-- If `η : 𝟭 C ≅ F ⋙ G` is part of a (not necessarily half-adjoint) equivalence, we can upgrade it to a refined natural isomorphism `adjointify_η η : 𝟭 C ≅ F ⋙ G` which exhibits the properties required for a half-adjoint equivalence. See `equivalence.mk`. -/ def adjointify_η : 𝟭 C ≅ F ⋙ G := calc 𝟭 C ≅ F ⋙ G : η ... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm ... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G) ... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G) ... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm ... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G) ... ≅ F ⋙ G : left_unitor (F ⋙ G) lemma adjointify_η_ε (X : C) : F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) := begin dsimp [adjointify_η], simp, have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this, rw [←assoc _ _ (F.map _)], have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this, have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this, rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this] end end /-- Every equivalence of categories consisting of functors `F` and `G` such that `F ⋙ G` and `G ⋙ F` are naturally isomorphic to identity functors can be transformed into a half-adjoint equivalence without changing `F` or `G`. -/ protected definition mk (F : C ⥤ D) (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D := ⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ /-- Equivalence of categories is reflexive. -/ @[refl, simps] def refl : C ≌ C := ⟨𝟭 C, 𝟭 C, iso.refl _, iso.refl _, λ X, category.id_comp _⟩ instance : inhabited (C ≌ C) := ⟨refl⟩ /-- Equivalence of categories is symmetric. -/ @[symm, simps] def symm (e : C ≌ D) : D ≌ C := ⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩ variables {E : Type u₃} [category.{v₃} E] /-- Equivalence of categories is transitive. -/ @[trans, simps] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E := { functor := e.functor ⋙ f.functor, inverse := f.inverse ⋙ e.inverse, unit_iso := begin refine iso.trans e.unit_iso _, exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) , end, counit_iso := begin refine iso.trans _ f.counit_iso, exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor) end, -- We wouldn't have needed to give this proof if we'd used `equivalence.mk`, -- but we choose to avoid using that here, for the sake of good structure projection `simp` -- lemmas. functor_unit_iso_comp' := λ X, begin dsimp, rw [← f.functor.map_comp_assoc, e.functor.map_comp, ←counit_inv_app_functor, fun_inv_map, iso.inv_hom_id_app_assoc, assoc, iso.inv_hom_id_app, counit_app_functor, ← functor.map_comp], erw [comp_id, iso.hom_inv_id_app, functor.map_id], end } /-- Composing a functor with both functors of an equivalence yields a naturally isomorphic functor. -/ def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor @[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) := by { dsimp [fun_inv_id_assoc], tidy } @[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) : (fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) := by { dsimp [fun_inv_id_assoc], tidy } /-- Composing a functor with both functors of an equivalence yields a naturally isomorphic functor. -/ def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F := (functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor @[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) := by { dsimp [inv_fun_id_assoc], tidy } @[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) : (inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) := by { dsimp [inv_fun_id_assoc], tidy } /-- If `C` is equivalent to `D`, then `C ⥤ E` is equivalent to `D ⥤ E`. -/ @[simps functor inverse unit_iso counit_iso] def congr_left (e : C ≌ D) : (C ⥤ E) ≌ (D ⥤ E) := equivalence.mk ((whiskering_left _ _ _).obj e.inverse) ((whiskering_left _ _ _).obj e.functor) (nat_iso.of_components (λ F, (e.fun_inv_id_assoc F).symm) (by tidy)) (nat_iso.of_components (λ F, e.inv_fun_id_assoc F) (by tidy)) /-- If `C` is equivalent to `D`, then `E ⥤ C` is equivalent to `E ⥤ D`. -/ @[simps functor inverse unit_iso counit_iso] def congr_right (e : C ≌ D) : (E ⥤ C) ≌ (E ⥤ D) := equivalence.mk ((whiskering_right _ _ _).obj e.functor) ((whiskering_right _ _ _).obj e.inverse) (nat_iso.of_components (λ F, F.right_unitor.symm ≪≫ iso_whisker_left F e.unit_iso ≪≫ functor.associator _ _ _) (by tidy)) (nat_iso.of_components (λ F, functor.associator _ _ _ ≪≫ iso_whisker_left F e.counit_iso ≪≫ F.right_unitor) (by tidy)) section cancellation_lemmas variables (e : C ≌ D) /- We need special forms of `cancel_nat_iso_hom_right(_assoc)` and `cancel_nat_iso_inv_right(_assoc)` for units and counits, because neither `simp` or `rw` will apply those lemmas in this setting without providing `e.unit_iso` (or similar) as an explicit argument. We also provide the lemmas for length four compositions, since they're occasionally useful. (e.g. in proving that equivalences take monos to monos) -/ @[simp] lemma cancel_unit_right {X Y : C} (f f' : X ⟶ Y) : f ≫ e.unit.app Y = f' ≫ e.unit.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_unit_inv_right {X Y : C} (f f' : X ⟶ e.inverse.obj (e.functor.obj Y)) : f ≫ e.unit_inv.app Y = f' ≫ e.unit_inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_counit_right {X Y : D} (f f' : X ⟶ e.functor.obj (e.inverse.obj Y)) : f ≫ e.counit.app Y = f' ≫ e.counit.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_counit_inv_right {X Y : D} (f f' : X ⟶ Y) : f ≫ e.counit_inv.app Y = f' ≫ e.counit_inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_unit_right_assoc {W X X' Y : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) : f ≫ g ≫ e.unit.app Y = f' ≫ g' ≫ e.unit.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_counit_inv_right_assoc {W X X' Y : D} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) : f ≫ g ≫ e.counit_inv.app Y = f' ≫ g' ≫ e.counit_inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_unit_right_assoc' {W X X' Y Y' Z : C} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) : f ≫ g ≫ h ≫ e.unit.app Z = f' ≫ g' ≫ h' ≫ e.unit.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_counit_inv_right_assoc' {W X X' Y Y' Z : D} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) : f ≫ g ≫ h ≫ e.counit_inv.app Z = f' ≫ g' ≫ h' ≫ e.counit_inv.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' := by simp only [←category.assoc, cancel_mono] end cancellation_lemmas section -- There's of course a monoid structure on `C ≌ C`, -- but let's not encourage using it. -- The power structure is nevertheless useful. /-- Powers of an auto-equivalence. -/ def pow (e : C ≌ C) : ℤ → (C ≌ C) | (int.of_nat 0) := equivalence.refl | (int.of_nat 1) := e | (int.of_nat (n+2)) := e.trans (pow (int.of_nat (n+1))) | (int.neg_succ_of_nat 0) := e.symm | (int.neg_succ_of_nat (n+1)) := e.symm.trans (pow (int.neg_succ_of_nat n)) instance : has_pow (C ≌ C) ℤ := ⟨pow⟩ @[simp] lemma pow_zero (e : C ≌ C) : e^(0 : ℤ) = equivalence.refl := rfl @[simp] lemma pow_one (e : C ≌ C) : e^(1 : ℤ) = e := rfl @[simp] lemma pow_neg_one (e : C ≌ C) : e^(-1 : ℤ) = e.symm := rfl -- TODO as necessary, add the natural isomorphisms `(e^a).trans e^b ≅ e^(a+b)`. -- At this point, we haven't even defined the category of equivalences. end end equivalence /-- A functor that is part of a (half) adjoint equivalence -/ class is_equivalence (F : C ⥤ D) := mk' :: (inverse : D ⥤ C) (unit_iso : 𝟭 C ≅ F ⋙ inverse) (counit_iso : inverse ⋙ F ≅ 𝟭 D) (functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫ counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously) restate_axiom is_equivalence.functor_unit_iso_comp' namespace is_equivalence instance of_equivalence (F : C ≌ D) : is_equivalence F.functor := { ..F } instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse := is_equivalence.of_equivalence F.symm open equivalence /-- To see that a functor is an equivalence, it suffices to provide an inverse functor `G` such that `F ⋙ G` and `G ⋙ F` are naturally isomorphic to identity functors. -/ protected definition mk {F : C ⥤ D} (G : D ⥤ C) (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F := ⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩ end is_equivalence namespace functor /-- Interpret a functor that is an equivalence as an equivalence. -/ def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D := ⟨F, is_equivalence.inverse F, is_equivalence.unit_iso, is_equivalence.counit_iso, is_equivalence.functor_unit_iso_comp⟩ instance is_equivalence_refl : is_equivalence (𝟭 C) := is_equivalence.of_equivalence equivalence.refl /-- The inverse functor of a functor that is an equivalence. -/ def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C := is_equivalence.inverse F instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv := is_equivalence.of_equivalence F.as_equivalence.symm @[simp] lemma as_equivalence_functor (F : C ⥤ D) [is_equivalence F] : F.as_equivalence.functor = F := rfl @[simp] lemma as_equivalence_inverse (F : C ⥤ D) [is_equivalence F] : F.as_equivalence.inverse = inv F := rfl @[simp] lemma inv_inv (F : C ⥤ D) [is_equivalence F] : inv (inv F) = F := rfl variables {E : Type u₃} [category.{v₃} E] instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] : is_equivalence (F ⋙ G) := is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G)) end functor namespace equivalence @[simp] lemma functor_inv (E : C ≌ D) : E.functor.inv = E.inverse := rfl @[simp] lemma inverse_inv (E : C ≌ D) : E.inverse.inv = E.functor := rfl @[simp] lemma functor_as_equivalence (E : C ≌ D) : E.functor.as_equivalence = E := by { cases E, congr, } @[simp] lemma inverse_as_equivalence (E : C ≌ D) : E.inverse.as_equivalence = E.symm := by { cases E, congr, } end equivalence namespace is_equivalence @[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) : F.map (F.inv.map f) = F.as_equivalence.counit.app X ≫ f ≫ F.as_equivalence.counit_inv.app Y := begin erw [nat_iso.naturality_2], refl end @[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) : F.inv.map (F.map f) = F.as_equivalence.unit_inv.app X ≫ f ≫ F.as_equivalence.unit.app Y := begin erw [nat_iso.naturality_1], refl end end is_equivalence namespace equivalence /-- An equivalence is essentially surjective. See https://stacks.math.columbia.edu/tag/02C3. -/ lemma ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F := ⟨λ Y, ⟨F.inv.obj Y, ⟨F.as_equivalence.counit_iso.app Y⟩⟩⟩ /-- An equivalence is faithful. See https://stacks.math.columbia.edu/tag/02C3. -/ @[priority 100] -- see Note [lower instance priority] instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F := { map_injective' := λ X Y f g w, begin have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w, simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p end }. /-- An equivalence is full. See https://stacks.math.columbia.edu/tag/02C3. -/ @[priority 100] -- see Note [lower instance priority] instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F := { preimage := λ X Y f, F.as_equivalence.unit.app X ≫ F.inv.map f ≫ F.as_equivalence.unit_inv.app Y, witness' := λ X Y f, F.inv.map_injective $ by simpa only [is_equivalence.inv_fun_map, assoc, iso.inv_hom_id_app_assoc, iso.inv_hom_id_app] using comp_id _ } @[simps] private noncomputable def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C := { obj := λ X, F.obj_preimage X, map := λ X Y f, F.preimage ((F.obj_obj_preimage_iso X).hom ≫ f ≫ (F.obj_obj_preimage_iso Y).inv), map_id' := λ X, begin apply F.map_injective, tidy end, map_comp' := λ X Y Z f g, by apply F.map_injective; simp } /-- A functor which is full, faithful, and essentially surjective is an equivalence. See https://stacks.math.columbia.edu/tag/02C3. -/ noncomputable def equivalence_of_fully_faithfully_ess_surj (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F := is_equivalence.mk (equivalence_inverse F) (nat_iso.of_components (λ X, (preimage_iso $ F.obj_obj_preimage_iso $ F.obj X).symm) (λ X Y f, by { apply F.map_injective, obviously })) (nat_iso.of_components F.obj_obj_preimage_iso (by tidy)) @[simp] lemma functor_map_inj_iff (e : C ≌ D) {X Y : C} (f g : X ⟶ Y) : e.functor.map f = e.functor.map g ↔ f = g := ⟨λ h, e.functor.map_injective h, λ h, h ▸ rfl⟩ @[simp] lemma inverse_map_inj_iff (e : C ≌ D) {X Y : D} (f g : X ⟶ Y) : e.inverse.map f = e.inverse.map g ↔ f = g := functor_map_inj_iff e.symm f g end equivalence end category_theory
13dc4e13314fbde13095c5aa2a69a489e63d8981
00de0c30dd1b090ed139f65c82ea6deb48c3f4c2
/src/data/int/basic.lean
368ffa56c1987a77a4c0a57db3f424d791b341d8
[ "Apache-2.0" ]
permissive
paulvanwamelen/mathlib
4b9c5c19eec71b475f3dd515cd8785f1c8515f26
79e296bdc9f83b9447dc1b81730d36f63a99f72d
refs/heads/master
1,667,766,172,625
1,590,239,595,000
1,590,239,595,000
266,392,625
0
0
Apache-2.0
1,590,257,277,000
1,590,257,277,000
null
UTF-8
Lean
false
false
53,291
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import algebra.char_zero import init_.data.int.order import algebra.ring import data.list.range open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b), { induction a with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction a with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ_inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [(*), int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end -- Will be generalized to Euclidean domains. protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_inj $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma add_div_of_dvd {a b c : ℤ} : c ∣ a → c ∣ b → (a + b) / c = a / c + b / c := begin intros h1 h2, by_cases h3 : c = 0, { rw [h3, zero_dvd_iff] at *, rw [h1, h2, h3], refl }, { apply eq_of_mul_eq_mul_right h3, rw add_mul, repeat {rw [int.div_mul_cancel]}; try {apply dvd_add}; assumption } end theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw int.mul_div_cancel_left, rw mul_assoc at h, apply _root_.eq_of_mul_eq_mul_left _ h, repeat {assumption} end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; unfold has_mul.mul; simp [int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (nat.pos_pow_of_pos _ dec_trivial) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical /- cast (injection into groups with one) -/ @[simp] theorem nat_cast_eq_coe_nat : ∀ n, @coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n = @coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n | 0 := rfl | (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n) /-- Coercion `ℕ → ℤ` as a `ring_hom`. -/ def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩ section cast variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] [has_neg α] /-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/ protected def cast : ℤ → α | (n : ℕ) := n | -[1+ n] := -(n+1) -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩ @[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl theorem cast_coe_nat' (n : ℕ) : (@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n := by simp @[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl end @[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] : ((1 : ℤ) : α) = 1 := nat.cast_one @[simp, norm_cast] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) : ((int.sub_nat_nat m n : ℤ) : α) = m - n := begin unfold sub_nat_nat, cases e : n - m, { simp [sub_nat_nat, e, nat.le_of_sub_eq_zero e] }, { rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e, nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] }, end @[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] : ∀ n, ((neg_of_nat n : ℤ) : α) = -n | 0 := neg_zero.symm | (n+1) := rfl @[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n | (m : ℕ) (n : ℕ) := nat.cast_add _ _ | (m : ℕ) -[1+ n] := cast_sub_nat_nat _ _ | -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $ show (n:α) = -(m+1) + n + (m+1), by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm, nat.cast_add, cast_succ, neg_add_cancel_left] | -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1), begin rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add], apply congr_arg (λ x:ℕ, -(x:α)), ac_refl end @[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n | (n : ℕ) := cast_neg_of_nat _ | -[1+ n] := (neg_neg _).symm @[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n := by simp [sub_eq_add_neg] @[simp] theorem cast_eq_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) = 0 ↔ n = 0 := ⟨λ h, begin cases n, { exact congr_arg coe (nat.cast_eq_zero.1 h) }, { rw [cast_neg_succ_of_nat, neg_eq_zero, ← cast_succ, nat.cast_eq_zero] at h, contradiction } end, λ h, by rw [h, cast_zero]⟩ @[simp, norm_cast] theorem cast_inj [add_group α] [has_one α] [char_zero α] {m n : ℤ} : (m : α) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] theorem cast_injective [add_group α] [has_one α] [char_zero α] : function.injective (coe : ℤ → α) | m n := cast_inj.1 theorem cast_ne_zero [add_group α] [has_one α] [char_zero α] {n : ℤ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n | (m : ℕ) (n : ℕ) := nat.cast_mul _ _ | (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $ show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg] | -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $ show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n, by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul] | -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1), by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg] /-- `coe : ℤ → α` as a `ring_hom`. -/ def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ @[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl theorem mul_cast_comm [ring α] (a : α) (n : ℤ) : a * n = n * a := by cases n; simp [nat.mul_cast_comm, left_distrib, right_distrib, *] @[simp, norm_cast] theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp} @[simp, norm_cast] theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp} @[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp theorem cast_nonneg [linear_ordered_ring α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n | (n : ℕ) := by simp | -[1+ n] := by simpa [not_le_of_gt (neg_succ_lt_zero n)] using show -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one @[simp, norm_cast] theorem cast_le [linear_ordered_ring α] {m n : ℤ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_ring α] {m n : ℤ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_ring α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_ring α] {n : ℤ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_ring α] {n : ℤ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_min [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [decidable_linear_ordered_comm_ring α] {a b : ℤ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem cast_abs [decidable_linear_ordered_comm_ring α] {q : ℤ} : ((abs q : ℤ) : α) = abs q := by simp [abs] end cast section decidable /-- List enumerating `[m, n)`. -/ def range (m n : ℤ) : list ℤ := (list.range (to_nat (n-m))).map $ λ r, m+r theorem mem_range_iff {m n r : ℤ} : r ∈ range m n ↔ m ≤ r ∧ r < n := ⟨λ H, let ⟨s, h1, h2⟩ := list.mem_map.1 H in h2 ▸ ⟨le_add_of_nonneg_right trivial, add_lt_of_lt_sub_left $ match n-m, h1 with | (k:ℕ), h1 := by rwa [list.mem_range, to_nat_coe_nat, ← coe_nat_lt] at h1 end⟩, λ ⟨h1, h2⟩, list.mem_map.2 ⟨to_nat (r-m), list.mem_range.2 $ by rw [← coe_nat_lt, to_nat_of_nonneg (sub_nonneg_of_le h1), to_nat_of_nonneg (sub_nonneg_of_le (le_of_lt (lt_of_le_of_lt h1 h2)))]; exact sub_lt_sub_right h2 _, show m + _ = _, by rw [to_nat_of_nonneg (sub_nonneg_of_le h1), add_sub_cancel'_right]⟩⟩ instance decidable_le_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r < n → P r) := decidable_of_iff (∀ r ∈ range m n, P r) $ by simp only [mem_range_iff, and_imp] instance decidable_le_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m ≤ r → r ≤ n → P r) := decidable_of_iff (∀ r ∈ range m (n+1), P r) $ by simp only [mem_range_iff, and_imp, lt_add_one_iff] instance decidable_lt_lt (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r < n → P r) := int.decidable_le_lt P _ _ instance decidable_lt_le (P : int → Prop) [decidable_pred P] (m n : ℤ) : decidable (∀ r, m < r → r ≤ n → P r) := int.decidable_le_le P _ _ end decidable end int open int theorem add_monoid_hom.eq_int_cast {A} [add_group A] [has_one A] (f : ℤ →+ A) (h1 : f 1 = 1) (n : ℤ) : f n = n := begin have : ∀ n : ℕ, f n = n, from λ n, (f.comp of_nat_hom.to_add_monoid_hom).eq_nat_cast h1 n, cases n, { exact this n }, rw [cast_neg_succ_of_nat, neg_succ_of_nat_eq, f.map_neg, f.map_add, h1, this] end namespace ring_hom variables {α : Type*} {β : Type*} [ring α] [ring β] @[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n := f.to_add_monoid_hom.eq_int_cast f.map_one n lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α := ring_hom.ext f.eq_int_cast @[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n := (f.comp (int.cast_ring_hom α)).eq_int_cast n end ring_hom @[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n := ((ring_hom.id ℤ).eq_int_cast n).symm
5eac837302939a6437a55eb08038947e8427333f
94e33a31faa76775069b071adea97e86e218a8ee
/src/computability/primrec.lean
1a29b1ea672bfb144b12531135426349de81087b
[ "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
51,901
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.join import logic.equiv.list import logic.function.iterate /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `nat → nat` which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open denumerable encodable function namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, pow_succ'] end primrec end nat /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim [] : nat.primrec (λ n, encodable.encode (decode n))) namespace primcodable open nat.primrec @[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := by letI : primcodable β := primcodable.of_equiv α e; exact encode_iff.1 primrec.encode theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1, { simp }, cases decode β n.unpair.2; simp end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, function.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ @default α _) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem option_get_or_else : primrec₂ (@option.get_or_else α) := primrec.of_eq (option_cases primrec₂.left primrec₂.right primrec₂.right) $ λ ⟨o, a⟩, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [swap], cases e : p.1 - p.2 with n, { simp [tsub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite (nat_le.comp primrec.snd primrec.fst) fst snd theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode₂ : primrec (decode₂ α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := fintype.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := (G a)^[n] (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_le (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, { simp }, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_right_le n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := option_iget.comp₂ list_nth theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_succ]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, simp [*, list.find_index]] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_succ] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) (equiv.refl _) instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) section ulower local attribute [instance, priority 100] encodable.decidable_range_encode encodable.decidable_eq_of_encodable instance ulower : primcodable (ulower α) := have primrec_pred (λ n, encodable.decode₂ α n ≠ none), from primrec.not (primrec.eq.comp (primrec.option_bind primrec.decode (primrec.ite (primrec.eq.comp (primrec.encode.comp primrec.snd) primrec.fst) (primrec.option_some.comp primrec.snd) (primrec.const _))) (primrec.const _)), primcodable.subtype $ primrec_pred.of_eq this (λ n, decode₂_ne_none_iff) end ulower end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem subtype_mk {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → β} {h : ∀ a, p (f a)} (hf : primrec f) : by haveI := primcodable.subtype hp; exact primrec (λ a, @subtype.mk β p (f a) (h a)) := subtype_val_iff.1 hf theorem option_get {f : α → option β} {h : ∀ a, (f a).is_some} : primrec f → primrec (λ a, option.get (h a)) := begin intro hf, refine (nat.primrec.pred.comp hf).of_eq (λ n, _), generalize hx : decode α n = x, cases x; simp end theorem ulower_down : primrec (ulower.down : α → ulower α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact subtype_mk primrec.encode theorem ulower_up : primrec (ulower.up : ulower α → α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact option_get (primrec.decode₂.comp subtype_val) theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (coe : fin n → ℕ) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' n f) (hg : @vec n m g) : vec (λ v, (f v ::ᵥ g v)) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y ::ᵥ IH ::ᵥ v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (tsub_eq_zero_iff_le.mp e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {simp}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
38989e315bc2a60288277d00c84ce4c9b83c8adf
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/logic/unique.lean
d37e460f49e62d7b1a7dd0a1f22164f75790d307
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
1,232
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} structure unique (α : Sort u) extends inhabited α := (uniq : ∀ a:α, a = default) attribute [class] unique instance punit.unique : unique punit.{u} := { default := punit.star, uniq := λ x, punit_eq x _ } namespace unique open function section variables [unique α] instance : inhabited α := to_inhabited ‹unique α› lemma eq_default (a : α) : a = default α := uniq _ a lemma default_eq (a : α) : default α = a := (uniq _ a).symm instance : subsingleton α := ⟨λ a b, by rw [eq_default a, eq_default b]⟩ end protected lemma subsingleton_unique' : ∀ (h₁ h₂ : unique α), h₁ = h₂ | ⟨⟨x⟩, h⟩ ⟨⟨y⟩, _⟩ := by congr; rw [h x, h y] instance subsingleton_unique : subsingleton (unique α) := ⟨unique.subsingleton_unique'⟩ def of_surjective {f : α → β} (hf : surjective f) [unique α] : unique β := { default := f (default _), uniq := λ b, begin cases hf b with a ha, subst ha, exact congr_arg f (eq_default a) end } end unique
4d0cf58d613a4d58c6a33fbe2f3fbc97da75bdcd
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast_ematch4.lean
7e39afb0440c4b0eaed2c072b7aa352935961642
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
273
lean
import data.nat open algebra nat section open nat set_option blast.simp false set_option blast.subst false set_option blast.ematch true attribute add.comm [forward] attribute add.assoc [forward] example (a b c : nat) : a + b + b + c = c + b + a + b := by blast end
efec03180f50f8fb7a7f46c73b93552edf14b991
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/transport/basic.lean
434e5798a6a7c988047ccfaf0a9b1c9fecf10ed1
[ "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
2,591
lean
import tactic.transport import order.bounded_lattice import algebra.lie.basic -- We verify that `transport` can move a `semiring` across an equivalence. -- Note that we've never even mentioned the idea of addition or multiplication to `transport`. def semiring.map {α : Type} [semiring α] {β : Type} (e : α ≃ β) : semiring β := by transport using e -- Indeed, it can equally well move a `semilattice_sup_top`. def sup_top.map {α : Type} [semilattice_sup_top α] {β : Type} (e : α ≃ β) : semilattice_sup_top β := by transport using e -- Verify definitional equality of the new structure data. example {α : Type} [semilattice_sup_top α] {β : Type} (e : α ≃ β) (x y : β) : begin haveI := sup_top.map e, exact (x ≤ y) = (e.symm x ≤ e.symm y), end := rfl -- Below we verify in more detail that the transported structure for `semiring` -- is definitionally what you would hope for. inductive mynat : Type | zero : mynat | succ : mynat → mynat def mynat_equiv : ℕ ≃ mynat := { to_fun := λ n, nat.rec_on n mynat.zero (λ n, mynat.succ), inv_fun := λ n, mynat.rec_on n nat.zero (λ n, nat.succ), left_inv := λ n, begin induction n, refl, exact congr_arg nat.succ n_ih, end, right_inv := λ n, begin induction n, refl, exact congr_arg mynat.succ n_ih, end } @[simp] lemma mynat_equiv_apply_zero : mynat_equiv 0 = mynat.zero := rfl @[simp] lemma mynat_equiv_apply_succ (n : ℕ) : mynat_equiv (n + 1) = mynat.succ (mynat_equiv n) := rfl @[simp] lemma mynat_equiv_symm_apply_zero : mynat_equiv.symm mynat.zero = 0:= rfl @[simp] lemma mynat_equiv_symm_apply_succ (n : mynat) : mynat_equiv.symm (mynat.succ n) = (mynat_equiv.symm n) + 1 := rfl instance semiring_mynat : semiring mynat := semiring.map mynat_equiv lemma mynat_add_def (a b : mynat) : a + b = mynat_equiv (mynat_equiv.symm a + mynat_equiv.symm b) := rfl -- Verify that we can do computations with the transported structure. example : (mynat.succ (mynat.succ mynat.zero)) + (mynat.succ mynat.zero) = (mynat.succ (mynat.succ (mynat.succ mynat.zero))) := rfl lemma mynat_zero_def : (0 : mynat) = mynat_equiv 0 := rfl lemma mynat_one_def : (1 : mynat) = mynat_equiv 1 := rfl lemma mynat_mul_def (a b : mynat) : a * b = mynat_equiv (mynat_equiv.symm a * mynat_equiv.symm b) := rfl example : (3 : mynat) + (7 : mynat) = (10 : mynat) := rfl example : (2 : mynat) * (2 : mynat) = (4 : mynat) := rfl example : (3 : mynat) + (7 : mynat) * (2 : mynat) = (17 : mynat) := rfl example : (2 : ℕ) • (3 : mynat) = (6 : mynat) := rfl example : (3 : mynat) ^ 2 = (9 : mynat) := rfl
ca68f3df6242b9a70258cc8a94603ffa28a43123
d3aa99b88d7159fbbb8ab10d699374ab7be89e03
/src/data/list/basic.lean
64391412adbe17fa1dca5c74a8da0ee7ac004978
[ "Apache-2.0" ]
permissive
mzinkevi/mathlib
62e0920edaf743f7fc53aaf42a08e372954af298
c718a22925872db4cb5f64c36ed6e6a07bdf647c
refs/heads/master
1,599,359,590,404
1,573,098,221,000
1,573,098,221,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
218,600
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Basic properties of lists. -/ import tactic.interactive tactic.mk_iff_of_inductive_prop logic.basic logic.function logic.relator algebra.group order.basic data.list.defs data.nat.basic data.option.basic data.bool data.prod data.fin open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ @[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe @[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /- mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] /- length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ lemma injective_length_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end lemma injective_length [subsingleton α] : injective (length : list α → ℕ) := injective_length_iff.mpr $ by apply_instance /- set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq [decidable_eq α] (x : α) : ({x} : list α) = [x] := by refl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [y, x] := by { rw [insert_neg, singleton_eq], show y ∉ [x], rw [mem_singleton], exact h.symm } /- bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [mem_cons_iff, forall_mem_cons'] theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) @[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /- list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /- append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t := by {induction s with b s H generalizing a, refl, simp only [foldl, cons_append], rw H _} theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s := by {induction s with b s H generalizing a, refl, simp only [foldr, cons_append], rw H _} @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_left h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_right' h rfl theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /- join -/ attribute [simp] join theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /- repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] /- bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ /- concat -/ @[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl @[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by induction l; intro h; contradiction @[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by induction l₁; simp only [*, cons_append, concat]; split; refl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl @[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by induction l₂ with b l₂ ih; simp only [concat_eq_append, nil_append, cons_append, append_assoc] /- reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl theorem reverse_injective : injective (@reverse α) := injective_of_left_inverse reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /- last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, refl} /- sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact append_sublist_append_of_sublist_right ih [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp only [reverse_reverse] at this; assumption, reverse_sublist⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp only [reverse_append, append_sublist_append_left, reverse_sublist_iff] at this; assumption, λ h, append_sublist_append_of_sublist_right h l⟩ theorem append_sublist_append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (append_sublist_append_of_sublist_right hl _).trans ((append_sublist_append_left _).2 hr) theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (subset_of_sublist s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ subset_of_sublist s theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /- index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /- nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < n) : (list.repeat a n).nth_le m (by rwa list.length_repeat) = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length: ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[ext] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], } @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /- map -/ lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α) (h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l := by revert a; induction l; intros; [refl, simp only [*, foldl]] theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α) (h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l := by revert a; induction l; intros; [refl, simp only [*, foldr]] theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem injective_map_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /- map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /- take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_all (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by simp, by simpa [take_cons, h] using drop_take m n l theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /- foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp /- scanl -/ lemma length_scanl {β : Type*} {f : α → β → α} : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /- mfoldl, mfoldr -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl variables [is_lawful_monad m] @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /- prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[simp, to_additive] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] end monoid @[simp, to_additive] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left' (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end /- lexicographic ordering -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {} {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /- all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /- map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap /- find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end @[simp] theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /- lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /- filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem map_sublist_map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s /- filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := subset_of_sublist $ filter_sublist l theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /- count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append @[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by rw [concat_eq_append, count_append, count_singleton] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /- prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ @[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] @[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp only [concat_eq_append, prefix_append] theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_left_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_left_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /- sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s, { simp only [sublists'_nil, mem_singleton], exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, simp only [sublists'_cons, mem_append, IH, mem_map], split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ h }, { exact cons_sublist_cons _ h }, { cases h with _ _ _ h s _ _ h, { exact or.inl h }, { exact or.inr ⟨s, h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, pow_succ, mul_succ, mul_zero, zero_add] @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc] theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih, {refl}, simp only [ih, foldr_cons] end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil] | (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := rfl | (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l] theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind], congr, funext x, apply congr_arg _, rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map, map_eq_map, map_id' (append_nil), append_nil] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l with hd tl ih; [refl, simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro, {rwa foldr}, simp only [foldr, mem_cons_iff, false_or, not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp only [map, map_append, sublists_concat]; exact ((append_sublist_append_left _).2 $ singleton_sublist.2 $ mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans ((append_sublist_append_right _).2 IH) /- sublists_len -/ def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β | 0 l f r := f [] :: r | (n+1) [] f r := r | (n+1) (a::l) f r := sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ list.cons a) r) def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) := sublists_len_aux n l id [] lemma sublists_len_aux_append {α β γ : Type*} : ∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ), sublists_len_aux n l (g ∘ f) (r.map g ++ s) = (sublists_len_aux n l f r).map g ++ s | 0 l f g r s := rfl | (n+1) [] f g r s := rfl | (n+1) (a::l) f g r s := begin unfold sublists_len_aux, rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl, sublists_len_aux_append, sublists_len_aux_append] end lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) : sublists_len_aux n l f r = (sublists_len n l).map f ++ r := by rw [sublists_len, ← sublists_len_aux_append]; refl lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) : sublists_len_aux 0 l f r = f [] :: r := by cases l; refl @[simp] lemma sublists_len_zero {α : Type*} (l : list α) : sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _ @[simp] lemma sublists_len_succ_nil {α : Type*} (n) : sublists_len (n+1) (@nil α) = [] := rfl @[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) : sublists_len (n + 1) (a::l) = sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) := by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id, append_nil]; refl @[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α), length (sublists_len n l) = nat.choose (length l) n | 0 l := by simp | (n+1) [] := by simp | (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α), sublists_len n l <+ sublists' l | 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _)) | (n+1) [] := nil_sublist _ | (n+1) (a::l) := begin rw [sublists_len_succ_cons, sublists'_cons], exact append_sublist_append (sublists_len_sublist_sublists' _ _) (map_sublist_map _ (sublists_len_sublist_sublists' _ _)) end lemma sublists_len_sublist_of_sublist {α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl}, { refine IH.trans _, rw sublists_len_succ_cons, apply sublist_append_left }, { simp [sublists_len_succ_cons], exact append_sublist_append IH (map_sublist_map _ (IHn s)) } end lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α}, l' ∈ sublists_len n l → length l' = n | 0 l l' (or.inl rfl) := rfl | (n+1) (a::l) l' h := begin rw [sublists_len_succ_cons, mem_append, mem_map] at h, rcases h with h | ⟨l', h, rfl⟩, { exact length_of_sublists_len h }, { exact congr_arg (+1) (length_of_sublists_len h) }, end lemma mem_sublists_len_self {α : Type*} {l l' : list α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH, { exact or.inl rfl }, { cases l₁ with b l₁, { exact or.inl rfl }, { rw [length, sublists_len_succ_cons], exact mem_append_left _ IH } }, { rw [length, sublists_len_succ_cons], exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) } end @[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := ⟨λ h, ⟨mem_sublists'.1 (subset_of_sublist (sublists_len_sublist_sublists' _ _) h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩ /- forall₂ -/ section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff @[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} : forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := ⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩ theorem forall₂.imp {R S : α → β → Prop} (H : ∀ a b, R a b → S a b) {l₁ l₂} (h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ := by induction h; constructor; solve_by_elim lemma forall₂.mp {r q s : α → β → Prop} (h : ∀a b, r a b → q a b → s a b) : ∀{l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂ | [] [] forall₂.nil forall₂.nil := forall₂.nil | (a::l₁) (b::l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) := forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs) lemma forall₂.flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l | [] _ := forall₂.nil | (a::as) h := forall₂.cons (h _ (mem_cons_self _ _)) (forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha) lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l := forall₂_same $ assume a h, is_refl.refl _ _ lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) := begin funext a b, apply propext, split, { assume h, induction h, {refl}, simp only [*]; split; refl }, { assume h, subst h, exact forall₂_refl _ } end @[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ @[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_cons_right_iff {b l u} : forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} : ∀l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀a∈l, p a) ∧ forall₂ r l u | [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and] | (a::l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons, and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm] @[simp] lemma forall₂_map_left_iff {f : γ → α} : ∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u | [] _ := by simp only [map, forall₂_nil_left_iff] | (a::l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff] @[simp] lemma forall₂_map_right_iff {f : γ → β} : ∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u | _ [] := by simp only [map, forall₂_nil_right_iff] | _ (b::u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff] lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r) | a₀ nil a₁ forall₂.nil forall₂.nil := rfl | (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r) | nil a₀ a₁ forall₂.nil forall₂.nil := rfl | (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) := ⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩ theorem forall₂_length_eq {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂ | _ _ forall₂.nil := rfl | _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂) theorem forall₂_zip {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b | _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁ | _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃ theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b := ⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩, λ h, begin cases h with h₁ h₂, induction l₁ with a l₁ IH generalizing l₂, { cases length_eq_zero.1 h₁.symm, constructor }, { cases l₂ with b l₂; injection h₁ with h₁, exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) } end⟩ theorem forall₂_take {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂) | 0 _ _ _ := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n] theorem forall₂_drop {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂) | 0 _ _ h := by simp only [drop, h] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n] theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ := have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h, by rwa [take_left] at h' theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ := have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h, by rwa [drop_left] at h' lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp only [not_mem_nil] | a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂) lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map | f g h [] [] forall₂.nil := forall₂.nil | f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂) lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append | [] [] h l₁ l₂ hl := hl | (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl) lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join | [] [] forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂) lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind := assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁) lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs) lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : (r ⇒ (↔)) p q) : (forall₂ r ⇒ forall₂ r) (filter p) (filter q) | _ _ forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := begin by_cases p a, { have : q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], }, end theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { rw filter_map_cons_none _ _ eq }, { rw filter_map_cons_some _ _ _ eq }, end lemma rel_filter_map : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := rel_foldl hf h end forall₂ /- sections -/ theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L := begin refine ⟨λ h, _, λ h, _⟩, { induction L generalizing f, {cases mem_singleton.1 h, exact forall₂.nil}, simp only [sections, bind_eq_bind, mem_bind, mem_map] at h, rcases h with ⟨_, _, _, _, rfl⟩, simp only [*, forall₂_cons, true_and] }, { induction h with a l f L al fL fs, {exact or.inl rfl}, simp only [sections, bind_eq_bind, mem_bind, mem_map], exact ⟨_, fs, _, al, rfl, rfl⟩ } end theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L := forall₂_length_eq (mem_sections.1 h) lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections | _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil | _ _ (forall₂.cons h₀ h₁) := rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀) /- permutations -/ section permutations @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl end permutations /- insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) @[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /- erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := subset_of_sublist (erasep_sublist l) theorem erasep_sublist_erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /- erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := subset_of_sublist (erase_sublist a l) theorem erase_sublist_erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact erasep_sublist_erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /- diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := subset_of_sublist $ diff_sublist _ _ theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem diff_sublist_of_sublist : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, diff_sublist_of_sublist (erase_sublist_erase _ h)] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (erase_sublist_erase b h) using_well_founded wf_tacs end diff /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := (zip_nil_right _).symm | l₁ [] := by rw zip_nil_right; refl | (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := rfl | l₁ [] := by simp only [length, zip_nil_right, min_zero] | (a::l₁) (b::l₂) := by by simp only [length, zip_cons_cons, length_zip l₁ l₂, min_add_add_right] theorem zip_append : ∀ {l₁ l₂ r₁ r₂ : list α} (h : length l₁ = length l₂), zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ | [] l₂ r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl | l₁ [] r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl | (a::l₁) (b::l₂) r₁ r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ_inj h)]; split; refl theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g) | [] l₂ := rfl | l₁ [] := by simp only [map, zip_nil_right] | (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) : zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) := by rw [← zip_map, map_id] theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) : zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) := by rw [← zip_map, map_id] theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α), zip (l.map f) (l.map g) = l.map (λ a, (f a, g a)) | [] := rfl | (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ | (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩ | (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h] @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd) | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp only [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp only [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁ | [] l₂ h := rfl | l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl | (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) : (unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)] @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := unzip_zip (length_reverse l).symm @[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l := by rw [← unzip_left, unzip_revzip] @[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse := by rw [← unzip_right, unzip_revzip] theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip] theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse := by simp [revzip] /- enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : Π {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := by { simp [enum_from,mem_enum_from ys], rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply lt_of_lt_of_le (nat.lt_add_of_pos_right zero_lt_one), apply nat.add_le_add_left, apply nat.le_add_right }, { replace h := mem_enum_from _ h, simp at h, revert h, apply and_implies _ (and_implies id or.inr), intro h, transitivity j+1, apply nat.le_add_right, exact h } } /- product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /- sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /- of_fn -/ theorem length_of_fn_aux {n} (f : fin n → α) : ∀ m h l, length (of_fn_aux f m h l) = length l + m | 0 h l := rfl | (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _) @[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) theorem nth_of_fn_aux {n} (f : fin n → α) (i) : ∀ m h l, (∀ i, nth l i = of_fn_nth_val f (i + m)) → nth (of_fn_aux f m h l) i = of_fn_nth_val f i | 0 h l H := H i | (succ m) h l H := nth_of_fn_aux m _ _ begin intro j, cases j with j, { simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] }, { simp only [nth, H, succ_add] } end @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = of_fn_nth_val f i := nth_of_fn_aux f _ _ _ _ $ λ i, by simp only [of_fn_nth_val, dif_neg (not_lt.2 (le_add_left n i))]; refl @[simp] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) : nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i := option.some.inj $ by rw [← nth_le_nth]; simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.2] theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read := suffices ∀ {m h l}, d_array.rev_iterate_aux a (λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, simp only [d_array.rev_iterate_aux, of_fn_aux, IH] end theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl theorem of_fn_succ {n} (f : fin (succ n) → α) : of_fn f = f 0 :: of_fn (λ i, f i.succ) := suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l = f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, rw [of_fn_aux, IH], refl end theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l | [] := rfl | (a::l) := by rw of_fn_succ; congr; simp only [fin.succ_val]; exact of_fn_nth_le l /- disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /- union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /- inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter /- bag_inter -/ section bag_inter variable [decidable_eq α] @[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] := by cases l; refl @[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] := by cases l; refl @[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) : (a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) := by cases l₂; exact if_pos h @[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) : (a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ := begin cases l₂, {simp only [bag_inter_nil]}, simp only [erase_of_not_mem h, list.bag_inter, if_neg h] end @[simp] theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ | [] l₂ := by simp only [nil_bag_inter, not_mem_nil, false_and] | (b::l₁) l₂ := begin by_cases b ∈ l₂, { rw [cons_bag_inter_of_pos _ h, mem_cons_iff, mem_cons_iff, mem_bag_inter], by_cases ba : a = b, { simp only [ba, h, eq_self_iff_true, true_or, true_and] }, { simp only [mem_erase_of_ne ba, ba, false_or] } }, { rw [cons_bag_inter_of_neg _ h, mem_bag_inter, mem_cons_iff, or_and_distrib_right], symmetry, apply or_iff_right_of_imp, rintro ⟨rfl, h'⟩, exact h.elim h' } end @[simp] theorem count_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, count a (l₁.bag_inter l₂) = min (count a l₁) (count a l₂) | [] l₂ := by simp | l₁ [] := by simp | (h₁ :: l₁) (h₂ :: l₂) := begin simp only [list.bag_inter, list.mem_cons_iff], by_cases p₁ : h₂ = h₁; by_cases p₂ : h₁ = a, { simp only [p₁, p₂, count_bag_inter, min_succ_succ, erase_cons_head, if_true, mem_cons_iff, count_cons_self, true_or, eq_self_iff_true] }, { simp only [p₁, ne.symm p₂, count_bag_inter, count_cons, erase_cons_head, if_true, mem_cons_iff, true_or, eq_self_iff_true, if_false] }, { rw p₂ at p₁, by_cases p₃ : a ∈ l₂, { simp only [p₁, ne.symm p₁, p₂, p₃, erase_cons, count_bag_inter, eq.symm (min_succ_succ _ _), succ_pred_eq_of_pos (count_pos.2 p₃), if_true, mem_cons_iff, false_or, count_cons_self, eq_self_iff_true, if_false, ne.def, not_false_iff, count_erase_self, list.count_cons_of_ne] }, { simp [ne.symm p₁, p₂, p₃] } }, { by_cases p₄ : h₁ ∈ l₂; simp only [ne.symm p₁, ne.symm p₂, p₄, count_bag_inter, if_true, if_false, mem_cons_iff, false_or, eq_self_iff_true, ne.def, not_false_iff,count_erase_of_ne, count_cons_of_ne] } end theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁ | [] l₂ := by simp [nil_sublist] | (b::l₁) l₂ := begin by_cases b ∈ l₂; simp [h], { apply cons_sublist_cons, apply bag_inter_sublist_left }, { apply sublist_cons_of_sublist, apply bag_inter_sublist_left } end theorem bag_inter_nil_iff_inter_nil : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ = [] ↔ l₁ ∩ l₂ = [] | [] l₂ := by simp | (b::l₁) l₂ := begin by_cases h : b ∈ l₂; simp [h], exact bag_inter_nil_iff_inter_nil l₁ l₂ end end bag_inter /- pairwise relation (generalized no duplicate) -/ section pairwise run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pairwise_iff variable {R : α → α → Prop} theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp only [pairwise.nil, pairwise_cons] at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; [exact pairwise.nil, simp only [*, pairwise_cons, forall_2_true_iff, and_true]] theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i) theorem forall_of_forall_of_pairwise (H : symmetric R) {l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) : ∀ (x ∈ l) (y ∈ l), R x y := begin induction l with a l IH, { exact forall_mem_nil _ }, cases forall_mem_cons.1 H₁ with H₁₁ H₁₂, cases pairwise_cons.1 H₂ with H₂₁ H₂₂, rintro x (rfl | hx) y (rfl | hy), exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy] end lemma forall_of_pairwise (H : symmetric R) {l : list α} (hl : pairwise R l) : (∀a∈l, ∀b∈l, a ≠ b → R a b) := forall_of_forall_of_pairwise (λ a b h hne, H (h hne.symm)) (λ _ _ h, (h rfl).elim) (pairwise.imp (λ _ _ h _, h) hl) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append], simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]] theorem pairwise_append_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_append_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp only [map, pairwise.nil] | (b::l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'], by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map] theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp only [option.mem_def], induction l with a l IH, { simp only [filter_map, pairwise.nil] }, cases e : f a with b, { rw [filter_map_cons_none _ _ e, IH, pairwise_cons], simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] }, rw [filter_map_cons_some _ _ _ e], simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'], end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons], simp only [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH, pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h] theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (not_lt_zero j).elim h | (a::l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (not_lt_zero _).elim h₂}, cases i with i, { exact H.1 _ (nth_le_mem l _ _) }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ pairwise.nil := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this /- pairwise reduct -/ variable [decidable_rel R] @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_map (f : β → α) : Π (l : list β), pw_filter R (map f l) = map f (pw_filter (λ x y, R (f x) (f y)) l) | [] := rfl | (x :: xs) := if h : ∀ b ∈ pw_filter R (map f xs), R (f x) b then have h' : ∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ b hb, h _ (by rw [pw_filter_map]; apply mem_map_of_mem _ hb), by rw [map,pw_filter_cons_of_pos h,pw_filter_cons_of_pos h',pw_filter_map,map] else have h' : ¬∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ hh, h $ λ a ha, by { rw [pw_filter_map,mem_map] at ha, rcases ha with ⟨b,hb₀,hb₁⟩, subst a, exact hh _ hb₀, }, by rw [map,pw_filter_cons_of_neg h,pw_filter_cons_of_neg h',pw_filter_map] theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := subset_of_sublist (pw_filter_sublist _) theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {refl}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH, { exact λ _ _, false.elim }, simp only [forall_mem_cons], by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end pairwise /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ section chain run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff variable {R : α → α → Prop} theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := by induction p with _ a b l r p IH; constructor; [exact H _ _ r, exact IH] theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp only [chain_cons, chain.nil, and_true] theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp only [map, chain.nil, chain_cons, *] theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, IH r'⟩ end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {exact pairwise_singleton _ _}, apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x::l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ theorem chain'_singleton (a : α) : chain' R [a] := chain.nil theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔ chain' R (l₁++[a]) ∧ chain' R (a::l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b::l₁) l₂ := chain_split theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R l := ((chain'_map f).1 p).imp H theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem chain'_of_pairwise : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a::l) h := chain_of_pairwise h theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a::l) := chain_iff_pairwise tr end chain /- no duplicates predicate -/ section nodup @[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_nil : @nodup α [] := pairwise.nil @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp only [nodup, pairwise_cons, forall_mem_ne] lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp only [nodup_nil] | _ _ (forall₂.cons hab h) := by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin induction l with a l IH; intro h, {exact nodup_nil}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1 | 0 := by simp [nat.zero_le] | 1 := by simp | (n+2) := iff_of_false (λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (le_add_left 2 n))) (not_le_of_lt $ le_add_left 2 n) @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp only [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_append_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp only [nodup_append, and.left_comm, disjoint_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) := nodup_map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup_of_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm] theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH, {refl}, by_cases b = a, { subst h, rw [erase_cons_head, filter_cons_of_neg], symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl }, { rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h } end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem nodup_diff [decidable_eq α] : ∀ {l₁ l₂ : list α} (h : l₁.nodup), (l₁.diff l₂).nodup | l₁ [] h := h | l₁ (a::l₂) h := by rw diff_cons; exact nodup_diff (nodup_erase_of_nodup _ h) 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 only [mem_filter, and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, forall_eq'] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂, d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := if h' : a ∈ l then by rw [insert_of_mem h']; exact h else by rw [insert_of_not_mem h', nodup_cons]; split; assumption theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] lemma nodup_sublists_len {α : Type*} (n) {l : list α} (nd : nodup l) : (sublists_len n l).nodup := nodup_of_sublist (sublists_len_sublist_sublists' _ _) (nodup_sublists'.2 nd) lemma diff_eq_filter_of_nodup [decidable_eq α] : ∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂) | l₁ [] hl₁ := by simp | l₁ (a::l₂) hl₁ := begin rw [diff_cons, diff_eq_filter_of_nodup (nodup_erase_of_nodup _ hl₁), nodup_erase_eq_filter _ hl₁, filter_filter], simp only [mem_cons_iff, not_or_distrib, and.comm], congr end lemma mem_diff_iff_of_nodup [decidable_eq α] {l₁ l₂ : list α} (hl₁ : l₁.nodup) {a : α} : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by rw [diff_eq_filter_of_nodup hl₁, mem_filter] lemma nodup_update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l), (l.update_nth n a).nodup | [] n a hl ha := nodup_nil | (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩ | (b::l) (n+1) a hl ha := nodup_cons.2 ⟨λ h, (mem_or_eq_of_mem_update_nth h).elim (nodup_cons.1 hl).1 (λ hba, ha (hba ▸ mem_cons_self _ _)), nodup_update_nth (nodup_cons.1 hl).2 (mt (mem_cons_of_mem _) ha)⟩ end nodup /- erase duplicates function -/ section erase_dup variable [decidable_eq α] @[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) : erase_dup (a::l) = erase_dup l := pw_filter_cons_of_neg $ by simpa only [forall_mem_ne] using h theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) : erase_dup (a::l) = a :: erase_dup l := pw_filter_cons_of_pos $ by simpa only [forall_mem_ne] using h @[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l := by simpa only [erase_dup, forall_mem_ne, not_not] using not_congr (@forall_mem_pw_filter α (≠) _ (λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l) @[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) : erase_dup (a::l) = erase_dup l := erase_dup_cons_of_mem' $ mem_erase_dup.2 h @[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) : erase_dup (a::l) = a :: erase_dup l := erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l := λ a, mem_erase_dup.2 theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self @[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l := pw_filter_idempotent theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ := begin induction l₁ with a l₁ IH, {refl}, rw [cons_union, ← IH], show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)), by_cases a ∈ erase_dup (l₁ ++ l₂); [ rw [erase_dup_cons_of_mem' h, insert_of_mem h], rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]] end end erase_dup /- iota and range(') -/ @[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n | s 0 := rfl | s (n+1) := congr_arg succ (length_range' _ _) @[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n | s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1 | s (succ n) := have m = s → m < s + n + 1, from λ e, e ▸ lt_succ_of_le (le_add_right _ _), have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m, by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm, (mem_cons_iff _ _ _).trans $ by simp only [mem_range', or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n | s 0 := rfl | s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n) theorem map_sub_range' (a) : ∀ (s n : ℕ) (h : a ≤ s), map (λ x, x - a) (range' s n) = range' (s - a) n | s 0 _ := rfl | s (n+1) h := begin convert congr_arg (cons (s-a)) (map_sub_range' (s+1) n (nat.le_succ_of_le h)), rw nat.succ_sub h, refl, end theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) @[simp] theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa only [length_range'] using length_le_of_sublist h, λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩ theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n := ⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $ (mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2, λ h, subset_of_sublist (range'_sublist_right.2 h)⟩ theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m) | s 0 (n+1) _ := rfl | s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] := by rw add_comm n 1; exact (range'_append s n 1).symm theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s) | 0 n := rfl | (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1) theorem range_eq_range' (n : ℕ) : range n = range' 0 n := (range_core_range' n 0).trans $ by rw zero_add theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) := by rw [range_eq_range', range_eq_range', range', add_comm, ← map_add_range']; congr; exact funext one_add theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) := by rw [range_eq_range', map_add_range']; refl @[simp] theorem length_range (n : ℕ) : length (range n) = n := by simp only [range_eq_range', length_range'] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp only [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp only [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp only [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp only [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add] @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := mt mem_range.1 $ lt_irrefl _ theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m := by simp only [range_eq_range', nth_range' _ h, zero_add] theorem range_concat (n : ℕ) : range (succ n) = range n ++ [n] := by simp only [range_eq_range', range'_concat, zero_add] theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp only [iota_eq_reverse_range', length_reverse, length_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff] theorem reverse_range' : ∀ s n : ℕ, reverse (range' s n) = map (λ i, s + n - 1 - i) (range n) | s 0 := rfl | s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map]; simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘), λ a i, show a - 1 - i = a - succ i, from pred_sub _ _, reverse_singleton, map_cons, nat.sub_zero, cons_append, nil_append, eq_self_iff_true, true_and, map_map] using reverse_range' s n def fin_range (n : ℕ) : list (fin n) := (range n).pmap fin.mk (λ _, list.mem_range.1) @[simp] lemma mem_fin_range {n : ℕ} (a : fin n) : a ∈ fin_range n := mem_pmap.2 ⟨a.1, mem_range.2 a.2, fin.eta _ _⟩ lemma nodup_fin_range (n : ℕ) : (fin_range n).nodup := nodup_pmap (λ _ _ _ _, fin.veq_of_eq) (nodup_range _) @[simp] lemma length_fin_range (n : ℕ) : (fin_range n).length = n := by rw [fin_range, length_pmap, length_range] @[to_additive] theorem prod_range_succ {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) : ((range n.succ).map f).prod = ((range n).map f).prod * f n := by rw [range_concat, map_append, map_singleton, prod_append, prod_cons, prod_nil, mul_one] /-- `Ico n m` is the list of natural numbers `n ≤ x < m`. (Ico stands for "interval, closed-open".) See also `data/set/intervals.lean` for `set.Ico`, modelling intervals in general preorders, and `multiset.Ico` and `finset.Ico` for `n ≤ x < m` as a multiset or as a finset. @TODO (anyone): Define `Ioo` and `Icc`, state basic lemmas about them. @TODO (anyone): Prove that `finset.Ico` and `set.Ico` agree. @TODO (anyone): Also do the versions for integers? @TODO (anyone): One could generalise even further, defining 'locally finite partial orders', for which `set.Ico a b` is `[finite]`, and 'locally finite total orders', for which there is a list model. -/ def Ico (n m : ℕ) : list ℕ := range' n (m - n) namespace Ico theorem zero_bot (n : ℕ) : Ico 0 n = range n := by rw [Ico, nat.sub_zero, range_eq_range'] @[simp] theorem length (n m : ℕ) : length (Ico n m) = m - n := by dsimp [Ico]; simp only [length_range'] theorem pairwise_lt (n m : ℕ) : pairwise (<) (Ico n m) := by dsimp [Ico]; simp only [pairwise_lt_range'] theorem nodup (n m : ℕ) : nodup (Ico n m) := by dsimp [Ico]; simp only [nodup_range'] @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := suffices n ≤ l ∧ l < n + (m - n) ↔ n ≤ l ∧ l < m, by simp [Ico, this], begin cases le_total n m with hnm hmn, { rw [nat.add_sub_of_le hnm] }, { rw [nat.sub_eq_zero_of_le hmn, add_zero], exact and_congr_right (assume hnl, iff.intro (assume hln, (not_le_of_gt hln hnl).elim) (assume hlm, lt_of_lt_of_le hlm hmn)) } end theorem eq_nil_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = [] := by simp [Ico, nat.sub_eq_zero_of_le h] theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := by rw [Ico, Ico, map_add_range', nat.add_sub_add_right, add_comm n k] theorem map_sub (n m k : ℕ) (h₁ : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := begin by_cases h₂ : n < m, { rw [Ico, Ico], rw nat.sub_sub_sub_cancel_right h₁, rw [map_sub_range' _ _ _ h₁] }, { simp at h₂, rw [eq_nil_of_le h₂], rw [eq_nil_of_le (nat.sub_le_sub_right h₂ _)], refl } end @[simp] theorem self_empty {n : ℕ} : Ico n n = [] := eq_nil_of_le (le_refl n) @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = [] ↔ m ≤ n := iff.intro (assume h, nat.le_of_sub_eq_zero $ by rw [← length, h]; refl) eq_nil_of_le lemma append_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ++ Ico m l = Ico n l := begin dunfold Ico, convert range'_append _ _ _, { exact (nat.add_sub_of_le hnm).symm }, { rwa [← nat.add_sub_assoc hnm, nat.sub_add_cancel] } end @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = [] := begin apply eq_nil_iff_forall_not_mem.2, intro a, simp only [and_imp, not_and, not_lt, list.mem_inter, list.Ico.mem], intros h₁ h₂ h₃, exfalso, exact not_lt_of_ge h₃ h₂ end @[simp] lemma bag_inter_consecutive (n m l : ℕ) : list.bag_inter (Ico n m) (Ico m l) = [] := (bag_inter_nil_iff_inter_nil _ _).2 (inter_consecutive n m l) @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = [n] := by dsimp [Ico]; simp [nat.add_sub_cancel_left] theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] := by rwa [← succ_singleton, append_consecutive]; exact nat.le_succ _ theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := by rw [← append_consecutive (nat.le_succ n) h, succ_singleton]; refl @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = [m - 1] := by dsimp [Ico]; rw nat.sub_sub_self h; simp theorem chain'_succ (n m : ℕ) : chain' (λa b, b = succ a) (Ico n m) := begin by_cases n < m, { rw [eq_cons h], exact chain_succ_range' _ _ }, { rw [eq_nil_of_le (le_of_not_gt h)], trivial } end @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := by simp; intros; refl lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := filter_eq_self.2 $ assume k hk, lt_of_lt_of_le (mem.1 hk).2 hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = [] := filter_eq_nil.2 $ assume k hk, not_lt_of_le $ le_trans hln $ (mem.1 hk).1 lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := begin cases le_total n l with hnl hln, { rw [← append_consecutive hnl hlm, filter_append, filter_lt_of_top_le (le_refl l), filter_lt_of_le_bot (le_refl l), append_nil] }, { rw [eq_nil_of_le hln, filter_lt_of_le_bot hln] } end @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := begin cases le_total m l with hml hlm, { rw [min_eq_left hml, filter_lt_of_top_le hml] }, { rw [min_eq_right hlm, filter_lt_of_ge hlm] } end lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := filter_eq_self.2 $ assume k hk, le_trans hln (mem.1 hk).1 lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = [] := filter_eq_nil.2 $ assume k hk, not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml) lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := begin cases le_total l m with hlm hml, { rw [← append_consecutive hnl hlm, filter_append, filter_le_of_top_le (le_refl l), filter_le_of_le_bot (le_refl l), nil_append] }, { rw [eq_nil_of_le hml, filter_le_of_top_le hml] } end @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (_root_.max n l) m := begin cases le_total n l with hnl hln, { rw [max_eq_right hnl, filter_le_of_le hnl] }, { rw [max_eq_left hln, filter_le_of_le_bot hln] } end end Ico @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp only [enum, enum_from_map_fst, range_eq_range'] theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val @[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) : nth_le (range n) i H = i := option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)] theorem of_fn_eq_pmap {α n} {f : fin n → α} : of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) := by rw [pmap_eq_map_attach]; from ext_le (by simp) (λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩]) theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) : nodup (of_fn f) := by rw of_fn_eq_pmap; from nodup_pmap (λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n) section tfae /- tfae: The Following (propositions) Are Equivalent -/ theorem tfae_nil : tfae [] := forall_mem_nil _ theorem tfae_singleton (p) : tfae [p] := by simp [tfae, -eq_iff_iff] theorem tfae_cons_of_mem {a b} {l : list Prop} (h : b ∈ l) : tfae (a::l) ↔ (a ↔ b) ∧ tfae l := ⟨λ H, ⟨H a (by simp) b (or.inr h), λ p hp q hq, H _ (or.inr hp) _ (or.inr hq)⟩, begin rintro ⟨ab, H⟩ p (rfl | hp) q (rfl | hq), { refl }, { exact ab.trans (H _ h _ hq) }, { exact (ab.trans (H _ h _ hp)).symm }, { exact H _ hp _ hq } end⟩ theorem tfae_cons_cons {a b} {l : list Prop} : tfae (a::b::l) ↔ (a ↔ b) ∧ tfae (b::l) := tfae_cons_of_mem (or.inl rfl) theorem tfae_of_forall (b : Prop) (l : list Prop) (h : ∀ a ∈ l, a ↔ b) : tfae l := λ a₁ h₁ a₂ h₂, (h _ h₁).trans (h _ h₂).symm theorem tfae_of_cycle {a b} {l : list Prop} : list.chain (→) a (b::l) → (ilast' b l → a) → tfae (a::b::l) := begin induction l with c l IH generalizing a b; simp only [tfae_cons_cons, tfae_singleton, and_true, chain_cons, chain.nil] at *, { intros a b, exact iff.intro a b }, rintros ⟨ab,⟨bc,ch⟩⟩ la, have := IH ⟨bc,ch⟩ (ab ∘ la), exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (ilast'_mem _ _)).1 ∘ bc⟩, this⟩ end theorem tfae.out {l} (h : tfae l) (n₁ n₂) (h₁ : n₁ < list.length l . tactic.exact_dec_trivial) (h₂ : n₂ < list.length l . tactic.exact_dec_trivial) : list.nth_le l n₁ h₁ ↔ list.nth_le l n₂ h₂ := h _ (list.nth_le_mem _ _ _) _ (list.nth_le_mem _ _ _) end tfae lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n := by simp [rotate] @[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; refl @[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate] @[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl @[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate'] @[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length | [] n := rfl | (a::l) 0 := rfl | (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp lemma rotate'_eq_take_append_drop : ∀ {l : list α} {n : ℕ}, n ≤ l.length → l.rotate' n = l.drop n ++ l.take n | [] n h := by simp [drop_append_of_le_length h] | l 0 h := by simp [take_append_of_le_length h] | (a::l) (n+1) h := have hnl : n ≤ l.length, from le_of_succ_le_succ h, have hnl' : n ≤ (l ++ [a]).length, by rw [length_append, length_cons, list.length, zero_add]; exact (le_of_succ_le h), by rw [rotate'_cons_succ, rotate'_eq_take_append_drop hnl', drop, take, drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m) | (a::l) 0 m := by simp | [] n m := by simp | (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ] @[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l := by rw rotate'_eq_take_append_drop (le_refl _); simp @[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l | 0 := by simp | (n+1) := calc l.rotate' (l.length * (n + 1)) = (l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length : by simp [-rotate'_length, nat.mul_succ, rotate'_rotate'] ... = l : by rw [rotate'_length, rotate'_length_mul] lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n := calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul ... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div] lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n := if h : l.length = 0 then by simp [length_eq_zero, *] at * else by rw [← rotate'_mod, rotate'_eq_take_append_drop (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))]; simp [rotate] lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate n.succ = (l ++ [a]).rotate n := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ] @[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l | [] _ n := by simp | (a::l) _ 0 := by simp | (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm] @[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length := by rw [rotate_eq_rotate', length_rotate'] lemma rotate_eq_take_append_drop {l : list α} {n : ℕ} : n ≤ l.length → l.rotate n = l.drop n ++ l.take n := by rw rotate_eq_rotate'; exact rotate'_eq_take_append_drop lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate'] @[simp] lemma rotate_length (l : list α) : rotate l l.length = l := by rw [rotate_eq_rotate', rotate'_length] @[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l := by rw [rotate_eq_rotate', rotate'_length_mul] lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ), (l.rotate n).prod = 1 | [] _ _ := by simp | (a::l) hl n := have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial), by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl; rw [← rotate_mod, rotate_eq_take_append_drop this, list.prod_append, mul_eq_one_iff_inv_eq, ← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one] section choose variables (p : α → Prop) [decidable_pred p] (l : list α) 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 namespace func variables {a : α} variables {as as1 as2 as3 : list α} localized "notation as ` {` m ` ↦ ` a `}` := list.func.set a as m" in list.func /- set -/ lemma length_set [inhabited α] : ∀ {m : ℕ} {as : list α}, (as {m ↦ a}).length = _root_.max as.length (m+1) | 0 [] := rfl | 0 (a::as) := by {rw max_eq_left, refl, simp [nat.le_add_right]} | (m+1) [] := by simp only [set, nat.zero_max, length, @length_set m] | (m+1) (a::as) := by simp only [set, nat.max_succ_succ, length, @length_set m] @[simp] lemma get_nil [inhabited α] {k : ℕ} : get k [] = default α := by {cases k; refl} lemma get_eq_default_of_le [inhabited α] : ∀ (k : ℕ) {as : list α}, as.length ≤ k → get k as = default α | 0 [] h1 := rfl | 0 (a::as) h1 := by cases h1 | (k+1) [] h1 := rfl | (k+1) (a::as) h1 := begin apply get_eq_default_of_le k, rw ← nat.succ_le_succ_iff, apply h1, end @[simp] lemma get_set [inhabited α] {a : α} : ∀ {k : ℕ} {as : list α}, get k (as {k ↦ a}) = a | 0 as := by {cases as; refl, } | (k+1) as := by {cases as; simp [get_set]} lemma eq_get_of_mem [inhabited α] {a : α} : ∀ {as : list α}, a ∈ as → ∃ n : nat, ∀ d : α, a = (get n as) | [] h := by cases h | (b::as) h := begin rw mem_cons_iff at h, cases h, { existsi 0, intro d, apply h }, { cases eq_get_of_mem h with n h2, existsi (n+1), apply h2 } end lemma mem_get_of_le [inhabited α] : ∀ {n : ℕ} {as : list α}, n < as.length → get n as ∈ as | _ [] h1 := by cases h1 | 0 (a::as) _ := or.inl rfl | (n+1) (a::as) h1 := begin apply or.inr, unfold get, apply mem_get_of_le, apply nat.lt_of_succ_lt_succ h1, end lemma mem_get_of_ne_zero [inhabited α] : ∀ {n : ℕ} {as : list α}, get n as ≠ default α → get n as ∈ as | _ [] h1 := begin exfalso, apply h1, rw get_nil end | 0 (a::as) h1 := or.inl rfl | (n+1) (a::as) h1 := begin unfold get, apply (or.inr (mem_get_of_ne_zero _)), apply h1 end lemma get_set_eq_of_ne [inhabited α] {a : α} : ∀ {as : list α} (k : ℕ) (m : ℕ), m ≠ k → get m (as {k ↦ a}) = get m as | as 0 m h1 := by { cases m, contradiction, cases as; simp only [set, get, get_nil] } | as (k+1) m h1 := begin cases as; cases m, simp only [set, get], { have h3 : get m (nil {k ↦ a}) = default α, { rw [get_set_eq_of_ne k m, get_nil], intro hc, apply h1, simp [hc] }, apply h3 }, simp only [set, get], { apply get_set_eq_of_ne k m, intro hc, apply h1, simp [hc], } end lemma get_map [inhabited α] [inhabited β] {f : α → β} : ∀ {n : ℕ} {as : list α}, n < as.length → get n (as.map f) = f (get n as) | _ [] h := by cases h | 0 (a::as) h := rfl | (n+1) (a::as) h1 := begin have h2 : n < length as, { rw [← nat.succ_le_iff, ← nat.lt_succ_iff], apply h1 }, apply get_map h2, end lemma get_map' [inhabited α] [inhabited β] {f : α → β} {n : ℕ} {as : list α} : f (default α) = (default β) → get n (as.map f) = f (get n as) := begin intro h1, by_cases h2 : n < as.length, { apply get_map h2, }, { rw not_lt at h2, rw [get_eq_default_of_le _ h2, get_eq_default_of_le, h1], rw [length_map], apply h2 } end lemma forall_val_of_forall_mem [inhabited α] {as : list α} {p : α → Prop} : p (default α) → (∀ x ∈ as, p x) → (∀ n, p (get n as)) := begin intros h1 h2 n, by_cases h3 : n < as.length, { apply h2 _ (mem_get_of_le h3) }, { rw not_lt at h3, rw get_eq_default_of_le _ h3, apply h1 } end /- equiv -/ lemma equiv_refl [inhabited α] : equiv as as := λ k, rfl lemma equiv_symm [inhabited α] : equiv as1 as2 → equiv as2 as1 := λ h1 k, (h1 k).symm lemma equiv_trans [inhabited α] : equiv as1 as2 → equiv as2 as3 → equiv as1 as3 := λ h1 h2 k, eq.trans (h1 k) (h2 k) lemma equiv_of_eq [inhabited α] : as1 = as2 → equiv as1 as2 := begin intro h1, rw h1, apply equiv_refl end lemma eq_of_equiv [inhabited α] : ∀ {as1 as2 : list α}, as1.length = as2.length → equiv as1 as2 → as1 = as2 | [] [] h1 h2 := rfl | (_::_) [] h1 h2 := by cases h1 | [] (_::_) h1 h2 := by cases h1 | (a1::as1) (a2::as2) h1 h2 := begin congr, { apply h2 0 }, have h3 : as1.length = as2.length, { simpa [add_left_inj, add_comm, length] using h1 }, apply eq_of_equiv h3, intro m, apply h2 (m+1) end /- neg -/ @[simp] lemma get_neg [inhabited α] [add_group α] {k : ℕ} {as : list α} : @get α ⟨0⟩ k (neg as) = -(@get α ⟨0⟩ k as) := by {unfold neg, rw (@get_map' α α ⟨0⟩), apply neg_zero} @[simp] lemma length_neg [inhabited α] [has_neg α] (as : list α) : (neg as).length = as.length := by simp only [neg, length_map] /- pointwise -/ lemma nil_pointwise [inhabited α] [inhabited β] {f : α → β → γ} : ∀ bs : list β, pointwise f [] bs = bs.map (f $ default α) | [] := rfl | (b::bs) := by simp only [nil_pointwise bs, pointwise, eq_self_iff_true, and_self, map] lemma pointwise_nil [inhabited α] [inhabited β] {f : α → β → γ} : ∀ as : list α, pointwise f as [] = as.map (λ a, f a $ default β) | [] := rfl | (a::as) := by simp only [pointwise_nil as, pointwise, eq_self_iff_true, and_self, list.map] lemma get_pointwise [inhabited α] [inhabited β] [inhabited γ] {f : α → β → γ} (h1 : f (default α) (default β) = default γ) : ∀ (k : nat) (as : list α) (bs : list β), get k (pointwise f as bs) = f (get k as) (get k bs) | k [] [] := by simp only [h1, get_nil, pointwise, get] | 0 [] (b::bs) := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) [] (b::bs) := by { have : get k (map (f $ default α) bs) = f (default α) (get k bs), { simpa [nil_pointwise, get_nil] using (get_pointwise k [] bs) }, simpa [get, get_nil, pointwise, map] } | 0 (a::as) [] := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) (a::as) [] := by simpa [get, get_nil, pointwise, map, pointwise_nil, get_nil] using get_pointwise k as [] | 0 (a::as) (b::bs) := by simp only [pointwise, get] | (k+1) (a::as) (b::bs) := by simp only [pointwise, get, get_pointwise k] lemma length_pointwise [inhabited α] [inhabited β] {f : α → β → γ} : ∀ {as : list α} {bs : list β}, (pointwise f as bs).length = _root_.max as.length bs.length | [] [] := rfl | [] (b::bs) := by simp only [pointwise, length, length_map, max_eq_right (nat.zero_le (length bs + 1))] | (a::as) [] := by simp only [pointwise, length, length_map, max_eq_left (nat.zero_le (length as + 1))] | (a::as) (b::bs) := by simp only [pointwise, length, nat.max_succ_succ, @length_pointwise as bs] /- add -/ @[simp] lemma get_add {α : Type u} [add_monoid α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (add xs ys) = ( @get α ⟨0⟩ k xs + @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply zero_add} @[simp] lemma length_add {α : Type u} [has_zero α] [has_add α] {xs ys : list α} : (add xs ys).length = _root_.max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_add {α : Type u} [add_monoid α] (as : list α) : add [] as = as := begin rw [add, @nil_pointwise α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, zero_add], refl end @[simp] lemma add_nil {α : Type u} [add_monoid α] (as : list α) : add as [] = as := begin rw [add, @pointwise_nil α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, add_zero], refl end lemma map_add_map {α : Type u} [add_monoid α] (f g : α → α) {as : list α} : add (as.map f) (as.map g) = as.map (λ x, f x + g x) := begin apply @eq_of_equiv _ (⟨0⟩ : inhabited α), { rw [length_map, length_add, max_eq_left, length_map], apply le_of_eq, rw [length_map, length_map] }, intros m, rw [get_add], by_cases h : m < length as, { repeat {rw [@get_map α α ⟨0⟩ ⟨0⟩ _ _ _ h]} }, rw not_lt at h, repeat {rw [get_eq_default_of_le m]}; try {rw length_map, apply h}, apply zero_add end /- sub -/ @[simp] lemma get_sub {α : Type u} [add_group α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (sub xs ys) = (@get α ⟨0⟩ k xs - @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply sub_zero} @[simp] lemma length_sub [has_zero α] [has_sub α] {xs ys : list α} : (sub xs ys).length = _root_.max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_sub {α : Type} [add_group α] (as : list α) : sub [] as = neg as := begin rw [sub, nil_pointwise], congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, zero_sub] end @[simp] lemma sub_nil {α : Type} [add_group α] (as : list α) : sub as [] = as := begin rw [sub, pointwise_nil], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, sub_zero], refl end end func namespace nat /-- The antidiagonal of a natural number `n` is the list of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : list (ℕ × ℕ) := (range (n+1)).map (λ i, (i, n - i)) /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := begin rw [antidiagonal, mem_map], split, { rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_sub_of_le hi }, { rintro rfl, refine ⟨x.fst, _, _⟩, { rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ }, { exact prod.ext rfl (nat.add_sub_cancel_left _ _) } } end /-- The length of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 := by rw [antidiagonal, length_map, length_range] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] := ext_le (length_antidiagonal 0) $ λ n h₁ h₂, begin rw [length_antidiagonal, lt_succ_iff, le_zero_iff] at h₁, subst n, simp [antidiagonal] end /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := nodup_map (@injective_of_left_inverse ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl) (nodup_range _) end nat end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x
1833e36ca7057b2cc946fd65212a4798df156629
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/dedekind_domain/selmer_group.lean
adcbbfc9e1fb39003619e30841c8667e914dd114
[ "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,854
lean
/- Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Kurniadi Angdinata -/ import algebra.hom.equiv.type_tags import data.zmod.quotient import ring_theory.dedekind_domain.adic_valuation import ring_theory.norm /-! # Selmer groups of fraction fields of Dedekind domains > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let $K$ be the field of fractions of a Dedekind domain $R$. For any set $S$ of prime ideals in the height one spectrum of $R$, and for any natural number $n$, the Selmer group $K(S, n)$ is defined to be the subgroup of the unit group $K^\times$ modulo $n$-th powers where each element has $v$-adic valuation divisible by $n$ for all prime ideals $v$ away from $S$. In other words, this is precisely $$ K(S, n) := \{x(K^\times)^n \in K^\times / (K^\times)^n \ \mid \ \forall v \notin S, \ \mathrm{ord}_v(x) \equiv 0 \pmod n\}. $$ There is a fundamental short exact sequence $$ 1 \to R_S^\times / (R_S^\times)^n \to K(S, n) \to \mathrm{Cl}_S(R)[n] \to 0, $$ where $R_S^\times$ is the $S$-unit group of $R$ and $\mathrm{Cl}_S(R)$ is the $S$-class group of $R$. If the flanking groups are both finite, then $K(S, n)$ is finite by the first isomorphism theorem. Such is the case when $R$ is the ring of integers of a number field $K$, $S$ is finite, and $n$ is positive, in which case $R_S^\times$ is finitely generated by Dirichlet's unit theorem and $\mathrm{Cl}_S(R)$ is finite by the class number theorem. This file defines the Selmer group $K(S, n)$ and some basic facts. ## Main definitions * `is_dedekind_domain.selmer_group`: the Selmer group. * TODO: maps in the sequence. ## Main statements * TODO: proofs of exactness of the sequence. * TODO: proofs of finiteness for global fields. ## Notations * `K⟮S, n⟯`: the Selmer group with parameters `K`, `S`, and `n`. ## Implementation notes The Selmer group is typically defined as a subgroup of the Galois cohomology group $H^1(K, \mu_n)$ with certain local conditions defined by $v$-adic valuations, where $\mu_n$ is the group of $n$-th roots of unity over a separable closure of $K$. Here $H^1(K, \mu_n)$ is identified with $K^\times / (K^\times)^n$ by the long exact sequence from Kummer theory and Hilbert's theorem 90, and the fundamental short exact sequence becomes an easy consequence of the snake lemma. This file will define all the maps explicitly for computational purposes, but isomorphisms to the Galois cohomological definition will be provided when possible. ## References https://doc.sagemath.org/html/en/reference/number_fields/sage/rings/number_field/selmer_group.html ## Tags class group, selmer group, unit group -/ local notation (name := quot) K/n := Kˣ ⧸ (pow_monoid_hom n : Kˣ →* Kˣ).range namespace is_dedekind_domain noncomputable theory open_locale classical discrete_valuation non_zero_divisors universes u v variables {R : Type u} [comm_ring R] [is_domain R] [is_dedekind_domain R] {K : Type v} [field K] [algebra R K] [is_fraction_ring R K] (v : height_one_spectrum R) /-! ### Valuations of non-zero elements -/ namespace height_one_spectrum /-- The multiplicative `v`-adic valuation on `Kˣ`. -/ def valuation_of_ne_zero_to_fun (x : Kˣ) : multiplicative ℤ := let hx := is_localization.sec R⁰ (x : K) in multiplicative.of_add $ (-(associates.mk v.as_ideal).count (associates.mk $ ideal.span {hx.fst}).factors : ℤ) - (-(associates.mk v.as_ideal).count (associates.mk $ ideal.span {(hx.snd : R)}).factors : ℤ) @[simp] lemma valuation_of_ne_zero_to_fun_eq (x : Kˣ) : (v.valuation_of_ne_zero_to_fun x : ℤₘ₀) = v.valuation (x : K) := begin change _ = _ * _, rw [units.coe_inv], change _ = ite _ _ _ * (ite (coe _ = _) _ _)⁻¹, rw [is_localization.to_localization_map_sec, if_neg $ is_localization.sec_fst_ne_zero le_rfl x.ne_zero, if_neg $ non_zero_divisors.coe_ne_zero _], any_goals { exact is_domain.to_nontrivial R }, refl end /-- The multiplicative `v`-adic valuation on `Kˣ`. -/ def valuation_of_ne_zero : Kˣ →* multiplicative ℤ := { to_fun := v.valuation_of_ne_zero_to_fun, map_one' := by { rw [← with_zero.coe_inj, valuation_of_ne_zero_to_fun_eq], exact map_one _ }, map_mul' := λ _ _, by { rw [← with_zero.coe_inj, with_zero.coe_mul], simp only [valuation_of_ne_zero_to_fun_eq], exact map_mul _ _ _ } } @[simp] lemma valuation_of_ne_zero_eq (x : Kˣ) : (v.valuation_of_ne_zero x : ℤₘ₀) = v.valuation (x : K) := valuation_of_ne_zero_to_fun_eq v x @[simp] lemma valuation_of_unit_eq (x : Rˣ) : v.valuation_of_ne_zero (units.map (algebra_map R K : R →* K) x) = 1 := begin rw [← with_zero.coe_inj, valuation_of_ne_zero_eq, units.coe_map, eq_iff_le_not_lt], split, { exact v.valuation_le_one x }, { cases x with x _ hx _, change ¬v.valuation (algebra_map R K x) < 1, apply_fun v.int_valuation at hx, rw [map_one, map_mul] at hx, rw [not_lt, ← hx, ← mul_one $ v.valuation _, valuation_of_algebra_map, mul_le_mul_left₀ $ left_ne_zero_of_mul_eq_one hx], exact v.int_valuation_le_one _ } end local attribute [semireducible] mul_opposite /-- The multiplicative `v`-adic valuation on `Kˣ` modulo `n`-th powers. -/ def valuation_of_ne_zero_mod (n : ℕ) : K/n →* multiplicative (zmod n) := (int.quotient_zmultiples_nat_equiv_zmod n).to_multiplicative.to_monoid_hom.comp $ quotient_group.map (pow_monoid_hom n : Kˣ →* Kˣ).range (add_subgroup.zmultiples (n : ℤ)).to_subgroup v.valuation_of_ne_zero begin rintro _ ⟨x, rfl⟩, exact ⟨v.valuation_of_ne_zero x, by simpa only [pow_monoid_hom_apply, map_pow, int.to_add_pow]⟩ end @[simp] lemma valuation_of_unit_mod_eq (n : ℕ) (x : Rˣ) : v.valuation_of_ne_zero_mod n (units.map (algebra_map R K : R →* K) x : K/n) = 1 := by rw [valuation_of_ne_zero_mod, monoid_hom.comp_apply, ← quotient_group.coe_mk', quotient_group.map_mk', valuation_of_unit_eq, quotient_group.coe_one, map_one] end height_one_spectrum /-! ### Selmer groups -/ variables {S S' : set $ height_one_spectrum R} {n : ℕ} /-- The Selmer group `K⟮S, n⟯`. -/ def selmer_group : subgroup $ K/n := { carrier := {x : K/n | ∀ v ∉ S, (v : height_one_spectrum R).valuation_of_ne_zero_mod n x = 1}, one_mem' := λ _ _, by rw [map_one], mul_mem' := λ _ _ hx hy v hv, by rw [map_mul, hx v hv, hy v hv, one_mul], inv_mem' := λ _ hx v hv, by rw [map_inv, hx v hv, inv_one] } localized "notation K`⟮`S, n`⟯` := @selmer_group _ _ _ _ K _ _ _ S n" in selmer_group namespace selmer_group lemma monotone (hS : S ≤ S') : K⟮S, n⟯ ≤ (K⟮S', n⟯) := λ _ hx v, hx v ∘ mt (@hS v) /-- The multiplicative `v`-adic valuations on `K⟮S, n⟯` for all `v ∈ S`. -/ def valuation : K⟮S, n⟯ →* S → multiplicative (zmod n) := { to_fun := λ x v, (v : height_one_spectrum R).valuation_of_ne_zero_mod n (x : K/n), map_one' := funext $ λ v, map_one _, map_mul' := λ x y, funext $ λ v, map_mul _ x y } lemma valuation_ker_eq : valuation.ker = (K⟮(∅ : set $ height_one_spectrum R), n⟯).subgroup_of (K⟮S, n⟯) := begin ext ⟨_, hx⟩, split, { intros hx' v _, by_cases hv : v ∈ S, { exact congr_fun hx' ⟨v, hv⟩ }, { exact hx v hv } }, { exact λ hx', funext $ λ v, hx' v $ set.not_mem_empty v } end /-- The natural homomorphism from `Rˣ` to `K⟮∅, n⟯`. -/ def from_unit {n : ℕ} : Rˣ →* K⟮(∅ : set $ height_one_spectrum R), n⟯ := { to_fun := λ x, ⟨quotient_group.mk $ units.map (algebra_map R K).to_monoid_hom x, λ v _, v.valuation_of_unit_mod_eq n x⟩, map_one' := by simpa only [map_one], map_mul' := λ _ _, by simpa only [map_mul] } lemma from_unit_ker [hn : fact $ 0 < n] : (@from_unit R _ _ _ K _ _ _ n).ker = (pow_monoid_hom n : Rˣ →* Rˣ).range := begin ext ⟨_, _, _, _⟩, split, { intro hx, rcases (quotient_group.eq_one_iff _).mp (subtype.mk.inj hx) with ⟨⟨v, i, vi, iv⟩, hx⟩, have hv : ↑(_ ^ n : Kˣ) = algebra_map R K _ := congr_arg units.val hx, have hi : ↑(_ ^ n : Kˣ)⁻¹ = algebra_map R K _ := congr_arg units.inv hx, rw [units.coe_pow] at hv, rw [← inv_pow, units.inv_mk, units.coe_pow] at hi, rcases @is_integrally_closed.exists_algebra_map_eq_of_is_integral_pow R _ _ _ _ _ _ _ v _ hn.out (hv.symm ▸ is_integral_algebra_map) with ⟨v', rfl⟩, rcases @is_integrally_closed.exists_algebra_map_eq_of_is_integral_pow R _ _ _ _ _ _ _ i _ hn.out (hi.symm ▸ is_integral_algebra_map) with ⟨i', rfl⟩, rw [← map_mul, map_eq_one_iff _ $ no_zero_smul_divisors.algebra_map_injective R K] at vi, rw [← map_mul, map_eq_one_iff _ $ no_zero_smul_divisors.algebra_map_injective R K] at iv, rw [units.coe_mk, ← map_pow] at hv, exact ⟨⟨v', i', vi, iv⟩, by simpa only [units.ext_iff, pow_monoid_hom_apply, units.coe_pow] using no_zero_smul_divisors.algebra_map_injective R K hv⟩ }, { rintro ⟨_, hx⟩, rw [← hx], exact subtype.mk_eq_mk.mpr ((quotient_group.eq_one_iff _).mpr ⟨_, by simp only [pow_monoid_hom_apply, map_pow]⟩) } end /-- The injection induced by the natural homomorphism from `Rˣ` to `K⟮∅, n⟯`. -/ def from_unit_lift [fact $ 0 < n] : R/n →* K⟮(∅ : set $ height_one_spectrum R), n⟯ := (quotient_group.ker_lift _).comp (quotient_group.quotient_mul_equiv_of_eq from_unit_ker).symm.to_monoid_hom lemma from_unit_lift_injective [fact $ 0 < n] : function.injective $ @from_unit_lift R _ _ _ K _ _ _ n _ := function.injective.comp (quotient_group.ker_lift_injective _) (mul_equiv.injective _) end selmer_group end is_dedekind_domain
9f1b3f6baec9337e2e8bf78ee4f4060d341e7439
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/submonoid/basic.lean
34d40b22dea98e39a7d433503c090e2b608cbbd2
[ "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
21,981
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import algebra.hom.group -- Only needed for notation import algebra.group.units import group_theory.subsemigroup.basic /-! # Submonoids: definition and `complete_lattice` structure > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines bundled multiplicative and additive submonoids. We also define a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid that includes this set, and prove a few results about extending properties from a dense set (i.e. a set with `closure s = ⊤`) to the whole monoid, see `submonoid.dense_induction` and `monoid_hom.of_mclosure_eq_top_left`/`monoid_hom.of_mclosure_eq_top_right`. ## Main definitions * `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`. * `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`. For each of the following definitions in the `submonoid` namespace, there is a corresponding definition in the `add_submonoid` namespace. * `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly not definitionally equal to the carrier of the original `submonoid`. * `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set. * `submonoid.gi` : `closure : set M → submonoid M` and coercion `coe : submonoid M → set M` form a `galois_insertion`; * `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`; * `monoid_hom.of_mclosure_eq_top_right`: if a map `f : M → N` between two monoids satisfies `f 1 = 1` and `f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism. E.g., if `f : ℕ → M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive monoid homomorphism. ## Implementation notes Submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. Note that `submonoid M` does not actually require `monoid M`, instead requiring only the weaker `mul_one_class M`. This file is designed to have very few dependencies. In particular, it should not use natural numbers. `submonoid` is implemented by extending `subsemigroup` requiring `one_mem'`. ## Tags submonoid, submonoids -/ variables {M : Type*} {N : Type*} variables {A : Type*} section non_assoc variables [mul_one_class M] {s : set M} variables [add_zero_class A] {t : set A} /-- `one_mem_class S M` says `S` is a type of subsets `s ≤ M`, such that `1 ∈ s` for all `s`. -/ class one_mem_class (S M : Type*) [has_one M] [set_like S M] : Prop := (one_mem : ∀ (s : S), (1 : M) ∈ s) export one_mem_class (one_mem) /-- `zero_mem_class S M` says `S` is a type of subsets `s ≤ M`, such that `0 ∈ s` for all `s`. -/ class zero_mem_class (S M : Type*) [has_zero M] [set_like S M] : Prop := (zero_mem : ∀ (s : S), (0 : M) ∈ s) export zero_mem_class (zero_mem) attribute [to_additive] one_mem_class section set_option old_structure_cmd true /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ @[ancestor subsemigroup] structure submonoid (M : Type*) [mul_one_class M] extends subsemigroup M := (one_mem' : (1 : M) ∈ carrier) end /-- A submonoid of a monoid `M` can be considered as a subsemigroup of that monoid. -/ add_decl_doc submonoid.to_subsemigroup /-- `submonoid_class S M` says `S` is a type of subsets `s ≤ M` that contain `1` and are closed under `(*)` -/ class submonoid_class (S M : Type*) [mul_one_class M] [set_like S M] extends mul_mem_class S M, one_mem_class S M : Prop section set_option old_structure_cmd true /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ @[ancestor add_subsemigroup] structure add_submonoid (M : Type*) [add_zero_class M] extends add_subsemigroup M := (zero_mem' : (0 : M) ∈ carrier) end /-- An additive submonoid of an additive monoid `M` can be considered as an additive subsemigroup of that additive monoid. -/ add_decl_doc add_submonoid.to_add_subsemigroup /-- `add_submonoid_class S M` says `S` is a type of subsets `s ≤ M` that contain `0` and are closed under `(+)` -/ class add_submonoid_class (S M : Type*) [add_zero_class M] [set_like S M] extends add_mem_class S M, zero_mem_class S M : Prop attribute [to_additive] submonoid submonoid_class @[to_additive] lemma pow_mem {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] {S : A} {x : M} (hx : x ∈ S) : ∀ (n : ℕ), x ^ n ∈ S | 0 := by { rw pow_zero, exact one_mem_class.one_mem S } | (n + 1) := by { rw pow_succ, exact mul_mem_class.mul_mem hx (pow_mem n) } namespace submonoid @[to_additive] instance : set_like (submonoid M) M := { coe := submonoid.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } @[to_additive] instance : submonoid_class (submonoid M) M := { one_mem := submonoid.one_mem', mul_mem := submonoid.mul_mem' } /-- See Note [custom simps projection] -/ @[to_additive " See Note [custom simps projection]"] def simps.coe (S : submonoid M) : set M := S initialize_simps_projections submonoid (carrier → coe) initialize_simps_projections add_submonoid (carrier → coe) @[simp, to_additive] lemma mem_carrier {s : submonoid M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma mem_mk {s : set M} {x : M} (h_one) (h_mul) : x ∈ mk s h_one h_mul ↔ x ∈ s := iff.rfl @[simp, to_additive] lemma coe_set_mk {s : set M} (h_one) (h_mul) : (mk s h_one h_mul : set M) = s := rfl @[simp, to_additive] lemma mk_le_mk {s t : set M} (h_one) (h_mul) (h_one') (h_mul') : mk s h_one h_mul ≤ mk t h_one' h_mul' ↔ s ⊆ t := iff.rfl /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/ @[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."] protected def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M := { carrier := s, one_mem' := hs.symm ▸ S.one_mem', mul_mem' := λ _ _, hs.symm ▸ S.mul_mem' } variable {S : submonoid M} @[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) : (S.copy s hs : set M) = s := rfl @[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S := set_like.coe_injective hs variable (S) /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] protected theorem one_mem : (1 : M) ∈ S := one_mem S /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] protected theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := mul_mem /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The additive submonoid `M` of the `add_monoid M`."] instance : has_top (submonoid M) := ⟨{ carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩ /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] instance : has_bot (submonoid M) := ⟨{ carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := λ a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩ @[to_additive] instance : inhabited (submonoid M) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : submonoid M) : set M) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : submonoid M) : set M) = {1} := rfl /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] instance : has_inf (submonoid M) := ⟨λ S₁ S₂, { carrier := S₁ ∩ S₂, one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩ @[simp, to_additive] lemma coe_inf (p p' : submonoid M) : ((p ⊓ p' : submonoid M) : set M) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, one_mem' := set.mem_bInter $ λ i h, i.one_mem, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_Inter₂.1 hx i h) (by apply set.mem_Inter₂.1 hy i h) }⟩ @[simp, norm_cast, to_additive] lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = ⋂ s ∈ S, ↑s := rfl @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → submonoid M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, norm_cast, to_additive] lemma coe_infi {ι : Sort*} {S : ι → submonoid M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (submonoid M) $ λ s, is_glb.of_image (λ S T, show (S : set M) ≤ T ↔ S ≤ T, from set_like.coe_subset_coe) is_glb_binfi } @[simp, to_additive] lemma subsingleton_iff : subsingleton (submonoid M) ↔ subsingleton M := ⟨ λ h, by exactI ⟨λ x y, have ∀ i : M, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : submonoid M) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩, λ h, by exactI ⟨λ x y, submonoid.ext $ λ i, subsingleton.elim 1 i ▸ by simp [submonoid.one_mem]⟩⟩ @[simp, to_additive] lemma nontrivial_iff : nontrivial (submonoid M) ↔ nontrivial M := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton M] : unique (submonoid M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mpr ‹_›) a _⟩ @[to_additive] instance [nontrivial M] : nontrivial (submonoid M) := nontrivial_iff.mpr ‹_› /-- The `submonoid` generated by a set. -/ @[to_additive "The `add_submonoid` generated by a set"] def closure (s : set M) : submonoid M := Inf {S | s ⊆ S} @[to_additive] lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : submonoid M, s ⊆ S → x ∈ S := mem_Inf /-- The submonoid generated by a set includes the set. -/ @[simp, to_additive "The `add_submonoid` generated by a set includes the set."] lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx @[to_additive] lemma not_mem_of_not_mem_closure {P : M} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) variable {S} open set /-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/ @[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"] lemma closure_le : closure s ≤ S ↔ s ⊆ S := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ /-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ @[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`"] lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ subset.trans h subset_closure @[to_additive] lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S := le_antisymm (closure_le.2 h₁) h₂ variable (S) /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator, to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all elements of the additive closure of `s`."] lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, Hmul, H1⟩).2 Hs h /-- A dependent version of `submonoid.closure_induction`. -/ @[elab_as_eliminator, to_additive "A dependent version of `add_submonoid.closure_induction`. "] lemma closure_induction' (s : set M) {p : Π x, x ∈ closure s → Prop} (Hs : ∀ x (h : x ∈ s), p x (subset_closure h)) (H1 : p 1 (one_mem _)) (Hmul : ∀ x hx y hy, p x hx → p y hy → p (x * y) (mul_mem hx hy)) {x} (hx : x ∈ closure s) : p x hx := begin refine exists.elim _ (λ (hx : x ∈ closure s) (hc : p x hx), hc), exact closure_induction hx (λ x hx, ⟨_, Hs x hx⟩) ⟨_, H1⟩ (λ x y ⟨hx', hx⟩ ⟨hy', hy⟩, ⟨_, Hmul _ _ _ _ hx hy⟩), end /-- An induction principle for closure membership for predicates with two arguments. -/ @[elab_as_eliminator, to_additive "An induction principle for additive closure membership for predicates with two arguments."] lemma closure_induction₂ {p : M → M → Prop} {x} {y : M} (hx : x ∈ closure s) (hy : y ∈ closure s) (Hs : ∀ (x ∈ s) (y ∈ s), p x y) (H1_left : ∀ x, p 1 x) (H1_right : ∀ x, p x 1) (Hmul_left : ∀ x y z, p x z → p y z → p (x * y) z) (Hmul_right : ∀ x y z, p z x → p z y → p z (x * y)) : p x y := closure_induction hx (λ x xs, closure_induction hy (Hs x xs) (H1_right x) (λ z y h₁ h₂, Hmul_right z _ _ h₁ h₂)) (H1_left y) (λ x z h₁ h₂, Hmul_left _ _ _ h₁ h₂) /-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 1`, and verify that `p x` and `p y` imply `p (x * y)`. -/ @[elab_as_eliminator, to_additive "If `s` is a dense set in an additive monoid `M`, `add_submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 0`, and verify that `p x` and `p y` imply `p (x + y)`."] lemma dense_induction {p : M → Prop} (x : M) {s : set M} (hs : closure s = ⊤) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := have ∀ x ∈ closure s, p x, from λ x hx, closure_induction hx Hs H1 Hmul, by simpa [hs] using this x variable (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure M _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {M} /-- Closure of a submonoid `S` equals `S`. -/ @[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"] lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S @[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ := (submonoid.gi M).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ := @coe_top M _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t := (submonoid.gi M).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (submonoid.gi M).gc.l_supr @[simp, to_additive] lemma closure_singleton_le_iff_mem (m : M) (p : submonoid M) : closure {m} ≤ p ↔ m ∈ p := by rw [closure_le, singleton_subset_iff, set_like.mem_coe] @[to_additive] lemma mem_supr {ι : Sort*} (p : ι → submonoid M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← closure_singleton_le_iff_mem, le_supr_iff], simp only [closure_singleton_le_iff_mem], end @[to_additive] lemma supr_eq_closure {ι : Sort*} (p : ι → submonoid M) : (⨆ i, p i) = submonoid.closure (⋃ i, (p i : set M)) := by simp_rw [submonoid.closure_Union, submonoid.closure_eq] @[to_additive] lemma disjoint_def {p₁ p₂ : submonoid M} : disjoint p₁ p₂ ↔ ∀ {x : M}, x ∈ p₁ → x ∈ p₂ → x = 1 := by simp_rw [disjoint_iff_inf_le, set_like.le_def, mem_inf, and_imp, mem_bot] @[to_additive] lemma disjoint_def' {p₁ p₂ : submonoid M} : disjoint p₁ p₂ ↔ ∀ {x y : M}, x ∈ p₁ → y ∈ p₂ → x = y → x = 1 := disjoint_def.trans ⟨λ h x y hx hy hxy, h hx $ hxy.symm ▸ hy, λ h x hx hx', h hx hx' rfl⟩ end submonoid namespace monoid_hom variables [mul_one_class N] open submonoid /-- The submonoid of elements `x : M` such that `f x = g x` -/ @[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"] def eq_mlocus (f g : M →* N) : submonoid M := { carrier := {x | f x = g x}, one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one], mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] } @[simp, to_additive] lemma eq_mlocus_same (f : M →* N) : f.eq_mlocus f = ⊤ := set_like.ext $ λ _, eq_self_iff_true _ /-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/ @[to_additive "If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure."] lemma eq_on_mclosure {f g : M →* N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_mlocus g, from closure_le.2 h @[to_additive] lemma eq_of_eq_on_mtop {f g : M →* N} (h : set.eq_on f g (⊤ : submonoid M)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h end monoid_hom end non_assoc section assoc variables [monoid M] [monoid N] {s : set M} section is_unit /-- The submonoid consisting of the units of a monoid -/ @[to_additive "The additive submonoid consisting of the additive units of an additive monoid"] def is_unit.submonoid (M : Type*) [monoid M] : submonoid M := { carrier := set_of is_unit, one_mem' := by simp only [is_unit_one, set.mem_set_of_eq], mul_mem' := by { intros a b ha hb, rw set.mem_set_of_eq at *, exact is_unit.mul ha hb } } @[to_additive] lemma is_unit.mem_submonoid_iff {M : Type*} [monoid M] (a : M) : a ∈ is_unit.submonoid M ↔ is_unit a := begin change a ∈ set_of is_unit ↔ is_unit a, rw set.mem_set_of_eq end end is_unit namespace monoid_hom open submonoid /-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid. Then `monoid_hom.of_mclosure_eq_top_left` defines a monoid homomorphism from `M` asking for a proof of `f (x * y) = f x * f y` only for `x ∈ s`. -/ @[to_additive "/-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid. Then `add_monoid_hom.of_mclosure_eq_top_left` defines an additive monoid homomorphism from `M` asking for a proof of `f (x + y) = f x + f y` only for `x ∈ s`. -/"] def of_mclosure_eq_top_left {M N} [monoid M] [monoid N] {s : set M} (f : M → N) (hs : closure s = ⊤) (h1 : f 1 = 1) (hmul : ∀ (x ∈ s) y, f (x * y) = f x * f y) : M →* N := { to_fun := f, map_one' := h1, map_mul' := λ x, dense_induction x hs hmul (λ y, by rw [one_mul, h1, one_mul]) $ λ a b ha hb y, by rw [mul_assoc, ha, ha, hb, mul_assoc] } @[simp, norm_cast, to_additive] lemma coe_of_mclosure_eq_top_left (f : M → N) (hs : closure s = ⊤) (h1 hmul) : ⇑(of_mclosure_eq_top_left f hs h1 hmul) = f := rfl /-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid. Then `monoid_hom.of_mclosure_eq_top_right` defines a monoid homomorphism from `M` asking for a proof of `f (x * y) = f x * f y` only for `y ∈ s`. -/ @[to_additive "/-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid. Then `add_monoid_hom.of_mclosure_eq_top_right` defines an additive monoid homomorphism from `M` asking for a proof of `f (x + y) = f x + f y` only for `y ∈ s`. -/"] def of_mclosure_eq_top_right {M N} [monoid M] [monoid N] {s : set M} (f : M → N) (hs : closure s = ⊤) (h1 : f 1 = 1) (hmul : ∀ x (y ∈ s), f (x * y) = f x * f y) : M →* N := { to_fun := f, map_one' := h1, map_mul' := λ x y, dense_induction y hs (λ y hy x, hmul x y hy) (by simp [h1]) (λ y₁ y₂ h₁ h₂ x, by simp only [← mul_assoc, h₁, h₂]) x } @[simp, norm_cast, to_additive] lemma coe_of_mclosure_eq_top_right (f : M → N) (hs : closure s = ⊤) (h1 hmul) : ⇑(of_mclosure_eq_top_right f hs h1 hmul) = f := rfl end monoid_hom end assoc
0a502bb17a3c15e2423496390786aa880a6affa5
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/solutions/thursday/category_theory/exercise3.lean
1690bbac305fa4fcbe31603bdccba060c3da3c3d
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,023
lean
import category_theory.equivalence open category_theory variables {C : Type*} [category C] variables {D : Type*} [category D] lemma equiv_reflects_mono {X Y : C} (f : X ⟶ Y) (e : C ≌ D) (hef : mono (e.functor.map f)) : mono f := -- Hint: when `e : C ≌ D`, `e.functor.map_injective` says -- `∀ f g, e.functor.map f = e.functor.map g → f = g` -- Hint: use `cancel_mono`. -- sorry begin tidy, apply e.functor.map_injective, apply (cancel_mono (e.functor.map f)).1, apply e.inverse.map_injective, simp, assumption end -- sorry lemma equiv_preserves_mono {X Y : C} (f : X ⟶ Y) [mono f] (e : C ≌ D) : mono (e.functor.map f) := -- Hint: if `w : f = g`, to obtain `F.map f = F.map G`, -- you can use `have w' := congr_arg (λ k, F.map k) w`. -- sorry begin tidy, replace w := congr_arg (λ k, e.inverse.map k) w, simp at w, simp only [←category.assoc, cancel_mono] at w, simp at w, exact w, end -- sorry /-! There are some further hints in `hints/category_theory/exercise3/` -/
d7ecb0320404b15eecc273920059d96a59b995ef
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Elab/Tactic/Simp.lean
be6e9e7f690fb74be2216c76aed9ab96890cdd2a
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,100
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.Meta.Tactic.Simp import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Location import Lean.Meta.Tactic.Replace namespace Lean.Elab.Tactic open Meta def simpTarget (config : Meta.Simp.Config) (simpLemmas : SimpLemmas) : TacticM Unit := do let (g, gs) ← getMainGoal withMVarContext g do let target ← instantiateMVars (← getMVarDecl g).type let r ← simp target config simpLemmas match r.proof? with | some proof => setGoals ((← replaceTargetEq g r.expr proof) :: gs) | none => setGoals ((← replaceTargetDefEq g r.expr) :: gs) -- TODO: improve simpLocalDecl and simpAll -- TODO: issues: self simplification -- TODO: add new assertion with simplified result and clear old ones after simplifying all locals def simpLocalDeclFVarId (config : Meta.Simp.Config) (simpLemmas : SimpLemmas) (fvarId : FVarId) : TacticM Unit := do let (g, gs) ← getMainGoal withMVarContext g do let localDecl ← getLocalDecl fvarId let r ← simp localDecl.type config simpLemmas match r.proof? with | some proof => setGoals ((← replaceLocalDecl g fvarId r.expr proof).mvarId :: gs) | none => setGoals ((← changeLocalDecl g fvarId r.expr (checkDefEq := false)) :: gs) def simpLocalDecl (config : Meta.Simp.Config) (simpLemmas : SimpLemmas) (userName : Name) : TacticM Unit := withMainMVarContext do let localDecl ← getLocalDeclFromUserName userName simpLocalDeclFVarId config simpLemmas localDecl.fvarId def simpAll (config : Meta.Simp.Config) (simpLemmas : SimpLemmas) : TacticM Unit := do let worked ← «try» (simpTarget config simpLemmas) withMainMVarContext do let mut worked := worked -- We must traverse backwards because `replaceLocalDecl` uses the revert/intro idiom for fvarId in (← getLCtx).getFVarIds.reverse do worked := worked || (← «try» <| simpLocalDeclFVarId config simpLemmas fvarId) unless worked do let (mvarId, _) ← getMainGoal throwTacticEx `simp mvarId "failed to simplify" def tryExactTrivial : TacticM Unit := do let (g, gs) ← getMainGoal let gType ← getMVarType g if gType.isConstOf ``True then assignExprMVar g (mkConst ``True.intro) setGoals gs else pure () unsafe def evalSimpConfigUnsafe (e : Expr) : TermElabM Meta.Simp.Config := Term.evalExpr Meta.Simp.Config ``Meta.Simp.Config e @[implementedBy evalSimpConfigUnsafe] constant evalSimpConfig (e : Expr) : TermElabM Meta.Simp.Config def elabSimpConfig (optConfig : Syntax) : TermElabM Meta.Simp.Config := do if optConfig.isNone then return {} else withLCtx {} {} <| withNewMCtxDepth <| Term.withSynthesize do let c ← Term.elabTermEnsuringType optConfig[0] (Lean.mkConst ``Meta.Simp.Config) evalSimpConfig (← instantiateMVars c) @[builtinTactic Lean.Parser.Tactic.simp] def evalSimp : Tactic := fun stx => do let lemmas ← mkSimpLemmas stx[1] let config ← elabSimpConfig stx[2] let loc := expandOptLocation stx[3] match loc with | Location.target => simpTarget config lemmas | Location.localDecls userNames => userNames.forM (simpLocalDecl config lemmas) | Location.wildcard => simpAll config lemmas tryExactTrivial where mkSimpLemmas (stx : Syntax) := do let lemmas ← getSimpLemmas if stx.isNone then return lemmas else /- syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? term -/ let (g, _) ← getMainGoal withMVarContext g do let mut lemmas := lemmas for simpLemma in stx[1].getSepArgs do let post := if simpLemma[0].isNone then true else simpLemma[0][0].getKind == ``Parser.Tactic.simpPost let term ← elabTerm simpLemma[1] none true lemmas ← lemmas.add term post return lemmas end Lean.Elab.Tactic
506ada8acb25c9ba6739c44df37081d2d23b0df6
f68ef9a599ec5575db7b285d4960e63c5d464ccc
/Exercises/cantor.lean
88a569723fb66e8c8807e97c44ef8b8883964a0e
[]
no_license
lucasmoschen/discrete-mathematics
a38d5970cc571b0b9d202bf6a43efeb8ed6f66e3
0f1945cc5eb094814c926cd6ae4a8b4c5c579a1e
refs/heads/master
1,677,111,757,003
1,611,500,097,000
1,611,500,097,000
205,903,359
1
0
null
null
null
null
UTF-8
Lean
false
false
821
lean
import data.set variables X Y: Type def surjective {X: Type} {Y: Type} (f : X → Y) : Prop := ∀ y, ∃ x, f x = y theorem Cantor : ∀ (A: set X), ¬ ∃ (f: A → set A), surjective f := begin intro A, intro h, cases h with f h1, have h2: ∃ x, f x = {t : A | ¬ (t ∈ f t)}, from h1 {t : A | ¬ (t ∈ f t)}, cases h2 with x h3, apply or.elim (classical.em (x ∈ {t : A | ¬ (t ∈ f t)})), intro h4, have h5: ¬ (x ∈ f x), from h4, rw (eq.symm h3) at h4, apply h5 h4, intro h4, rw (eq.symm h3) at h4, have h5: x ∈ {t : A | ¬ (t ∈ f t)}, from h4, rw (eq.symm h3) at h5, apply h4 h5, end
a34aadc1a012457c9d228a119ca145668dd78098
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/monoidal/discrete.lean
f32ed6597d3198aecd2838197ea1930186fd55e9
[ "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
2,238
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 algebra.hom.group import category_theory.discrete_category import category_theory.monoidal.natural_transformation /-! # Monoids as discrete monoidal categories The discrete category on a monoid is a monoidal category. Multiplicative morphisms induced monoidal functors. -/ universes u open category_theory open category_theory.discrete variables (M : Type u) [monoid M] namespace category_theory @[to_additive discrete.add_monoidal, simps tensor_obj_as tensor_unit_as] instance discrete.monoidal : monoidal_category (discrete M) := { tensor_unit := discrete.mk 1, tensor_obj := λ X Y, discrete.mk (X.as * Y.as), tensor_hom := λ W X Y Z f g, eq_to_hom (by rw [eq_of_hom f, eq_of_hom g]), left_unitor := λ X, discrete.eq_to_iso (one_mul X.as), right_unitor := λ X, discrete.eq_to_iso (mul_one X.as), associator := λ X Y Z, discrete.eq_to_iso (mul_assoc _ _ _ ), } variables {M} {N : Type u} [monoid N] /-- A multiplicative morphism between monoids gives a monoidal functor between the corresponding discrete monoidal categories. -/ @[to_additive discrete.add_monoidal_functor "An additive morphism between add_monoids gives a monoidal functor between the corresponding discrete monoidal categories.", simps] def discrete.monoidal_functor (F : M →* N) : monoidal_functor (discrete M) (discrete N) := { obj := λ X, discrete.mk (F X.as), map := λ X Y f, discrete.eq_to_hom (F.congr_arg (eq_of_hom f)), ε := discrete.eq_to_hom F.map_one.symm, μ := λ X Y, discrete.eq_to_hom (F.map_mul X.as Y.as).symm, } variables {K : Type u} [monoid K] /-- The monoidal natural isomorphism corresponding to composing two multiplicative morphisms. -/ @[to_additive discrete.add_monoidal_functor_comp "The monoidal natural isomorphism corresponding to composing two additive morphisms."] def discrete.monoidal_functor_comp (F : M →* N) (G : N →* K) : discrete.monoidal_functor F ⊗⋙ discrete.monoidal_functor G ≅ discrete.monoidal_functor (G.comp F) := { hom := { app := λ X, 𝟙 _, }, inv := { app := λ X, 𝟙 _, }, } end category_theory
0308f27467df0e132a47e3ef6f76b72787993a43
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/real/cau_seq.lean
ff4f3327c78f5fd618a5381cd956b8a7271106d2
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
25,971
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.big_operators.order /-! # Cauchy sequences A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology. This is a concrete implementation that is useful for simplicity and computability reasons. ## Important definitions * `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val * `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy. * `cau_seq`: the type of Cauchy sequences valued in type `β` with respect to an absolute value function `abv`. ## Tags sequence, cauchy, abs val, absolute value -/ open_locale big_operators /-- A function `f` is an absolute value if it is nonnegative, zero only at 0, additive, and multiplicative. -/ class is_absolute_value {α} [discrete_linear_ordered_field α] {β} [ring β] (f : β → α) : Prop := (abv_nonneg [] : ∀ x, 0 ≤ f x) (abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0) (abv_add [] : ∀ x y, f (x + y) ≤ f x + f y) (abv_mul [] : ∀ x y, f (x * y) = f x * f y) namespace is_absolute_value variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl theorem abv_one' (h : (1:β) ≠ 0) : abv 1 = 1 := (mul_right_inj' $ mt (abv_eq_zero abv).1 h).1 $ by rw [← abv_mul abv, mul_one, mul_one] theorem abv_one {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] : abv 1 = 1 := abv_one' abv one_ne_zero theorem abv_pos {a : β} : 0 < abv a ↔ a ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv] theorem abv_neg (a : β) : abv (-a) = abv a := by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _), ← abv_mul abv, ← abv_mul abv]; simp theorem abv_sub (a b : β) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv_neg abv] theorem abv_inv {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a : β) : abv a⁻¹ = (abv a)⁻¹ := classical.by_cases (λ h : a = 0, by simp [h, abv_zero abv]) (λ h, mul_right_cancel' (mt (abv_eq_zero abv).1 h) $ by rw [← abv_mul abv]; simp [h, mt (abv_eq_zero abv).1 h, abv_one abv]) theorem abv_div {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a b : β) : abv (a / b) = abv a / abv b := by rw [division_def, abv_mul abv, abv_inv abv]; refl lemma abv_sub_le (a b c : β) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : β) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b lemma abs_abv_sub_le_abv_sub (a b : β) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _, by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩ lemma abv_pow {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] (a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n := by induction n; simp [abv_mul abv, pow_succ, abv_one abv, *] end is_absolute_value instance abs_is_absolute_value {α} [discrete_linear_ordered_field α] : is_absolute_value (abs : α → α) := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[nolint ge_or_gt] -- see Note [nolint_ge] theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} : (∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) → ∃ i, ∀ j ≥ i, P j ∧ Q j | ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩ section variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem rat_add_continuous_lemma {ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε := ⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂, by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem rat_mul_continuous_lemma {ε K₁ K₂ : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ → abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε := begin have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _), have εK := div_pos (half_pos ε0) K0, refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)), replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK) (mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) this end @[nolint ge_or_gt] -- see Note [nolint_ge] theorem rat_inv_continuous_lemma {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] {ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) : ∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b → abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε := begin have KK := mul_pos K0 K0, have εK := mul_pos ε0 KK, refine ⟨_, εK, λ a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel ε (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos ε0 KK) KK end end /-- A sequence is Cauchy if the distance between its entries tends to zero. -/ def is_cau_seq {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) (f : ℕ → β) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε namespace is_cau_seq variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₂ (hf : is_cau_seq abv f) {ε : α} (ε0 : ε > 0) : ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := begin refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _), rw ← add_halves ε, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₃ (hf : is_cau_seq abv f) {ε : α} (ε0 : ε > 0) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩ end is_cau_seq /-- `cau_seq β abv` is the type of `β`-valued Cauchy sequences, with respect to the absolute value function `abv`. -/ def cau_seq {α : Type*} [discrete_linear_ordered_field α] (β : Type*) [ring β] (abv : β → α) : Type* := {f : ℕ → β // is_cau_seq abv f} namespace cau_seq variables {α : Type*} [discrete_linear_ordered_field α] section ring variables {β : Type*} [ring β] {abv : β → α} instance : has_coe_to_fun (cau_seq β abv) := ⟨_, subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq β abv) _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2 @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy (f : cau_seq β abv) : ∀ {ε}, ε > 0 → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2 /-- Given a Cauchy sequence `f`, create a Cauchy sequence from a sequence `g` with the same values as `f`. -/ def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv := ⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ variable [is_absolute_value abv] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₂ (f : cau_seq β abv) {ε} : ε > 0 → ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy₃ (f : cau_seq β abv) {ε} : ε > 0 → ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃ theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := ∑ j in finset.range (i+1), abv (f j), have : ∀ j ≤ i, abv (f j) ≤ R, { intros j ij, change (λ j, abv (f j)) j ≤ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, λ j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end @[nolint ge_or_gt] -- see Note [nolint_ge] theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ instance : has_add (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl variable (abv) /-- The constant Cauchy sequence. -/ def const (x : β) : cau_seq β abv := ⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y := ⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩ instance : has_zero (cau_seq β abv) := ⟨const 0⟩ instance : has_one (cau_seq β abv) := ⟨const 1⟩ instance : inhabited (cau_seq β abv) := ⟨0⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl theorem const_add (x y : β) : const (x + y) = const x + const y := ext $ λ i, rfl instance : has_mul (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl theorem const_mul (x y : β) : const (x * y) = const x * const y := ext $ λ i, rfl instance : has_neg (cau_seq β abv) := ⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : β) : const (-x) = -const x := ext $ λ i, rfl instance : ring (cau_seq β abv) := by refine {neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, ..}; { intros, apply ext, simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm] } instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] : comm_ring (cau_seq β abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } theorem const_sub (x y : β) : const (x - y) = const x - const y := by rw [sub_eq_add_neg, const_add, const_neg, sub_eq_add_neg] @[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl /-- `lim_zero f` holds when `f` approaches 0. -/ def lim_zero {abv : β → α} (f : cau_seq β abv) : Prop := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε theorem add_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | ε ε0 := (exists_forall_ge_and (hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $ λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂) theorem mul_lim_zero_right (f : cau_seq β abv) {g} (hg : lim_zero g) : lim_zero (f * g) | ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos ε0 F0).imp $ λ i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem mul_lim_zero_left {f} (g : cau_seq β abv) (hg : lim_zero f) : lim_zero (f * g) | ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in (hg _ $ div_pos ε0 G0).imp $ λ i H j ij, by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _); rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero_right _ hf theorem sub_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := add_lim_zero hf (neg_lim_zero hg) theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) := by simpa using neg_lim_zero hfg theorem zero_lim_zero : lim_zero (0 : cau_seq β abv) | ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩ theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _), λ e, e.symm ▸ zero_lim_zero⟩ instance equiv : setoid (cau_seq β abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], λ f g h, by simpa using neg_lim_zero h, λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε : α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε := (exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $ λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, λ l, by simpa using add_lim_zero h l⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (λ ε ε0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos ε0) with i hi, rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩, refine ⟨j, λ k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : ℕ → β) (g : cau_seq β abv) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f | ε ε0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in ⟨i, λ j ij, begin cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f := assume : lim_zero f, have lim_zero (f - 0), by simpa, hf this lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 := have lim_zero (f - 0), from hf, have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa, show lim_zero (g*f - 0), by simpa lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 := assume : lim_zero (f*g - 0), have hlz : lim_zero (f*g), by simpa, have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf), have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg), begin rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩, rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩, have : a1 * a2 > 0, from mul_pos ha1 ha2, cases hlz _ this with N hN, let i := max N (max N1 N2), have hN' := hN i (le_max_left _ _), have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)), have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)), apply not_le_of_lt hN', change _ ≤ abv (_ * _), rw is_absolute_value.abv_mul abv, apply mul_le_mul; try { assumption }, { apply le_of_lt ha2 }, { apply is_absolute_value.abv_nonneg abv } end theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] end ring section comm_ring variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 := by rw mul_comm; apply mul_equiv_zero _ hf end comm_ring section integral_domain variables {β : Type*} [integral_domain β] (abv : β → α) [is_absolute_value abv] lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) := assume h, have ∀ ε > 0, ∃ i, ∀ k, k ≥ i → abv (1 - 0) < ε, from h, have h1 : abv 1 ≤ 0, from le_of_not_gt $ assume h2 : abv 1 > 0, exists.elim (this _ h2) $ λ i hi, lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _), have h2 : abv 1 ≥ 0, from is_absolute_value.abv_nonneg _ _, have abv 1 = 0, from le_antisymm h1 h2, have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this, absurd this one_ne_zero end integral_domain section field variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩ /-- Given a Cauchy sequence `f` with nonzero limit, create a Cauchy sequence with values equal to the inverses of the values of `f`. -/ def inv (f : cau_seq β abv) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 := λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, λ j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using ε0⟩ theorem const_inv {x : β} (hx : x ≠ 0) : const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := ext (assume n, by simp[inv_apply, const_apply]) end field section abs local notation `const` := const abs /-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/ def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, h₂⟩ := h _ (le_refl _) in not_lt_of_le h₁ (abs_lt.1 h₂).2 theorem const_pos {x : α} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)), λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩ theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩ theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, λ j ij, begin cases h j ij with h₁ h₂, have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (λ h, ⟨K, K0, i, λ j ij, _⟩); have := (hi _ ij).1; cases hi _ (le_refl _) with h₁ h₂, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ h₂ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ } end instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq α abs} (fg : f < g) (gh : g ≈ h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq α abs} (fg : f ≈ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) lemma le_of_eq_of_le {f g h : cau_seq α abs} (hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h := hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg) (or.inr ∘ setoid.trans hfg) lemma le_of_le_of_eq {f g h : cau_seq α abs} (hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h := hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh)) (λ h, or.inr (setoid.trans h hgh)) instance : preorder (cau_seq α abs) := { lt := (<), le := λ f g, f < g ∨ f ≈ g, le_refl := λ f, or.inr (setoid.refl _), le_trans := λ f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := λ f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_right (mt (λ h, or.inr (setoid.symm h)) h₂)⟩ } theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f := (trichotomy (g - f)).imp_right (λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : α} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv lemma le_of_exists {f g : cau_seq α abs} (h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g := let ⟨i, hi⟩ := h in (or.assoc.2 (cau_seq.lt_total f g)).elim id (λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in not_lt_of_ge (hi (max i j) (le_max_left _ _)) (sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _)))))) theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, λ i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ end abs end cau_seq
92e2dc226296779ecf508b9a9927d51d5d88e0a8
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Meta/LevelDefEq.lean
05298df335447ad9edc23b3c501dfdca2fd4f844
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,935
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 -/ import Lean.Util.CollectMVars import Lean.Util.ReplaceExpr import Lean.Meta.Basic import Lean.Meta.InferType namespace Lean.Meta private partial def decAux? : Level → MetaM (Option Level) | Level.zero _ => return none | Level.param _ _ => return none | Level.mvar mvarId _ => do let mctx ← getMCtx match mctx.getLevelAssignment? mvarId with | some u => decAux? u | none => if (← isReadOnlyLevelMVar mvarId) then return none else let u ← mkFreshLevelMVar assignLevelMVar mvarId (mkLevelSucc u) return u | Level.succ u _ => return u | u => let process (u v : Level) : MetaM (Option Level) := do match (← decAux? u) with | none => return none | some u => do match (← decAux? v) with | none => return none | some v => return mkLevelMax' u v match u with | Level.max u v _ => process u v /- Remark: If `decAux? v` returns `some ...`, then `imax u v` is equivalent to `max u v`. -/ | Level.imax u v _ => process u v | _ => unreachable! def decLevel? (u : Level) : MetaM (Option Level) := do let mctx ← getMCtx match (← decAux? u) with | some v => return some v | none => do modify fun s => { s with mctx := mctx } return none def decLevel (u : Level) : MetaM Level := do match (← decLevel? u) with | some u => return u | none => throwError "invalid universe level, {u} is not greater than 0" /- This method is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`. Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level, and then decrement 1 to obtain `u`. -/ def getDecLevel (type : Expr) : MetaM Level := do decLevel (← getLevel type) /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v _ => visit u || visit v | _ => false where visit : Level → Bool | Level.max u v _ => visit u || visit v | u => u != lvl && lvl.occurs u /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : MVarId) : Level → Level → Level | Level.max u v _, acc => mkMaxArgsDiff mvarId v <| mkMaxArgsDiff mvarId u acc | l@(Level.mvar id _), acc => if id != mvarId then mkLevelMax' acc l else acc | l, acc => mkLevelMax' acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : MVarId) (v : Level) : MetaM Unit := do assert! v.isMax let n ← mkFreshLevelMVar assignLevelMVar mvarId <| mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := do let ref ← getRef let ctx ← read trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" modifyPostponed fun postponed => postponed.push { lhs := lhs, rhs := rhs, ref := ref, ctx? := ctx.defEqCtx? } private def isMVarWithGreaterDepth (v : Level) (mvarId : MVarId) : MetaM Bool := match v with | Level.mvar mvarId' _ => return (← getLevelMVarDepth mvarId') > (← getLevelMVarDepth mvarId) | _ => return false mutual private partial def solve (u v : Level) : MetaM LBool := do match u, v with | Level.mvar mvarId _, _ => if (← isReadOnlyLevelMVar mvarId) then return LBool.undef else if (← getConfig).ignoreLevelMVarDepth && (← isMVarWithGreaterDepth v mvarId) then -- If both `u` and `v` are both metavariables, but depth of v is greater, then we assign `v := u`. -- This can only happen when `ignoreLevelDepth` is set to true. assignLevelMVar v.mvarId! u return LBool.true else if !u.occurs v then assignLevelMVar u.mvarId! v return LBool.true else if v.isMax && !strictOccursMax u v then solveSelfMax u.mvarId! v return LBool.true else return LBool.undef | _, Level.mvar .. => LBool.undef -- Let `solve v u` to handle this case | Level.zero _, Level.max v₁ v₂ _ => Bool.toLBool <$> (isLevelDefEqAux levelZero v₁ <&&> isLevelDefEqAux levelZero v₂) | Level.zero _, Level.imax _ v₂ _ => Bool.toLBool <$> isLevelDefEqAux levelZero v₂ | Level.zero _, Level.succ .. => return LBool.false | Level.succ u _, v => if v.isParam then return LBool.false else if u.isMVar && u.occurs v then return LBool.undef else match (← Meta.decLevel? v) with | some v => Bool.toLBool <$> isLevelDefEqAux u v | none => return LBool.undef | _, _ => return LBool.undef partial def isLevelDefEqAux : Level → Level → MetaM Bool | Level.succ lhs _, Level.succ rhs _ => isLevelDefEqAux lhs rhs | lhs, rhs => do if lhs.getLevelOffset == rhs.getLevelOffset then return lhs.getOffset == rhs.getOffset else trace[Meta.isLevelDefEq.step] "{lhs} =?= {rhs}" let lhs' ← instantiateLevelMVars lhs let lhs' := lhs'.normalize let rhs' ← instantiateLevelMVars rhs let rhs' := rhs'.normalize if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else let r ← solve lhs rhs; if r != LBool.undef then return r == LBool.true else let r ← solve rhs lhs; if r != LBool.undef then return r == LBool.true else do let mctx ← getMCtx if !mctx.hasAssignableLevelMVar lhs && !mctx.hasAssignableLevelMVar rhs then let ctx ← read if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" Meta.throwIsDefEqStuck else return false else postponeIsLevelDefEq lhs rhs return true end def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false private def getNumPostponed : MetaM Nat := do return (← getPostponed).size open Std (PersistentArray) def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps /-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/ private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr := e.replace fun | Expr.const _ us _ => if us.any p then some (e.setPPUniverses true) else none | Expr.sort u _ => if p u then some (e.setPPUniverses true) else none | _ => none private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do match entry.ctx? with | none => return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}" | some ctx => withLCtx ctx.lctx ctx.localInstances do let s := entry.lhs.collectMVars entry.rhs.collectMVars /- `p u` is true if it contains a universe metavariable in `s` -/ let p (u : Level) := u.any fun | Level.mvar m _ => s.contains m | _ => false let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p try addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}" catch _ => addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}" def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "stuck at solving universe constraint" entry def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "failed to solve universe constraint" entry private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := traceCtx `Meta.isLevelDefEq.postponed.step do let ps ← getResetPostponed for p in ps do unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do if exceptionOnFailure then throwError (← mkLevelErrorMessage p) else return false return true partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else traceCtx `Meta.isLevelDefEq.postponed do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else trace[Meta.isLevelDefEq.postponed] "processing #{numPostponed} postponed is-def-eq level constraints" if !(← processPostponedStep exceptionOnFailure) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints" return mayPostpone loop /-- `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning. We currently try to postpone universe constraints as much as possible, even when by postponing them we are not sure whether `x` really succeeded or not. -/ @[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let s ← saveState let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then let newPostponed ← getPostponed setPostponed (postponed ++ newPostponed) return true else s.restore return false else s.restore return false catch ex => s.restore throw ex def isLevelDefEq (u v : Level) : MetaM Bool := traceCtx `Meta.isLevelDefEq do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v trace[Meta.isLevelDefEq] "{u} =?= {v} ... {if b then "success" else "failure"}" return b def isExprDefEq (t s : Expr) : MetaM Bool := traceCtx `Meta.isDefEq <| withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do let b ← checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s trace[Meta.isDefEq] "{t} =?= {s} ... {if b then "success" else "failure"}" return b abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s builtin_initialize registerTraceClass `Meta.isLevelDefEq registerTraceClass `Meta.isLevelDefEq.step registerTraceClass `Meta.isLevelDefEq.postponed end Lean.Meta
5823248d81d43b7dd321288fd849da7840f79045
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/field_theory/adjoin.lean
36ab02ab7b3eec5af6ddc6bcf0a0eaa91b2321db
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,305
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.intermediate_field import field_theory.splitting_field import field_theory.separable import ring_theory.adjoin_root import ring_theory.power_basis /-! # Adjoining Elements to Fields In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`. - `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x` in `E` then `F = E` ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ open finite_dimensional polynomial open_locale classical namespace intermediate_field section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin : intermediate_field F E := { algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)), ..subfield.closure (set.range (algebra_map F E) ∪ S) } end adjoin_def section lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] @[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T := ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H, λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr (set.union_subset (intermediate_field.set_range_subset T) H)⟩ lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff /-- Galois insertion between `adjoin` and `coe`. -/ def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe := { choice := λ S _, adjoin F S, gc := intermediate_field.gc, le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (intermediate_field F E) := galois_insertion.lift_complete_lattice intermediate_field.gi instance : inhabited (intermediate_field F E) := ⟨⊤⟩ lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) := begin suffices : set.range (algebra_map F E) = (⊥ : intermediate_field F E), { rw this, refl }, { change set.range (algebra_map F E) = subfield.closure (set.range (algebra_map F E) ∪ ∅), simp [←set.image_univ, ←ring_hom.map_field_closure] } end lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) := subfield.subset_closure $ or.inr trivial @[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ := by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] } @[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ := by { ext, rw [mem_to_subalgebra, iff_true_right algebra.mem_top], exact mem_top } /-- Construct an algebra isomorphism from an equality of intermediate fields -/ @[simps apply] def equiv_of_eq {S T : intermediate_field F E} (h : S = T) : S ≃ₐ[F] T := by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy @[simp] lemma equiv_of_eq_symm {S T : intermediate_field F E} (h : S = T) : (equiv_of_eq h).symm = equiv_of_eq h.symm := rfl @[simp] lemma equiv_of_eq_rfl (S : intermediate_field F E) : equiv_of_eq (rfl : S = S) = alg_equiv.refl := by { ext, refl } @[simp] lemma equiv_of_eq_trans {S T U : intermediate_field F E} (hST : S = T) (hTU : T = U) : (equiv_of_eq hST).trans (equiv_of_eq hTU) = equiv_of_eq (trans hST hTU) := rfl variables (F E) /-- The bottom intermediate_field is isomorphic to the field. -/ noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F := (subalgebra.equiv_of_eq _ _ bot_to_subalgebra).trans (algebra.bot_equiv F E) variables {F E} @[simp] lemma bot_equiv_def (x : F) : bot_equiv F E (algebra_map F (⊥ : intermediate_field F E) x) = x := alg_equiv.commutes (bot_equiv F E) x noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F := (intermediate_field.bot_equiv F E).to_alg_hom.to_ring_hom.to_algebra instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E := is_scalar_tower.of_algebra_map_eq begin intro x, let ϕ := algebra.of_id F (⊥ : subalgebra F E), let ψ := alg_equiv.of_bijective ϕ ((algebra.bot_equiv F E).symm.bijective), change (↑x : E) = ↑(ψ (ψ.symm ⟨x, _⟩)), rw alg_equiv.apply_symm_apply ψ ⟨x, _⟩, refl end /-- The top intermediate_field is isomorphic to the field. -/ noncomputable def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E := (subalgebra.equiv_of_eq _ _ top_to_subalgebra).trans algebra.top_equiv @[simp] lemma top_equiv_def (x : (⊤ : intermediate_field F E)) : top_equiv x = ↑x := begin suffices : algebra.to_top (top_equiv x) = algebra.to_top (x : E), { rwa subtype.ext_iff at this }, exact alg_equiv.apply_symm_apply (alg_equiv.of_bijective algebra.to_top ⟨λ _ _, subtype.mk.inj, λ x, ⟨x.val, by { ext, refl }⟩⟩ : E ≃ₐ[F] (⊤ : subalgebra F E)) (subalgebra.equiv_of_eq _ _ top_to_subalgebra x), end @[simp] lemma coe_bot_eq_self (K : intermediate_field F E) : ↑(⊥ : intermediate_field K E) = K := by { ext, rw [mem_lift2, mem_bot], exact set.ext_iff.mp subtype.range_coe x } @[simp] lemma coe_top_eq_top (K : intermediate_field F E) : ↑(⊤ : intermediate_field K E) = (⊤ : intermediate_field F E) := set_like.ext_iff.mpr $ λ _, mem_lift2.trans (iff_of_true mem_top mem_top) end lattice section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) lemma adjoin_eq_range_algebra_map_adjoin : (adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S := intermediate_field.algebra_map_mem (adjoin F S) x lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S := begin intros x hx, cases hx with f hf, rw ← hf, exact adjoin.algebra_map_mem F S f, end instance adjoin.field_coe : has_coe_t F (adjoin F S) := {coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩} lemma subset_adjoin : S ⊆ adjoin F S := λ x hx, subfield.subset_closure (or.inr hx) instance adjoin.set_coe : has_coe_t S (adjoin F S) := {coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩} @[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T := galois_connection.monotone_l gc h lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩ lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S := λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩ lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S := λ x hx, subset_adjoin F S (H hx) @[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (∅ : set E) = ⊥ := eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _)) /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/ lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K) (HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K := begin apply subfield.closure_le.mpr, rw set.union_subset_iff, exact ⟨HF, HS⟩, end lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E] {S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔ set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' := ⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩, λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩ /-- `F[S][T] = F[S ∪ T]` -/ lemma adjoin_adjoin_left (T : set E) : ↑(adjoin (adjoin F S) T) = adjoin F (S ∪ T) := begin rw set_like.ext'_iff, change ↑(adjoin (adjoin F S) T) = _, apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split, { rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx }, { exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) }, { exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) }, { exact set.union_subset (subset_adjoin_of_subset_left _ (subset_adjoin _ _)) (subset_adjoin _ _) }, end @[simp] lemma adjoin_insert_adjoin (x : E) : adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) := le_antisymm (adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _), adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩)) (adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _))) /-- `F[S][T] = F[T][S]` -/ lemma adjoin_adjoin_comm (T : set E) : ↑(adjoin (adjoin F S) T) = (↑(adjoin (adjoin F T) S) : (intermediate_field F E)) := by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm] lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') : (adjoin F S).map f = adjoin F (f '' S) := begin ext x, show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔ x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S), rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp, f.comp_algebra_map], refl, end lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra := algebra.adjoin_le (subset_adjoin _ _) lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) : (adjoin F S).to_subalgebra = algebra.adjoin F S := le_antisymm (show adjoin F S ≤ { neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S}, from adjoin_le_iff.mpr (algebra.subset_adjoin)) (algebra_adjoin_le_adjoin _ _) lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E) (h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S := begin apply to_subalgebra_injective, rw h, refine (adjoin_eq_algebra_adjoin _ _ _).symm, intros x, convert K.inv_mem, rw ← h, refl end @[elab_as_eliminator] lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s) (Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p x⁻¹) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x)) ((algebra_map F E).map_one ▸ Hmap 1) Hadd Hneg Hinv Hmul /-- Variation on `set.insert` to enable good notation for adjoining elements to fields. Used to preferentially use `singleton` rather than `insert` when adjoining one element. -/ --this definition of notation is courtesy of Kyle Miller on zulip class insert {α : Type*} (s : set α) := (insert : α → set α) @[priority 1000] instance insert_empty {α : Type*} : insert (∅ : set α) := { insert := λ x, @singleton _ _ set.has_singleton x } @[priority 900] instance insert_nonempty {α : Type*} (s : set α) : insert s := { insert := λ x, set.insert x s } notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l section adjoin_simple variables (α : E) lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ := subset_adjoin F {α} (set.mem_singleton α) /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩ @[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl @[simp] lemma adjoin_simple.is_integral_gen : is_integral F (adjoin_simple.gen F α) ↔ is_integral F α := by { conv_rhs { rw ← adjoin_simple.algebra_map_gen F α }, rw is_integral_algebra_map_iff (algebra_map F⟮α⟯ E).injective, apply_instance } lemma adjoin_simple_adjoin_simple (β : E) : ↑F⟮α⟯⟮β⟯ = F⟮α, β⟯ := adjoin_adjoin_left _ _ _ lemma adjoin_simple_comm (β : E) : ↑F⟮α⟯⟮β⟯ = (↑F⟮β⟯⟮α⟯ : intermediate_field F E) := adjoin_adjoin_comm _ _ _ -- TODO: develop the API for `subalgebra.is_field_of_algebraic` so it can be used here lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) : (F⟮α⟯).to_subalgebra = algebra.adjoin F {α} := begin apply adjoin_eq_algebra_adjoin, intros x hx, by_cases x = 0, { rw [h, inv_zero], exact subalgebra.zero_mem (algebra.adjoin F {α}) }, let ϕ := alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly F α, haveI := minpoly.irreducible hα, suffices : ϕ ⟨x, hx⟩ * (ϕ ⟨x, hx⟩)⁻¹ = 1, { convert subtype.mem (ϕ.symm (ϕ ⟨x, hx⟩)⁻¹), refine (eq_inv_of_mul_right_eq_one _).symm, apply_fun ϕ.symm at this, rw [alg_equiv.map_one, alg_equiv.map_mul, alg_equiv.symm_apply_apply] at this, rw [←subsemiring.coe_one, ←this, subsemiring.coe_mul, subtype.coe_mk] }, rw mul_inv_cancel (mt (λ key, _) h), rw ← ϕ.map_zero at key, change ↑(⟨x, hx⟩ : algebra.adjoin F {α}) = _, rw [ϕ.injective key, subalgebra.coe_zero] end end adjoin_simple end adjoin_def section adjoin_intermediate_field_lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E} @[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) := by { rw [eq_bot_iff, adjoin_le_iff], refl, } @[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) := by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff } @[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥) @[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (one_mem ⊥) @[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) @[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) section adjoin_dim open finite_dimensional module variables {K L : intermediate_field F E} @[simp] lemma dim_eq_one_iff : module.rank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra, subalgebra.dim_eq_one_iff, bot_to_subalgebra] @[simp] lemma finrank_eq_one_iff : finrank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← finrank_eq_finrank_subalgebra, subalgebra.finrank_eq_one_iff, bot_to_subalgebra] lemma dim_adjoin_eq_one_iff : module.rank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans dim_eq_one_iff adjoin_eq_bot_iff lemma dim_adjoin_simple_eq_one_iff : module.rank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff } lemma finrank_adjoin_eq_one_iff : finrank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans finrank_eq_one_iff adjoin_eq_bot_iff lemma finrank_adjoin_simple_eq_one_iff : finrank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw [finrank_adjoin_eq_one_iff], exact set.singleton_subset_iff } /-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact dim_adjoin_simple_eq_one_iff.mp (h x), end lemma bot_eq_top_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact finrank_adjoin_simple_eq_one_iff.mp (h x), end lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h) lemma subsingleton_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_eq_one h) /-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ := begin apply bot_eq_top_of_finrank_adjoin_eq_one, exact λ x, by linarith [h x, show 0 < finrank F F⟮x⟯, from finrank_pos], end lemma subsingleton_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_le_one h) end adjoin_dim end adjoin_intermediate_field_lattice section adjoin_integral_element variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} variables {K : Type*} [field K] [algebra F K] lemma minpoly_gen {α : E} (h : is_integral F α) : minpoly F (adjoin_simple.gen F α) = minpoly F α := begin rw ← adjoin_simple.algebra_map_gen F α at h, have inj := (algebra_map F⟮α⟯ E).injective, exact minpoly.eq_of_algebra_map_eq inj ((is_integral_algebra_map_iff inj).mp h) (adjoin_simple.algebra_map_gen _ _).symm end variables (F) lemma aeval_gen_minpoly (α : E) : aeval (adjoin_simple.gen F α) (minpoly F α) = 0 := begin ext, convert minpoly.aeval F α, conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] }, exact is_scalar_tower.algebra_map_aeval F F⟮α⟯ E _ _ end /-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/ noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) : adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ := alg_equiv.of_bijective (adjoin_root.lift_hom (minpoly F α) (adjoin_simple.gen F α) (aeval_gen_minpoly F α)) (begin set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α : _), haveI := minpoly.irreducible h, split, { exact ring_hom.injective f }, { suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f), { exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy⟩) }, exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy, ⟨y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩)) (set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α), by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩)) } end) lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) : adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) = adjoin_simple.gen F α := adjoin_root.lift_root (aeval_gen_minpoly F α) section power_basis variables {L : Type*} [field L] [algebra K L] /-- The elements `1, x, ..., x ^ (d - 1)` form a basis for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def power_basis_aux {x : L} (hx : is_integral K x) : basis (fin (minpoly K x).nat_degree) K K⟮x⟯ := (adjoin_root.power_basis (minpoly.ne_zero hx)).basis.map (adjoin_root_equiv_adjoin K hx).to_linear_equiv /-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ @[simps] noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) : power_basis K K⟮x⟯ := { gen := adjoin_simple.gen K x, dim := (minpoly K x).nat_degree, basis := power_basis_aux hx, basis_eq_pow := λ i, by rw [power_basis_aux, basis.map_apply, power_basis.basis_eq_pow, alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow, adjoin_root.power_basis_gen, adjoin_root_equiv_adjoin_apply_root] } lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ := power_basis.finite_dimensional (adjoin.power_basis hx) lemma adjoin.finrank {x : L} (hx : is_integral K x) : finite_dimensional.finrank K K⟮x⟯ = (minpoly K x).nat_degree := begin rw power_basis.finrank (adjoin.power_basis hx : _), refl end end power_basis /-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots of `minpoly α` in `K`. -/ noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) : (F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} := (adjoin.power_basis h).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x, by rw [adjoin.power_basis_gen, minpoly_gen h, equiv.refl_apply])) /-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/ noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) : fintype (F⟮α⟯ →ₐ[F] K) := power_basis.alg_hom.fintype (adjoin.power_basis h) lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F K)) : @fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) = (minpoly F α).nat_degree := begin rw alg_hom.card_of_power_basis; simp only [adjoin.power_basis_dim, adjoin.power_basis_gen, minpoly_gen h, h_sep, h_splits], end end adjoin_integral_element section induction variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] /-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that `intermediate_field.adjoin F t = S`. -/ def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg := ⟨t, rfl⟩ theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : intermediate_field F E).fg := ⟨∅, adjoin_empty F E⟩ lemma fg_of_fg_to_subalgebra (S : intermediate_field F E) (h : S.to_subalgebra.fg) : S.fg := begin cases h with t ht, exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩ end lemma fg_of_noetherian (S : intermediate_field F E) [is_noetherian F E] : S.fg := S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P ↑K⟮x⟯) : P (adjoin F ↑S) := begin apply finset.induction_on' S, { exact base }, { intros a s h1 _ _ h4, rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left], exact ih (adjoin F s) a h1 h4 } end lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) (hK : K.fg) : P K := begin obtain ⟨S, rfl⟩ := hK, exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK), end lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) : P K := begin letI : is_noetherian F E := is_noetherian.iff_fg.2 infer_instance, exact induction_on_adjoin_fg P base ih K K.fg_of_noetherian end end induction section alg_hom_mk_adjoin_splits variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E} /-- Lifts `L → K` of `F → K` -/ def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K) variables {F E K} noncomputable instance : order_bot (lifts F E K) := { le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t), le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩, le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans (hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩, le_antisymm := begin rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩, have : x1 = y1 := le_antisymm hxy1 hyx1, subst this, congr, exact alg_hom.ext (λ s, hxy2 s s rfl), end, bot := ⟨⊥, (algebra.of_id F K).comp (bot_equiv F E).to_alg_hom⟩, bot_le := λ x, ⟨bot_le, λ s t hst, begin cases intermediate_field.mem_bot.mp s.mem with u hu, rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes], rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes], end⟩ } noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩ lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) : x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : zorn.chain (≤) c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) : ∃ z : lifts F E K, z ∈ set.insert ⊥ c ∧ x ≤ z ∧ y ≤ z := begin cases (zorn.chain_insert hc (λ _ _ _, or.inl bot_le)).total_of_refl hx hy with hxy hyx, { exact ⟨y, hy, hxy, le_refl y⟩ }, { exact ⟨x, hx, le_refl x, hyx⟩ }, end lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : zorn.chain (≤) c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) (hz : z ∈ set.insert ⊥ c) : ∃ w : lifts F E K, w ∈ set.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w := begin obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy, obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv, exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩, end /-- An upper bound on a chain of lifts -/ def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : intermediate_field F E := { carrier := λ s, ∃ x : (lifts F E K), x ∈ set.insert ⊥ c ∧ (s ∈ x.1 : Prop), zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩, one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩, neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ }, inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ }, add_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ }, mul_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ }, algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ } /-- The lift on the upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : lifts.upper_bound_intermediate_field hc →ₐ[F] K := { to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩, map_zero' := alg_hom.map_zero _, map_one' := alg_hom.map_one _, map_add' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s + t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add], refl, end, map_mul' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s * t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul], refl, end, commutes' := λ _, alg_hom.commutes _ _ } /-- An upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : lifts F E K := ⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩ lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : zorn.chain (≤) c) : ∃ ub, ∀ a ∈ c, a ≤ ub := ⟨lifts.upper_bound hc, begin intros x hx, split, { exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ }, { intros s t hst, change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx) (classical.some_spec t.mem).1, rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz], exact congr_arg z.2 (subtype.ext hst) }, end⟩ /-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/ noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K := let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower s h1 in let key : (minpoly x.1 s).splits x.2.to_ring_hom := splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1)) ((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)})) (minpoly.dvd_map_of_is_scalar_tower _ _ _) in ⟨↑x.1⟮s⟯, (@alg_hom_equiv_sigma F x.1 (↑x.1⟮s⟯ : intermediate_field F E) K _ _ _ _ _ _ _ (intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun ⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by { simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map], exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩ lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 := ⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)], letI : algebra x.1 K := x.2.to_ring_hom.to_algebra, exact (alg_hom.commutes _ t), end⟩ lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 := mem_adjoin_simple_self x.1 s lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 := ⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩ lemma alg_hom_mk_adjoin_splits (hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) : nonempty (adjoin F S →ₐ[F] K) := begin obtain ⟨x : lifts F E K, hx⟩ := zorn.zorn_partial_order lifts.exists_upper_bound, refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t, x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩, rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩, rwa hx y h1 at h2 end lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤) (hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) : nonempty (E →ₐ[F] K) := begin cases alg_hom_mk_adjoin_splits hK with ϕ, rw hS at ϕ, exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩, end end alg_hom_mk_adjoin_splits end intermediate_field section power_basis variables {K L : Type*} [field K] [field L] [algebra K L] namespace power_basis open intermediate_field /-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/ noncomputable def equiv_adjoin_simple (pb : power_basis K L) : K⟮pb.gen⟯ ≃ₐ[K] L := (adjoin.power_basis pb.is_integral_gen).equiv_of_minpoly pb (minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective (adjoin.power_basis pb.is_integral_gen).is_integral_gen (by rw [adjoin.power_basis_gen, adjoin_simple.algebra_map_gen])) @[simp] lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f := equiv_of_minpoly_aeval _ pb _ f @[simp] lemma equiv_adjoin_simple_gen (pb : power_basis K L) : pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen := equiv_of_minpoly_gen _ pb _ @[simp] lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f := by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_aeval, adjoin.power_basis_gen] @[simp] lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) : pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) := by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_gen, adjoin.power_basis_gen] end power_basis end power_basis
c2d39a6d091e50c3c3bee08618df140abc55993b
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/equiv/fin.lean
67c35fd52b49eb86a421b0a2a06cb406ee42ffbe
[ "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
14,091
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.fin import data.equiv.basic import tactic.norm_num /-! # Equivalences for `fin n` -/ universe variables u variables {m n : ℕ} /-- Equivalence between `fin 0` and `empty`. -/ def fin_zero_equiv : fin 0 ≃ empty := equiv.equiv_empty _ /-- Equivalence between `fin 0` and `pempty`. -/ def fin_zero_equiv' : fin 0 ≃ pempty.{u} := equiv.equiv_pempty _ /-- Equivalence between `fin 1` and `unit`. -/ def fin_one_equiv : fin 1 ≃ unit := equiv_punit_of_unique /-- Equivalence between `fin 2` and `bool`. -/ def fin_two_equiv : fin 2 ≃ bool := ⟨@fin.cases 1 (λ_, bool) ff (λ_, tt), λb, cond b 1 0, begin refine fin.cases _ _, by norm_num, refine fin.cases _ _, by norm_num, exact λi, fin_zero_elim i end, begin rintro ⟨_|_⟩, { refl }, { rw ← fin.succ_zero_eq_one, refl } end⟩ /-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/ def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m := equiv.subtype_equiv_right (λ x, by subst h) @[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) : fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ := rfl @[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) : (fin_congr h).symm = fin_congr h.symm := rfl @[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) : (fin_congr h k : ℕ) = k := by { cases k, refl, } lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) : ((fin_congr h).symm k : ℕ) = k := by { cases k, refl, } /-- An equivalence that removes `i` and maps it to `none`. This is a version of `fin.pred_above` that produces `option (fin n)` instead of mapping both `i.cast_succ` and `i.succ` to `i`. -/ def fin_succ_equiv' {n : ℕ} (i : fin (n + 1)) : fin (n + 1) ≃ option (fin n) := have hx0 : ∀ {i x : fin (n + 1)}, i < x → x ≠ 0, from λ i x hix, ne_of_gt (lt_of_le_of_lt i.zero_le hix), have hiltx : ∀ {i x : fin (n + 1)}, ¬ i < x → ¬ x = i → x < i, from λ i x hix hxi, lt_of_le_of_ne (le_of_not_lt hix) hxi, have hxltn : ∀ {i x : fin (n + 1)}, ¬ i < x → ¬ x = i → (x : ℕ) < n, from λ i x hix hxi, lt_of_lt_of_le (hiltx hix hxi) (nat.le_of_lt_succ i.2), { to_fun := λ x, if hix : i < x then some (x.pred (hx0 hix)) else if hxi : x = i then none else some (x.cast_lt (hxltn hix hxi)), inv_fun := λ x, x.cases_on' i (fin.succ_above i), left_inv := λ x, if hix : i < x then have hi : i ≤ fin.cast_succ (x.pred (hx0 hix)), by { simp only [fin.le_iff_coe_le_coe, fin.coe_cast_succ, fin.coe_pred], exact nat.le_pred_of_lt hix }, by simp [dif_pos hix, option.cases_on'_some, fin.succ_above_above _ _ hi, fin.succ_pred] else if hxi : x = i then by simp [hxi] else have hi : fin.cast_succ (x.cast_lt (hxltn hix hxi)) < i, from lt_of_le_of_ne (le_of_not_gt hix) (by simp [hxi]), by simp only [dif_neg hix, dif_neg hxi, option.cases_on'_some, fin.succ_above_below _ _ hi, fin.cast_succ_cast_lt], right_inv := λ x, by { cases x, { simp }, { dsimp, split_ifs, { simp [fin.succ_above_above _ _ ((fin.lt_succ_above_iff _ _).1 h)] }, { simpa [fin.succ_above_ne] using h_1 }, { have : fin.cast_succ x < i, { rwa [fin.lt_succ_above_iff, not_le] at h }, simp [fin.succ_above_below _ _ this] } } } } @[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i) i = none := by simp [fin_succ_equiv'] lemma fin_succ_equiv'_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i) m.cast_succ = some m := by simp [fin_succ_equiv', dif_neg (not_lt_of_gt h), ne_of_lt h] lemma fin_succ_equiv'_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i) m.succ = some m := by simp [fin_succ_equiv', fin.le_cast_succ_iff, *] at * @[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i).symm none = i := rfl lemma fin_succ_equiv'_symm_some_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm (some m) = m.cast_succ := by simp [fin_succ_equiv', ne_of_gt h, fin.succ_above, not_le_of_gt h] lemma fin_succ_equiv'_symm_some_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm (some m) = m.succ := by simp [fin_succ_equiv', fin.succ_above, h.not_lt] lemma fin_succ_equiv'_symm_coe_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm m = m.cast_succ := fin_succ_equiv'_symm_some_below h lemma fin_succ_equiv'_symm_coe_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm m = m.succ := fin_succ_equiv'_symm_some_above h /-- Equivalence between `fin (n + 1)` and `option (fin n)`. This is a version of `fin.pred` that produces `option (fin n)` instead of requiring a proof that the input is not `0`. -/ def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' 0 @[simp] lemma fin_succ_equiv_zero {n : ℕ} : (fin_succ_equiv n) 0 = none := by cases n; refl @[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n): (fin_succ_equiv n) m.succ = some m := begin cases n, { exact m.elim0 }, rw [fin_succ_equiv, fin_succ_equiv'_above (fin.zero_le _)], end @[simp] lemma fin_succ_equiv_symm_none {n : ℕ} : (fin_succ_equiv n).symm none = 0 := by cases n; refl @[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm (some m) = m.succ := begin cases n, { exact m.elim0 }, rw [fin_succ_equiv, fin_succ_equiv'_symm_some_above (fin.zero_le _)], end @[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm m = m.succ := fin_succ_equiv_symm_some m /-- The equiv version of `fin.pred_above_zero`. -/ lemma fin_succ_equiv'_zero {n : ℕ} : fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv n := rfl /-- `equiv` between `fin (n + 1)` and `option (fin n)` sending `fin.last n` to `none` -/ def fin_succ_equiv_last {n : ℕ} : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' (fin.last n) @[simp] lemma fin_succ_equiv_last_cast_succ {n : ℕ} (i : fin n) : fin_succ_equiv_last i.cast_succ = some i := fin_succ_equiv'_below i.2 @[simp] lemma fin_succ_equiv_last_last {n : ℕ} : fin_succ_equiv_last (fin.last n) = none := by simp [fin_succ_equiv_last] @[simp] lemma fin_succ_equiv_last_symm_some {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm (some i) = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_coe {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm ↑i = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_none {n : ℕ} : fin_succ_equiv_last.symm none = fin.last n := fin_succ_equiv'_symm_none _ /-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/ def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) := { to_fun := λ x, sum.rec_on x (λ y, ⟨y.1, nat.lt_of_lt_of_le y.2 $ nat.le_add_right m n⟩) (λ y, ⟨m + y.1, nat.add_lt_add_left y.2 m⟩), inv_fun := λ x, if H : x.1 < m then sum.inl ⟨x.1, H⟩ else sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $ show m + (x.1 - m) < m + n, from (nat.add_sub_of_le $ le_of_not_gt H).symm ▸ x.2⟩, left_inv := λ x, begin cases x with y y, { simp [fin.ext_iff, y.is_lt], }, { have H : ¬m + y.val < m := not_lt_of_ge (nat.le_add_right _ _), simp [H, nat.add_sub_cancel_left, fin.ext_iff] } end, right_inv := λ x, begin by_cases H : (x:ℕ) < m, { dsimp, rw [dif_pos H], simp }, { dsimp, rw [dif_neg H], simp [fin.ext_iff, nat.add_sub_of_le (le_of_not_gt H)] } end } @[simp] lemma fin_sum_fin_equiv_apply_left (i : fin m) : (fin_sum_fin_equiv (sum.inl i) : fin (m + n)) = fin.cast_add n i := rfl @[simp] lemma fin_sum_fin_equiv_apply_right (i : fin n) : (fin_sum_fin_equiv (sum.inr i) : fin (m + n)) = fin.cast_add_right m i := rfl @[simp] lemma fin_sum_fin_equiv_symm_apply_left (x : fin (m + n)) (h : ↑x < m) : fin_sum_fin_equiv.symm x = sum.inl ⟨x.1, h⟩ := by simp [fin_sum_fin_equiv, dif_pos h] @[simp] lemma fin_sum_fin_equiv_symm_apply_right (x : fin (m + n)) (h : m ≤ ↑x) : fin_sum_fin_equiv.symm x = sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $ show m + (x.1 - m) < m + n, from (nat.add_sub_of_le $ h).symm ▸ x.2⟩ := by simp [fin_sum_fin_equiv, dif_neg (not_lt.mpr h)] @[simp] lemma fin_sum_fin_equiv_symm_apply_cast_add {m n : ℕ} (i : fin m) : fin_sum_fin_equiv.symm (fin.cast_add n i) = sum.inl i := begin rw [fin_sum_fin_equiv_symm_apply_left _ (fin.cast_add_lt _ _)], simp end @[simp] lemma fin_sum_fin_equiv_symm_apply_cast_add_right {m n : ℕ} (i : fin m) : fin_sum_fin_equiv.symm (fin.cast_add_right n i) = sum.inr i := begin rw [fin_sum_fin_equiv_symm_apply_right _ (fin.le_cast_add_right _ _)], simp end /-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/ def fin_add_flip : fin (m + n) ≃ fin (n + m) := (fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv @[simp] lemma fin_add_flip_apply_left {k : ℕ} (h : k < m) (hk : k < m + n := nat.lt_add_right k m n h) (hnk : n + k < n + m := add_lt_add_left h n) : fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ := begin dsimp [fin_add_flip, fin_sum_fin_equiv], rw [dif_pos h], refl, end @[simp] lemma fin_add_flip_apply_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) : fin_add_flip (⟨k, h₂⟩ : fin (m + n)) = ⟨k - m, lt_of_le_of_lt (nat.sub_le _ _) (by { convert h₂ using 1, simp [add_comm] })⟩ := begin dsimp [fin_add_flip, fin_sum_fin_equiv], rw [dif_neg (not_lt.mpr h₁)], refl, end /-- Rotate `fin n` one step to the right. -/ def fin_rotate : Π n, equiv.perm (fin n) | 0 := equiv.refl _ | (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _)) lemma fin_rotate_of_lt {k : ℕ} (h : k < n) : fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ := begin dsimp [fin_rotate], simp [h, add_comm], end lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ := begin dsimp [fin_rotate], rw fin_add_flip_apply_right, simp, end lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 := fin_rotate_last' lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) : @fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) := begin ext ⟨i, h⟩, by_cases h' : i < n, { rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'], refl, }, { have h'' : n = i, { simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, }, subst h'', rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)], refl, } end @[simp] lemma fin_rotate_zero : fin_rotate 0 = equiv.refl _ := rfl @[simp] lemma fin_rotate_one : fin_rotate 1 = equiv.refl _ := subsingleton.elim _ _ @[simp] lemma fin_rotate_succ_apply {n : ℕ} (i : fin n.succ) : fin_rotate n.succ i = i + 1 := begin cases n, { simp }, rcases i.le_last.eq_or_lt with rfl|h, { simp [fin_rotate_last] }, { cases i, simp only [fin.lt_iff_coe_lt_coe, fin.coe_last, fin.coe_mk] at h, simp [fin_rotate_of_lt h, fin.eq_iff_veq, fin.add_def, nat.mod_eq_of_lt (nat.succ_lt_succ h)] }, end @[simp] lemma fin_rotate_apply_zero {n : ℕ} : fin_rotate n.succ 0 = 1 := by rw [fin_rotate_succ_apply, zero_add] lemma coe_fin_rotate_of_ne_last {n : ℕ} {i : fin n.succ} (h : i ≠ fin.last n) : (fin_rotate n.succ i : ℕ) = i + 1 := begin rw fin_rotate_succ_apply, have : (i : ℕ) < n := lt_of_le_of_ne (nat.succ_le_succ_iff.mp i.2) (fin.coe_injective.ne h), exact fin.coe_add_one_of_lt this end lemma coe_fin_rotate {n : ℕ} (i : fin n.succ) : (fin_rotate n.succ i : ℕ) = if i = fin.last n then 0 else i + 1 := by rw [fin_rotate_succ_apply, fin.coe_add_one i] /-- Equivalence between `fin m × fin n` and `fin (m * n)` -/ def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) := { to_fun := λ x, ⟨x.2.1 + n * x.1.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero x.1 $ by subst H; from x.2, (⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩, ⟨x.1 % n, nat.mod_lt _ H⟩), left_inv := λ ⟨x, y⟩, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } /-- Promote a `fin n` into a larger `fin m`, as a subtype where the underlying values are retained. This is the `order_iso` version of `fin.cast_le`. -/ @[simps apply symm_apply] def fin.cast_le_order_iso {n m : ℕ} (h : n ≤ m) : fin n ≃o {i : fin m // (i : ℕ) < n} := { to_fun := λ i, ⟨fin.cast_le h i, by simpa using i.is_lt⟩, inv_fun := λ i, ⟨i, i.prop⟩, left_inv := λ _, by simp, right_inv := λ _, by simp, map_rel_iff' := λ _ _, by simp } /-- `fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton /-- `fin 1` is a subsingleton. -/ instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
0d69c5538d255d5615dcc1393cd629fa98c98559
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/limits/shapes/wide_pullbacks.lean
c7edbed3b3aeaa0dc73a1d4827d328fafdfa7ea2
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
5,289
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.limits import category_theory.sparse /-! # Wide pullbacks We define the category `wide_pullback_shape`, (resp. `wide_pushout_shape`) which is the category obtained from a discrete category of type `J` by adjoining a terminal (resp. initial) element. Limits of this shape are wide pullbacks (pushouts). The convenience method `wide_cospan` (`wide_span`) constructs a functor from this category, hitting the given morphisms. We use `wide_pullback_shape` to define ordinary pullbacks (pushouts) by using `J := walking_pair`, which allows easy proofs of some related lemmas. Furthermore, wide pullbacks are used to show the existence of limits in the slice category. Namely, if `C` has wide pullbacks then `C/B` has limits for any object `B` in `C`. Typeclasses `has_wide_pullbacks` and `has_finite_wide_pullbacks` assert the existence of wide pullbacks and finite wide pullbacks. -/ universes v u open category_theory category_theory.limits namespace category_theory.limits variable (J : Type v) /-- A wide pullback shape for any type `J` can be written simply as `option J`. -/ @[derive inhabited] def wide_pullback_shape := option J /-- A wide pushout shape for any type `J` can be written simply as `option J`. -/ @[derive inhabited] def wide_pushout_shape := option J namespace wide_pullback_shape variable {J} /-- The type of arrows for the shape indexing a wide pullback. -/ @[derive decidable_eq] inductive hom : wide_pullback_shape J → wide_pullback_shape J → Type v | id : Π X, hom X X | term : Π (j : J), hom (some j) none attribute [nolint unused_arguments] hom.decidable_eq instance struct : category_struct (wide_pullback_shape J) := { hom := hom, id := λ j, hom.id j, comp := λ j₁ j₂ j₃ f g, begin cases f, exact g, cases g, apply hom.term _ end } instance hom.inhabited : inhabited (hom none none) := ⟨hom.id (none : wide_pullback_shape J)⟩ local attribute [tidy] tactic.case_bash instance subsingleton_hom (j j' : wide_pullback_shape J) : subsingleton (j ⟶ j') := ⟨by tidy⟩ instance category : small_category (wide_pullback_shape J) := sparse_category @[simp] lemma hom_id (X : wide_pullback_shape J) : hom.id X = 𝟙 X := rfl variables {C : Type u} [category.{v} C] /-- Construct a functor out of the wide pullback shape given a J-indexed collection of arrows to a fixed object. -/ @[simps] def wide_cospan (B : C) (objs : J → C) (arrows : Π (j : J), objs j ⟶ B) : wide_pullback_shape J ⥤ C := { obj := λ j, option.cases_on j B objs, map := λ X Y f, begin cases f with _ j, { apply (𝟙 _) }, { exact arrows j } end } /-- Every diagram is naturally isomorphic (actually, equal) to a `wide_cospan` -/ def diagram_iso_wide_cospan (F : wide_pullback_shape J ⥤ C) : F ≅ wide_cospan (F.obj none) (λ j, F.obj (some j)) (λ j, F.map (hom.term j)) := nat_iso.of_components (λ j, eq_to_iso $ by tidy) $ by tidy end wide_pullback_shape namespace wide_pushout_shape variable {J} /-- The type of arrows for the shape indexing a wide psuhout. -/ @[derive decidable_eq] inductive hom : wide_pushout_shape J → wide_pushout_shape J → Type v | id : Π X, hom X X | init : Π (j : J), hom none (some j) attribute [nolint unused_arguments] hom.decidable_eq instance struct : category_struct (wide_pushout_shape J) := { hom := hom, id := λ j, hom.id j, comp := λ j₁ j₂ j₃ f g, begin cases f, exact g, cases g, apply hom.init _ end } instance hom.inhabited : inhabited (hom none none) := ⟨hom.id (none : wide_pushout_shape J)⟩ local attribute [tidy] tactic.case_bash instance subsingleton_hom (j j' : wide_pushout_shape J) : subsingleton (j ⟶ j') := ⟨by tidy⟩ instance category : small_category (wide_pushout_shape J) := sparse_category @[simp] lemma hom_id (X : wide_pushout_shape J) : hom.id X = 𝟙 X := rfl variables {C : Type u} [category.{v} C] /-- Construct a functor out of the wide pushout shape given a J-indexed collection of arrows from a fixed object. -/ @[simps] def wide_span (B : C) (objs : J → C) (arrows : Π (j : J), B ⟶ objs j) : wide_pushout_shape J ⥤ C := { obj := λ j, option.cases_on j B objs, map := λ X Y f, begin cases f with _ j, { apply (𝟙 _) }, { exact arrows j } end } /-- Every diagram is naturally isomorphic (actually, equal) to a `wide_span` -/ def diagram_iso_wide_span (F : wide_pushout_shape J ⥤ C) : F ≅ wide_span (F.obj none) (λ j, F.obj (some j)) (λ j, F.map (hom.init j)) := nat_iso.of_components (λ j, eq_to_iso $ by tidy) $ by tidy end wide_pushout_shape variables (C : Type u) [category.{v} C] /-- `has_wide_pullbacks` represents a choice of wide pullback for every collection of morphisms -/ abbreviation has_wide_pullbacks : Type (max (v+1) u) := Π (J : Type v), has_limits_of_shape (wide_pullback_shape J) C /-- `has_wide_pushouts` represents a choice of wide pushout for every collection of morphisms -/ abbreviation has_wide_pushouts : Type (max (v+1) u) := Π (J : Type v), has_colimits_of_shape (wide_pushout_shape J) C end category_theory.limits
0b05c06ba4f49f9938cc03e763726bcecb0a2201
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/information_theory/hamming.lean
c1aacfc128e444d6d4d8a3a15df0dfab352ef9f3
[ "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
14,135
lean
/- Copyright (c) 2022 Wrenna Robson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wrenna Robson -/ import analysis.normed.group.basic /-! # Hamming spaces The Hamming metric counts the number of places two members of a (finite) Pi type differ. The Hamming norm is the same as the Hamming metric over additive groups, and counts the number of places a member of a (finite) Pi type differs from zero. This is a useful notion in various applications, but in particular it is relevant in coding theory, in which it is fundamental for defining the minimum distance of a code. ## Main definitions * `hamming_dist x y`: the Hamming distance between `x` and `y`, the number of entries which differ. * `hamming_norm x`: the Hamming norm of `x`, the number of non-zero entries. * `hamming β`: a type synonym for `Π i, β i` with `dist` and `norm` provided by the above. * `hamming.to_hamming`, `hamming.of_hamming`: functions for casting between `hamming β` and `Π i, β i`. * `hamming.normed_add_comm_group`: the Hamming norm forms a normed group on `hamming β`. -/ section hamming_dist_norm open finset function variables {α ι : Type*} {β : ι → Type*} [fintype ι] [Π i, decidable_eq (β i)] variables {γ : ι → Type*} [Π i, decidable_eq (γ i)] /-- The Hamming distance function to the naturals. -/ def hamming_dist (x y : Π i, β i) : ℕ := (univ.filter (λ i, x i ≠ y i)).card /-- Corresponds to `dist_self`. -/ @[simp] lemma hamming_dist_self (x : Π i, β i) : hamming_dist x x = 0 := by { rw [hamming_dist, card_eq_zero, filter_eq_empty_iff], exact λ _ _ H, H rfl } /-- Corresponds to `dist_nonneg`. -/ lemma hamming_dist_nonneg {x y : Π i, β i} : 0 ≤ hamming_dist x y := zero_le _ /-- Corresponds to `dist_comm`. -/ lemma hamming_dist_comm (x y : Π i, β i) : hamming_dist x y = hamming_dist y x := by simp_rw [hamming_dist, ne_comm] /-- Corresponds to `dist_triangle`. -/ lemma hamming_dist_triangle (x y z : Π i, β i) : hamming_dist x z ≤ hamming_dist x y + hamming_dist y z := begin classical, simp_rw hamming_dist, refine le_trans (card_mono _) (card_union_le _ _), rw ← filter_or, refine monotone_filter_right _ _, intros i h, by_contra' H, exact h (eq.trans H.1 H.2) end /-- Corresponds to `dist_triangle_left`. -/ lemma hamming_dist_triangle_left (x y z : Π i, β i) : hamming_dist x y ≤ hamming_dist z x + hamming_dist z y := by { rw hamming_dist_comm z, exact hamming_dist_triangle _ _ _ } /-- Corresponds to `dist_triangle_right`. -/ lemma hamming_dist_triangle_right (x y z : Π i, β i) : hamming_dist x y ≤ hamming_dist x z + hamming_dist y z := by { rw hamming_dist_comm y, exact hamming_dist_triangle _ _ _ } /-- Corresponds to `swap_dist`. -/ theorem swap_hamming_dist : swap (@hamming_dist _ β _ _) = hamming_dist := by { funext x y, exact hamming_dist_comm _ _ } /-- Corresponds to `eq_of_dist_eq_zero`. -/ lemma eq_of_hamming_dist_eq_zero {x y : Π i, β i} : hamming_dist x y = 0 → x = y := by simp_rw [hamming_dist, card_eq_zero, filter_eq_empty_iff, not_not, funext_iff, mem_univ, forall_true_left, imp_self] /-- Corresponds to `dist_eq_zero`. -/ @[simp] lemma hamming_dist_eq_zero {x y : Π i, β i} : hamming_dist x y = 0 ↔ x = y := ⟨eq_of_hamming_dist_eq_zero, (λ H, by {rw H, exact hamming_dist_self _})⟩ /-- Corresponds to `zero_eq_dist`. -/ @[simp] lemma hamming_zero_eq_dist {x y : Π i, β i} : 0 = hamming_dist x y ↔ x = y := by rw [eq_comm, hamming_dist_eq_zero] /-- Corresponds to `dist_ne_zero`. -/ lemma hamming_dist_ne_zero {x y : Π i, β i} : hamming_dist x y ≠ 0 ↔ x ≠ y := hamming_dist_eq_zero.not /-- Corresponds to `dist_pos`. -/ @[simp] lemma hamming_dist_pos {x y : Π i, β i} : 0 < hamming_dist x y ↔ x ≠ y := by rw [←hamming_dist_ne_zero, iff_not_comm, not_lt, le_zero_iff] @[simp] lemma hamming_dist_lt_one {x y : Π i, β i} : hamming_dist x y < 1 ↔ x = y := by rw [nat.lt_one_iff, hamming_dist_eq_zero] lemma hamming_dist_le_card_fintype {x y : Π i, β i} : hamming_dist x y ≤ fintype.card ι := card_le_univ _ lemma hamming_dist_comp_le_hamming_dist (f : Π i, γ i → β i) {x y : Π i, γ i} : hamming_dist (λ i, f i (x i)) (λ i, f i (y i)) ≤ hamming_dist x y := card_mono (monotone_filter_right _ $ λ i H1 H2, H1 $ congr_arg (f i) H2) lemma hamming_dist_comp (f : Π i, γ i → β i) {x y : Π i, γ i} (hf : Π i, injective (f i)) : hamming_dist (λ i, f i (x i)) (λ i, f i (y i)) = hamming_dist x y := begin refine le_antisymm (hamming_dist_comp_le_hamming_dist _) _, exact card_mono (monotone_filter_right _ $ λ i H1 H2, H1 $ hf i H2) end lemma hamming_dist_smul_le_hamming_dist [Π i, has_smul α (β i)] {k : α} {x y : Π i, β i} : hamming_dist (k • x) (k • y) ≤ hamming_dist x y := hamming_dist_comp_le_hamming_dist $ λ i, (•) k /-- Corresponds to `dist_smul` with the discrete norm on `α`. -/ lemma hamming_dist_smul [Π i, has_smul α (β i)] {k : α} {x y : Π i, β i} (hk : Π i, is_smul_regular (β i) k) : hamming_dist (k • x) (k • y) = hamming_dist x y := hamming_dist_comp (λ i, (•) k) hk section has_zero variables [Π i, has_zero (β i)] [Π i, has_zero (γ i)] /-- The Hamming weight function to the naturals. -/ def hamming_norm (x : Π i, β i) : ℕ := (univ.filter (λ i, x i ≠ 0)).card /-- Corresponds to `dist_zero_right`. -/ @[simp] lemma hamming_dist_zero_right (x : Π i, β i) : hamming_dist x 0 = hamming_norm x := rfl /-- Corresponds to `dist_zero_left`. -/ @[simp] lemma hamming_dist_zero_left : hamming_dist (0 : Π i, β i) = hamming_norm := funext $ λ x, by rw [hamming_dist_comm, hamming_dist_zero_right] /-- Corresponds to `norm_nonneg`. -/ @[simp] lemma hamming_norm_nonneg {x : Π i, β i} : 0 ≤ hamming_norm x := zero_le _ /-- Corresponds to `norm_zero`. -/ @[simp] lemma hamming_norm_zero : hamming_norm (0 : Π i, β i) = 0 := hamming_dist_self _ /-- Corresponds to `norm_eq_zero`. -/ @[simp] lemma hamming_norm_eq_zero {x : Π i, β i} : hamming_norm x = 0 ↔ x = 0 := hamming_dist_eq_zero /-- Corresponds to `norm_ne_zero_iff`. -/ lemma hamming_norm_ne_zero_iff {x : Π i, β i} : hamming_norm x ≠ 0 ↔ x ≠ 0 := hamming_norm_eq_zero.not /-- Corresponds to `norm_pos_iff`. -/ @[simp] lemma hamming_norm_pos_iff {x : Π i, β i} : 0 < hamming_norm x ↔ x ≠ 0 := hamming_dist_pos @[simp] lemma hamming_norm_lt_one {x : Π i, β i} : hamming_norm x < 1 ↔ x = 0 := hamming_dist_lt_one lemma hamming_norm_le_card_fintype {x : Π i, β i} : hamming_norm x ≤ fintype.card ι := hamming_dist_le_card_fintype lemma hamming_norm_comp_le_hamming_norm (f : Π i, γ i → β i) {x : Π i, γ i} (hf : Π i, f i 0 = 0) : hamming_norm (λ i, f i (x i)) ≤ hamming_norm x := by {convert hamming_dist_comp_le_hamming_dist f, simp_rw hf, refl} lemma hamming_norm_comp (f : Π i, γ i → β i) {x : Π i, γ i} (hf₁ : Π i, injective (f i)) (hf₂ : Π i, f i 0 = 0) : hamming_norm (λ i, f i (x i)) = hamming_norm x := by {convert hamming_dist_comp f hf₁, simp_rw hf₂, refl} lemma hamming_norm_smul_le_hamming_norm [has_zero α] [Π i, smul_with_zero α (β i)] {k : α} {x : Π i, β i} : hamming_norm (k • x) ≤ hamming_norm x := hamming_norm_comp_le_hamming_norm (λ i (c : β i), k • c) (λ i, by simp_rw smul_zero) lemma hamming_norm_smul [has_zero α] [Π i, smul_with_zero α (β i)] {k : α} (hk : ∀ i, is_smul_regular (β i) k) (x : Π i, β i) : hamming_norm (k • x) = hamming_norm x := hamming_norm_comp (λ i (c : β i), k • c) hk (λ i, by simp_rw smul_zero) end has_zero /-- Corresponds to `dist_eq_norm`. -/ lemma hamming_dist_eq_hamming_norm [Π i, add_group (β i)] (x y : Π i, β i) : hamming_dist x y = hamming_norm (x - y) := by simp_rw [hamming_norm, hamming_dist, pi.sub_apply, sub_ne_zero] end hamming_dist_norm /-! ### The `hamming` type synonym -/ /-- Type synonym for a Pi type which inherits the usual algebraic instances, but is equipped with the Hamming metric and norm, instead of `pi.normed_add_comm_group` which uses the sup norm. -/ def hamming {ι : Type*} (β : ι → Type*) : Type* := Π i, β i namespace hamming variables {α ι : Type*} {β : ι → Type*} /-! Instances inherited from normal Pi types. -/ instance [Π i, inhabited (β i)] : inhabited (hamming β) := ⟨λ i, default⟩ instance [decidable_eq ι] [fintype ι] [Π i, fintype (β i)] : fintype (hamming β) := pi.fintype instance [inhabited ι] [∀ i, nonempty (β i)] [nontrivial (β default)] : nontrivial (hamming β) := pi.nontrivial instance [fintype ι] [Π i, decidable_eq (β i)] : decidable_eq (hamming β) := fintype.decidable_pi_fintype instance [Π i, has_zero (β i)] : has_zero (hamming β) := pi.has_zero instance [Π i, has_neg (β i)] : has_neg (hamming β) := pi.has_neg instance [Π i, has_add (β i)] : has_add (hamming β) := pi.has_add instance [Π i, has_sub (β i)] : has_sub (hamming β) := pi.has_sub instance [Π i, has_smul α (β i)] : has_smul α (hamming β) := pi.has_smul instance [has_zero α] [Π i, has_zero (β i)] [Π i, smul_with_zero α (β i)] : smul_with_zero α (hamming β) := pi.smul_with_zero _ instance [Π i, add_monoid (β i)] : add_monoid (hamming β) := pi.add_monoid instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (hamming β) := pi.add_comm_monoid instance [Π i, add_comm_group (β i)] : add_comm_group (hamming β) := pi.add_comm_group instance (α) [semiring α] (β : ι → Type*) [Π i, add_comm_monoid (β i)] [Π i, module α (β i)] : module α (hamming β) := pi.module _ _ _ /-! API to/from the type synonym. -/ /-- `to_hamming` is the identity function to the `hamming` of a type. -/ @[pattern] def to_hamming : (Π i, β i) ≃ hamming β := equiv.refl _ /-- `of_hamming` is the identity function from the `hamming` of a type. -/ @[pattern] def of_hamming : hamming β ≃ Π i, β i := equiv.refl _ @[simp] lemma to_hamming_symm_eq : (@to_hamming _ β).symm = of_hamming := rfl @[simp] lemma of_hamming_symm_eq : (@of_hamming _ β).symm = to_hamming := rfl @[simp] lemma to_hamming_of_hamming (x : hamming β) : to_hamming (of_hamming x) = x := rfl @[simp] lemma of_hamming_to_hamming (x : Π i, β i) : of_hamming (to_hamming x) = x := rfl @[simp] lemma to_hamming_inj {x y : Π i, β i} : to_hamming x = to_hamming y ↔ x = y := iff.rfl @[simp] lemma of_hamming_inj {x y : hamming β} : of_hamming x = of_hamming y ↔ x = y := iff.rfl @[simp] lemma to_hamming_zero [Π i, has_zero (β i)] : to_hamming (0 : Π i, β i) = 0 := rfl @[simp] lemma of_hamming_zero [Π i, has_zero (β i)] : of_hamming (0 : hamming β) = 0 := rfl @[simp] lemma to_hamming_neg [Π i, has_neg (β i)] {x : Π i, β i} : to_hamming (-x) = - to_hamming x := rfl @[simp] lemma of_hamming_neg [Π i, has_neg (β i)] {x : hamming β} : of_hamming (-x) = - of_hamming x := rfl @[simp] lemma to_hamming_add [Π i, has_add (β i)] {x y : Π i, β i} : to_hamming (x + y) = to_hamming x + to_hamming y := rfl @[simp] lemma of_hamming_add [Π i, has_add (β i)] {x y : hamming β} : of_hamming (x + y) = of_hamming x + of_hamming y := rfl @[simp] lemma to_hamming_sub [Π i, has_sub (β i)] {x y : Π i, β i} : to_hamming (x - y) = to_hamming x - to_hamming y := rfl @[simp] lemma of_hamming_sub [Π i, has_sub (β i)] {x y : hamming β} : of_hamming (x - y) = of_hamming x - of_hamming y := rfl @[simp] lemma to_hamming_smul [Π i, has_smul α (β i)] {r : α} {x : Π i, β i} : to_hamming (r • x) = r • to_hamming x := rfl @[simp] lemma of_hamming_smul [Π i, has_smul α (β i)] {r : α} {x : hamming β} : of_hamming (r • x) = r • of_hamming x := rfl section /-! Instances equipping `hamming` with `hamming_norm` and `hamming_dist`. -/ variables [fintype ι] [Π i, decidable_eq (β i)] instance : has_dist (hamming β) := ⟨λ x y, hamming_dist (of_hamming x) (of_hamming y)⟩ @[simp, push_cast] lemma dist_eq_hamming_dist (x y : hamming β) : dist x y = hamming_dist (of_hamming x) (of_hamming y) := rfl instance : pseudo_metric_space (hamming β) := { dist_self := by { push_cast, exact_mod_cast hamming_dist_self }, dist_comm := by { push_cast, exact_mod_cast hamming_dist_comm }, dist_triangle := by { push_cast, exact_mod_cast hamming_dist_triangle }, to_uniform_space := ⊥, uniformity_dist := uniformity_dist_of_mem_uniformity _ _ $ λ s, begin push_cast, split, { refine λ hs, ⟨1, zero_lt_one, λ _ _ hab, _⟩, rw_mod_cast [hamming_dist_lt_one] at hab, rw [of_hamming_inj, ← mem_id_rel] at hab, exact hs hab }, { rintros ⟨_, hε, hs⟩ ⟨_, _⟩ hab, rw mem_id_rel at hab, rw hab, refine hs (lt_of_eq_of_lt _ hε), exact_mod_cast hamming_dist_self _ } end, to_bornology := ⟨⊥, bot_le⟩, cobounded_sets := begin ext, push_cast, refine iff_of_true (filter.mem_sets.mpr filter.mem_bot) ⟨fintype.card ι, λ _ _ _ _, _⟩, exact_mod_cast hamming_dist_le_card_fintype end, ..hamming.has_dist } @[simp, push_cast] lemma nndist_eq_hamming_dist (x y : hamming β) : nndist x y = hamming_dist (of_hamming x) (of_hamming y) := rfl instance : metric_space (hamming β) := { eq_of_dist_eq_zero := by { push_cast, exact_mod_cast @eq_of_hamming_dist_eq_zero _ _ _ _ }, ..hamming.pseudo_metric_space } instance [Π i, has_zero (β i)] : has_norm (hamming β) := ⟨λ x, hamming_norm (of_hamming x)⟩ @[simp, push_cast] lemma norm_eq_hamming_norm [Π i, has_zero (β i)] (x : hamming β) : ‖x‖ = hamming_norm (of_hamming x) := rfl instance [Π i, add_comm_group (β i)] : seminormed_add_comm_group (hamming β) := { dist_eq := by { push_cast, exact_mod_cast hamming_dist_eq_hamming_norm }, ..pi.add_comm_group } @[simp, push_cast] lemma nnnorm_eq_hamming_norm [Π i, add_comm_group (β i)] (x : hamming β) : ‖x‖₊ = hamming_norm (of_hamming x) := rfl instance [Π i, add_comm_group (β i)] : normed_add_comm_group (hamming β) := { ..hamming.seminormed_add_comm_group } end end hamming
a395fe0858d0e639e7c7ecae2872ebcb084b83ca
41ed4e6eacdd37c176d4ecf70193b40b9f9e1a93
/src/thomaes_function.lean
168b722300c3a41079c20bc5be9010c379aa68f0
[]
no_license
FrickHazard/thomaes-function
ae67a4a0d01cf00d128639eec4740879a057240d
260ba849187a5a1867ec988370010e6aebc31f00
refs/heads/main
1,689,771,900,819
1,631,674,532,000
1,631,674,532,000
392,437,647
2
0
null
1,628,695,346,000
1,628,020,204,000
Lean
UTF-8
Lean
false
false
7,273
lean
/- Copyright (c) 2015, 2017 Ender Doe. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ender Doe, Kevin Buzzard -/ import data.real.irrational local notation `|` x `|` := abs x open_locale classical /-- The thomae's function on reals also known as the "Popcorn" function. -/ noncomputable def thomaes_function (r : ℝ) : ℝ := if h : ∃ (q : ℚ), (q : ℝ) = r then (classical.some h).denom⁻¹ else 0 theorem thomaes_at_irrational_eq_zero {x : ℝ} (h: irrational x) : thomaes_function x = 0 := dif_neg $ h /-- The thomae function, restricted to the rationals and taking values in the rationals. -/ def thomae_rat (q : ℚ) : ℚ := q.denom⁻¹ @[norm_cast] lemma coe_thomae_rat (q : ℚ) : thomaes_function q = thomae_rat q := begin unfold thomaes_function, rw dif_pos (⟨q, rfl⟩ : ∃ (q_1 : ℚ), (q_1 : ℝ) = ↑q), { generalize_proofs h, unfold thomae_rat, norm_num, congr', exact_mod_cast classical.some_spec h }, end @[norm_cast] lemma coe_thomae_rat' (q : ℚ) : (thomae_rat q : ℝ) = thomaes_function q := (coe_thomae_rat q).symm @[simp] lemma thomae_rat_num (q : ℚ) : (thomae_rat q).num = 1 := by simp [thomae_rat, rat.inv_coe_nat_num q.pos ] @[simp] lemma thomae_rat_denom (q : ℚ) : (thomae_rat q).denom = q.denom := by simp [thomae_rat, rat.inv_coe_nat_denom q.pos] theorem thomae_rat_pos (q : ℚ) : 0 < (thomae_rat q) := begin apply rat.num_pos_iff_pos.mp, rw thomae_rat_num, exact zero_lt_one, end -- add to rat library? theorem rat.add_int_denom (z: ℤ) (q : ℚ) : (q + z).denom = q.denom := begin rw rat.add_num_denom, simp, rw rat.mk_eq_div, -- I copied this trick from above suffices :(((((q.num + ↑(q.denom) * z) : ℤ) : ℚ) / ((q.denom) : ℤ)).denom : ℤ) = q.denom, exact_mod_cast this, apply rat.denom_div_eq_of_coprime, exact_mod_cast q.pos, exact int.coprime_iff_nat_coprime.mp (is_coprime.add_mul_left_left (int.coprime_iff_nat_coprime.mpr (by exact_mod_cast q.cop)) _), end @[simp] theorem thomaes_is_perodic (n : ℤ) (x : ℝ) : thomaes_function (x + n) = thomaes_function x := begin by_cases (irrational x), rw [ thomaes_at_irrational_eq_zero (by exact_mod_cast irrational.add_rat n h), thomaes_at_irrational_eq_zero h ], unfold irrational at h, push_neg at h, cases h with q q_eq_x, subst q_eq_x, norm_cast, apply rat.eq_iff_mul_eq_mul.mpr, simp [thomae_rat_num, thomae_rat_denom], symmetry, exact rat.add_int_denom _ _, end theorem irrational_ne_rat {x: ℝ} (q : ℚ) (h: irrational x) : x ≠ q := λ h2, h ⟨q, h2.symm⟩ lemma δᵢ_pos {x : ℝ} (i : ℕ) (h : irrational x) : 0 < min (|x - ⌊x * i⌋ / (i :ℝ)|) (|x - (⌊x * i⌋ + 1) / (i :ℝ)|) := begin simp only [abs_pos, gt_iff_lt, lt_min_iff], split, { suffices : x ≠ ((⌊x * ↑i⌋ / i) : ℚ), exact_mod_cast sub_ne_zero.mpr this, exact irrational_ne_rat _ h }, { suffices : x ≠ (((⌊x * ↑i⌋ + 1) / i) : ℚ), exact_mod_cast sub_ne_zero.mpr this, exact irrational_ne_rat _ h }, end lemma floor_lt_irrational (x : ℝ) (h : irrational x) : ↑⌊x⌋ < x := begin cases lt_or_eq_of_le (floor_le x) with h2 h2, { exact h2 }, exact false.elim (irrational_ne_rat (⌊ x ⌋) h (by exact_mod_cast h2.symm)), end lemma irrational.floor_mul_div_lt {x : ℝ} (h: irrational x) {i: ℕ} (hi : 0 < i) : ((⌊x * i⌋ / i) : ℝ) < x := begin rw div_lt_iff (show 0 < (i : ℝ), by assumption_mod_cast), apply floor_lt_irrational, convert irrational.mul_rat h (show (i : ℚ) ≠ 0, by exact_mod_cast (ne_of_lt hi).symm) using 2, norm_cast, end lemma irrational.floor_mul_add_one_div_lt {i: ℕ} (x : ℝ) (hi : 0 < i) : x < ((⌊x * i⌋ + 1) : ℝ) / (i : ℝ) := begin rw lt_div_iff (show 0 < (i : ℝ), by assumption_mod_cast), exact lt_floor_add_one _, end theorem δᵢ_between {x: ℝ} {r : ℝ} {i : ℕ} (hx0 : irrational x) (hn0 : 0 < i) (h : |r - x| < min (|x - ⌊x * i⌋ / (i :ℝ)|) (|x - (⌊x * i⌋ + 1) / (i :ℝ)|)) : (⌊x * i⌋ / i : ℝ) < r ∧ r < ((⌊x * i⌋ + 1) / i : ℝ) := begin simp only [lt_min_iff] at h, rw abs_of_pos (sub_pos_of_lt (irrational.floor_mul_div_lt hx0 hn0)) at h, rw abs_of_neg (sub_neg_of_lt (irrational.floor_mul_add_one_div_lt x hn0)) at h, split, linarith [(abs_lt.mp h.left).left], linarith [(abs_lt.mp h.right).right], end theorem no_rat_between (n : ℤ) (q : ℚ) (l: (n / q.denom : ℚ) < q) (r: q < ((n + 1) / q.denom : ℚ)) : false := begin nth_rewrite 1 ←rat.num_div_denom q at l, nth_rewrite 0 ←rat.num_div_denom q at r, have h : (0 : ℚ) < q.denom := by exact_mod_cast q.pos, have l' := (mul_lt_mul_right h).mp ((div_lt_div_iff h h).mp l), norm_cast at l', have r' := (mul_lt_mul_right h).mp ((div_lt_div_iff h h).mp r), norm_cast at r', linarith, end theorem thomaes_continous_at_irrational {x} (h : irrational x) : continuous_at thomaes_function x := begin apply metric.continuous_at_iff.mpr, simp_rw [real.dist_eq, thomaes_at_irrational_eq_zero h, sub_zero], intros ε ε_pos, obtain ⟨r, hr⟩ := exists_nat_one_div_lt ε_pos, have r_add_one_pos : 0 < r + 1 := nat.succ_pos r, rw one_div at hr, let δᵢ : ℝ → ℕ → ℝ := λ x i, min (|x - ⌊x * i⌋ / (i :ℝ)|) (|x - (⌊x * i⌋ + 1) / (i :ℝ)|), obtain ⟨i_min, ⟨i_pos, i_le_r⟩, i_min_indice⟩ := set.exists_min_image _ (δᵢ x) -- δ indices are finite and nonempty (set.Ioc_ℕ_finite 0 _) (⟨1, zero_lt_one, nat.one_le_of_lt r_add_one_pos⟩), refine ⟨δᵢ x i_min, δᵢ_pos i_min h, λ x₁ hδ, _⟩, by_cases H : ∃ q : ℚ, (q : ℝ) = x₁, { obtain ⟨q, rfl⟩ := H, norm_cast, rw abs_of_pos (thomae_rat_pos q), have r_add_one_le_q_denom : (r + 1) ≤ q.denom, { by_contradiction H, push_neg at H, have lt_delta_of_q := lt_of_lt_of_le hδ (i_min_indice q.denom ⟨q.pos, le_of_lt H⟩), obtain ⟨l, r⟩ := δᵢ_between h q.pos lt_delta_of_q, exact no_rat_between (⌊ x * q.denom⌋) q (by exact_mod_cast l) (by exact_mod_cast r) }, rw thomae_rat, exact_mod_cast (lt_of_le_of_lt ( (inv_le_inv (show 0 < ((q.denom : ℚ) : ℝ), by exact_mod_cast q.pos) (show 0 < (r + 1 :ℝ ), by exact_mod_cast r_add_one_pos)).mpr (by exact_mod_cast r_add_one_le_q_denom)) hr), }, { rw thomaes_at_irrational_eq_zero H, simpa using ε_pos }, end theorem thomaes_discontinous_at_rational (q : ℚ) : ¬continuous_at thomaes_function q := begin intro h, simp only [metric.continuous_at_iff] at h, norm_cast at h, specialize h (thomae_rat q) (by exact_mod_cast (thomae_rat_pos q)), rcases h with ⟨δ, δ_pos, hδ⟩, simp_rw real.dist_eq at hδ, rcases exists_irrational_btwn δ_pos with ⟨r, ⟨r_irrat, r_pos, r_lt_δ⟩⟩, specialize hδ (show |(r + q) - q| < δ, by simpa [abs_of_pos r_pos]), rw [ thomaes_at_irrational_eq_zero (irrational.add_rat q r_irrat) ] at hδ, simp only [zero_sub, abs_neg] at hδ, rw abs_of_pos (show ((thomae_rat q) : ℝ) > 0, by exact_mod_cast (thomae_rat_pos q)) at hδ, exact (lt_self_iff_false _).mp hδ, end
af7026e0369d53d205db10a238999226f1d1307e
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/algebra/ordered_ring.lean
911695d701b487224a64edf489cd63ccf8280fc2
[ "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
16,048
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.ordered_group init.algebra.ring /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_comm_monoid α := (mul_le_mul_of_nonneg_left: ∀ a b c : α, a ≤ b → 0 ≤ c → c * a ≤ c * b) (mul_le_mul_of_nonneg_right: ∀ a b c : α, a ≤ b → 0 ≤ c → a * c ≤ b * c) (mul_lt_mul_of_pos_left: ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right: ∀ a b c : α, a < b → 0 < c → a * c < b * c) variable {α : Type u} section ordered_semiring variable [ordered_semiring α] lemma mul_le_mul_of_nonneg_left {a b c : α} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := ordered_semiring.mul_le_mul_of_nonneg_left a b c h₁ h₂ lemma mul_le_mul_of_nonneg_right {a b c : α} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := ordered_semiring.mul_le_mul_of_nonneg_right a b c h₁ h₂ lemma mul_lt_mul_of_pos_left {a b c : α} (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right {a b c : α} (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ -- TODO: there are four variations, depending on which variables we assume to be nonneg lemma mul_le_mul {a b c d : α} (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_nonneg {a b : α} (ha : a ≥ 0) (hb : b ≥ 0) : a * b ≥ 0 := have h : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonpos_of_nonneg_of_nonpos {a b : α} (ha : a ≥ 0) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonpos_of_nonneg {a b : α} (ha : a ≤ 0) (hb : b ≥ 0) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_lt_mul {a b c d : α} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul' {a b c d : α} (h1 : a < c) (h2 : b < d) (h3 : b ≥ 0) (h4 : c > 0) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right (le_of_lt h1) h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_pos {a b : α} (ha : a > 0) (hb : b > 0) : a * b > 0 := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg {a b : α} (ha : a > 0) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos {a b : α} (ha : a < 0) (hb : b > 0) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_self_lt_mul_self {a b : α} (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' h2 h2 h1 (lt_of_le_of_lt h1 h2) end ordered_semiring class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_strong_order_pair α := (zero_lt_one : zero < one) section linear_ordered_semiring variable [linear_ordered_semiring α] lemma zero_lt_one : 0 < (1:α) := linear_ordered_semiring.zero_lt_one α lemma zero_le_one : 0 ≤ (1:α) := le_of_lt zero_lt_one lemma lt_of_mul_lt_mul_left {a b c : α} (h : c * a < c * b) (hc : c ≥ 0) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left h1 hc, not_lt_of_ge h2 h) lemma lt_of_mul_lt_mul_right {a b c : α} (h : a * c < b * c) (hc : c ≥ 0) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right h1 hc, not_lt_of_ge h2 h) lemma le_of_mul_le_mul_left {a b c : α} (h : c * a ≤ c * b) (hc : c > 0) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, not_le_of_gt h2 h) lemma le_of_mul_le_mul_right {a b c : α} (h : a * c ≤ b * c) (hc : c > 0) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, not_le_of_gt h2 h) lemma pos_of_mul_pos_left {a b : α} (h : 0 < a * b) (h1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume h2 : b ≤ 0, have h3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos h1 h2, not_lt_of_ge h3 h) lemma pos_of_mul_pos_right {a b : α} (h : 0 < a * b) (h1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume h2 : a ≤ 0, have h3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg h2 h1, not_lt_of_ge h3 h) lemma nonneg_of_mul_nonneg_left {a b : α} (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg h1 h2) h) lemma nonneg_of_mul_nonneg_right {a b : α} (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos h2 h1) h) lemma neg_of_mul_neg_left {a b : α} (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume h2 : b ≥ 0, not_lt_of_ge (mul_nonneg h1 h2) h) lemma neg_of_mul_neg_right {a b : α} (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume h2 : a ≥ 0, not_lt_of_ge (mul_nonneg h2 h1) h) lemma nonpos_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, not_le_of_gt (mul_pos h1 h2) h) lemma nonpos_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, not_le_of_gt (mul_pos h2 h1) h) end linear_ordered_semiring class decidable_linear_ordered_semiring (α : Type u) extends linear_ordered_semiring α, decidable_linear_order α class ordered_ring (α : Type u) extends ring α, ordered_comm_group α, zero_ne_one_class α := (mul_nonneg : ∀ a b : α, 0 ≤ a → 0 ≤ b → 0 ≤ a * b) (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) lemma ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring α] {a b c : α} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ c * (b - a), from ordered_ring.mul_nonneg c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring α] {a b c : α} (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring α] {a b c : α} (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply lt_of_sub_pos this end lemma ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring α] {a b c : α} (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply lt_of_sub_pos this end instance ordered_ring.to_ordered_semiring [s : ordered_ring α] : ordered_semiring α := { s with mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left α _, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right α _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, lt_of_add_lt_add_left := @lt_of_add_lt_add_left α _} section ordered_ring variable [ordered_ring α] lemma mul_le_mul_of_nonpos_left {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [-neg_mul_eq_neg_mul, -neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [-neg_mul_eq_mul_neg, -neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [-neg_mul_eq_neg_mul, -neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [-neg_mul_eq_mul_neg, -neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this end ordered_ring class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_strong_order_pair α := (zero_lt_one : lt zero one) instance linear_ordered_ring.to_linear_ordered_semiring [s : linear_ordered_ring α] : linear_ordered_semiring α := { s with mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left α _, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right α _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left α _ } section linear_ordered_ring variable [linear_ordered_ring α] lemma mul_self_nonneg (a : α) : a * a ≥ 0 := or.elim (le_total 0 a) (assume h : a ≥ 0, mul_nonneg h h) (assume h : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos h h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos {a b : α} (hab : a * b > 0) : (a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := match lt_trichotomy 0 a with | or.inl hlt₁ := match lt_trichotomy 0 b with | or.inl hlt₂ := or.inl ⟨hlt₁, hlt₂⟩ | or.inr (or.inl heq₂) := begin rw [-heq₂, mul_zero] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₂) := absurd hab (lt_asymm (mul_neg_of_pos_of_neg hlt₁ hgt₂)) end | or.inr (or.inl heq₁) := begin rw [-heq₁, zero_mul] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₁) := match lt_trichotomy 0 b with | or.inl hlt₂ := absurd hab (lt_asymm (mul_neg_of_neg_of_pos hgt₁ hlt₂)) | or.inr (or.inl heq₂) := begin rw [-heq₂, mul_zero] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₂) := or.inr ⟨hgt₁, hgt₂⟩ end end lemma gt_of_mul_lt_mul_neg_left {a b c : α} (h : c * a < c * b) (hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma zero_gt_neg_one : -1 < (0:α) := begin note this := neg_lt_neg (@zero_lt_one α _), rwa neg_zero at this end lemma le_of_mul_le_of_ge_one {a b c : α} (h : a * c ≤ b) (hb : b ≥ 0) (hc : c ≥ 1) : a ≤ b := have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (lt_of_lt_of_le zero_lt_one hc) lemma nonneg_le_nonneg_of_squares_le {a b : α} (ha : a ≥ 0) (hb : b ≥ 0) (h : a * a ≤ b * b) : a ≤ b := begin apply le_of_not_gt, intro hab, note hposa := lt_of_le_of_lt hb hab, note h' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt hab) hb ... < a * a : mul_lt_mul_of_pos_left hab hposa, apply (not_le_of_gt h') h end end linear_ordered_ring class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α lemma linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring α] {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := match lt_trichotomy 0 a with | or.inl hlt₁ := match lt_trichotomy 0 b with | or.inl hlt₂ := have 0 < a * b, from mul_pos hlt₁ hlt₂, begin rw h at this, exact absurd this (lt_irrefl _) end | or.inr (or.inl heq₂) := or.inr heq₂.symm | or.inr (or.inr hgt₂) := have 0 > a * b, from mul_neg_of_pos_of_neg hlt₁ hgt₂, begin rw h at this, exact absurd this (lt_irrefl _) end end | or.inr (or.inl heq₁) := or.inl heq₁.symm | or.inr (or.inr hgt₁) := match lt_trichotomy 0 b with | or.inl hlt₂ := have 0 > a * b, from mul_neg_of_neg_of_pos hgt₁ hlt₂, begin rw h at this, exact absurd this (lt_irrefl _) end | or.inr (or.inl heq₂) := or.inr heq₂.symm | or.inr (or.inr hgt₂) := have 0 < a * b, from mul_pos_of_neg_of_neg hgt₁ hgt₂, begin rw h at this, exact absurd this (lt_irrefl _) end end end instance linear_ordered_comm_ring.to_integral_domain [s: linear_ordered_comm_ring α] : integral_domain α := {s with eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero α s } class decidable_linear_ordered_comm_ring (α : Type u) extends linear_ordered_comm_ring α, decidable_linear_ordered_comm_group α instance decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [d : decidable_linear_ordered_comm_ring α] : decidable_linear_ordered_semiring α := let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in {d with zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, add_right_cancel := @linear_ordered_semiring.add_right_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, lt_of_add_lt_add_left := @linear_ordered_semiring.lt_of_add_lt_add_left α s, mul_le_mul_of_nonneg_left := @linear_ordered_semiring.mul_le_mul_of_nonneg_left α s, mul_le_mul_of_nonneg_right := @linear_ordered_semiring.mul_le_mul_of_nonneg_right α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s}
80ecbb87b943dced2baf6c7adc36b8506fdae301
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/fin/basic.lean
2be427042b55460c383daab4d80f0bc6928f69c4
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
72,477
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import algebra.ne_zero import algebra.order.with_zero import order.rel_iso.basic import data.nat.order.basic import order.hom.set /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; * `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the `nat`-like base cases of `C 0` and `C (i.succ)`. * `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument. * `fin.cases` : define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = fin.succ j`, `j : fin n`, defined using `fin.induction`. * `fin.reverse_induction`: reverse induction on `i : fin (n + 1)`; given `C (fin.last n)` and `∀ i : fin n, C (fin.succ i) → C (fin.cast_succ i)`, constructs all values `C i` by going down; * `fin.last_cases`: define `f : Π i, fin (n + 1), C i` by separately handling the cases `i = fin.last n` and `i = fin.cast_succ j`, a special case of `fin.reverse_induction`; * `fin.add_cases`: define a function on `fin (m + n)` by separately handling the cases `fin.cast_add n i` and `fin.nat_add m i`; * `fin.succ_above_cases`: given `i : fin (n + 1)`, define a function on `fin (n + 1)` by separately handling the cases `j = i` and `j = fin.succ_above i k`, same as `fin.insert_nth` but marked as eliminator and works for `Sort*`. ### Order embeddings and an order isomorphism * `fin.order_iso_subtype` : coercion to `{ i // i < n }` as an `order_iso`; * `fin.coe_embedding` : coercion to natural numbers as an `embedding`; * `fin.coe_order_embedding` : coercion to natural numbers as an `order_embedding`; * `fin.succ_embedding` : `fin.succ` as an `order_embedding`; * `fin.cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`; * `fin.cast eq` : order isomorphism between `fin n` and fin m` provided that `n = m`, see also `equiv.fin_congr`; * `fin.cast_add m` : embed `fin n` into `fin (n+m)`; * `fin.cast_succ` : embed `fin n` into `fin (n+1)`; * `fin.succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `fin.add_nat m i` : add `m` on `i` on the right, generalizes `fin.succ`; * `fin.nat_add n i` adds `n` on `i` on the left; ### Other casts * `fin.of_nat'`: given a positive number `n` (deduced from `[ne_zero n]`), `fin.of_nat' i` is `i % n` interpreted as an element of `fin n`; * `fin.cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `fin.pred_above (p : fin n) i` : embed `i : fin (n+1)` into `fin n` by subtracting one if `p < i`; * `fin.cast_pred` : embed `fin (n + 2)` into `fin (n + 1)` by mapping `fin.last (n + 1)` to `fin.last n`; * `fin.sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`; * `fin.clamp n m` : `min n m` as an element of `fin (m + 1)`; * `fin.div_nat i` : divides `i : fin (m * n)` by `n`; * `fin.mod_nat i` : takes the mod of `i : fin (m * n)` by `n`; ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. * `fin.rev : fin n → fin n` : the antitone involution given by `i ↦ n-(i+1)` -/ universes u v open fin nat function /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0 namespace fin /-- A non-dependent variant of `elim0`. -/ def elim0' {α : Sort*} (x : fin 0) : α := x.elim0 variables {n m : ℕ} {a b : fin n} instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨fin.val⟩ lemma val_injective : function.injective (@fin.val n) := @fin.eq_of_veq n protected lemma prop (a : fin n) : a.val < n := a.2 @[simp] lemma is_lt (a : fin n) : (a : ℕ) < n := a.2 protected lemma pos (i : fin n) : 0 < n := lt_of_le_of_lt (nat.zero_le _) i.is_lt lemma pos_iff_nonempty {n : ℕ} : 0 < n ↔ nonempty (fin n) := ⟨λ h, ⟨⟨0, h⟩⟩, λ ⟨i⟩, i.pos⟩ /-- Equivalence between `fin n` and `{ i // i < n }`. -/ @[simps apply symm_apply] def equiv_subtype : fin n ≃ { i // i < n } := { to_fun := λ a, ⟨a.1, a.2⟩, inv_fun := λ a, ⟨a.1, a.2⟩, left_inv := λ ⟨_, _⟩, rfl, right_inv := λ ⟨_, _⟩, rfl } section coe /-! ### coercions and constructions -/ @[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a := by cases a; refl @[ext] lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h lemma ext_iff {a b : fin n} : a = b ↔ (a : ℕ) = b := iff.intro (congr_arg _) fin.eq_of_veq lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := fin.val_injective lemma coe_eq_coe (a b : fin n) : (a : ℕ) = b ↔ a = b := ext_iff.symm lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 := ⟨vne_of_ne, ne_of_vne⟩ @[simp, nolint simp_nf] -- built-in reduction doesn't always work theorem mk_eq_mk {a h a' h'} : @mk n a h = @mk n a' h' ↔ a = a' := ext_iff protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : (⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b := eq_iff_veq _ _ lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k := fin.eq_iff_veq a ⟨k, hk⟩ @[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma mk_coe (i : fin n) : (⟨i, i.property⟩ : fin n) = i := fin.eta _ _ lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl @[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected lemma heq_fun_iff {α : Sort*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} : f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) := by { subst h, simp [function.funext_iff] } protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ (i : ℕ) = (j : ℕ) := by { subst h, simp [coe_eq_coe] } lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ end coe section order /-! ### order -/ lemma is_le (i : fin (n + 1)) : (i : ℕ) ≤ n := le_of_lt_succ i.is_lt @[simp] lemma is_le' : (a : ℕ) ≤ n := le_of_lt a.is_lt lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl lemma mk_lt_of_lt_coe {a : ℕ} (h : a < b) : (⟨a, h.trans b.is_lt⟩ : fin n) < b := h lemma mk_le_of_le_coe {a : ℕ} (h : a ≤ b) : (⟨a, h.trans_lt b.is_lt⟩ : fin n) ≤ b := h /-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b := iff.rfl /-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b := iff.rfl instance {n : ℕ} : linear_order (fin n) := @linear_order.lift (fin n) _ _ ⟨λ x y, ⟨max x y, max_rec' (< n) x.2 y.2⟩⟩ ⟨λ x y, ⟨min x y, min_rec' (< n) x.2 y.2⟩⟩ fin.val fin.val_injective (λ _ _, rfl) (λ _ _, rfl) @[simp] lemma mk_le_mk {x y : nat} {hx} {hy} : (⟨x, hx⟩ : fin n) ≤ ⟨y, hy⟩ ↔ x ≤ y := iff.rfl @[simp] lemma mk_lt_mk {x y : nat} {hx} {hy} : (⟨x, hx⟩ : fin n) < ⟨y, hy⟩ ↔ x < y := iff.rfl @[simp] lemma min_coe : min (a : ℕ) n = a := by simp @[simp] lemma max_coe : max (a : ℕ) n = n := by simp instance {n : ℕ} : partial_order (fin n) := by apply_instance lemma coe_strict_mono : strict_mono (coe : fin n → ℕ) := λ _ _, id /-- The equivalence `fin n ≃ { i // i < n }` is an order isomorphism. -/ @[simps apply symm_apply] def order_iso_subtype : fin n ≃o { i // i < n } := equiv_subtype.to_order_iso (by simp [monotone]) (by simp [monotone]) /-- The inclusion map `fin n → ℕ` is an embedding. -/ @[simps apply] def coe_embedding : fin n ↪ ℕ := ⟨coe, coe_injective⟩ @[simp] lemma equiv_subtype_symm_trans_val_embedding : equiv_subtype.symm.to_embedding.trans coe_embedding = embedding.subtype (< n) := rfl /-- The inclusion map `fin n → ℕ` is an order embedding. -/ @[simps apply] def coe_order_embedding (n) : (fin n) ↪o ℕ := ⟨coe_embedding, λ a b, iff.rfl⟩ /-- The ordering on `fin n` is a well order. -/ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (coe_order_embedding n).is_well_order /-- Use the ordering on `fin n` for checking recursive definitions. For example, the following definition is not accepted by the termination checker, unless we declare the `has_well_founded` instance: ```lean def factorial {n : ℕ} : fin n → ℕ | ⟨0, _⟩ := 1 | ⟨i + 1, hi⟩ := (i + 1) * factorial ⟨i, i.lt_succ_self.trans hi⟩ ``` -/ instance {n : ℕ} : has_well_founded (fin n) := ⟨_, measure_wf coe⟩ instance has_zero_of_ne_zero [ne_zero n] : has_zero (fin n) := ⟨⟨0, ne_zero.pos _⟩⟩ /-- Given a positive `n`, `fin.of_nat' i` is `i % n` as an element of `fin n`. -/ def of_nat' [ne_zero n] (i : ℕ) : fin n := ⟨i%n, mod_lt _ $ ne_zero.pos n⟩ instance has_one_of_ne_zero [ne_zero n] : has_one (fin n) := ⟨of_nat' 1⟩ @[simp] lemma coe_zero (n : ℕ) [ne_zero n] : ((0 : fin n) : ℕ) = 0 := rfl attribute [simp] val_zero @[simp] lemma val_zero' (n) [ne_zero n] : (0 : fin n).val = 0 := rfl @[simp] lemma mk_zero [ne_zero n] : (⟨0, nat.pos_of_ne_zero (ne_zero.ne n)⟩ : fin n) = (0 : fin _) := rfl @[simp] lemma zero_le [ne_zero n] (a : fin n) : 0 ≤ a := zero_le a.1 lemma zero_lt_one : (0 : fin (n + 2)) < 1 := nat.zero_lt_one @[simp] lemma not_lt_zero (a : fin n.succ) : ¬a < 0. lemma pos_iff_ne_zero [ne_zero n] (a : fin n) : 0 < a ↔ a ≠ 0 := by rw [← coe_fin_lt, coe_zero, pos_iff_ne_zero, ne.def, ne.def, ext_iff, coe_zero] lemma eq_zero_or_eq_succ {n : ℕ} (i : fin (n+1)) : i = 0 ∨ ∃ j : fin n, i = j.succ := begin rcases i with ⟨_|j, h⟩, { left, refl, }, { right, exact ⟨⟨j, nat.lt_of_succ_lt_succ h⟩, rfl⟩, } end lemma eq_succ_of_ne_zero {n : ℕ} {i : fin (n + 1)} (hi : i ≠ 0) : ∃ j : fin n, i = j.succ := (eq_zero_or_eq_succ i).resolve_left hi /-- The antitone involution `fin n → fin n` given by `i ↦ n-(i+1)`. -/ def rev : equiv.perm (fin n) := involutive.to_perm (λ i, ⟨n - (i + 1), tsub_lt_self i.pos (nat.succ_pos _)⟩) $ λ i, ext $ by rw [coe_mk, coe_mk, ← tsub_tsub, tsub_tsub_cancel_of_le (nat.add_one_le_iff.2 i.is_lt), add_tsub_cancel_right] @[simp] lemma coe_rev (i : fin n) : (i.rev : ℕ) = n - (i + 1) := rfl lemma rev_involutive : involutive (@rev n) := involutive.to_perm_involutive _ lemma rev_injective : injective (@rev n) := rev_involutive.injective lemma rev_surjective : surjective (@rev n) := rev_involutive.surjective lemma rev_bijective : bijective (@rev n) := rev_involutive.bijective @[simp] lemma rev_inj {i j : fin n} : i.rev = j.rev ↔ i = j := rev_injective.eq_iff @[simp] lemma rev_rev (i : fin n) : i.rev.rev = i := rev_involutive _ @[simp] lemma rev_symm : (@rev n).symm = rev := rfl lemma rev_eq {n a : ℕ} (i : fin (n+1)) (h : n=a+i) : i.rev = ⟨a, nat.lt_succ_iff.mpr (nat.le.intro (h.symm))⟩ := begin ext, dsimp, conv_lhs { congr, rw h, }, rw [add_assoc, add_tsub_cancel_right], end @[simp] lemma rev_le_rev {i j : fin n} : i.rev ≤ j.rev ↔ j ≤ i := by simp only [le_iff_coe_le_coe, coe_rev, tsub_le_tsub_iff_left (nat.add_one_le_iff.2 j.is_lt), add_le_add_iff_right] @[simp] lemma rev_lt_rev {i j : fin n} : i.rev < j.rev ↔ j < i := lt_iff_lt_of_le_iff_le rev_le_rev /-- `fin.rev n` as an order-reversing isomorphism. -/ @[simps apply to_equiv] def rev_order_iso {n} : (fin n)ᵒᵈ ≃o fin n := ⟨order_dual.of_dual.trans rev, λ i j, rev_le_rev⟩ @[simp] lemma rev_order_iso_symm_apply (i : fin n) : rev_order_iso.symm i = order_dual.to_dual i.rev := rfl /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ @[simp, norm_cast] lemma coe_last (n : ℕ) : (last n : ℕ) = n := rfl lemma last_val (n : ℕ) : (last n).val = n := rfl theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt instance : bounded_order (fin (n+1)) := { top := last n, le_top := le_last, bot := 0, bot_le := zero_le } instance : lattice (fin (n + 1)) := linear_order.to_lattice lemma last_pos : (0 : fin (n + 2)) < last (n + 1) := by simp [lt_iff_coe_lt_coe] lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n := le_antisymm (le_last i) (not_lt.1 h) lemma top_eq_last (n : ℕ) : ⊤ = fin.last n := rfl lemma bot_eq_zero (n : ℕ) : ⊥ = (0 : fin (n+1)) := rfl section variables {α : Type*} [preorder α] open set /-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity map. In this lemma we state that for each `i : fin n` we have `(e i : ℕ) = (i : ℕ)`. -/ @[simp] lemma coe_order_iso_apply (e : fin n ≃o fin m) (i : fin n) : (e i : ℕ) = i := begin rcases i with ⟨i, hi⟩, rw [fin.coe_mk], induction i using nat.strong_induction_on with i h, refine le_antisymm (forall_lt_iff_le.1 $ λ j hj, _) (forall_lt_iff_le.1 $ λ j hj, _), { have := e.symm.lt_iff_lt.2 (mk_lt_of_lt_coe hj), rw e.symm_apply_apply at this, convert this, simpa using h _ this (e.symm _).is_lt }, { rwa [← h j hj (hj.trans hi), ← lt_iff_coe_lt_coe, e.lt_iff_lt] } end instance order_iso_subsingleton : subsingleton (fin n ≃o α) := ⟨λ e e', by { ext i, rw [← e.symm.apply_eq_iff_eq, e.symm_apply_apply, ← e'.trans_apply, ext_iff, coe_order_iso_apply] }⟩ instance order_iso_subsingleton' : subsingleton (α ≃o fin n) := order_iso.symm_injective.subsingleton instance order_iso_unique : unique (fin n ≃o fin n) := unique.mk' _ /-- Two strictly monotone functions from `fin n` are equal provided that their ranges are equal. -/ lemma strict_mono_unique {f g : fin n → α} (hf : strict_mono f) (hg : strict_mono g) (h : range f = range g) : f = g := have (hf.order_iso f).trans (order_iso.set_congr _ _ h) = hg.order_iso g, from subsingleton.elim _ _, congr_arg (function.comp (coe : range g → α)) (funext $ rel_iso.ext_iff.1 this) /-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/ lemma order_embedding_eq {f g : fin n ↪o α} (h : range f = range g) : f = g := rel_embedding.ext $ funext_iff.1 $ strict_mono_unique f.strict_mono g.strict_mono h end end order section add /-! ### addition, numerals, and coercion from nat -/ lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl lemma coe_one' (n : ℕ) [ne_zero n] : ((1 : fin n) : ℕ) = 1 % n := rfl @[simp] lemma val_one (n : ℕ) : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma coe_one (n : ℕ) : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩ lemma nontrivial_iff_two_le : nontrivial (fin n) ↔ 2 ≤ n := by rcases n with _|_|n; simp [fin.nontrivial, not_nontrivial, nat.succ_le_iff] lemma subsingleton_iff_le_one : subsingleton (fin n) ↔ n ≤ 1 := by rcases n with _|_|n; simp [is_empty.subsingleton, unique.subsingleton, not_subsingleton] section monoid @[simp] protected lemma add_zero [ne_zero n] (k : fin n) : k + 0 = k := by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)] @[simp] protected lemma zero_add [ne_zero n] (k : fin n) : (0 : fin n) + k = k := by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)] instance add_comm_monoid (n : ℕ) [ne_zero n] : add_comm_monoid (fin n) := { add := (+), add_assoc := by simp [eq_iff_veq, add_def, add_assoc], zero := 0, zero_add := fin.zero_add, add_zero := fin.add_zero, add_comm := by simp [eq_iff_veq, add_def, add_comm] } instance [ne_zero n] : add_monoid_with_one (fin n) := { one := 1, nat_cast := fin.of_nat', nat_cast_zero := rfl, nat_cast_succ := λ i, eq_of_veq (add_mod _ _ _), .. fin.add_comm_monoid n } end monoid lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add_eq_ite {n : ℕ} (a b : fin n) : (↑(a + b) : ℕ) = if n ≤ a + b then a + b - n else a + b := by rw [fin.coe_add, nat.add_mod_eq_ite, nat.mod_eq_of_lt (show ↑a < n, from a.2), nat.mod_eq_of_lt (show ↑b < n, from b.2)] lemma coe_bit0 {n : ℕ} (k : fin n) : ((bit0 k : fin n) : ℕ) = bit0 (k : ℕ) % n := by { cases k, refl } lemma coe_bit1 {n : ℕ} [ne_zero n] (k : fin n) : ((bit1 k : fin n) : ℕ) = bit1 (k : ℕ) % n := by simp [bit1, coe_add, coe_bit0, coe_one'] lemma coe_add_one_of_lt {n : ℕ} {i : fin n.succ} (h : i < last _) : (↑(i + 1) : ℕ) = i + 1 := begin -- First show that `((1 : fin n.succ) : ℕ) = 1`, because `n.succ` is at least 2. cases n, { cases h }, -- Then just unfold the definitions. rw [fin.coe_add, fin.coe_one, nat.mod_eq_of_lt (nat.succ_lt_succ _)], exact h end @[simp] lemma last_add_one : ∀ n, last n + 1 = 0 | 0 := subsingleton.elim _ _ | (n + 1) := by { ext, rw [coe_add, coe_zero, coe_last, coe_one, nat.mod_self] } lemma coe_add_one {n : ℕ} (i : fin (n + 1)) : ((i + 1 : fin (n + 1)) : ℕ) = if i = last _ then 0 else i + 1 := begin rcases (le_last i).eq_or_lt with rfl|h, { simp }, { simpa [h.ne] using coe_add_one_of_lt h } end section bit @[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) : (⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) := eq_of_veq (nat.mod_eq_of_lt h).symm @[simp] lemma mk_bit1 {m n : ℕ} [ne_zero n] (h : bit1 m < n) : (⟨bit1 m, h⟩ : fin n) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt ((m + m).lt_succ_self.trans h)⟩ : fin _) := begin ext, simp only [bit1, bit0] at h, simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h], end end bit @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl section of_nat_coe @[simp] lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a := rfl @[simp] lemma of_nat'_eq_coe (n : ℕ) [ne_zero n] (a : ℕ) : (of_nat' a : fin n) = a := rfl /-- Converting an in-range number to `fin n` produces a result whose value is the original number. -/ lemma coe_val_of_lt {n : ℕ} [ne_zero n] {a : ℕ} (h : a < n) : ((a : fin n).val) = a := begin rw ←of_nat'_eq_coe, exact nat.mod_eq_of_lt h end /-- Converting the value of a `fin n` to `fin n` results in the same value. -/ lemma coe_val_eq_self {n : ℕ} [ne_zero n] (a : fin n) : (a.val : fin n) = a := begin rw fin.eq_iff_veq, exact coe_val_of_lt a.property end /-- Coercing an in-range number to `fin n`, and converting back to `ℕ`, results in that number. -/ lemma coe_coe_of_lt {n : ℕ} [ne_zero n] {a : ℕ} (h : a < n) : ((a : fin n) : ℕ) = a := coe_val_of_lt h /-- Converting a `fin n` to `ℕ` and back results in the same value. -/ @[simp] lemma coe_coe_eq_self {n : ℕ} [ne_zero n] (a : fin n) : ((a : ℕ) : fin n) = a := coe_val_eq_self a lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n := by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] } lemma le_coe_last (i : fin (n + 1)) : i ≤ n := by { rw fin.coe_nat_eq_last, exact fin.le_last i } end of_nat_coe lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 := begin cases n, { exact absurd h (nat.not_lt_zero _) }, { rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h, rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h], exact nat.zero_lt_succ _ } end lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0 lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos @[simp] lemma zero_eq_one_iff [ne_zero n]: (0 : fin n) = 1 ↔ n = 1 := begin split, { intro h, have := congr_arg (coe : fin n → ℕ) h, simp only [fin.coe_zero, ← nat.dvd_iff_mod_eq_zero, fin.coe_one', @eq_comm _ 0] at this, exact eq_one_of_dvd_one this }, { unfreezingI { rintro rfl }, refl } end @[simp] lemma one_eq_zero_iff [ne_zero n]: (1 : fin n) = 0 ↔ n = 1 := by rw [eq_comm, zero_eq_one_iff] end add section succ /-! ### succ and casts into larger fin types -/ @[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 := by cases j; simp [fin.succ] @[simp] lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe] /-- `fin.succ` as an `order_embedding` -/ def succ_embedding (n : ℕ) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono fin.succ $ λ ⟨i, hi⟩ ⟨j, hj⟩ h, succ_lt_succ h @[simp] lemma coe_succ_embedding : ⇑(succ_embedding n) = fin.succ := rfl @[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b := (succ_embedding n).le_iff_le @[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b := (succ_embedding n).lt_iff_lt lemma succ_injective (n : ℕ) : injective (@fin.succ n) := (succ_embedding n).injective @[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b := (succ_injective n).eq_iff lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ ext_iff.1 heq @[simp] lemma succ_zero_eq_one [ne_zero n] : fin.succ (0 : fin n) = 1 := begin unfreezingI { cases n }, { exact (ne_zero.ne 0 rfl).elim }, { refl } end /-- Version of `succ_zero_eq_one` to be used by `dsimp` -/ @[simp] lemma succ_zero_eq_one' : fin.succ (0 : fin (n+1)) = 1 := rfl @[simp] lemma succ_one_eq_two [ne_zero n] : fin.succ (1 : fin (n + 1)) = 2 := begin unfreezingI { cases n }, { exact (ne_zero.ne 0 rfl).elim }, { refl } end /-- Version of `succ_one_eq_two` to be used by `dsimp` -/ @[simp] lemma succ_one_eq_two' : fin.succ (1 : fin (n + 2)) = 2 := rfl @[simp] lemma succ_mk (n i : ℕ) (h : i < n) : fin.succ ⟨i, h⟩ = ⟨i + 1, nat.succ_lt_succ h⟩ := rfl lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ := by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i } lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ := begin cases n, { exact fin_zero_elim a }, { rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a } end @[simp] lemma add_one_lt_iff {n : ℕ} {k : fin (n + 2)} : k + 1 < k ↔ k = last _ := begin simp only [lt_iff_coe_lt_coe, coe_add, coe_last, ext_iff], cases k with k hk, rcases (le_of_lt_succ hk).eq_or_lt with rfl|hk', { simp }, { simp [hk'.ne, mod_eq_of_lt (succ_lt_succ hk'), le_succ _] } end @[simp] lemma add_one_le_iff {n : ℕ} {k : fin (n + 1)} : k + 1 ≤ k ↔ k = last _ := begin cases n, { simp [subsingleton.elim (k + 1) k, subsingleton.elim (fin.last _) k] }, rw [←not_iff_not, ←add_one_lt_iff, lt_iff_le_and_ne, not_and'], refine ⟨λ h _, h, λ h, h _⟩, rw [ne.def, ext_iff, coe_add_one], split_ifs with hk hk; simp [hk, eq_comm], end @[simp] lemma last_le_iff {n : ℕ} {k : fin (n + 1)} : last n ≤ k ↔ k = last n := top_le_iff @[simp] lemma lt_add_one_iff {n : ℕ} {k : fin (n + 1)} : k < k + 1 ↔ k < last n := begin rw ←not_iff_not, simp end @[simp] lemma le_zero_iff {n : ℕ} [ne_zero n] {k : fin n} : k ≤ 0 ↔ k = 0 := ⟨λ h, fin.eq_of_veq $ by rw [nat.eq_zero_of_le_zero h]; refl, by rintro rfl; refl⟩ lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a) /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ @[simp] lemma coe_cast_lt (i : fin m) (h : i.1 < n) : (cast_lt i h : ℕ) = i := rfl @[simp] lemma cast_lt_mk (i n m : ℕ) (hn : i < n) (hm : i < m) : cast_lt ⟨i, hn⟩ hm = ⟨i, hm⟩ := rfl /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) : fin n ↪o fin m := order_embedding.of_strict_mono (λ a, cast_lt a (lt_of_lt_of_le a.2 h)) $ λ a b h, h @[simp] lemma coe_cast_le (h : n ≤ m) (i : fin n) : (cast_le h i : ℕ) = i := rfl @[simp] lemma cast_le_mk (i n m : ℕ) (hn : i < n) (h : n ≤ m) : cast_le h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h⟩ := rfl @[simp] lemma cast_le_zero {n m : ℕ} (h : n.succ ≤ m.succ) : cast_le h 0 = 0 := by simp [eq_iff_veq] @[simp] lemma range_cast_le {n k : ℕ} (h : n ≤ k) : set.range (cast_le h) = {i | (i : ℕ) < n} := set.ext (λ x, ⟨λ ⟨y, hy⟩, hy ▸ y.2, λ hx, ⟨⟨x, hx⟩, fin.ext rfl⟩⟩) @[simp] lemma coe_of_injective_cast_le_symm {n k : ℕ} (h : n ≤ k) (i : fin k) (hi) : ((equiv.of_injective _ (cast_le h).injective).symm ⟨i, hi⟩ : ℕ) = i := begin rw ← coe_cast_le, exact congr_arg coe (equiv.apply_of_injective_symm _ _) end @[simp] lemma cast_le_succ {m n : ℕ} (h : (m + 1) ≤ (n + 1)) (i : fin m) : cast_le h i.succ = (cast_le (nat.succ_le_succ_iff.mp h) i).succ := by simp [fin.eq_iff_veq] @[simp] lemma cast_le_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) (i : fin k) : fin.cast_le mn (fin.cast_le km i) = fin.cast_le (km.trans mn) i := fin.ext (by simp only [coe_cast_le]) @[simp] lemma cast_le_comp_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) : fin.cast_le mn ∘ fin.cast_le km = fin.cast_le (km.trans mn) := funext (cast_le_cast_le km mn) /-- `cast eq i` embeds `i` into a equal `fin` type, see also `equiv.fin_congr`. -/ def cast (eq : n = m) : fin n ≃o fin m := { to_equiv := ⟨cast_le eq.le, cast_le eq.symm.le, λ a, eq_of_veq rfl, λ a, eq_of_veq rfl⟩, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma symm_cast (h : n = m) : (cast h).symm = cast h.symm := rfl /-- While `fin.coe_order_iso_apply` is a more general case of this, we mark this `simp` anyway as it is eligible for `dsimp`. -/ @[simp] lemma coe_cast (h : n = m) (i : fin n) : (cast h i : ℕ) = i := rfl @[simp] lemma cast_zero {n' : ℕ} [ne_zero n] {h : n = n'} : cast h (0 : fin n) = by { haveI : ne_zero n' := by { rw ← h; apply_instance }, exact 0 } := ext rfl @[simp] lemma cast_last {n' : ℕ} {h : n + 1 = n' + 1} : cast h (last n) = last n' := ext (by rw [coe_cast, coe_last, coe_last, nat.succ_injective h]) @[simp] lemma cast_mk (h : n = m) (i : ℕ) (hn : i < n) : cast h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h.le⟩ := rfl @[simp] lemma cast_trans {k : ℕ} (h : n = m) (h' : m = k) {i : fin n} : cast h' (cast h i) = cast (eq.trans h h') i := rfl @[simp] lemma cast_refl (h : n = n := rfl) : cast h = order_iso.refl (fin n) := by { ext, refl } lemma cast_le_of_eq {m n : ℕ} (h : m = n) {h' : m ≤ n} : (cast_le h' : fin m → fin n) = fin.cast h := funext (λ _, rfl) /-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma cast_to_equiv (h : n = m) : (cast h).to_equiv = equiv.cast (h ▸ rfl) := by { subst h, simp } /-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma cast_eq_cast (h : n = m) : (cast h : fin n → fin m) = _root_.cast (h ▸ rfl) := by { subst h, ext, simp } /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. See also `fin.nat_add` and `fin.add_nat`. -/ def cast_add (m) : fin n ↪o fin (n + m) := cast_le $ nat.le_add_right n m @[simp] lemma coe_cast_add (m : ℕ) (i : fin n) : (cast_add m i : ℕ) = i := rfl @[simp] lemma cast_add_zero : (cast_add 0 : fin n → fin (n + 0)) = cast rfl := rfl lemma cast_add_lt {m : ℕ} (n : ℕ) (i : fin m) : (cast_add n i : ℕ) < m := i.2 @[simp] lemma cast_add_mk (m : ℕ) (i : ℕ) (h : i < n) : cast_add m ⟨i, h⟩ = ⟨i, lt_add_right i n m h⟩ := rfl @[simp] lemma cast_add_cast_lt (m : ℕ) (i : fin (n + m)) (hi : i.val < n) : cast_add m (cast_lt i hi) = i := ext rfl @[simp] lemma cast_lt_cast_add (m : ℕ) (i : fin n) : cast_lt (cast_add m i) (cast_add_lt m i) = i := ext rfl /-- For rewriting in the reverse direction, see `fin.cast_cast_add_left`. -/ lemma cast_add_cast {n n' : ℕ} (m : ℕ) (i : fin n') (h : n' = n) : cast_add m (fin.cast h i) = fin.cast (congr_arg _ h) (cast_add m i) := ext rfl lemma cast_cast_add_left {n n' m : ℕ} (i : fin n') (h : n' + m = n + m) : cast h (cast_add m i) = cast_add m (cast (add_right_cancel h) i) := ext rfl @[simp] lemma cast_cast_add_right {n m m' : ℕ} (i : fin n) (h : n + m' = n + m) : cast h (cast_add m' i) = cast_add m i := ext rfl lemma cast_add_cast_add {m n p : ℕ} (i : fin m) : cast_add p (cast_add n i) = cast (add_assoc _ _ _).symm (cast_add (n + p) i) := ext rfl /-- The cast of the successor is the succesor of the cast. See `fin.succ_cast_eq` for rewriting in the reverse direction. -/ @[simp] lemma cast_succ_eq {n' : ℕ} (i : fin n) (h : n.succ = n'.succ) : cast h i.succ = (cast (nat.succ.inj h) i).succ := ext $ by simp lemma succ_cast_eq {n' : ℕ} (i : fin n) (h : n = n') : (cast h i).succ = cast (by rw h) i.succ := ext $ by simp /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ : fin n ↪o fin (n + 1) := cast_add 1 @[simp] lemma coe_cast_succ (i : fin n) : (i.cast_succ : ℕ) = i := rfl @[simp] lemma cast_succ_mk (n i : ℕ) (h : i < n) : cast_succ ⟨i, h⟩ = ⟨i, nat.lt.step h⟩ := rfl @[simp] lemma cast_cast_succ {n' : ℕ} {h : n + 1 = n' + 1} {i : fin n} : cast h (cast_succ i) = cast_succ (cast (nat.succ_injective h) i) := by { ext, simp only [coe_cast, coe_cast_succ] } lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ := lt_iff_coe_lt_coe.2 $ by simp only [coe_cast_succ, coe_succ, nat.lt_succ_self] lemma le_cast_succ_iff {i : fin (n + 1)} {j : fin n} : i ≤ j.cast_succ ↔ i < j.succ := by simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe] using nat.succ_le_succ_iff.symm lemma cast_succ_lt_iff_succ_le {n : ℕ} {i : fin n} {j : fin (n+1)} : i.cast_succ < j ↔ i.succ ≤ j := by simpa only [fin.lt_iff_coe_lt_coe, fin.le_iff_coe_le_coe, fin.coe_succ, fin.coe_cast_succ] using nat.lt_iff_add_one_le @[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl @[simp] lemma succ_eq_last_succ {n : ℕ} (i : fin n.succ) : i.succ = last (n + 1) ↔ i = last n := by rw [← succ_last, (succ_injective _).eq_iff] @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) : cast_lt (cast_succ a) h = a := by cases a; refl @[simp] lemma cast_succ_lt_cast_succ_iff : a.cast_succ < b.cast_succ ↔ a < b := (@cast_succ n).lt_iff_lt lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) := (cast_succ : fin n ↪o _).injective lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := (cast_succ_injective n).eq_iff lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt @[simp] lemma cast_succ_zero [ne_zero n] : cast_succ (0 : fin n) = 0 := rfl @[simp] lemma cast_succ_one {n : ℕ} : fin.cast_succ (1 : fin (n + 2)) = 1 := rfl /-- `cast_succ i` is positive when `i` is positive -/ lemma cast_succ_pos [ne_zero n] {i : fin n} (h : 0 < i) : 0 < cast_succ i := by simpa [lt_iff_coe_lt_coe] using h @[simp] lemma cast_succ_eq_zero_iff [ne_zero n] (a : fin n) : a.cast_succ = 0 ↔ a = 0 := fin.ext_iff.trans $ (fin.ext_iff.trans $ by exact iff.rfl).symm lemma cast_succ_ne_zero_iff [ne_zero n] (a : fin n) : a.cast_succ ≠ 0 ↔ a ≠ 0 := not_iff_not.mpr $ cast_succ_eq_zero_iff a lemma cast_succ_fin_succ (n : ℕ) (j : fin n) : cast_succ (fin.succ j) = fin.succ (cast_succ j) := by simp [fin.ext_iff] @[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ := begin ext, exact coe_val_of_lt (nat.lt.step a.is_lt), end @[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ := begin cases n, { exact fin_zero_elim a }, { simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] } end lemma lt_succ : a.cast_succ < a.succ := by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val } @[simp] lemma range_cast_succ {n : ℕ} : set.range (cast_succ : fin n → fin n.succ) = {i | (i : ℕ) < n} := range_cast_le _ @[simp] lemma coe_of_injective_cast_succ_symm {n : ℕ} (i : fin (n+1)) (hi) : ((equiv.of_injective cast_succ (cast_succ_injective _)).symm ⟨i, hi⟩ : ℕ) = i := begin rw ← coe_cast_succ, exact congr_arg coe (equiv.apply_of_injective_symm _ _) end lemma succ_cast_succ {n : ℕ} (i : fin n) : i.cast_succ.succ = i.succ.cast_succ := fin.ext (by simp) /-- `add_nat m i` adds `m` to `i`, generalizes `fin.succ`. -/ def add_nat (m) : fin n ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_right h _ @[simp] lemma coe_add_nat (m : ℕ) (i : fin n) : (add_nat m i : ℕ) = i + m := rfl @[simp] lemma add_nat_one {i : fin n} : add_nat 1 i = i.succ := by { ext, rw [coe_add_nat, coe_succ] } lemma le_coe_add_nat (m : ℕ) (i : fin n) : m ≤ add_nat m i := nat.le_add_left _ _ @[simp] lemma add_nat_mk (n i : ℕ) (hi : i < m) : add_nat n ⟨i, hi⟩ = ⟨i + n, add_lt_add_right hi n⟩ := rfl @[simp] lemma cast_add_nat_zero {n n' : ℕ} (i : fin n) (h : n + 0 = n') : cast h (add_nat 0 i) = cast ((add_zero _).symm.trans h) i := ext $ add_zero _ /-- For rewriting in the reverse direction, see `fin.cast_add_nat_left`. -/ lemma add_nat_cast {n n' m : ℕ} (i : fin n') (h : n' = n) : add_nat m (cast h i) = cast (congr_arg _ h) (add_nat m i) := ext rfl lemma cast_add_nat_left {n n' m : ℕ} (i : fin n') (h : n' + m = n + m) : cast h (add_nat m i) = add_nat m (cast (add_right_cancel h) i) := ext rfl @[simp] lemma cast_add_nat_right {n m m' : ℕ} (i : fin n) (h : n + m' = n + m) : cast h (add_nat m' i) = add_nat m i := ext $ (congr_arg ((+) (i : ℕ)) (add_left_cancel h) : _) /-- `nat_add n i` adds `n` to `i` "on the left". -/ def nat_add (n) {m} : fin m ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_left h _ @[simp] lemma coe_nat_add (n : ℕ) {m : ℕ} (i : fin m) : (nat_add n i : ℕ) = n + i := rfl @[simp] lemma nat_add_mk (n i : ℕ) (hi : i < m) : nat_add n ⟨i, hi⟩ = ⟨n + i, add_lt_add_left hi n⟩ := rfl lemma le_coe_nat_add (m : ℕ) (i : fin n) : m ≤ nat_add m i := nat.le_add_right _ _ lemma nat_add_zero {n : ℕ} : fin.nat_add 0 = (fin.cast (zero_add n).symm).to_rel_embedding := by { ext, apply zero_add } /-- For rewriting in the reverse direction, see `fin.cast_nat_add_right`. -/ lemma nat_add_cast {n n' : ℕ} (m : ℕ) (i : fin n') (h : n' = n) : nat_add m (cast h i) = cast (congr_arg _ h) (nat_add m i) := ext rfl lemma cast_nat_add_right {n n' m : ℕ} (i : fin n') (h : m + n' = m + n) : cast h (nat_add m i) = nat_add m (cast (add_left_cancel h) i) := ext rfl @[simp] lemma cast_nat_add_left {n m m' : ℕ} (i : fin n) (h : m' + n = m + n) : cast h (nat_add m' i) = nat_add m i := ext $ (congr_arg (+ (i : ℕ)) (add_right_cancel h) : _) lemma cast_add_nat_add (p m : ℕ) {n : ℕ} (i : fin n) : cast_add p (nat_add m i) = cast (add_assoc _ _ _).symm (nat_add m (cast_add p i)) := ext rfl lemma nat_add_cast_add (p m : ℕ) {n : ℕ} (i : fin n) : nat_add m (cast_add p i) = cast (add_assoc _ _ _) (cast_add p (nat_add m i)) := ext rfl lemma nat_add_nat_add (m n : ℕ) {p : ℕ} (i : fin p) : nat_add m (nat_add n i) = cast (add_assoc _ _ _) (nat_add (m + n) i) := ext $ (add_assoc _ _ _).symm @[simp] lemma cast_nat_add_zero {n n' : ℕ} (i : fin n) (h : 0 + n = n') : cast h (nat_add 0 i) = cast ((zero_add _).symm.trans h) i := ext $ zero_add _ @[simp] lemma cast_nat_add (n : ℕ) {m : ℕ} (i : fin m) : cast (add_comm _ _) (nat_add n i) = add_nat n i := ext $ add_comm _ _ @[simp] lemma cast_add_nat {n : ℕ} (m : ℕ) (i : fin n) : cast (add_comm _ _) (add_nat m i) = nat_add m i := ext $ add_comm _ _ @[simp] lemma nat_add_last {m n : ℕ} : nat_add n (last m) = last (n + m) := rfl lemma nat_add_cast_succ {m n : ℕ} {i : fin m} : nat_add n (cast_succ i) = cast_succ (nat_add n i) := rfl end succ section pred /-! ### pred -/ @[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 := by { cases j, refl } @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by { cases i, refl } lemma pred_eq_iff_eq_succ {n : ℕ} (i : fin (n+1)) (hi : i ≠ 0) (j : fin n) : i.pred hi = j ↔ i = j.succ := ⟨λ h, by simp only [← h, fin.succ_pred], λ h, by simp only [h, fin.pred_succ]⟩ @[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) : fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ := by simp only [ext_iff, coe_pred, coe_mk, add_tsub_cancel_right] -- This is not a simp lemma by default, because `pred_mk_succ` is nicer when it applies. lemma pred_mk {n : ℕ} (i : ℕ) (h : i < n + 1) (w) : fin.pred ⟨i, h⟩ w = ⟨i - 1, by rwa tsub_lt_iff_right (nat.succ_le_of_lt $ nat.pos_of_ne_zero (fin.vne_of_ne w))⟩ := rfl @[simp] lemma pred_le_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha ≤ b.pred hb ↔ a ≤ b := by rw [←succ_le_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_lt_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha < b.pred hb ↔ a < b := by rw [←succ_lt_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] @[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) : pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h := begin rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, add_tsub_cancel_right], exact add_lt_add_right h 1, end /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n := ⟨(i : ℕ) - m, by { rw [tsub_lt_iff_right h], exact i.is_lt }⟩ @[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m := rfl @[simp] lemma sub_nat_mk {i : ℕ} (h₁ : i < n + m) (h₂ : m ≤ i) : sub_nat m ⟨i, h₁⟩ h₂ = ⟨i - m, (tsub_lt_iff_right h₂).2 h₁⟩ := rfl @[simp] lemma pred_cast_succ_succ (i : fin n) : pred (cast_succ i.succ) (ne_of_gt (cast_succ_pos i.succ_pos)) = i.cast_succ := by simp [eq_iff_veq] @[simp] lemma add_nat_sub_nat {i : fin (n + m)} (h : m ≤ i) : add_nat m (sub_nat m i h) = i := ext $ tsub_add_cancel_of_le h @[simp] lemma sub_nat_add_nat (i : fin n) (m : ℕ) (h : m ≤ add_nat m i := le_coe_add_nat m i) : sub_nat m (add_nat m i) h = i := ext $ add_tsub_cancel_right i m @[simp] lemma nat_add_sub_nat_cast {i : fin (n + m)} (h : n ≤ i) : nat_add n (sub_nat n (cast (add_comm _ _) i) h) = i := by simp [← cast_add_nat] end pred section div_mod /-- Compute `i / n`, where `n` is a `nat` and inferred the type of `i`. -/ def div_nat (i : fin (m * n)) : fin m := ⟨i / n, nat.div_lt_of_lt_mul $ mul_comm m n ▸ i.prop⟩ @[simp] lemma coe_div_nat (i : fin (m * n)) : (i.div_nat : ℕ) = i / n := rfl /-- Compute `i % n`, where `n` is a `nat` and inferred the type of `i`. -/ def mod_nat (i : fin (m * n)) : fin n := ⟨i % n, nat.mod_lt _ $ pos_of_mul_pos_right i.pos m.zero_le⟩ @[simp] lemma coe_mod_nat (i : fin (m * n)) : (i.mod_nat : ℕ) = i % n := rfl end div_mod section rec /-! ### recursion and induction principles -/ /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ @[elab_as_eliminator] def succ_rec {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. -/ @[elab_as_eliminator] def induction {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : Π (i : fin (n + 1)), C i := begin rintro ⟨i, hi⟩, induction i with i IH, { rwa [fin.mk_zero] }, { refine hs ⟨i, lt_of_succ_lt_succ hi⟩ _, exact IH (lt_of_succ_lt hi) } end @[simp] lemma induction_zero {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : (induction h0 hs : _) 0 = h0 := rfl @[simp] lemma induction_succ {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) (i : fin n) : (induction h0 hs : _) i.succ = hs i (induction h0 hs i.cast_succ) := by cases i; refl /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. A version of `fin.induction` taking `i : fin (n + 1)` as the first argument. -/ @[elab_as_eliminator] def induction_on (i : fin (n + 1)) {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : C i := induction h0 hs i /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) : Π (i : fin (succ n)), C i := induction H0 (λ i _, Hs i) @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl @[simp] theorem cases_succ' {n} {C : fin (succ n) → Sort*} {H0 Hs} {i : ℕ} (h : i + 1 < n + 1) : @fin.cases n C H0 Hs ⟨i.succ, h⟩ = Hs ⟨i, lt_of_succ_lt_succ h⟩ := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, h.elim (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ lemma forall_fin_one {p : fin 1 → Prop} : (∀ i, p i) ↔ p 0 := @unique.forall_iff (fin 1) _ p lemma exists_fin_one {p : fin 1 → Prop} : (∃ i, p i) ↔ p 0 := @unique.exists_iff (fin 1) _ p lemma forall_fin_two {p : fin 2 → Prop} : (∀ i, p i) ↔ p 0 ∧ p 1 := forall_fin_succ.trans $ and_congr_right $ λ _, forall_fin_one lemma exists_fin_two {p : fin 2 → Prop} : (∃ i, p i) ↔ p 0 ∨ p 1 := exists_fin_succ.trans $ or_congr_right' exists_fin_one lemma fin_two_eq_of_eq_zero_iff {a b : fin 2} (h : a = 0 ↔ b = 0) : a = b := by { revert a b, simp [forall_fin_two] } /-- Define `C i` by reverse induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `hlast` handles the base case on `C (fin.last n)`, and `hs` defines the inductive step using `C i.succ`, inducting downwards. -/ @[elab_as_eliminator] def reverse_induction {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) : Π (i : fin (n + 1)), C i | i := if hi : i = fin.last n then _root_.cast (by rw hi) hlast else let j : fin n := ⟨i, lt_of_le_of_ne (nat.le_of_lt_succ i.2) (λ h, hi (fin.ext h))⟩ in have wf : n + 1 - j.succ < n + 1 - i, begin cases i, rw [tsub_lt_tsub_iff_left_of_le]; simp [*, nat.succ_le_iff], end, have hi : i = fin.cast_succ j, from fin.ext rfl, _root_.cast (by rw hi) (hs _ (reverse_induction j.succ)) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ i : fin (n+1), n + 1 - i)⟩], dec_tac := `[assumption] } @[simp] lemma reverse_induction_last {n : ℕ} {C : fin (n + 1) → Sort*} (h0 : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) : (reverse_induction h0 hs (fin.last n) : C (fin.last n)) = h0 := by rw [reverse_induction]; simp @[simp] lemma reverse_induction_cast_succ {n : ℕ} {C : fin (n + 1) → Sort*} (h0 : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) (i : fin n): (reverse_induction h0 hs i.cast_succ : C i.cast_succ) = hs i (reverse_induction h0 hs i.succ) := begin rw [reverse_induction, dif_neg (ne_of_lt (fin.cast_succ_lt_last i))], cases i, refl end /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = fin.last n` and `i = j.cast_succ`, `j : fin n`. -/ @[elab_as_eliminator] def last_cases {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin (n + 1)) : C i := reverse_induction hlast (λ i _, hcast i) i @[simp] lemma last_cases_last {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) : (fin.last_cases hlast hcast (fin.last n): C (fin.last n)) = hlast := reverse_induction_last _ _ @[simp] lemma last_cases_cast_succ {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin n) : (fin.last_cases hlast hcast (fin.cast_succ i): C (fin.cast_succ i)) = hcast i := reverse_induction_cast_succ _ _ _ /-- Define `f : Π i : fin (m + n), C i` by separately handling the cases `i = cast_add n i`, `j : fin m` and `i = nat_add m j`, `j : fin n`. -/ @[elab_as_eliminator] def add_cases {m n : ℕ} {C : fin (m + n) → Sort u} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin (m + n)) : C i := if hi : (i : ℕ) < m then eq.rec_on (cast_add_cast_lt n i hi) (hleft (cast_lt i hi)) else eq.rec_on (nat_add_sub_nat_cast (le_of_not_lt hi)) (hright _) @[simp] lemma add_cases_left {m n : ℕ} {C : fin (m + n) → Sort*} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin m) : @add_cases _ _ C hleft hright (fin.cast_add n i) = hleft i := begin cases i with i hi, rw [add_cases, dif_pos (cast_add_lt _ _)], refl end @[simp] lemma add_cases_right {m n : ℕ} {C : fin (m + n) → Sort*} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin n) : @add_cases _ _ C hleft hright (nat_add m i) = hright i := begin have : ¬ (nat_add m i : ℕ) < m, from (le_coe_nat_add _ _).not_lt, rw [add_cases, dif_neg this], refine eq_of_heq ((eq_rec_heq _ _).trans _), congr' 1, simp end end rec lemma lift_fun_iff_succ {α : Type*} (r : α → α → Prop) [is_trans α r] {f : fin (n + 1) → α} : ((<) ⇒ r) f f ↔ ∀ i : fin n, r (f i.cast_succ) (f i.succ) := begin split, { intros H i, exact H i.cast_succ_lt_succ }, { refine λ H i, fin.induction _ _, { exact λ h, (h.not_le (zero_le i)).elim }, { intros j ihj hij, rw [← le_cast_succ_iff] at hij, rcases hij.eq_or_lt with rfl|hlt, exacts [H j, trans (ihj hlt) (H j)] } } end /-- A function `f` on `fin (n + 1)` is strictly monotone if and only if `f i < f (i + 1)` for all `i`. -/ lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin (n + 1) → α} : strict_mono f ↔ ∀ i : fin n, f i.cast_succ < f i.succ := lift_fun_iff_succ (<) /-- A function `f` on `fin (n + 1)` is monotone if and only if `f i ≤ f (i + 1)` for all `i`. -/ lemma monotone_iff_le_succ {α : Type*} [preorder α] {f : fin (n + 1) → α} : monotone f ↔ ∀ i : fin n, f i.cast_succ ≤ f i.succ := monotone_iff_forall_lt.trans $ lift_fun_iff_succ (≤) /-- A function `f` on `fin (n + 1)` is strictly antitone if and only if `f (i + 1) < f i` for all `i`. -/ lemma strict_anti_iff_succ_lt {α : Type*} [preorder α] {f : fin (n + 1) → α} : strict_anti f ↔ ∀ i : fin n, f i.succ < f i.cast_succ := lift_fun_iff_succ (>) /-- A function `f` on `fin (n + 1)` is antitone if and only if `f (i + 1) ≤ f i` for all `i`. -/ lemma antitone_iff_succ_le {α : Type*} [preorder α] {f : fin (n + 1) → α} : antitone f ↔ ∀ i : fin n, f i.succ ≤ f i.cast_succ := antitone_iff_forall_lt.trans $ lift_fun_iff_succ (≥) section add_group open nat int /-- Negation on `fin n` -/ instance (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨(n - a) % n, nat.mod_lt _ a.pos⟩⟩ /-- Abelian group structure on `fin n`. -/ instance (n : ℕ) [ne_zero n] : add_comm_group (fin n) := { add_left_neg := λ ⟨a, ha⟩, fin.ext $ trans (nat.mod_add_mod _ _ _) $ by { rw [fin.coe_mk, fin.coe_zero, tsub_add_cancel_of_le, nat.mod_self], exact le_of_lt ha }, sub_eq_add_neg := λ ⟨a, ha⟩ ⟨b, hb⟩, fin.ext $ show (a + (n - b)) % n = (a + (n - b) % n) % n, by simp, sub := fin.sub, ..fin.add_comm_monoid n, ..fin.has_neg n } protected lemma coe_neg (a : fin n) : ((-a : fin n) : ℕ) = (n - a) % n := rfl protected lemma coe_sub (a b : fin n) : ((a - b : fin n) : ℕ) = (a + (n - b)) % n := by cases a; cases b; refl @[simp] lemma coe_fin_one (a : fin 1) : ↑a = 0 := by rw [subsingleton.elim a 0, fin.coe_zero] @[simp] lemma coe_neg_one : ↑(-1 : fin (n + 1)) = n := begin cases n, { simp }, rw [fin.coe_neg, fin.coe_one, nat.succ_sub_one, nat.mod_eq_of_lt], constructor end lemma coe_sub_one {n} (a : fin (n + 1)) : ↑(a - 1) = if a = 0 then n else a - 1 := begin cases n, { simp }, split_ifs, { simp [h] }, rw [sub_eq_add_neg, coe_add_eq_ite, coe_neg_one, if_pos, add_comm, add_tsub_add_eq_tsub_left], rw [add_comm ↑a, add_le_add_iff_left, nat.one_le_iff_ne_zero], rwa fin.ext_iff at h end lemma coe_sub_iff_le {n : ℕ} {a b : fin n} : (↑(a - b) : ℕ) = a - b ↔ b ≤ a := begin cases n, {exact fin_zero_elim a}, rw [le_iff_coe_le_coe, fin.coe_sub, ←add_tsub_assoc_of_le b.is_lt.le a], cases le_or_lt (b : ℕ) a with h h, { simp [←tsub_add_eq_add_tsub h, h, nat.mod_eq_of_lt ((nat.sub_le _ _).trans_lt a.is_lt)] }, { rw [nat.mod_eq_of_lt, tsub_eq_zero_of_le h.le, tsub_eq_zero_iff_le, ←not_iff_not], { simpa [b.is_lt.trans_le (le_add_self)] using h }, { rwa [tsub_lt_iff_left (b.is_lt.le.trans (le_add_self)), add_lt_add_iff_right] } } end lemma coe_sub_iff_lt {n : ℕ} {a b : fin n} : (↑(a - b) : ℕ) = n + a - b ↔ a < b := begin cases n, {exact fin_zero_elim a}, rw [lt_iff_coe_lt_coe, fin.coe_sub, add_comm], cases le_or_lt (b : ℕ) a with h h, { simpa [add_tsub_assoc_of_le h, ←not_le, h] using ((nat.mod_lt _ (nat.succ_pos _)).trans_le le_self_add).ne }, { simp [←tsub_tsub_assoc b.is_lt.le h.le, ←tsub_add_eq_add_tsub b.is_lt.le, nat.mod_eq_of_lt (tsub_lt_self (nat.succ_pos _) (tsub_pos_of_lt h)), h] } end @[simp] lemma lt_sub_one_iff {n : ℕ} {k : fin (n + 2)} : k < k - 1 ↔ k = 0 := begin rcases k with ⟨(_|k), hk⟩, simp [lt_iff_coe_lt_coe], have : (k + 1 + (n + 1)) % (n + 2) = k % (n + 2), { rw [add_right_comm, add_assoc, add_mod_right] }, simp [lt_iff_coe_lt_coe, ext_iff, fin.coe_sub, succ_eq_add_one, this, mod_eq_of_lt ((lt_succ_self _).trans hk)] end @[simp] lemma le_sub_one_iff {n : ℕ} {k : fin (n + 1)} : k ≤ k - 1 ↔ k = 0 := begin cases n, { simp [subsingleton.elim (k - 1) k, subsingleton.elim 0 k] }, rw [←lt_sub_one_iff, le_iff_lt_or_eq, lt_sub_one_iff, or_iff_left_iff_imp, eq_comm, sub_eq_iff_eq_add], simp end @[simp] lemma sub_one_lt_iff {n : ℕ} {k : fin (n + 1)} : k - 1 < k ↔ 0 < k := not_iff_not.1 $ by simp only [not_lt, le_sub_one_iff, le_zero_iff] lemma last_sub (i : fin (n + 1)) : last n - i = i.rev := ext $ by rw [coe_sub_iff_le.2 i.le_last, coe_last, coe_rev, nat.succ_sub_succ_eq_sub] end add_group section succ_above lemma succ_above_aux (p : fin (n + 1)) : strict_mono (λ i : fin n, if i.cast_succ < p then i.cast_succ else i.succ) := (cast_succ : fin n ↪o _).strict_mono.ite (succ_embedding n).strict_mono (λ i j hij hj, lt_trans ((cast_succ : fin n ↪o _).lt_iff_lt.2 hij) hj) (λ i, (cast_succ_lt_succ i).le) /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n + 1)) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono _ p.succ_above_aux /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/ lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) : p.succ_above i = i.cast_succ := by { rw [succ_above], exact if_pos h } @[simp] lemma succ_above_ne_zero_zero [ne_zero n] {a : fin (n + 1)} (ha : a ≠ 0) : a.succ_above 0 = 0 := begin rw fin.succ_above_below, { refl }, { exact bot_lt_iff_ne_bot.mpr ha } end lemma succ_above_eq_zero_iff [ne_zero n] {a : fin (n + 1)} {b : fin n} (ha : a ≠ 0) : a.succ_above b = 0 ↔ b = 0 := by simp only [←succ_above_ne_zero_zero ha, order_embedding.eq_iff_eq] lemma succ_above_ne_zero [ne_zero n] {a : fin (n + 1)} {b : fin n} (ha : a ≠ 0) (hb : b ≠ 0) : a.succ_above b ≠ 0 := mt (succ_above_eq_zero_iff ha).mp hb /-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/ @[simp] lemma succ_above_zero : ⇑(succ_above (0 : fin (n + 1))) = fin.succ := rfl /-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/ @[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ := by { ext, simp only [succ_above_below, cast_succ_lt_last] } lemma succ_above_last_apply (i : fin n) : succ_above (fin.last n) i = i.cast_succ := by rw succ_above_last /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `succ` when the resulting `p < i.succ`. -/ lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) : p.succ_above i = i.succ := by simp [succ_above, h.not_lt] /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ := lt_or_ge (cast_succ i) p /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ := or.cases_on (succ_above_lt_ge p i) (λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i))) /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater results in a value that is less than `p`. -/ @[simp] lemma succ_above_lt_iff (p : fin (n + 1)) (i : fin n) : p.succ_above i < p ↔ i.cast_succ < p := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { exact H }, { rw succ_above_above _ _ H at h, exact lt_trans (cast_succ_lt_succ i) h } }, { intro h, rw succ_above_below _ _ h, exact h } end /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser results in a value that is greater than `p`. -/ lemma lt_succ_above_iff (p : fin (n + 1)) (i : fin n) : p < p.succ_above i ↔ p ≤ i.cast_succ := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { rw succ_above_below _ _ H at h, exact le_of_lt h }, { exact H } }, { intro h, rw succ_above_above _ _ h, exact lt_of_le_of_lt h (cast_succ_lt_succ i) }, end /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` never results in `p` itself -/ theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p := begin intro eq, by_cases H : i.cast_succ < p, { simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H }, { simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i } end /-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/ lemma succ_above_pos [ne_zero n] (p : fin (n + 1)) (i : fin n) (h : 0 < i) : 0 < p.succ_above i := begin by_cases H : i.cast_succ < p, { simpa [succ_above_below _ _ H] using cast_succ_pos h }, { simp [succ_above_above _ _ (le_of_not_lt H)] }, end @[simp] lemma succ_above_cast_lt {x y : fin (n + 1)} (h : x < y) (hx : x.1 < n := lt_of_lt_of_le h y.le_last) : y.succ_above (x.cast_lt hx) = x := by { rw [succ_above_below, cast_succ_cast_lt], exact h } @[simp] lemma succ_above_pred {x y : fin (n + 1)} (h : x < y) (hy : y ≠ 0 := (x.zero_le.trans_lt h).ne') : x.succ_above (y.pred hy) = y := by { rw [succ_above_above, succ_pred], simpa [le_iff_coe_le_coe] using nat.le_pred_of_lt h } lemma cast_lt_succ_above {x : fin n} {y : fin (n + 1)} (h : cast_succ x < y) (h' : (y.succ_above x).1 < n := lt_of_lt_of_le ((succ_above_lt_iff _ _).2 h) (le_last y)) : (y.succ_above x).cast_lt h' = x := by simp only [succ_above_below _ _ h, cast_lt_cast_succ] lemma pred_succ_above {x : fin n} {y : fin (n + 1)} (h : y ≤ cast_succ x) (h' : y.succ_above x ≠ 0 := (y.zero_le.trans_lt $ (lt_succ_above_iff _ _).2 h).ne') : (y.succ_above x).pred h' = x := by simp only [succ_above_above _ _ h, pred_succ] lemma exists_succ_above_eq {x y : fin (n + 1)} (h : x ≠ y) : ∃ z, y.succ_above z = x := begin cases h.lt_or_lt with hlt hlt, exacts [⟨_, succ_above_cast_lt hlt⟩, ⟨_, succ_above_pred hlt⟩], end @[simp] lemma exists_succ_above_eq_iff {x y : fin (n + 1)} : (∃ z, x.succ_above z = y) ↔ y ≠ x := begin refine ⟨_, exists_succ_above_eq⟩, rintro ⟨y, rfl⟩, exact succ_above_ne _ _ end /-- The range of `p.succ_above` is everything except `p`. -/ @[simp] lemma range_succ_above (p : fin (n + 1)) : set.range (p.succ_above) = {p}ᶜ := set.ext $ λ _, exists_succ_above_eq_iff @[simp] lemma range_succ (n : ℕ) : set.range (fin.succ : fin n → fin (n + 1)) = {0}ᶜ := range_succ_above 0 @[simp] lemma exists_succ_eq_iff {x : fin (n + 1)} : (∃ y, fin.succ y = x) ↔ x ≠ 0 := @exists_succ_above_eq_iff n 0 x /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) := (succ_above x).injective /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_inj {x : fin (n + 1)} : x.succ_above a = x.succ_above b ↔ a = b := succ_above_right_injective.eq_iff /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_injective : injective (@succ_above n) := λ _ _ h, by simpa [range_succ_above] using congr_arg (λ f : fin n ↪o fin (n + 1), (set.range f)ᶜ) h /-- `succ_above` is injective at the pivot -/ @[simp] lemma succ_above_left_inj {x y : fin (n + 1)} : x.succ_above = y.succ_above ↔ x = y := succ_above_left_injective.eq_iff @[simp] lemma zero_succ_above {n : ℕ} (i : fin n) : (0 : fin (n + 1)).succ_above i = i.succ := rfl @[simp] lemma succ_succ_above_zero {n : ℕ} [ne_zero n] (i : fin n) : (i.succ).succ_above 0 = 0 := succ_above_below _ _ (succ_pos _) @[simp] lemma succ_succ_above_succ {n : ℕ} (i : fin (n + 1)) (j : fin n) : (i.succ).succ_above j.succ = (i.succ_above j).succ := (lt_or_ge j.cast_succ i).elim (λ h, have h' : j.succ.cast_succ < i.succ, by simpa [lt_iff_coe_lt_coe] using h, by { ext, simp [succ_above_below _ _ h, succ_above_below _ _ h'] }) (λ h, have h' : i.succ ≤ j.succ.cast_succ, by simpa [le_iff_coe_le_coe] using h, by { ext, simp [succ_above_above _ _ h, succ_above_above _ _ h'] }) @[simp] lemma one_succ_above_zero {n : ℕ} : (1 : fin (n + 2)).succ_above 0 = 0 := succ_succ_above_zero 0 /-- By moving `succ` to the outside of this expression, we create opportunities for further simplification using `succ_above_zero` or `succ_succ_above_zero`. -/ @[simp] lemma succ_succ_above_one {n : ℕ} [ne_zero n] (i : fin (n + 1)) : (i.succ).succ_above 1 = (i.succ_above 0).succ := by rw [← succ_succ_above_succ i 0, succ_zero_eq_one] @[simp] lemma one_succ_above_succ {n : ℕ} (j : fin n) : (1 : fin (n + 2)).succ_above j.succ = j.succ.succ := succ_succ_above_succ 0 j @[simp] lemma one_succ_above_one {n : ℕ} : (1 : fin (n + 3)).succ_above 1 = 2 := succ_succ_above_succ 0 0 end succ_above section pred_above /-- `pred_above p i` embeds `i : fin (n+1)` into `fin n` by subtracting one if `p < i`. -/ def pred_above (p : fin n) (i : fin (n+1)) : fin n := if h : p.cast_succ < i then i.pred (ne_of_lt (lt_of_le_of_lt (zero_le p.cast_succ) h)).symm else i.cast_lt (lt_of_le_of_lt (le_of_not_lt h) p.2) lemma pred_above_right_monotone (p : fin n) : monotone p.pred_above := λ a b H, begin dsimp [pred_above], split_ifs with ha hb hb, all_goals { simp only [le_iff_coe_le_coe, coe_pred], }, { exact pred_le_pred H, }, { calc _ ≤ _ : nat.pred_le _ ... ≤ _ : H, }, { simp at ha, exact le_pred_of_lt (lt_of_le_of_lt ha hb), }, { exact H, }, end lemma pred_above_left_monotone (i : fin (n + 1)) : monotone (λ p, pred_above p i) := λ a b H, begin dsimp [pred_above], split_ifs with ha hb hb, all_goals { simp only [le_iff_coe_le_coe, coe_pred] }, { exact pred_le _, }, { have : b < a := cast_succ_lt_cast_succ_iff.mpr (hb.trans_le (le_of_not_gt ha)), exact absurd H this.not_le } end /-- `cast_pred` embeds `i : fin (n + 2)` into `fin (n + 1)` by lowering just `last (n + 1)` to `last n`. -/ def cast_pred (i : fin (n + 2)) : fin (n + 1) := pred_above (last n) i @[simp] lemma cast_pred_zero : cast_pred (0 : fin (n + 2)) = 0 := rfl @[simp] lemma cast_pred_one : cast_pred (1 : fin (n + 2)) = 1 := by { cases n, apply subsingleton.elim, refl } @[simp] theorem pred_above_zero {i : fin (n + 2)} (hi : i ≠ 0) : pred_above 0 i = i.pred hi := begin dsimp [pred_above], rw dif_pos, exact (pos_iff_ne_zero _).mpr hi, end @[simp] lemma cast_pred_last : cast_pred (last (n + 1)) = last n := eq_of_veq (by simp [cast_pred, pred_above, cast_succ_lt_last]) @[simp] lemma cast_pred_mk (n i : ℕ) (h : i < n + 1) : cast_pred ⟨i, lt_succ_of_lt h⟩ = ⟨i, h⟩ := begin have : ¬cast_succ (last n) < ⟨i, lt_succ_of_lt h⟩, { simpa [lt_iff_coe_lt_coe] using le_of_lt_succ h }, simp [cast_pred, pred_above, this] end lemma coe_cast_pred {n : ℕ} (a : fin (n + 2)) (hx : a < fin.last _) : (a.cast_pred : ℕ) = a := begin rcases a with ⟨a, ha⟩, rw cast_pred_mk, exacts [rfl, hx], end lemma pred_above_below (p : fin (n + 1)) (i : fin (n + 2)) (h : i ≤ p.cast_succ) : p.pred_above i = i.cast_pred := begin have : i ≤ (last n).cast_succ := h.trans p.le_last, simp [pred_above, cast_pred, h.not_lt, this.not_lt] end @[simp] lemma pred_above_last : pred_above (fin.last n) = cast_pred := rfl lemma pred_above_last_apply (i : fin n) : pred_above (fin.last n) i = i.cast_pred := by rw pred_above_last lemma pred_above_above (p : fin n) (i : fin (n + 1)) (h : p.cast_succ < i) : p.pred_above i = i.pred (p.cast_succ.zero_le.trans_lt h).ne.symm := by simp [pred_above, h] lemma cast_pred_monotone : monotone (@cast_pred n) := pred_above_right_monotone (last _) /-- Sending `fin (n+1)` to `fin n` by subtracting one from anything above `p` then back to `fin (n+1)` with a gap around `p` is the identity away from `p`. -/ @[simp] lemma succ_above_pred_above {p : fin n} {i : fin (n + 1)} (h : i ≠ p.cast_succ) : p.cast_succ.succ_above (p.pred_above i) = i := begin dsimp [pred_above, succ_above], rcases p with ⟨p, _⟩, rcases i with ⟨i, _⟩, cases lt_or_le i p with H H, { rw dif_neg, rw if_pos, refl, exact H, simp, apply le_of_lt H, }, { rw dif_pos, rw if_neg, swap 3, -- For some reason `simp` doesn't fire fully unless we discharge the third goal. { exact lt_of_le_of_ne H (ne.symm h), }, { simp, }, { simp only [fin.mk_eq_mk, ne.def, fin.cast_succ_mk] at h, simp only [pred, fin.mk_lt_mk, not_lt], exact nat.le_pred_of_lt (nat.lt_of_le_and_ne H (ne.symm h)), }, }, end /-- Sending `fin n` into `fin (n + 1)` with a gap at `p` then back to `fin n` by subtracting one from anything above `p` is the identity. -/ @[simp] lemma pred_above_succ_above (p : fin n) (i : fin n) : p.pred_above (p.cast_succ.succ_above i) = i := begin dsimp [pred_above, succ_above], rcases p with ⟨p, _⟩, rcases i with ⟨i, _⟩, split_ifs, { rw dif_neg, { refl }, { simp_rw [if_pos h], simp only [subtype.mk_lt_mk, not_lt], exact le_of_lt h, }, }, { rw dif_pos, { refl, }, { simp_rw [if_neg h], exact lt_succ_iff.mpr (not_lt.mp h), }, }, end lemma cast_succ_pred_eq_pred_cast_succ {a : fin (n + 1)} (ha : a ≠ 0) (ha' := a.cast_succ_ne_zero_iff.mpr ha) : (a.pred ha).cast_succ = a.cast_succ.pred ha' := by { cases a, refl } /-- `pred` commutes with `succ_above`. -/ lemma pred_succ_above_pred {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0) (hk := succ_above_ne_zero ha hb) : (a.pred ha).succ_above (b.pred hb) = (a.succ_above b).pred hk := begin obtain hbelow | habove := lt_or_le b.cast_succ a, -- `rwa` uses them { rw fin.succ_above_below, { rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_inj, fin.succ_above_below] }, { rwa [cast_succ_pred_eq_pred_cast_succ , pred_lt_pred_iff] } }, { rw fin.succ_above_above, have : (b.pred hb).succ = b.succ.pred (fin.succ_ne_zero _), by rw [succ_pred, pred_succ], { rwa [this, fin.pred_inj, fin.succ_above_above] }, { rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_le_pred_iff] } } end /-- `succ` commutes with `pred_above`. -/ @[simp] lemma succ_pred_above_succ (a : fin n) (b : fin (n+1)) : a.succ.pred_above b.succ = (a.pred_above b).succ := begin obtain h₁ | h₂ := lt_or_le a.cast_succ b, { rw [fin.pred_above_above _ _ h₁, fin.succ_pred, fin.pred_above_above, fin.pred_succ], simpa only [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, add_lt_add_iff_right] using h₁, }, { cases n, { exfalso, exact not_lt_zero' a.is_lt, }, { rw [fin.pred_above_below a b h₂, fin.pred_above_below a.succ b.succ (by simpa only [le_iff_coe_le_coe, coe_succ, coe_cast_succ, add_le_add_iff_right] using h₂)], ext, have h₀ : (b : ℕ) < n+1, { simp only [le_iff_coe_le_coe, coe_cast_succ] at h₂, simpa only [lt_succ_iff] using h₂.trans a.is_le, }, have h₁ : (b.succ : ℕ) < n+2, { rw ← nat.succ_lt_succ_iff at h₀, simpa only [coe_succ] using h₀, }, simp only [coe_cast_pred b h₀, coe_cast_pred b.succ h₁, coe_succ], }, }, end @[simp] theorem cast_pred_cast_succ (i : fin (n + 1)) : cast_pred i.cast_succ = i := by simp [cast_pred, pred_above, le_last] lemma cast_succ_cast_pred {i : fin (n + 2)} (h : i < last _) : cast_succ i.cast_pred = i := begin rw [cast_pred, pred_above, dif_neg], { simp [fin.eq_iff_veq] }, { exact h.not_le } end lemma coe_cast_pred_le_self (i : fin (n + 2)) : (i.cast_pred : ℕ) ≤ i := begin rcases i.le_last.eq_or_lt with rfl|h, { simp }, { rw [cast_pred, pred_above, dif_neg], { simp }, { simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe, lt_succ_iff] using h } } end lemma coe_cast_pred_lt_iff {i : fin (n + 2)} : (i.cast_pred : ℕ) < i ↔ i = fin.last _ := begin rcases i.le_last.eq_or_lt with rfl|H, { simp }, { simp only [ne_of_lt H], rw ←cast_succ_cast_pred H, simp } end lemma lt_last_iff_coe_cast_pred {i : fin (n + 2)} : i < fin.last _ ↔ (i.cast_pred : ℕ) = i := begin rcases i.le_last.eq_or_lt with rfl|H, { simp }, { simp only [H], rw ←cast_succ_cast_pred H, simp } end end pred_above /-- `min n m` as an element of `fin (m + 1)` -/ def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m @[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ @[simp] lemma coe_of_nat_eq_mod (m n : ℕ) [ne_zero m] : ((n : fin m) : ℕ) = n % m := rfl section mul /-! ### mul -/ lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] protected lemma mul_one [ne_zero n] (k : fin n) : k * 1 = k := begin unfreezingI { cases n }, { simp }, unfreezingI { cases n }, { simp }, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] end protected lemma mul_comm (a b : fin n) : a * b = b * a := fin.eq_of_veq $ by rw [mul_def, mul_def, mul_comm] @[simp] protected lemma one_mul [ne_zero n] (k : fin n) : (1 : fin n) * k = k := by rw [fin.mul_comm, fin.mul_one] @[simp] protected lemma mul_zero [ne_zero n] (k : fin n) : k * 0 = 0 := by simp [eq_iff_veq, mul_def] @[simp] protected lemma zero_mul [ne_zero n] (k : fin n) : (0 : fin n) * k = 0 := by simp [eq_iff_veq, mul_def] end mul section -- Note that here we are disabling the "safety" of reflected, to allow us to reuse `nat.mk_numeral`. -- The usual way to provide the required `reflected` instance would be via rewriting to prove that -- the expression we use here is equivalent. local attribute [semireducible] reflected meta instance reflect : Π n, has_reflect (fin n) | 0 := fin_zero_elim | (n + 1) := nat.mk_numeral `(fin n.succ) `(by apply_instance : has_zero (fin n.succ)) `(by apply_instance : has_one (fin n.succ)) `(by apply_instance : has_add (fin n.succ)) ∘ fin.val end end fin
4445562f059a9bbb6e2a4f9fb4c341408db1fd5a
7c2dd01406c42053207061adb11703dc7ce0b5e5
/src/exercises/05_sequence_limits.lean
2c68967e243af16a123a8e3e2863ecc319c3c894
[ "Apache-2.0" ]
permissive
leanprover-community/tutorials
50ec79564cbf2ad1afd1ac43d8ee3c592c2883a8
79a6872a755c4ae0c2aca57e1adfdac38b1d8bb1
refs/heads/master
1,687,466,144,386
1,672,061,276,000
1,672,061,276,000
189,169,918
186
81
Apache-2.0
1,686,350,300,000
1,559,113,678,000
Lean
UTF-8
Lean
false
false
5,894
lean
import data.real.basic import algebra.group.pi import tuto_lib notation `|`x`|` := abs x /- In this file we manipulate the elementary definition of limits of sequences of real numbers. mathlib has a much more general definition of limits, but here we want to practice using the logical operators and relations covered in the previous files. A sequence u is a function from ℕ to ℝ, hence Lean says u : ℕ → ℝ The definition we'll be using is: -- Definition of « u tends to l » def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε Note the use of `∀ ε > 0, ...` which is an abbreviation of `∀ ε, ε > 0 → ... ` In particular, a statement like `h : ∀ ε > 0, ...` can be specialized to a given ε₀ by `specialize h ε₀ hε₀` where hε₀ is a proof of ε₀ > 0. Also recall that, wherever Lean expects some proof term, we can start a tactic mode proof using the keyword `by` (followed by curly braces if you need more than one tactic invocation). For instance, if the local context contains: δ : ℝ δ_pos : δ > 0 h : ∀ ε > 0, ... then we can specialize h to the real number δ/2 using: `specialize h (δ/2) (by linarith)` where `by linarith` will provide the proof of `δ/2 > 0` expected by Lean. We'll take this opportunity to use two new tactics: `norm_num` will perform numerical normalization on the goal and `norm_num at h` will do the same in assumption `h`. This will get rid of trivial calculations on numbers, like replacing |l - l| by zero in the next exercise. `congr'` will try to prove equalities between applications of functions by recursively proving the arguments are the same. For instance, if the goal is `f x + g y = f z + g t` then congr will replace it by two goals: `x = z` and `y = t`. You can limit the recursion depth by specifying a natural number after `congr'`. For instance, in the above example, `congr' 1` will give new goals `f x = f z` and `g y = g t`, which only inspect arguments of the addition and not deeper. -/ variables (u v w : ℕ → ℝ) (l l' : ℝ) -- If u is constant with value l then u tends to l -- 0033 example : (∀ n, u n = l) → seq_limit u l := begin sorry end /- When dealing with absolute values, we'll use lemmas: abs_le {x y : ℝ} : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y abs_add (x y : ℝ) : |x + y| ≤ |x| + |y| abs_sub_comm (x y : ℝ) : |x - y| = |y - x| You should probably write them down on a sheet of paper that you keep at hand since they are used in many exercises. -/ -- Assume l > 0. Then u tends to l implies u n ≥ l/2 for large enough n -- 0034 example (hl : l > 0) : seq_limit u l → ∃ N, ∀ n ≥ N, u n ≥ l/2 := begin sorry end /- When dealing with max, you can use ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q You should probably add them to the sheet of paper where you wrote the `abs` lemmas since they are used in many exercises. Let's see an example. -/ -- If u tends to l and v tends l' then u+v tends to l+l' example (hu : seq_limit u l) (hv : seq_limit v l') : seq_limit (u + v) (l + l') := begin intros ε ε_pos, cases hu (ε/2) (by linarith) with N₁ hN₁, cases hv (ε/2) (by linarith) with N₂ hN₂, use max N₁ N₂, intros n hn, cases ge_max_iff.mp hn with hn₁ hn₂, have fact₁ : |u n - l| ≤ ε/2, from hN₁ n (by linarith), -- note the use of `from`. -- This is an alias for `exact`, -- but reads nicer in this context have fact₂ : |v n - l'| ≤ ε/2, from hN₂ n (by linarith), calc |(u + v) n - (l + l')| = |u n + v n - (l + l')| : rfl ... = |(u n - l) + (v n - l')| : by congr' 1 ; ring ... ≤ |u n - l| + |v n - l'| : by apply abs_add ... ≤ ε : by linarith, end /- In the above proof, we used `have` to prepare facts for `linarith` consumption in the last line. Since we have direct proof terms for them, we can feed them directly to `linarith` as in the next proof of the same statement. Another variation we introduce is rewriting using `ge_max_iff` and letting `linarith` handle the conjunction, instead of creating two new assumptions. -/ example (hu : seq_limit u l) (hv : seq_limit v l') : seq_limit (u + v) (l + l') := begin intros ε ε_pos, cases hu (ε/2) (by linarith) with N₁ hN₁, cases hv (ε/2) (by linarith) with N₂ hN₂, use max N₁ N₂, intros n hn, rw ge_max_iff at hn, calc |(u + v) n - (l + l')| = |u n + v n - (l + l')| : rfl ... = |(u n - l) + (v n - l')| : by congr' 1 ; ring ... ≤ |u n - l| + |v n - l'| : by apply abs_add ... ≤ ε : by linarith [hN₁ n (by linarith), hN₂ n (by linarith)], end /- Let's do something similar: the squeezing theorem. -/ -- 0035 example (hu : seq_limit u l) (hw : seq_limit w l) (h : ∀ n, u n ≤ v n) (h' : ∀ n, v n ≤ w n) : seq_limit v l := begin sorry end /- What about < ε? -/ -- 0036 example (u l) : seq_limit u l ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| < ε := begin sorry end /- In the next exercise, we'll use eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y -/ -- A sequence admits at most one limit -- 0037 example : seq_limit u l → seq_limit u l' → l = l' := begin sorry end /- Let's now practice deciphering definitions before proving. -/ def non_decreasing (u : ℕ → ℝ) := ∀ n m, n ≤ m → u n ≤ u m def is_seq_sup (M : ℝ) (u : ℕ → ℝ) := (∀ n, u n ≤ M) ∧ ∀ ε > 0, ∃ n₀, u n₀ ≥ M - ε -- 0038 example (M : ℝ) (h : is_seq_sup M u) (h' : non_decreasing u) : seq_limit u M := begin sorry end
cafafbae96cd1838554a93ec466204e15721128f
618003631150032a5676f229d13a079ac875ff77
/src/field_theory/perfect_closure.lean
959ef695c52c790c5a64f657b099d7e2ff3fb8f1
[ "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
16,682
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.char_p import data.equiv.ring import algebra.group_with_zero_power import algebra.iterate_hom /-! # The perfect closure of a field -/ universes u v open function section defs variables (K : Type u) [field K] (p : ℕ) [fact p.prime] [char_p K p] /-- A perfect field is a field of characteristic p that has p-th root. -/ class perfect_field (K : Type u) [field K] (p : ℕ) [fact p.prime] [char_p K p] : Type u := (pth_root' : K → K) (frobenius_pth_root' : ∀ x, frobenius K p (pth_root' x) = x) /-- Frobenius automorphism of a perfect field. -/ def frobenius_equiv [perfect_field K p] : K ≃+* K := { inv_fun := perfect_field.pth_root' p, left_inv := λ x, frobenius_inj K p $ perfect_field.frobenius_pth_root' _, right_inv := perfect_field.frobenius_pth_root', .. frobenius K p } /-- `p`-th root of a number in a `perfect_field` as a `ring_hom`. -/ def pth_root [perfect_field K p] : K →+* K := (frobenius_equiv K p).symm.to_ring_hom end defs section variables {K : Type u} [field K] {L : Type v} [field L] (f : K →* L) (g : K →+* L) {p : ℕ} [fact p.prime] [char_p K p] [perfect_field K p] [char_p L p] [perfect_field L p] @[simp] lemma coe_frobenius_equiv : ⇑(frobenius_equiv K p) = frobenius K p := rfl @[simp] lemma coe_frobenius_equiv_symm : ⇑(frobenius_equiv K p).symm = pth_root K p := rfl @[simp] theorem frobenius_pth_root (x : K) : frobenius K p (pth_root K p x) = x := (frobenius_equiv K p).apply_symm_apply x @[simp] theorem pth_root_frobenius (x : K) : pth_root K p (frobenius K p x) = x := (frobenius_equiv K p).symm_apply_apply x theorem left_inverse_pth_root_frobenius : left_inverse (pth_root K p) (frobenius K p) := pth_root_frobenius theorem eq_pth_root_iff {x y : K} : x = pth_root K p y ↔ frobenius K p x = y := (frobenius_equiv K p).to_equiv.eq_symm_apply theorem pth_root_eq_iff {x y : K} : pth_root K p x = y ↔ x = frobenius K p y := (frobenius_equiv K p).to_equiv.symm_apply_eq theorem monoid_hom.map_pth_root (x : K) : f (pth_root K p x) = pth_root L p (f x) := eq_pth_root_iff.2 $ by rw [← f.map_frobenius, frobenius_pth_root] theorem monoid_hom.map_iterate_pth_root (x : K) (n : ℕ) : f (pth_root K p^[n] x) = (pth_root L p^[n] (f x)) := semiconj.iterate_right f.map_pth_root n x theorem ring_hom.map_pth_root (x : K) : g (pth_root K p x) = pth_root L p (g x) := g.to_monoid_hom.map_pth_root x theorem ring_hom.map_iterate_pth_root (x : K) (n : ℕ) : g (pth_root K p^[n] x) = (pth_root L p^[n] (g x)) := g.to_monoid_hom.map_iterate_pth_root x n end section variables (K : Type u) [comm_ring K] (p : ℕ) [fact p.prime] [char_p K p] /-- `perfect_closure K p` is the quotient by this relation. -/ inductive perfect_closure.r : (ℕ × K) → (ℕ × K) → Prop | intro : ∀ n x, perfect_closure.r (n, x) (n+1, frobenius K p x) mk_iff_of_inductive_prop perfect_closure.r perfect_closure.r_iff /-- The perfect closure is the smallest extension that makes frobenius surjective. -/ def perfect_closure : Type u := quot (perfect_closure.r K p) end namespace perfect_closure variables (K : Type u) section ring variables [comm_ring K] (p : ℕ) [fact p.prime] [char_p K p] /-- Constructor for `perfect_closure`. -/ def mk (x : ℕ × K) : perfect_closure K p := quot.mk (r K p) x @[simp] lemma quot_mk_eq_mk (x : ℕ × K) : (quot.mk (r K p) x : perfect_closure K p) = mk K p x := rfl variables {K p} /-- Lift a function `ℕ × K → L` to a function on `perfect_closure K p`. -/ @[elab_as_eliminator] def lift_on {L : Type*} (x : perfect_closure K p) (f : ℕ × K → L) (hf : ∀ x y, r K p x y → f x = f y) : L := quot.lift_on x f hf @[simp] lemma lift_on_mk {L : Sort*} (f : ℕ × K → L) (hf : ∀ x y, r K p x y → f x = f y) (x : ℕ × K) : (mk K p x).lift_on f hf = f x := rfl @[elab_as_eliminator] lemma induction_on (x : perfect_closure K p) {q : perfect_closure K p → Prop} (h : ∀ x, q (mk K p x)) : q x := quot.induction_on x h variables (K p) private lemma mul_aux_left (x1 x2 y : ℕ × K) (H : r K p x1 x2) : mk K p (x1.1 + y.1, ((frobenius K p)^[y.1] x1.2) * ((frobenius K p)^[x1.1] y.2)) = mk K p (x2.1 + y.1, ((frobenius K p)^[y.1] x2.2) * ((frobenius K p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro n x := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_mul, nat.succ_add]; apply r.intro end private lemma mul_aux_right (x y1 y2 : ℕ × K) (H : r K p y1 y2) : mk K p (x.1 + y1.1, ((frobenius K p)^[y1.1] x.2) * ((frobenius K p)^[x.1] y1.2)) = mk K p (x.1 + y2.1, ((frobenius K p)^[y2.1] x.2) * ((frobenius K p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro n y := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_mul]; apply r.intro end instance : has_mul (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.lift (λ y:ℕ×K, mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) * ((frobenius K p)^[x.1] y.2))) (mul_aux_right K p x)) (λ x1 x2 (H : r K p x1 x2), funext $ λ e, quot.induction_on e $ λ y, mul_aux_left K p x1 x2 y H)⟩ @[simp] lemma mk_mul_mk (x y : ℕ × K) : mk K p x * mk K p y = mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) * ((frobenius K p)^[x.1] y.2)) := rfl instance : comm_monoid (perfect_closure K p) := { mul_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, mul_assoc, ring_hom.iterate_map_mul, ← iterate_add_apply, add_comm, add_left_comm], one := mk K p (0, 1), one_mul := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_one, iterate_zero_apply, one_mul, zero_add]), mul_one := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_one, iterate_zero_apply, mul_one, add_zero]), mul_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm, mul_comm])), .. (infer_instance : has_mul (perfect_closure K p)) } lemma one_def : (1 : perfect_closure K p) = mk K p (0, 1) := rfl instance : inhabited (perfect_closure K p) := ⟨1⟩ private lemma add_aux_left (x1 x2 y : ℕ × K) (H : r K p x1 x2) : mk K p (x1.1 + y.1, ((frobenius K p)^[y.1] x1.2) + ((frobenius K p)^[x1.1] y.2)) = mk K p (x2.1 + y.1, ((frobenius K p)^[y.1] x2.2) + ((frobenius K p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro n x := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_add, nat.succ_add]; apply r.intro end private lemma add_aux_right (x y1 y2 : ℕ × K) (H : r K p y1 y2) : mk K p (x.1 + y1.1, ((frobenius K p)^[y1.1] x.2) + ((frobenius K p)^[x.1] y1.2)) = mk K p (x.1 + y2.1, ((frobenius K p)^[y2.1] x.2) + ((frobenius K p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro n y := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_add]; apply r.intro end instance : has_add (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.lift (λ y:ℕ×K, mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) + ((frobenius K p)^[x.1] y.2))) (add_aux_right K p x)) (λ x1 x2 (H : r K p x1 x2), funext $ λ e, quot.induction_on e $ λ y, add_aux_left K p x1 x2 y H)⟩ @[simp] lemma mk_add_mk (x y : ℕ × K) : mk K p x + mk K p y = mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) + ((frobenius K p)^[x.1] y.2)) := rfl instance : has_neg (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, mk K p (x.1, -x.2)) (λ x y (H : r K p x y), match x, y, H with | _, _, r.intro n x := quot.sound $ by rw ← frobenius_neg; apply r.intro end)⟩ @[simp] lemma neg_mk (x : ℕ × K) : - mk K p x = mk K p (x.1, -x.2) := rfl instance : has_zero (perfect_closure K p) := ⟨mk K p (0, 0)⟩ lemma zero_def : (0 : perfect_closure K p) = mk K p (0, 0) := rfl theorem mk_zero (n : ℕ) : mk K p (n, 0) = 0 := by induction n with n ih; [refl, rw ← ih]; symmetry; apply quot.sound; have := r.intro n (0:K); rwa [frobenius_zero K p] at this theorem r.sound (m n : ℕ) (x y : K) (H : frobenius K p^[m] x = y) : mk K p (n, x) = mk K p (m + n, y) := by subst H; induction m with m ih; [simp only [zero_add, iterate_zero_apply], rw [ih, nat.succ_add, iterate_succ']]; apply quot.sound; apply r.intro instance : comm_ring (perfect_closure K p) := { add_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, ring_hom.iterate_map_add, ← iterate_add_apply, add_comm, add_left_comm], zero := 0, zero_add := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_zero, iterate_zero_apply, zero_add]), add_zero := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_zero, iterate_zero_apply, add_zero]), add_left_neg := λ e, quot.induction_on e (λ ⟨n, x⟩, by simp only [quot_mk_eq_mk, neg_mk, mk_add_mk, ring_hom.iterate_map_neg, add_left_neg, mk_zero]), add_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm])), left_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm, add_left_comm]; apply r.sound; simp only [ring_hom.iterate_map_mul, ring_hom.iterate_map_add, ← iterate_add_apply, mul_add, add_comm, add_left_comm], right_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm _ s, add_left_comm _ s]; apply r.sound; simp only [ring_hom.iterate_map_mul, ring_hom.iterate_map_add, ← iterate_add_apply, add_mul, add_comm, add_left_comm], .. (infer_instance : has_add (perfect_closure K p)), .. (infer_instance : has_neg (perfect_closure K p)), .. (infer_instance : comm_monoid (perfect_closure K p)) } theorem eq_iff' (x y : ℕ × K) : mk K p x = mk K p y ↔ ∃ z, (frobenius K p^[y.1 + z] x.2) = (frobenius K p^[x.1 + z] y.2) := begin split, { intro H, replace H := quot.exact _ H, induction H, case eqv_gen.rel : x y H { cases H with n x, exact ⟨0, rfl⟩ }, case eqv_gen.refl : H { exact ⟨0, rfl⟩ }, case eqv_gen.symm : x y H ih { cases ih with w ih, exact ⟨w, ih.symm⟩ }, case eqv_gen.trans : x y z H1 H2 ih1 ih2 { cases ih1 with z1 ih1, cases ih2 with z2 ih2, existsi z2+(y.1+z1), rw [← add_assoc, iterate_add_apply, ih1], rw [← iterate_add_apply, add_comm, iterate_add_apply, ih2], rw [← iterate_add_apply], simp only [add_comm, add_left_comm] } }, intro H, cases x with m x, cases y with n y, cases H with z H, dsimp only at H, rw [r.sound K p (n+z) m x _ rfl, r.sound K p (m+z) n y _ rfl, H], rw [add_assoc, add_comm, add_comm z] end theorem nat_cast (n x : ℕ) : (x : perfect_closure K p) = mk K p (n, x) := begin induction n with n ih, { induction x with x ih, {refl}, rw [nat.cast_succ, nat.cast_succ, ih], refl }, rw ih, apply quot.sound, conv {congr, skip, skip, rw ← frobenius_nat_cast K p x}, apply r.intro end theorem int_cast (x : ℤ) : (x : perfect_closure K p) = mk K p (0, x) := by induction x; simp only [int.cast_of_nat, int.cast_neg_succ_of_nat, nat_cast K p 0]; refl theorem nat_cast_eq_iff (x y : ℕ) : (x : perfect_closure K p) = y ↔ (x : K) = y := begin split; intro H, { rw [nat_cast K p 0, nat_cast K p 0, eq_iff'] at H, cases H with z H, simpa only [zero_add, iterate_fixed (frobenius_nat_cast K p _)] using H }, rw [nat_cast K p 0, nat_cast K p 0, H] end instance : char_p (perfect_closure K p) p := begin constructor, intro x, rw ← char_p.cast_eq_zero_iff K, rw [← nat.cast_zero, nat_cast_eq_iff, nat.cast_zero] end theorem frobenius_mk (x : ℕ × K) : (frobenius (perfect_closure K p) p : perfect_closure K p → perfect_closure K p) (mk K p x) = mk _ _ (x.1, x.2^p) := begin simp only [frobenius_def], cases x with n x, dsimp only, suffices : ∀ p':ℕ, mk K p (n, x) ^ p' = mk K p (n, x ^ p'), { apply this }, intro p, induction p with p ih, case nat.zero { apply r.sound, rw [(frobenius _ _).iterate_map_one, pow_zero] }, case nat.succ { rw [pow_succ, ih], symmetry, apply r.sound, simp only [pow_succ, (frobenius _ _).iterate_map_mul] } end /-- Embedding of `K` into `perfect_closure K p` -/ def of : K →+* perfect_closure K p := { to_fun := λ x, mk _ _ (0, x), map_one' := rfl, map_mul' := λ x y, rfl, map_zero' := rfl, map_add' := λ x y, rfl } lemma of_apply (x : K) : of K p x = mk _ _ (0, x) := rfl end ring theorem eq_iff [integral_domain K] (p : ℕ) [fact p.prime] [char_p K p] (x y : ℕ × K) : quot.mk (r K p) x = quot.mk (r K p) y ↔ (frobenius K p^[y.1] x.2) = (frobenius K p^[x.1] y.2) := (eq_iff' K p x y).trans ⟨λ ⟨z, H⟩, (frobenius_inj K p).iterate z $ by simpa only [add_comm, iterate_add] using H, λ H, ⟨0, H⟩⟩ section field variables [field K] (p : ℕ) [fact p.prime] [char_p K p] instance : has_inv (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.mk (r K p) (x.1, x.2⁻¹)) (λ x y (H : r K p x y), match x, y, H with | _, _, r.intro n x := quot.sound $ by { simp only [frobenius_def], rw ← inv_pow', apply r.intro } end)⟩ instance : field (perfect_closure K p) := { zero_ne_one := λ H, zero_ne_one ((eq_iff _ _ _ _).1 H), mul_inv_cancel := λ e, induction_on e $ λ ⟨m, x⟩ H, have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2 (by simp only [(frobenius _ _).iterate_map_one, (frobenius K p).iterate_map_zero, iterate_zero_apply, ← (frobenius _ p).iterate_map_mul] at this ⊢; rw [mul_inv_cancel this, (frobenius _ _).iterate_map_one]), inv_zero := congr_arg (quot.mk (r K p)) (by rw [inv_zero]), .. (infer_instance : has_inv (perfect_closure K p)), .. (infer_instance : comm_ring (perfect_closure K p)) } instance : perfect_field (perfect_closure K p) p := { pth_root' := λ e, lift_on e (λ x, mk K p (x.1 + 1, x.2)) (λ x y H, match x, y, H with | _, _, r.intro n x := quot.sound (r.intro _ _) end), frobenius_pth_root' := λ e, induction_on e (λ ⟨n, x⟩, by { simp only [lift_on_mk, frobenius_mk], exact (quot.sound $ r.intro _ _).symm }) } theorem eq_pth_root (x : ℕ × K) : mk K p x = (pth_root (perfect_closure K p) p^[x.1] (of K p x.2)) := begin rcases x with ⟨m, x⟩, induction m with m ih, {refl}, rw [iterate_succ_apply', ← ih]; refl end /-- Given a field `K` of characteristic `p` and a perfect field `L` of the same characteristic, any homomorphism `K →+* L` can be lifted to `perfect_closure K p`. -/ def lift (L : Type v) [field L] [char_p L p] [perfect_field L p] : (K →+* L) ≃ (perfect_closure K p →+* L) := begin have := left_inverse_pth_root_frobenius.iterate, refine_struct { .. }, field to_fun { intro f, refine_struct { .. }, field to_fun { refine λ e, lift_on e (λ x, pth_root L p^[x.1] (f x.2)) _, rintro a b ⟨n⟩, simp only [f.map_frobenius, iterate_succ_apply, pth_root_frobenius] }, field map_one' { exact f.map_one }, field map_zero' { exact f.map_zero }, field map_mul' { rintro ⟨x⟩ ⟨y⟩, simp only [quot_mk_eq_mk, lift_on_mk, mk_mul_mk, ring_hom.map_iterate_frobenius, ring_hom.iterate_map_mul, ring_hom.map_mul], rw [iterate_add_apply, this _ _, add_comm, iterate_add_apply, this _ _] }, field map_add' { rintro ⟨x⟩ ⟨y⟩, simp only [quot_mk_eq_mk, lift_on_mk, mk_add_mk, ring_hom.map_iterate_frobenius, ring_hom.iterate_map_add, ring_hom.map_add], rw [iterate_add_apply, this _ _, add_comm x.1, iterate_add_apply, this _ _] } }, field inv_fun { exact λ f, f.comp (of K p) }, field left_inv { intro f, ext x, refl }, field right_inv { intro f, ext ⟨x⟩, simp only [ring_hom.coe_mk, quot_mk_eq_mk, ring_hom.comp_apply, lift_on_mk], rw [eq_pth_root, ring_hom.map_iterate_pth_root] } end end field end perfect_closure
589bd4233ef5a6f71cc396181f3894a6dba84a9b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/separation.lean
2474f8efbb18c18ae2d0acfcf10d210fc2d42e9a
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
16,717
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Separation properties of topological spaces. -/ import topology.subset_properties open set filter open_locale topological_space local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- A T₀ space, also known as a Kolmogorov space, is a topological space where for every pair `x ≠ y`, there is an open set containing one but not the other. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U))) theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [ha : nonempty α] : ∃ x:α, is_open ({x}:set α) := have H : ∀ (T : finset α), T ≠ ∅ → ∃ x ∈ T, ∃ u, is_open u ∧ {x} = {y | y ∈ T} ∩ u := begin classical, intro T, apply finset.case_strong_induction_on T, { intro h, exact (h rfl).elim }, { intros x S hxS ih h, by_cases hs : S = ∅, { existsi [x, finset.mem_insert_self x S, univ, is_open_univ], rw [hs, inter_univ], refl }, { rcases ih S (finset.subset.refl S) hs with ⟨y, hy, V, hv1, hv2⟩, by_cases hxV : x ∈ V, { cases t0_space.t0 x y (λ hxy, hxS $ by rwa hxy) with U hu, rcases hu with ⟨hu1, ⟨hu2, hu3⟩ | ⟨hu2, hu3⟩⟩, { existsi [x, finset.mem_insert_self x S, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hzx, rw set.mem_singleton_iff at hzx, rw hzx, exact ⟨finset.mem_insert_self x S, ⟨hu2, hxV⟩⟩ }, { intro hz, rw set.mem_singleton_iff, rcases hz with ⟨hz1, hz2, hz3⟩, cases finset.mem_insert.1 hz1 with hz4 hz4, { exact hz4 }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V, { exact ⟨hz4, hz3⟩ }, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, rw h1 at hz2, exact (hu3 hz2).elim } } }, { existsi [y, finset.mem_insert_of_mem hy, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, refine ⟨finset.mem_insert_of_mem hy, hu2, _⟩, have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 }, { intro hz, rw set.mem_singleton_iff, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hu3 hz2.1).elim }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V := ⟨hz3, hz2.2⟩, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, exact h1 } } } }, { existsi [y, finset.mem_insert_of_mem hy, V, hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, split, { exact finset.mem_insert_of_mem hy }, { have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 } }, { intro hz, rw hv2, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hxV hz2).elim }, { exact ⟨hz3, hz2⟩ } } } } } end, begin apply nonempty.elim ha, intro x, specialize H finset.univ (finset.ne_empty_of_mem $ finset.mem_univ x), rcases H with ⟨y, hyf, U, hu1, hu2⟩, existsi y, have h1 : {y : α | y ∈ finset.univ} = (univ : set α), { exact set.eq_univ_of_forall (λ x : α, by rw mem_set_of_eq; exact finset.mem_univ x) }, rw h1 at hu2, rw set.univ_inter at hu2, rw hu2, exact hu1 end /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, ⟨-{x}, is_open_compl_iff.2 is_closed_singleton, or.inr ⟨λ hyx, or.cases_on hyx h.symm id, λ hx, hx $ or.inl rfl⟩⟩⟩ lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ 𝓝 y := mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := closure_eq_of_is_closed is_closed_singleton /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := ⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy, let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in ⟨u, λ z hz1 hz2, ((ext_iff _ _).1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩ lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : 𝓝 x ⊓ 𝓝 y ≠ ⊥) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in have u ∩ v ∈ 𝓝 x ⊓ 𝓝 y, from inter_mem_inf_sets (mem_nhds_sets hu hx) (mem_nhds_sets hv hy), h $ empty_in_sets_eq_bot.mp $ huv ▸ this lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, 𝓝 x ⊓ 𝓝 y ≠ ⊥ → x = y := ⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot, assume h, ⟨assume x y xy, have 𝓝 x ⊓ 𝓝 y = ⊥ := classical.by_contradiction (mt h xy), let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this, ⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu', ⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in ⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint.mono uu' vv' u'v'⟩⟩⟩ lemma t2_iff_ultrafilter : t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ 𝓝 x → f ≤ 𝓝 y → x = y := t2_iff_nhds.trans ⟨assume h f x y u fx fy, h $ ne_bot_of_le_ne_bot u.1 (le_inf fx fy), assume h x y xy, let ⟨f, hf, uf⟩ := exists_ultrafilter xy in h f uf (le_trans hf inf_le_left) (le_trans hf inf_le_right)⟩ @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : l ≠ ⊥) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot (map_ne_bot hl) $ le_inf ha hb section lim variables [nonempty α] [t2_space α] {f : filter α} lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ 𝓝 a) : lim f = a := eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot hf $ le_inf (lim_spec ⟨_, h⟩) h @[simp] lemma lim_nhds_eq {a : α} : lim (𝓝 a) = a := lim_eq nhds_ne_bot (le_refl _) @[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) : lim (𝓝 a ⊓ principal s) = a := lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left end lim @[priority 100] -- see Note [lower instance priority] instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, mem_insert _ _, mem_insert _ _, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } private lemma separated_by_f {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : tα ≤ tβ.induced f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst inf_le_left h₁) (λ h₂, separated_by_f prod.snd inf_le_right h₂)⟩ instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (infi_le _ i) hi⟩ lemma is_closed_diagonal [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_ne_bot $ assume : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ 𝓝 a₁ at ht₁, change t₂ ∈ 𝓝 a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end variables [topological_space β] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ -s, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ 𝓝 x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) end separation section regularity section prio set_option default_priority 100 -- see Note [default priority] /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥) end prio lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃t∈(𝓝 a), t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ -s' ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨-t, mem_sets_of_eq_bot $ by rwa [compl_compl], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ variable (α) @[priority 100] -- see Note [lower instance priority] instance regular_space.t2_space [regular_space α] : t2_space α := ⟨λ x y hxy, let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton (mt mem_singleton_iff.1 hxy), ⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs, ⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in ⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys, eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩ end regularity section normality section prio set_option default_priority 100 -- see Note [default priority] /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v) end prio theorem normal_separation [normal_space α] (s t : set α) (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := normal_space.normal s t H1 H2 H3 @[priority 100] -- see Note [lower instance priority] instance normal_space.regular_space [normal_space α] : regular_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton (λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in ⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2 ⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated hs.compact ht.compact st.eq_bot end end normality
b307520da7f08b3178e9272640aa7729679505e5
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/algebra/big_operators/pi.lean
ba1408cdb6d068c02670e65cb5df7bc3bf3d3b2b
[ "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
3,429
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.ring.pi import algebra.big_operators.basic import data.fintype.basic import algebra.group.prod /-! # Big operators for Pi Types This file contains theorems relevant to big operators in binary and arbitrary product of monoids and groups -/ open_locale big_operators namespace pi @[to_additive] lemma list_prod_apply {α : Type*} {β : α → Type*} [Πa, monoid (β a)] (a : α) (l : list (Πa, β a)) : l.prod a = (l.map (λf:Πa, β a, f a)).prod := (monoid_hom.apply β a).map_list_prod _ @[to_additive] lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α) (s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod := (monoid_hom.apply β a).map_multiset_prod _ end pi @[simp, to_additive] lemma finset.prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) a = ∏ c in s, g c a := (monoid_hom.apply β a).map_prod _ _ @[simp, to_additive] lemma fintype.prod_apply {α : Type*} {β : α → Type*} {γ : Type*} [fintype γ] [∀a, comm_monoid (β a)] (a : α) (g : γ → Πa, β a) : (∏ c, g c) a = ∏ c, g c a := finset.prod_apply a finset.univ g @[to_additive prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (∏ x in s, f x, ∏ x in s, g x) = ∏ x in s, (f x, g x) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) section single variables {I : Type*} [decidable_eq I] {Z : I → Type*} variables [Π i, add_comm_monoid (Z i)] -- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here. lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) : ∑ i, pi.single i (f i) = f := begin ext a, rw [finset.sum_apply, finset.sum_eq_single a], { simp, }, { intros b _ h, simp [h.symm], }, { intro h, exfalso, simpa using h, }, end @[ext] lemma add_monoid_hom.functions_ext [fintype I] (G : Type*) [add_comm_monoid G] (g h : (Π i, Z i) →+ G) (w : ∀ (i : I) (x : Z i), g (pi.single i x) = h (pi.single i x)) : g = h := begin ext k, rw [←finset.univ_sum_single k, add_monoid_hom.map_sum, add_monoid_hom.map_sum], apply finset.sum_congr rfl, intros, apply w, end end single section ring_hom open pi variables {I : Type*} [decidable_eq I] {f : I → Type*} variables [Π i, semiring (f i)] -- we need `apply`+`convert` because Lean fails to unify different `add_monoid` instances -- on `Π i, f i` @[ext] lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Π i, f i) →+* G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := begin apply ring_hom.coe_add_monoid_hom_injective, convert add_monoid_hom.functions_ext _ _ _ _; assumption end end ring_hom namespace prod variables {α β γ : Type*} [comm_monoid α] [comm_monoid β] {s : finset γ} {f : γ → α × β} @[to_additive] lemma fst_prod : (∏ c in s, f c).1 = ∏ c in s, (f c).1 := (monoid_hom.fst α β).map_prod f s @[to_additive] lemma snd_prod : (∏ c in s, f c).2 = ∏ c in s, (f c).2 := (monoid_hom.snd α β).map_prod f s end prod
4d7e851a4febd5a2472c60e1d9c7f7d6698e3a64
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/polynomial_galois_group.lean
d522d1b6ba71fd98b76d9c2dc8a7f906ab42dae8
[ "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
21,925
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import analysis.complex.polynomial import field_theory.galois import group_theory.perm.cycle.type /-! # Galois Groups of Polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we introduce the Galois group of a polynomial `p` over a field `F`, defined as the automorphism group of its splitting field. We also provide some results about some extension `E` above `p.splitting_field`, and some specific results about the Galois groups of ℚ-polynomials with specific numbers of non-real roots. ## Main definitions - `polynomial.gal p`: the Galois group of a polynomial p. - `polynomial.gal.restrict p E`: the restriction homomorphism `(E ≃ₐ[F] E) → gal p`. - `polynomial.gal.gal_action p E`: the action of `gal p` on the roots of `p` in `E`. ## Main results - `polynomial.gal.restrict_smul`: `restrict p E` is compatible with `gal_action p E`. - `polynomial.gal.gal_action_hom_injective`: `gal p` acting on the roots of `p` in `E` is faithful. - `polynomial.gal.restrict_prod_injective`: `gal (p * q)` embeds as a subgroup of `gal p × gal q`. - `polynomial.gal.card_of_separable`: For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. - `polynomial.gal.gal_action_hom_bijective_of_prime_degree`: An irreducible polynomial of prime degree with two non-real roots has full Galois group. ## Other results - `polynomial.gal.card_complex_roots_eq_card_real_add_card_not_gal_inv`: The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ noncomputable theory open_locale polynomial open finite_dimensional namespace polynomial variables {F : Type*} [field F] (p q : F[X]) (E : Type*) [field E] [algebra F E] /-- The Galois group of a polynomial. -/ @[derive [group, fintype]] def gal := p.splitting_field ≃ₐ[F] p.splitting_field namespace gal instance : has_coe_to_fun p.gal (λ _, p.splitting_field → p.splitting_field) := alg_equiv.has_coe_to_fun instance apply_mul_semiring_action : mul_semiring_action p.gal p.splitting_field := alg_equiv.apply_mul_semiring_action @[ext] lemma ext {σ τ : p.gal} (h : ∀ x ∈ p.root_set p.splitting_field, σ x = τ x) : σ = τ := begin refine alg_equiv.ext (λ x, (alg_hom.mem_equalizer σ.to_alg_hom τ.to_alg_hom x).mp ((set_like.ext_iff.mp _ x).mpr algebra.mem_top)), rwa [eq_top_iff, ←splitting_field.adjoin_root_set, algebra.adjoin_le_iff], end /-- If `p` splits in `F` then the `p.gal` is trivial. -/ def unique_gal_of_splits (h : p.splits (ring_hom.id F)) : unique p.gal := { default := 1, uniq := λ f, alg_equiv.ext (λ x, by { obtain ⟨y, rfl⟩ := algebra.mem_bot.mp ((set_like.ext_iff.mp ((is_splitting_field.splits_iff _ p).mp h) x).mp algebra.mem_top), rw [alg_equiv.commutes, alg_equiv.commutes] }) } instance [h : fact (p.splits (ring_hom.id F))] : unique p.gal := unique_gal_of_splits _ (h.1) instance unique_gal_zero : unique (0 : F[X]).gal := unique_gal_of_splits _ (splits_zero _) instance unique_gal_one : unique (1 : F[X]).gal := unique_gal_of_splits _ (splits_one _) instance unique_gal_C (x : F) : unique (C x).gal := unique_gal_of_splits _ (splits_C _ _) instance unique_gal_X : unique (X : F[X]).gal := unique_gal_of_splits _ (splits_X _) instance unique_gal_X_sub_C (x : F) : unique (X - C x).gal := unique_gal_of_splits _ (splits_X_sub_C _) instance unique_gal_X_pow (n : ℕ) : unique (X ^ n : F[X]).gal := unique_gal_of_splits _ (splits_X_pow _ _) instance [h : fact (p.splits (algebra_map F E))] : algebra p.splitting_field E := (is_splitting_field.lift p.splitting_field p h.1).to_ring_hom.to_algebra instance [h : fact (p.splits (algebra_map F E))] : is_scalar_tower F p.splitting_field E := is_scalar_tower.of_algebra_map_eq (λ x, ((is_splitting_field.lift p.splitting_field p h.1).commutes x).symm) -- The `algebra p.splitting_field E` instance above behaves badly when -- `E := p.splitting_field`, since it may result in a unification problem -- `is_splitting_field.lift.to_ring_hom.to_algebra =?= algebra.id`, -- which takes an extremely long time to resolve, causing timeouts. -- Since we don't really care about this definition, marking it as irreducible -- causes that unification to error out early. attribute [irreducible] gal.algebra /-- Restrict from a superfield automorphism into a member of `gal p`. -/ def restrict [fact (p.splits (algebra_map F E))] : (E ≃ₐ[F] E) →* p.gal := alg_equiv.restrict_normal_hom p.splitting_field lemma restrict_surjective [fact (p.splits (algebra_map F E))] [normal F E] : function.surjective (restrict p E) := alg_equiv.restrict_normal_hom_surjective E section roots_action /-- The function taking `roots p p.splitting_field` to `roots p E`. This is actually a bijection, see `polynomial.gal.map_roots_bijective`. -/ def map_roots [fact (p.splits (algebra_map F E))] : root_set p p.splitting_field → root_set p E := set.maps_to.restrict (is_scalar_tower.to_alg_hom F p.splitting_field E) _ _ $ root_set_maps_to _ lemma map_roots_bijective [h : fact (p.splits (algebra_map F E))] : function.bijective (map_roots p E) := begin split, { exact λ _ _ h, subtype.ext (ring_hom.injective _ (subtype.ext_iff.mp h)) }, { intro y, -- this is just an equality of two different ways to write the roots of `p` as an `E`-polynomial have key := roots_map (is_scalar_tower.to_alg_hom F p.splitting_field E : p.splitting_field →+* E) ((splits_id_iff_splits _).mpr (is_splitting_field.splits p.splitting_field p)), rw [map_map, alg_hom.comp_algebra_map] at key, have hy := subtype.mem y, simp only [root_set, finset.mem_coe, multiset.mem_to_finset, key, multiset.mem_map] at hy, rcases hy with ⟨x, hx1, hx2⟩, exact ⟨⟨x, (@multiset.mem_to_finset _ (classical.dec_eq _) _ _).mpr hx1⟩, subtype.ext hx2⟩ } end /-- The bijection between `root_set p p.splitting_field` and `root_set p E`. -/ def roots_equiv_roots [fact (p.splits (algebra_map F E))] : (root_set p p.splitting_field) ≃ (root_set p E) := equiv.of_bijective (map_roots p E) (map_roots_bijective p E) instance gal_action_aux : mul_action p.gal (root_set p p.splitting_field) := { smul := λ ϕ, set.maps_to.restrict ϕ _ _ $ root_set_maps_to ϕ.to_alg_hom, one_smul := λ _, by { ext, refl }, mul_smul := λ _ _ _, by { ext, refl } } /-- The action of `gal p` on the roots of `p` in `E`. -/ instance gal_action [fact (p.splits (algebra_map F E))] : mul_action p.gal (root_set p E) := { smul := λ ϕ x, roots_equiv_roots p E (ϕ • ((roots_equiv_roots p E).symm x)), one_smul := λ _, by simp only [equiv.apply_symm_apply, one_smul], mul_smul := λ _ _ _, by simp only [equiv.apply_symm_apply, equiv.symm_apply_apply, mul_smul] } variables {p E} /-- `polynomial.gal.restrict p E` is compatible with `polynomial.gal.gal_action p E`. -/ @[simp] lemma restrict_smul [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑((restrict p E ϕ) • x) = ϕ x := begin let ψ := alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F p.splitting_field E), change ↑(ψ (ψ.symm _)) = ϕ x, rw alg_equiv.apply_symm_apply ψ, change ϕ (roots_equiv_roots p E ((roots_equiv_roots p E).symm x)) = ϕ x, rw equiv.apply_symm_apply (roots_equiv_roots p E), end variables (p E) /-- `polynomial.gal.gal_action` as a permutation representation -/ def gal_action_hom [fact (p.splits (algebra_map F E))] : p.gal →* equiv.perm (root_set p E) := mul_action.to_perm_hom _ _ lemma gal_action_hom_restrict [fact (p.splits (algebra_map F E))] (ϕ : E ≃ₐ[F] E) (x : root_set p E) : ↑(gal_action_hom p E (restrict p E ϕ) x) = ϕ x := restrict_smul ϕ x /-- `gal p` embeds as a subgroup of permutations of the roots of `p` in `E`. -/ lemma gal_action_hom_injective [fact (p.splits (algebra_map F E))] : function.injective (gal_action_hom p E) := begin rw injective_iff_map_eq_one, intros ϕ hϕ, ext x hx, have key := equiv.perm.ext_iff.mp hϕ (roots_equiv_roots p E ⟨x, hx⟩), change roots_equiv_roots p E (ϕ • (roots_equiv_roots p E).symm (roots_equiv_roots p E ⟨x, hx⟩)) = roots_equiv_roots p E ⟨x, hx⟩ at key, rw equiv.symm_apply_apply at key, exact subtype.ext_iff.mp (equiv.injective (roots_equiv_roots p E) key), end end roots_action variables {p q} /-- `polynomial.gal.restrict`, when both fields are splitting fields of polynomials. -/ def restrict_dvd (hpq : p ∣ q) : q.gal →* p.gal := by haveI := classical.dec (q = 0); exact if hq : q = 0 then 1 else @restrict F _ p _ _ _ ⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩ lemma restrict_dvd_def [decidable (q = 0)] (hpq : p ∣ q) : restrict_dvd hpq = if hq : q = 0 then 1 else @restrict F _ p _ _ _ ⟨splits_of_splits_of_dvd (algebra_map F q.splitting_field) hq (splitting_field.splits q) hpq⟩ := by convert rfl lemma restrict_dvd_surjective (hpq : p ∣ q) (hq : q ≠ 0) : function.surjective (restrict_dvd hpq) := by classical; simp only [restrict_dvd_def, dif_neg hq, restrict_surjective] variables (p q) /-- The Galois group of a product maps into the product of the Galois groups. -/ def restrict_prod : (p * q).gal →* p.gal × q.gal := monoid_hom.prod (restrict_dvd (dvd_mul_right p q)) (restrict_dvd (dvd_mul_left q p)) /-- `polynomial.gal.restrict_prod` is actually a subgroup embedding. -/ lemma restrict_prod_injective : function.injective (restrict_prod p q) := begin by_cases hpq : (p * q) = 0, { haveI : unique (p * q).gal, { rw hpq, apply_instance }, exact λ f g h, eq.trans (unique.eq_default f) (unique.eq_default g).symm }, intros f g hfg, classical, simp only [restrict_prod, restrict_dvd_def] at hfg, simp only [dif_neg hpq, monoid_hom.prod_apply, prod.mk.inj_iff] at hfg, ext x hx, rw [root_set_def, polynomial.map_mul, polynomial.roots_mul] at hx, cases multiset.mem_add.mp (multiset.mem_to_finset.mp hx) with h h, { haveI : fact (p.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_right p q)⟩, have key : x = algebra_map (p.splitting_field) (p * q).splitting_field ((roots_equiv_roots p _).inv_fun ⟨x, (@multiset.mem_to_finset _ (classical.dec_eq _) _ _).mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots p _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.1 _) }, { haveI : fact (q.splits (algebra_map F (p * q).splitting_field)) := ⟨splits_of_splits_of_dvd _ hpq (splitting_field.splits (p * q)) (dvd_mul_left q p)⟩, have key : x = algebra_map (q.splitting_field) (p * q).splitting_field ((roots_equiv_roots q _).inv_fun ⟨x, (@multiset.mem_to_finset _ (classical.dec_eq _) _ _).mpr h⟩) := subtype.ext_iff.mp (equiv.apply_symm_apply (roots_equiv_roots q _) ⟨x, _⟩).symm, rw [key, ←alg_equiv.restrict_normal_commutes, ←alg_equiv.restrict_normal_commutes], exact congr_arg _ (alg_equiv.ext_iff.mp hfg.2 _) }, { rwa [ne.def, mul_eq_zero, map_eq_zero, map_eq_zero, ←mul_eq_zero] } end lemma mul_splits_in_splitting_field_of_mul {p₁ q₁ p₂ q₂ : F[X]} (hq₁ : q₁ ≠ 0) (hq₂ : q₂ ≠ 0) (h₁ : p₁.splits (algebra_map F q₁.splitting_field)) (h₂ : p₂.splits (algebra_map F q₂.splitting_field)) : (p₁ * p₂).splits (algebra_map F (q₁ * q₂).splitting_field) := begin apply splits_mul, { rw ← (splitting_field.lift q₁ (splits_of_splits_of_dvd (algebra_map F (q₁ * q₂).splitting_field) (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_right q₁ q₂))).comp_algebra_map, exact splits_comp_of_splits _ _ h₁ }, { rw ← (splitting_field.lift q₂ (splits_of_splits_of_dvd (algebra_map F (q₁ * q₂).splitting_field) (mul_ne_zero hq₁ hq₂) (splitting_field.splits _) (dvd_mul_left q₂ q₁))).comp_algebra_map, exact splits_comp_of_splits _ _ h₂ }, end /-- `p` splits in the splitting field of `p ∘ q`, for `q` non-constant. -/ lemma splits_in_splitting_field_of_comp (hq : q.nat_degree ≠ 0) : p.splits (algebra_map F (p.comp q).splitting_field) := begin let P : F[X] → Prop := λ r, r.splits (algebra_map F (r.comp q).splitting_field), have key1 : ∀ {r : F[X]}, irreducible r → P r, { intros r hr, by_cases hr' : nat_degree r = 0, { exact splits_of_nat_degree_le_one _ (le_trans (le_of_eq hr') zero_le_one) }, obtain ⟨x, hx⟩ := exists_root_of_splits _ (splitting_field.splits (r.comp q)) (λ h, hr' ((mul_eq_zero.mp (nat_degree_comp.symm.trans (nat_degree_eq_of_degree_eq_some h))).resolve_right hq)), rw [←aeval_def, aeval_comp] at hx, have h_normal : normal F (r.comp q).splitting_field := splitting_field.normal (r.comp q), have qx_int := normal.is_integral h_normal (aeval x q), exact splits_of_splits_of_dvd _ (minpoly.ne_zero qx_int) (normal.splits h_normal _) ((minpoly.irreducible qx_int).dvd_symm hr (minpoly.dvd F _ hx)) }, have key2 : ∀ {p₁ p₂ : F[X]}, P p₁ → P p₂ → P (p₁ * p₂), { intros p₁ p₂ hp₁ hp₂, by_cases h₁ : p₁.comp q = 0, { cases comp_eq_zero_iff.mp h₁ with h h, { rw [h, zero_mul], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, by_cases h₂ : p₂.comp q = 0, { cases comp_eq_zero_iff.mp h₂ with h h, { rw [h, mul_zero], exact splits_zero _ }, { exact false.rec _ (hq (by rw [h.2, nat_degree_C])) } }, have key := mul_splits_in_splitting_field_of_mul h₁ h₂ hp₁ hp₂, rwa ← mul_comp at key }, exact wf_dvd_monoid.induction_on_irreducible p (splits_zero _) (λ _, splits_of_is_unit _) (λ _ _ _ h, key2 (key1 h)), end /-- `polynomial.gal.restrict` for the composition of polynomials. -/ def restrict_comp (hq : q.nat_degree ≠ 0) : (p.comp q).gal →* p.gal := let h : fact (splits (algebra_map F (p.comp q).splitting_field) p) := ⟨splits_in_splitting_field_of_comp p q hq⟩ in @restrict F _ p _ _ _ h lemma restrict_comp_surjective (hq : q.nat_degree ≠ 0) : function.surjective (restrict_comp p q hq) := by simp only [restrict_comp, restrict_surjective] variables {p q} /-- For a separable polynomial, its Galois group has cardinality equal to the dimension of its splitting field over `F`. -/ lemma card_of_separable (hp : p.separable) : fintype.card p.gal = finrank F p.splitting_field := begin haveI : is_galois F p.splitting_field := is_galois.of_separable_splitting_field hp, exact is_galois.card_aut_eq_finrank F p.splitting_field, end lemma prime_degree_dvd_card [char_zero F] (p_irr : irreducible p) (p_deg : p.nat_degree.prime) : p.nat_degree ∣ fintype.card p.gal := begin rw gal.card_of_separable p_irr.separable, have hp : p.degree ≠ 0 := λ h, nat.prime.ne_zero p_deg (nat_degree_eq_zero_iff_degree_le_zero.mpr (le_of_eq h)), let α : p.splitting_field := root_of_splits (algebra_map F p.splitting_field) (splitting_field.splits p) hp, have hα : is_integral F α := algebra.is_integral_of_finite _ _ α, use finite_dimensional.finrank F⟮α⟯ p.splitting_field, suffices : (minpoly F α).nat_degree = p.nat_degree, { rw [←finite_dimensional.finrank_mul_finrank F F⟮α⟯ p.splitting_field, intermediate_field.adjoin.finrank hα, this] }, suffices : minpoly F α ∣ p, { have key := (minpoly.irreducible hα).dvd_symm p_irr this, apply le_antisymm, { exact nat_degree_le_of_dvd this p_irr.ne_zero }, { exact nat_degree_le_of_dvd key (minpoly.ne_zero hα) } }, apply minpoly.dvd F α, rw [aeval_def, map_root_of_splits _ (splitting_field.splits p) hp], end section rationals lemma splits_ℚ_ℂ {p : ℚ[X]} : fact (p.splits (algebra_map ℚ ℂ)) := ⟨is_alg_closed.splits_codomain p⟩ local attribute [instance] splits_ℚ_ℂ /-- The number of complex roots equals the number of real roots plus the number of roots not fixed by complex conjugation (i.e. with some imaginary component). -/ lemma card_complex_roots_eq_card_real_add_card_not_gal_inv (p : ℚ[X]) : (p.root_set ℂ).to_finset.card = (p.root_set ℝ).to_finset.card + (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card := begin by_cases hp : p = 0, { haveI : is_empty (p.root_set ℂ) := by { rw [hp, root_set_zero], apply_instance }, simp_rw [(gal_action_hom p ℂ _).support.eq_empty_of_is_empty, hp, root_set_zero, set.to_finset_empty, finset.card_empty] }, have inj : function.injective (is_scalar_tower.to_alg_hom ℚ ℝ ℂ) := (algebra_map ℝ ℂ).injective, rw [←finset.card_image_of_injective _ subtype.coe_injective, ←finset.card_image_of_injective _ inj], let a : finset ℂ := _, let b : finset ℂ := _, let c : finset ℂ := _, change a.card = b.card + c.card, have ha : ∀ z : ℂ, z ∈ a ↔ aeval z p = 0, { intro z, rw [set.mem_to_finset, mem_root_set_of_ne hp], apply_instance }, have hb : ∀ z : ℂ, z ∈ b ↔ aeval z p = 0 ∧ z.im = 0, { intro z, simp_rw [finset.mem_image, exists_prop, set.mem_to_finset, mem_root_set_of_ne hp], split, { rintros ⟨w, hw, rfl⟩, exact ⟨by rw [aeval_alg_hom_apply, hw, alg_hom.map_zero], rfl⟩ }, { rintros ⟨hz1, hz2⟩, have key : is_scalar_tower.to_alg_hom ℚ ℝ ℂ z.re = z := by { ext, refl, rw hz2, refl }, exact ⟨z.re, inj (by rwa [←aeval_alg_hom_apply, key, alg_hom.map_zero]), key⟩ } }, have hc0 : ∀ w : p.root_set ℂ, gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ)) w = w ↔ w.val.im = 0, { intro w, rw [subtype.ext_iff, gal_action_hom_restrict], exact complex.conj_eq_iff_im }, have hc : ∀ z : ℂ, z ∈ c ↔ aeval z p = 0 ∧ z.im ≠ 0, { intro z, simp_rw [finset.mem_image, exists_prop], split, { rintros ⟨w, hw, rfl⟩, exact ⟨(mem_root_set.mp w.2).2, mt (hc0 w).mpr (equiv.perm.mem_support.mp hw)⟩ }, { rintros ⟨hz1, hz2⟩, exact ⟨⟨z, mem_root_set.mpr ⟨hp, hz1⟩⟩, equiv.perm.mem_support.mpr (mt (hc0 _).mp hz2), rfl⟩ } }, rw ← finset.card_disjoint_union, { apply congr_arg finset.card, simp_rw [finset.ext_iff, finset.mem_union, ha, hb, hc], tauto }, { rw finset.disjoint_left, intros z, rw [hb, hc], tauto }, { apply_instance }, end /-- An irreducible polynomial of prime degree with two non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree {p : ℚ[X]} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots : fintype.card (p.root_set ℂ) = fintype.card (p.root_set ℝ) + 2) : function.bijective (gal_action_hom p ℂ) := begin classical, have h1 : fintype.card (p.root_set ℂ) = p.nat_degree, { simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots], { exact is_alg_closed.splits_codomain p }, { exact nodup_roots ((separable_map (algebra_map ℚ ℂ)).mpr p_irr.separable) } }, have h2 : fintype.card p.gal = fintype.card (gal_action_hom p ℂ).range := fintype.card_congr (monoid_hom.of_injective (gal_action_hom_injective p ℂ)).to_equiv, let conj := restrict p ℂ (complex.conj_ae.restrict_scalars ℚ), refine ⟨gal_action_hom_injective p ℂ, λ x, (congr_arg (has_mem.mem x) (show (gal_action_hom p ℂ).range = ⊤, from _)).mpr (subgroup.mem_top x)⟩, apply equiv.perm.subgroup_eq_top_of_swap_mem, { rwa h1 }, { rw h1, convert prime_degree_dvd_card p_irr p_deg using 1, convert h2.symm }, { exact ⟨conj, rfl⟩ }, { rw ← equiv.perm.card_support_eq_two, apply nat.add_left_cancel, rw [←p_roots, ←set.to_finset_card (root_set p ℝ), ←set.to_finset_card (root_set p ℂ)], exact (card_complex_roots_eq_card_real_add_card_not_gal_inv p).symm }, end /-- An irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group. -/ lemma gal_action_hom_bijective_of_prime_degree' {p : ℚ[X]} (p_irr : irreducible p) (p_deg : p.nat_degree.prime) (p_roots1 : fintype.card (p.root_set ℝ) + 1 ≤ fintype.card (p.root_set ℂ)) (p_roots2 : fintype.card (p.root_set ℂ) ≤ fintype.card (p.root_set ℝ) + 3) : function.bijective (gal_action_hom p ℂ) := begin apply gal_action_hom_bijective_of_prime_degree p_irr p_deg, let n := (gal_action_hom p ℂ (restrict p ℂ (complex.conj_ae.restrict_scalars ℚ))).support.card, have hn : 2 ∣ n := equiv.perm.two_dvd_card_support (by rw [←monoid_hom.map_pow, ←monoid_hom.map_pow, show alg_equiv.restrict_scalars ℚ complex.conj_ae ^ 2 = 1, from alg_equiv.ext complex.conj_conj, monoid_hom.map_one, monoid_hom.map_one]), have key := card_complex_roots_eq_card_real_add_card_not_gal_inv p, simp_rw [set.to_finset_card] at key, rw [key, add_le_add_iff_left] at p_roots1 p_roots2, rw [key, add_right_inj], suffices : ∀ m : ℕ, 2 ∣ m → 1 ≤ m → m ≤ 3 → m = 2, { exact this n hn p_roots1 p_roots2 }, rintros m ⟨k, rfl⟩ h2 h3, exact le_antisymm (nat.lt_succ_iff.mp (lt_of_le_of_ne h3 (show 2 * k ≠ 2 * 1 + 1, from nat.two_mul_ne_two_mul_add_one))) (nat.succ_le_iff.mpr (lt_of_le_of_ne h2 (show 2 * 0 + 1 ≠ 2 * k, from nat.two_mul_ne_two_mul_add_one.symm))), end end rationals end gal end polynomial
482d4b50925e16bd467500bf06a37dd821d0e83f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/534.lean
4dad681ac2b0fca1db2a4ed60271a20482c75979
[ "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
252
lean
def foo (array : Array Nat) : Nat -> Nat | 0 => 0 | n + 1 => let array := array.filter (!.==5) if array.isEmpty then 0 else let arrayOfLast := #[array.back] foo arrayOfLast n def main : IO Unit := IO.println ("hi")
1fd03cb565131a8b994f054677f30118752ed319
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/linear_algebra/nonsingular_inverse.lean
e4ccbb77e7ed5c3c6252bcaf2d32ed51cba53eee
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,376
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Tim Baanen. -/ import algebra.associated import linear_algebra.determinant import tactic.linarith import tactic.ring_exp /-! # Nonsingular inverses In this file, we define an inverse for square matrices of invertible determinant. For matrices that are not square or not of full rank, there is a more general notion of pseudoinverses which we do not consider here. The definition of inverse used in this file is the adjugate divided by the determinant. The adjugate is calculated with Cramer's rule, which we introduce first. The vectors returned by Cramer's rule are given by the linear map `cramer`, which sends a matrix `A` and vector `b` to the vector consisting of the determinant of replacing the `i`th column of `A` with `b` at index `i` (written as `(A.update_column i b).det`). Using Cramer's rule, we can compute for each matrix `A` the matrix `adjugate A`. The entries of the adjugate are the determinants of each minor of `A`. Instead of defining a minor to be `A` with row `i` and column `j` deleted, we replace the `i`th row of `A` with the `j`th basis vector; this has the same determinant as the minor but more importantly equals Cramer's rule applied to `A` and the `j`th basis vector, simplifying the subsequent proofs. We prove the adjugate behaves like `det A • A⁻¹`. Finally, we show that dividing the adjugate by `det A` (if possible), giving a matrix `nonsing_inv A`, will result in a multiplicative inverse to `A`. ## References * https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix ## Tags matrix inverse, cramer, cramer's rule, adjugate -/ namespace matrix universes u v variables {n : Type u} [decidable_eq n] [fintype n] {α : Type v} [comm_ring α] open_locale matrix big_operators open equiv equiv.perm finset section cramer /-! ### `cramer` section Introduce the linear map `cramer` with values defined by `cramer_map`. After defining `cramer_map` and showing it is linear, we will restrict our proofs to using `cramer`. -/ variables (A : matrix n n α) (b : n → α) /-- `cramer_map A b i` is the determinant of the matrix `A` with column `i` replaced with `b`, and thus `cramer_map A b` is the vector output by Cramer's rule on `A` and `b`. If `A ⬝ x = b` has a unique solution in `x`, `cramer_map A` sends the vector `b` to `A.det • x`. Otherwise, the outcome of `cramer_map` is well-defined but not necessarily useful. -/ def cramer_map (i : n) : α := (A.update_column i b).det lemma cramer_map_is_linear (i : n) : is_linear_map α (λ b, cramer_map A b i) := { map_add := det_update_column_add _ _, map_smul := det_update_column_smul _ _ } lemma cramer_is_linear : is_linear_map α (cramer_map A) := begin split; intros; ext i, { apply (cramer_map_is_linear A i).1 }, { apply (cramer_map_is_linear A i).2 } end /-- `cramer A b i` is the determinant of the matrix `A` with column `i` replaced with `b`, and thus `cramer A b` is the vector output by Cramer's rule on `A` and `b`. If `A ⬝ x = b` has a unique solution in `x`, `cramer A` sends the vector `b` to `A.det • x`. Otherwise, the outcome of `cramer` is well-defined but not necessarily useful. -/ def cramer (A : matrix n n α) : (n → α) →ₗ[α] (n → α) := is_linear_map.mk' (cramer_map A) (cramer_is_linear A) lemma cramer_apply (i : n) : cramer A b i = (A.update_column i b).det := rfl lemma cramer_transpose_row_self (i : n) : Aᵀ.cramer (A i) = λ j, ite (i = j) A.det 0 := begin ext j, rw cramer_apply, by_cases h : i = j, { -- i = j: this entry should be `A.det` rw [update_column_transpose, det_transpose], simp [update_row, h], }, { -- i ≠ j: this entry should be 0 rw [if_neg h, update_column_transpose, det_transpose], apply det_zero_of_row_eq h, rw [update_row_self, update_row_ne], apply h } end /-- Use linearity of `cramer` to take it out of a summation. -/ lemma sum_cramer {β} (s : finset β) (f : β → n → α) : ∑ x in s, cramer A (f x) = cramer A (∑ x in s, f x) := (linear_map.map_sum (cramer A)).symm /-- Use linearity of `cramer` and vector evaluation to take `cramer A _ i` out of a summation. -/ lemma sum_cramer_apply {β} (s : finset β) (f : n → β → α) (i : n) : ∑ x in s, cramer A (λ j, f j x) i = cramer A (λ (j : n), ∑ x in s, f j x) i := calc ∑ x in s, cramer A (λ j, f j x) i = (∑ x in s, cramer A (λ j, f j x)) i : (finset.sum_apply i s _).symm ... = cramer A (λ (j : n), ∑ x in s, f j x) i : by { rw [sum_cramer, cramer_apply], congr' with j, apply finset.sum_apply } end cramer section adjugate /-! ### `adjugate` section Define the `adjugate` matrix and a few equations. These will hold for any matrix over a commutative ring, while the `inv` section is specifically for invertible matrices. -/ /-- The adjugate matrix is the transpose of the cofactor matrix. Typically, the cofactor matrix is defined by taking the determinant of minors, i.e. the matrix with a row and column removed. However, the proof of `mul_adjugate` becomes a lot easier if we define the minor as replacing a column with a basis vector, since it allows us to use facts about the `cramer` map. -/ def adjugate (A : matrix n n α) : matrix n n α := λ i, cramer Aᵀ (λ j, if i = j then 1 else 0) lemma adjugate_def (A : matrix n n α) : adjugate A = λ i, cramer Aᵀ (λ j, if i = j then 1 else 0) := rfl lemma adjugate_apply (A : matrix n n α) (i j : n) : adjugate A i j = (A.update_row j (λ j, if i = j then 1 else 0)).det := by { rw adjugate_def, simp only, rw [cramer_apply, update_column_transpose, det_transpose], } lemma adjugate_transpose (A : matrix n n α) : (adjugate A)ᵀ = adjugate (Aᵀ) := begin ext i j, rw [transpose_apply, adjugate_apply, adjugate_apply, update_row_transpose, det_transpose], rw [det_apply', det_apply'], apply finset.sum_congr rfl, intros σ _, congr' 1, by_cases i = σ j, { -- Everything except `(i , j)` (= `(σ j , j)`) is given by A, and the rest is a single `1`. congr; ext j', have := (@equiv.injective _ _ σ j j' : σ j = σ j' → j = j'), rw [update_row_apply, update_column_apply], finish }, { -- Otherwise, we need to show that there is a `0` somewhere in the product. have : (∏ j' : n, update_column A j (λ (i' : n), ite (i = i') 1 0) (σ j') j') = 0, { apply prod_eq_zero (mem_univ j), rw [update_column_self], exact if_neg h }, rw this, apply prod_eq_zero (mem_univ (σ⁻¹ i)), erw [apply_symm_apply σ i, update_row_self], apply if_neg, intro h', exact h ((symm_apply_eq σ).mp h'.symm) } end /-- Since the map `b ↦ cramer A b` is linear in `b`, it must be multiplication by some matrix. This matrix is `A.adjugate`. -/ lemma cramer_eq_adjugate_mul_vec (A : matrix n n α) (b : n → α) : cramer A b = A.adjugate.mul_vec b := begin nth_rewrite 1 ← A.transpose_transpose, rw [← adjugate_transpose, adjugate_def], have : b = ∑ i, (b i) • (λ j, if i = j then 1 else 0), { ext i, simp, }, rw this, ext k, simp [mul_vec, dot_product, mul_comm], end lemma mul_adjugate_apply (A : matrix n n α) (i j k) : A i k * adjugate A k j = cramer Aᵀ (λ j, if k = j then A i k else 0) j := begin erw [←smul_eq_mul, ←pi.smul_apply, ←linear_map.map_smul], congr' with l, rw [pi.smul_apply, smul_eq_mul, mul_boole], end lemma mul_adjugate (A : matrix n n α) : A ⬝ adjugate A = A.det • 1 := begin ext i j, rw [mul_apply, smul_apply, one_apply, mul_boole], simp [mul_adjugate_apply, sum_cramer_apply, cramer_transpose_row_self], end lemma adjugate_mul (A : matrix n n α) : adjugate A ⬝ A = A.det • 1 := calc adjugate A ⬝ A = (Aᵀ ⬝ (adjugate Aᵀ))ᵀ : by rw [←adjugate_transpose, ←transpose_mul, transpose_transpose] ... = A.det • 1 : by rw [mul_adjugate (Aᵀ), det_transpose, transpose_smul, transpose_one] /-- `det_adjugate_of_cancel` is an auxiliary lemma for computing `(adjugate A).det`, used in `det_adjugate_eq_one` and `det_adjugate_of_is_unit`. The formula for the determinant of the adjugate of an `n` by `n` matrix `A` is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases. This lemma `det_adjugate_of_cancel` covers the case that `det A` cancels on the left of the equation `A.det * b = A.det ^ n`. -/ lemma det_adjugate_of_cancel {A : matrix n n α} (h : ∀ b, A.det * b = A.det ^ fintype.card n → b = A.det ^ (fintype.card n - 1)) : (adjugate A).det = A.det ^ (fintype.card n - 1) := h (adjugate A).det (calc A.det * (adjugate A).det = (A ⬝ adjugate A).det : (det_mul _ _).symm ... = A.det ^ fintype.card n : by simp [mul_adjugate]) lemma adjugate_eq_one_of_card_eq_one {A : matrix n n α} (h : fintype.card n = 1) : adjugate A = 1 := begin haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le, ext i j, simp [subsingleton.elim i j, adjugate_apply, det_eq_elem_of_card_eq_one h j], end @[simp] lemma adjugate_zero (h : 1 < fintype.card n) : adjugate (0 : matrix n n α) = 0 := begin ext i j, obtain ⟨j', hj'⟩ : ∃ j', j' ≠ j := fintype.exists_ne_of_one_lt_card h j, apply det_eq_zero_of_column_eq_zero j', intro j'', simp [update_column_ne hj'], end lemma det_adjugate_eq_one {A : matrix n n α} (h : A.det = 1) : (adjugate A).det = 1 := calc (adjugate A).det = A.det ^ (fintype.card n - 1) : det_adjugate_of_cancel (λ b hb, by simpa [h] using hb) ... = 1 : by rw [h, one_pow] /-- `det_adjugate_of_is_unit` gives the formula for `(adjugate A).det` if `A.det` has an inverse. The formula for the determinant of the adjugate of an `n` by `n` matrix `A` is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases. This lemma `det_adjugate_of_is_unit` covers the case that `det A` has an inverse. -/ lemma det_adjugate_of_is_unit {A : matrix n n α} (h : is_unit A.det) : (adjugate A).det = A.det ^ (fintype.card n - 1) := begin rcases is_unit_iff_exists_inv'.mp h with ⟨a, ha⟩, by_cases card_lt_zero : fintype.card n ≤ 0, { have h : fintype.card n = 0 := by linarith, simp [det_eq_one_of_card_eq_zero h] }, have zero_lt_card : 0 < fintype.card n := by linarith, have n_nonempty : nonempty n := fintype.card_pos_iff.mp zero_lt_card, by_cases card_lt_one : fintype.card n ≤ 1, { have h : fintype.card n = 1 := by linarith, simp [h, adjugate_eq_one_of_card_eq_one h] }, have one_lt_card : 1 < fintype.card n := by linarith, have zero_lt_card_sub_one : 0 < fintype.card n - 1 := (nat.sub_lt_sub_right_iff (refl 1)).mpr one_lt_card, apply det_adjugate_of_cancel, intros b hb, calc b = a * (det A ^ (fintype.card n - 1 + 1)) : by rw [←one_mul b, ←ha, mul_assoc, hb, nat.sub_add_cancel zero_lt_card] ... = a * det A * det A ^ (fintype.card n - 1) : by ring_exp ... = det A ^ (fintype.card n - 1) : by rw [ha, one_mul] end end adjugate section inv /-! ### `inv` section Defines the matrix `nonsing_inv A` and proves it is the inverse matrix of a square matrix `A` as long as `det A` has a multiplicative inverse. -/ variables (A : matrix n n α) open_locale classical lemma is_unit_det_transpose (h : is_unit A.det) : is_unit Aᵀ.det := by { rw det_transpose, exact h, } /-- The inverse of a square matrix, when it is invertible (and zero otherwise).-/ noncomputable def nonsing_inv : matrix n n α := if h : is_unit A.det then (↑h.unit⁻¹ : α) • A.adjugate else 0 noncomputable instance : has_inv (matrix n n α) := ⟨matrix.nonsing_inv⟩ lemma nonsing_inv_apply (h : is_unit A.det) : A⁻¹ = (↑h.unit⁻¹ : α) • A.adjugate := by { change A.nonsing_inv = _, dunfold nonsing_inv, simp only [dif_pos, h], } lemma transpose_nonsing_inv (h : is_unit A.det) : (A⁻¹)ᵀ = (Aᵀ)⁻¹ := begin have h' := A.is_unit_det_transpose h, have dets_eq : (↑h.unit : α) = ↑h'.unit := by rw [h.unit_spec, h'.unit_spec, det_transpose], rw [A.nonsing_inv_apply h, Aᵀ.nonsing_inv_apply h', units.inv_unique dets_eq, A.adjugate_transpose.symm], refl, end /-- The `nonsing_inv` of `A` is a right inverse. -/ @[simp] lemma mul_nonsing_inv (h : is_unit A.det) : A ⬝ A⁻¹ = 1 := by rw [A.nonsing_inv_apply h, mul_smul, mul_adjugate, smul_smul, units.inv_mul_of_eq h.unit_spec, one_smul] /-- The `nonsing_inv` of `A` is a left inverse. -/ @[simp] lemma nonsing_inv_mul (h : is_unit A.det) : A⁻¹ ⬝ A = 1 := calc A⁻¹ ⬝ A = (Aᵀ ⬝ (Aᵀ)⁻¹)ᵀ : by { rw [transpose_mul, Aᵀ.transpose_nonsing_inv (A.is_unit_det_transpose h), transpose_transpose], } ... = 1ᵀ : by { rw Aᵀ.mul_nonsing_inv, exact A.is_unit_det_transpose h, } ... = 1 : transpose_one @[simp] lemma nonsing_inv_det (h : is_unit A.det) : A⁻¹.det * A.det = 1 := by rw [←det_mul, A.nonsing_inv_mul h, det_one] lemma is_unit_nonsing_inv_det (h : is_unit A.det) : is_unit A⁻¹.det := is_unit_of_mul_eq_one _ _ (A.nonsing_inv_det h) @[simp] lemma nonsing_inv_nonsing_inv (h : is_unit A.det) : (A⁻¹)⁻¹ = A := calc (A⁻¹)⁻¹ = 1 ⬝ (A⁻¹)⁻¹ : by rw matrix.one_mul ... = A ⬝ A⁻¹ ⬝ (A⁻¹)⁻¹ : by rw A.mul_nonsing_inv h ... = A : by { rw [matrix.mul_assoc, (A⁻¹).mul_nonsing_inv (A.is_unit_nonsing_inv_det h), matrix.mul_one], } /-- A matrix whose determinant is a unit is itself a unit. -/ noncomputable def nonsing_inv_unit (h : is_unit A.det) : units (matrix n n α) := { val := A, inv := A⁻¹, val_inv := by { rw matrix.mul_eq_mul, apply A.mul_nonsing_inv h, }, inv_val := by { rw matrix.mul_eq_mul, apply A.nonsing_inv_mul h, } } lemma is_unit_iff_is_unit_det : is_unit A ↔ is_unit A.det := begin split; intros h, { -- is_unit A → is_unit A.det suffices : ∃ (B : matrix n n α), A ⬝ B = 1, { rcases this with ⟨B, hB⟩, apply is_unit_of_mul_eq_one _ B.det, rw [←det_mul, hB, det_one], }, refine ⟨↑h.unit⁻¹, _⟩, conv_lhs { congr, rw ←h.unit_spec, }, exact h.unit.mul_inv, }, { -- is_unit A.det → is_unit A exact is_unit_unit (A.nonsing_inv_unit h), }, end lemma is_unit_det_of_left_inverse (B : matrix n n α) (h : B ⬝ A = 1) : is_unit A.det := ⟨{ val := A.det, inv := B.det, val_inv := by rw [mul_comm, ← det_mul, h, det_one], inv_val := by rw [← det_mul, h, det_one], }, rfl⟩ lemma is_unit_det_of_right_inverse (B : matrix n n α) (h : A ⬝ B = 1) : is_unit A.det := ⟨{ val := A.det, inv := B.det, val_inv := by rw [← det_mul, h, det_one], inv_val := by rw [mul_comm, ← det_mul, h, det_one], }, rfl⟩ lemma nonsing_inv_left_right (B : matrix n n α) (h : A ⬝ B = 1) : B ⬝ A = 1 := begin have h' : is_unit B.det := B.is_unit_det_of_left_inverse A h, calc B ⬝ A = (B ⬝ A) ⬝ (B ⬝ B⁻¹) : by simp only [h', matrix.mul_one, mul_nonsing_inv] ... = B ⬝ ((A ⬝ B) ⬝ B⁻¹) : by simp only [matrix.mul_assoc] ... = B ⬝ B⁻¹ : by simp only [h, matrix.one_mul] ... = 1 : mul_nonsing_inv B h', end lemma nonsing_inv_right_left (B : matrix n n α) (h : B ⬝ A = 1) : A ⬝ B = 1 := B.nonsing_inv_left_right A h end inv /- One form of Cramer's rule. -/ @[simp] lemma det_smul_inv_mul_vec_eq_cramer (A : matrix n n α) (b : n → α) (h : is_unit A.det) : A.det • A⁻¹.mul_vec b = cramer A b := begin rw [cramer_eq_adjugate_mul_vec, A.nonsing_inv_apply h, ← smul_mul_vec_assoc], conv_lhs { congr, congr, rw ← h.unit_spec, }, rw units.smul_inv_smul, end /- A stronger form of Cramer's rule that allows us to solve some instances of `A ⬝ x = b` even if the determinant is not a unit. A sufficient (but still not necessary) condition is that `A.det` divides `b`. -/ @[simp] lemma mul_vec_cramer (A : matrix n n α) (b : n → α) : A.mul_vec (cramer A b) = A.det • b := by rw [cramer_eq_adjugate_mul_vec, mul_vec_mul_vec, mul_adjugate, smul_mul_vec_assoc, mul_vec_one] end matrix
ccb9583c07600b3da26208a3ac421fa5defc6804
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/nonarchimedean/adic_topology.lean
3190120464aac9b57f9b004b239455b2603e34c9
[ "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,307
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import ring_theory.ideal.operations import topology.algebra.nonarchimedean.bases import topology.uniform_space.completion import topology.algebra.uniform_ring /-! # Adic topology > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given a commutative ring `R` and an ideal `I` in `R`, this file constructs the unique topology on `R` which is compatible with the ring structure and such that a set is a neighborhood of zero if and only if it contains a power of `I`. This topology is non-archimedean: every neighborhood of zero contains an open subgroup, namely a power of `I`. It also studies the predicate `is_adic` which states that a given topological ring structure is adic, proving a characterization and showing that raising an ideal to a positive power does not change the associated topology. Finally, it defines `with_ideal`, a class registering an ideal in a ring and providing the corresponding adic topology to the type class inference system. ## Main definitions and results * `ideal.adic_basis`: the basis of submodules given by powers of an ideal. * `ideal.adic_topology`: the adic topology associated to an ideal. It has the above basis for neighborhoods of zero. * `ideal.nonarchimedean`: the adic topology is non-archimedean * `is_ideal_adic_iff`: A topological ring is `J`-adic if and only if it admits the powers of `J` as a basis of open neighborhoods of zero. * `with_ideal`: a class registering an ideal in a ring. ## Implementation notes The `I`-adic topology on a ring `R` has a contrived definition using `I^n • ⊤` instead of `I` to make sure it is definitionally equal to the `I`-topology on `R` seen as a `R`-module. -/ variables {R : Type*} [comm_ring R] open set topological_add_group submodule filter open_locale topology pointwise namespace ideal lemma adic_basis (I : ideal R) : submodules_ring_basis (λ n : ℕ, (I^n • ⊤ : ideal R)) := { inter := begin suffices : ∀ i j : ℕ, ∃ k, I ^ k ≤ I ^ i ∧ I ^ k ≤ I ^ j, by simpa, intros i j, exact ⟨max i j, pow_le_pow (le_max_left i j), pow_le_pow (le_max_right i j)⟩ end, left_mul := begin suffices : ∀ (a : R) (i : ℕ), ∃ j : ℕ, a • I ^ j ≤ I ^ i, by simpa, intros r n, use n, rintro a ⟨x, hx, rfl⟩, exact (I ^ n).smul_mem r hx end, mul := begin suffices : ∀ (i : ℕ), ∃ (j : ℕ), ↑(I ^ j) * ↑(I ^ j) ⊆ ↑(I ^ i), by simpa, intro n, use n, rintro a ⟨x, b, hx, hb, rfl⟩, exact (I^n).smul_mem x hb end } /-- The adic ring filter basis associated to an ideal `I` is made of powers of `I`. -/ def ring_filter_basis (I : ideal R) := I.adic_basis.to_ring_subgroups_basis.to_ring_filter_basis /-- The adic topology associated to an ideal `I`. This topology admits powers of `I` as a basis of neighborhoods of zero. It is compatible with the ring structure and is non-archimedean. -/ def adic_topology (I : ideal R) : topological_space R := (adic_basis I).topology lemma nonarchimedean (I : ideal R) : @nonarchimedean_ring R _ I.adic_topology := I.adic_basis.to_ring_subgroups_basis.nonarchimedean /-- For the `I`-adic topology, the neighborhoods of zero has basis given by the powers of `I`. -/ lemma has_basis_nhds_zero_adic (I : ideal R) : has_basis (@nhds R I.adic_topology (0 : R)) (λ n : ℕ, true) (λ n, ((I^n : ideal R) : set R)) := ⟨begin intros U, rw I.ring_filter_basis.to_add_group_filter_basis.nhds_zero_has_basis.mem_iff, split, { rintros ⟨-, ⟨i, rfl⟩, h⟩, replace h : ↑(I ^ i) ⊆ U := by simpa using h, use [i, trivial, h] }, { rintros ⟨i, -, h⟩, exact ⟨(I^i : ideal R), ⟨i, by simp⟩, h⟩ } end⟩ lemma has_basis_nhds_adic (I : ideal R) (x : R) : has_basis (@nhds R I.adic_topology x) (λ n : ℕ, true) (λ n, (λ y, x + y) '' (I^n : ideal R)) := begin letI := I.adic_topology, have := I.has_basis_nhds_zero_adic.map (λ y, x + y), rwa map_add_left_nhds_zero x at this end variables (I : ideal R) (M : Type*) [add_comm_group M] [module R M] lemma adic_module_basis : I.ring_filter_basis.submodules_basis (λ n : ℕ, (I^n) • (⊤ : submodule R M)) := { inter := λ i j, ⟨max i j, le_inf_iff.mpr ⟨smul_mono_left $ pow_le_pow (le_max_left i j), smul_mono_left $ pow_le_pow (le_max_right i j)⟩⟩, smul := λ m i, ⟨(I^i • ⊤ : ideal R), ⟨i, rfl⟩, λ a a_in, by { replace a_in : a ∈ I^i := by simpa [(I^i).mul_top] using a_in, exact smul_mem_smul a_in mem_top }⟩ } /-- The topology on a `R`-module `M` associated to an ideal `M`. Submodules $I^n M$, written `I^n • ⊤` form a basis of neighborhoods of zero. -/ def adic_module_topology : topological_space M := @module_filter_basis.topology R M _ I.adic_basis.topology _ _ (I.ring_filter_basis.module_filter_basis (I.adic_module_basis M)) /-- The elements of the basis of neighborhoods of zero for the `I`-adic topology on a `R`-module `M`, seen as open additive subgroups of `M`. -/ def open_add_subgroup (n : ℕ) : @open_add_subgroup R _ I.adic_topology := { is_open' := begin letI := I.adic_topology, convert (I.adic_basis.to_ring_subgroups_basis.open_add_subgroup n).is_open, simp end, ..(I^n).to_add_subgroup} end ideal section is_adic /-- Given a topology on a ring `R` and an ideal `J`, `is_adic J` means the topology is the `J`-adic one. -/ def is_adic [H : topological_space R] (J : ideal R) : Prop := H = J.adic_topology /-- A topological ring is `J`-adic if and only if it admits the powers of `J` as a basis of open neighborhoods of zero. -/ lemma is_adic_iff [top : topological_space R] [topological_ring R] {J : ideal R} : is_adic J ↔ (∀ n : ℕ, is_open ((J^n : ideal R) : set R)) ∧ (∀ s ∈ 𝓝 (0 : R), ∃ n : ℕ, ((J^n : ideal R) : set R) ⊆ s) := begin split, { intro H, change _ = _ at H, rw H, letI := J.adic_topology, split, { intro n, exact (J.open_add_subgroup n).is_open' }, { intros s hs, simpa using J.has_basis_nhds_zero_adic.mem_iff.mp hs } }, { rintro ⟨H₁, H₂⟩, apply topological_add_group.ext, { apply @topological_ring.to_topological_add_group }, { apply (ring_subgroups_basis.to_ring_filter_basis _).to_add_group_filter_basis .is_topological_add_group }, { ext s, letI := ideal.adic_basis J, rw J.has_basis_nhds_zero_adic.mem_iff, split; intro H, { rcases H₂ s H with ⟨n, h⟩, use [n, trivial, h] }, { rcases H with ⟨n, -, hn⟩, rw mem_nhds_iff, refine ⟨_, hn, H₁ n, (J^n).zero_mem⟩ } } } end variables [topological_space R] [topological_ring R] lemma is_ideal_adic_pow {J : ideal R} (h : is_adic J) {n : ℕ} (hn : 0 < n) : is_adic (J^n) := begin rw is_adic_iff at h ⊢, split, { intro m, rw ← pow_mul, apply h.left }, { intros V hV, cases h.right V hV with m hm, use m, refine set.subset.trans _ hm, cases n, { exfalso, exact nat.not_succ_le_zero 0 hn }, rw [← pow_mul, nat.succ_mul], apply ideal.pow_le_pow, apply nat.le_add_left } end lemma is_bot_adic_iff {A : Type*} [comm_ring A] [topological_space A] [topological_ring A] : is_adic (⊥ : ideal A) ↔ discrete_topology A := begin rw is_adic_iff, split, { rintro ⟨h, h'⟩, rw discrete_topology_iff_open_singleton_zero, simpa using h 1 }, { introsI, split, { simp, }, { intros U U_nhds, use 1, simp [mem_of_mem_nhds U_nhds] } }, end end is_adic /-- The ring `R` is equipped with a preferred ideal. -/ class with_ideal (R : Type*) [comm_ring R] := (I : ideal R) namespace with_ideal variables (R) [with_ideal R] @[priority 100] instance : topological_space R := I.adic_topology @[priority 100] instance : nonarchimedean_ring R := ring_subgroups_basis.nonarchimedean _ @[priority 100] instance : uniform_space R := topological_add_group.to_uniform_space R @[priority 100] instance : uniform_add_group R := topological_add_comm_group_is_uniform /-- The adic topology on a `R` module coming from the ideal `with_ideal.I`. This cannot be an instance because `R` cannot be inferred from `M`. -/ def topological_space_module (M : Type*) [add_comm_group M] [module R M] : topological_space M := (I : ideal R).adic_module_topology M /- The next examples are kept to make sure potential future refactors won't break the instance chaining. -/ example : nonarchimedean_ring R := by apply_instance example : topological_ring (uniform_space.completion R) := by apply_instance example (M : Type*) [add_comm_group M] [module R M] : @topological_add_group M (with_ideal.topological_space_module R M) _:= by apply_instance example (M : Type*) [add_comm_group M] [module R M] : @has_continuous_smul R M _ _ (with_ideal.topological_space_module R M) := by apply_instance example (M : Type*) [add_comm_group M] [module R M] : @nonarchimedean_add_group M _ (with_ideal.topological_space_module R M) := submodules_basis.nonarchimedean _ end with_ideal
5bd7f3e66d2c68cc2a6f053efd72181b811342ba
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/number_theory/pell.lean
b264f897e356338f4d9080d8fe6eac7227183193
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
62,380
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 data.int.basic data.nat.prime data.nat.modeq /-- 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, but of course both parts are real here since `d` is nonnegative. -/ structure zsqrtd (d : ℕ) := mk {} :: (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⟩ @[simp] theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl @[simp] theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ def zero : ℤ√d := of_int 0 instance : has_zero ℤ√d := ⟨zsqrtd.zero⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl /-- The one of the ring -/ def one : ℤ√d := of_int 1 instance : has_one ℤ√d := ⟨zsqrtd.one⟩ @[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` -/ def add : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩ instance : has_add ℤ√d := ⟨zsqrtd.add⟩ @[simp] theorem add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re : ∀ z w : ℤ√d, (z + w).re = z.re + w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem add_im : ∀ z w : ℤ√d, (z + w).im = z.im + w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := add_re _ _ @[simp] theorem bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := add_im _ _ @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := by simp [bit1] @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ def neg : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨-x, -y⟩ instance : has_neg ℤ√d := ⟨zsqrtd.neg⟩ @[simp] theorem neg_re : ∀ z : ℤ√d, (-z).re = -z.re | ⟨x, y⟩ := rfl @[simp] theorem neg_im : ∀ z : ℤ√d, (-z).im = -z.im | ⟨x, y⟩ := rfl /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨x, -y⟩ @[simp] theorem conj_re : ∀ z : ℤ√d, (conj z).re = z.re | ⟨x, y⟩ := rfl @[simp] theorem conj_im : ∀ z : ℤ√d, (conj z).im = -z.im | ⟨x, y⟩ := rfl /-- Multiplication in `ℤ√d` -/ def mul : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩ instance : has_mul ℤ√d := ⟨zsqrtd.mul⟩ @[simp] theorem mul_re : ∀ z w : ℤ√d, (z * w).re = z.re * w.re + d * z.im * w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem mul_im : ∀ z w : ℤ√d, (z * w).im = z.re * w.im + z.im * w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl instance : comm_ring ℤ√d := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), one := 1, ..}; { intros, simp [ext, add_mul, mul_add, mul_comm, mul_left_comm] } instance : add_comm_monoid ℤ√d := by apply_instance 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 instance : zero_ne_one_class ℤ√d := { zero := 0, one := 1, zero_ne_one := dec_trivial } @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := by induction n; simp * @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := by induction n; simp * theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq] @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; simp * theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := 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, mul_comm] theorem conj_mul : Π {a b : ℤ√d}, conj (a * b) = conj a * conj b := by simp [ext] protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := by simp [ext] protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := by simp [ext] protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := by simp [ext] protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h /-- 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], 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 _), simpa [mul_add, mul_left_comm, mul_comm] } /-- "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) /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b protected def le (a b : ℤ√d) : Prop := nonneg (b - a) instance : has_le ℤ√d := ⟨zsqrtd.le⟩ protected def lt (a b : ℤ√d) : Prop := ¬(b ≤ a) instance : has_lt ℤ√d := ⟨zsqrtd.lt⟩ 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 (a b : ℤ√d) : decidable (a ≤ b) := 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_refl _) 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 theorem 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⟩; dsimp [add, nonneg] at ha hb ⊢, { 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 *))) }, { 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 *))) }, { 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 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 _ _ z (by simp *))) }, { apply nat.le_add_right } }, { rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem le_refl (a : ℤ√d) : a ≤ a := show nonneg (a - a), by simp protected theorem le_trans {a b c : ℤ√d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := have nonneg (b - a + (c - b)), from nonneg_add ab bc, have nonneg (c - a + (b - b)), by simpa [-add_right_neg, add_left_comm], by simpa 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 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]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe]⟩ end in begin refine ⟨x + d*y, zsqrtd.le_trans h _⟩, rw [← int.cast_coe_nat, ← of_int_eq_coe], 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 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 := let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t instance : preorder ℤ√d := { le := zsqrtd.le, le_refl := zsqrtd.le_refl, le_trans := @zsqrtd.le_trans, lt := zsqrtd.lt, lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } 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 rw ← int.cast_coe_nat; 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_add (nonneg_smul ha) (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]; 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]; 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]; 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]; 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 : c > 0) : ¬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_square (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_square _ _) | ⟨-[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_square _ _) 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 : decidable_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 h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero 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 $ eq_of_mul_eq_mul_right 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 $ eq_of_mul_eq_mul_right 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 : integral_domain ℤ√d := { zero_ne_one := zero_ne_one, eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, ..zsqrtd.comm_ring } 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 : decidable_linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, add_lt_add_left := @zsqrtd.add_lt_add_left, zero_ne_one := zero_ne_one, mul_nonneg := @zsqrtd.mul_nonneg, mul_pos := @zsqrtd.mul_pos, zero_lt_one := dec_trivial, ..zsqrtd.comm_ring, ..zsqrtd.decidable_linear_order } instance : decidable_linear_ordered_semiring ℤ√d := by apply_instance instance : linear_ordered_semiring ℤ√d := by apply_instance instance : ordered_semiring ℤ√d := by apply_instance end end zsqrtd namespace pell open nat section parameters {a : ℕ} (a1 : a > 1) include a1 private def d := a*a - 1 @[simp] theorem d_pos : 0 < d := nat.sub_pos_of_lt (mul_lt_mul a1 (le_of_lt a1) dec_trivial dec_trivial : 1*1<a*a) /-- The Pell sequences, defined together in mutual recursion. -/ def pell : ℕ → ℕ × ℕ := λn, nat.rec_on n (1, 0) (λn xy, (xy.1*a + d*xy.2, xy.1 + xy.2*a)) /-- The Pell `x` sequence. -/ def xn (n : ℕ) : ℕ := (pell n).1 /-- The Pell `y` sequence. -/ def yn (n : ℕ) : ℕ := (pell n).2 @[simp] theorem pell_val (n : ℕ) : pell n = (xn n, yn n) := show pell n = ((pell n).1, (pell n).2), from match pell n with (a, b) := rfl end @[simp] theorem xn_zero : xn 0 = 1 := rfl @[simp] theorem yn_zero : yn 0 = 0 := rfl @[simp] theorem xn_succ (n : ℕ) : xn (n+1) = xn n * a + d * yn n := rfl @[simp] theorem yn_succ (n : ℕ) : yn (n+1) = xn n + yn n * a := rfl @[simp] theorem xn_one : xn 1 = a := by simp @[simp] theorem yn_one : yn 1 = 1 := by simp def xz (n : ℕ) : ℤ := xn n def yz (n : ℕ) : ℤ := yn n def az : ℤ := a theorem asq_pos : 0 < a*a := le_trans (le_of_lt a1) (by have := @nat.mul_le_mul_left 1 a a (le_of_lt a1); rwa mul_one at this) theorem dz_val : ↑d = az*az - 1 := have 1 ≤ a*a, from asq_pos, show ↑(a*a - 1) = _, by rw int.coe_nat_sub this; refl @[simp] theorem xz_succ (n : ℕ) : xz (n+1) = xz n * az + ↑d * yz n := rfl @[simp] theorem yz_succ (n : ℕ) : yz (n+1) = xz n + yz n * az := rfl /-- The Pell sequence can also be viewed as an element of `ℤ√d` -/ def pell_zd (n : ℕ) : ℤ√d := ⟨xn n, yn n⟩ @[simp] theorem pell_zd_re (n : ℕ) : (pell_zd n).re = xn n := rfl @[simp] theorem pell_zd_im (n : ℕ) : (pell_zd n).im = yn n := rfl /-- The property of being a solution to the Pell equation, expressed as a property of elements of `ℤ√d`. -/ def is_pell : ℤ√d → Prop | ⟨x, y⟩ := x*x - d*y*y = 1 theorem is_pell_nat {x y : ℕ} : is_pell ⟨x, y⟩ ↔ x*x - d*y*y = 1 := ⟨λh, int.coe_nat_inj (by rw int.coe_nat_sub (int.le_of_coe_nat_le_coe_nat $ int.le.intro_sub h); exact h), λh, show ((x*x : ℕ) - (d*y*y:ℕ) : ℤ) = 1, by rw [← int.coe_nat_sub $ le_of_lt $ nat.lt_of_sub_eq_succ h, h]; refl⟩ theorem is_pell_norm : Π {b : ℤ√d}, is_pell b ↔ b * b.conj = 1 | ⟨x, y⟩ := by simp [zsqrtd.ext, is_pell, mul_comm] theorem is_pell_mul {b c : ℤ√d} (hb : is_pell b) (hc : is_pell c) : is_pell (b * c) := is_pell_norm.2 (by simp [mul_comm, mul_left_comm, zsqrtd.conj_mul, pell.is_pell_norm.1 hb, pell.is_pell_norm.1 hc]) theorem is_pell_conj : ∀ {b : ℤ√d}, is_pell b ↔ is_pell b.conj | ⟨x, y⟩ := by simp [is_pell, zsqrtd.conj] @[simp] theorem pell_zd_succ (n : ℕ) : pell_zd (n+1) = pell_zd n * ⟨a, 1⟩ := by simp [zsqrtd.ext] theorem is_pell_one : is_pell ⟨a, 1⟩ := show az*az-d*1*1=1, by simp [dz_val] theorem is_pell_pell_zd : ∀ (n : ℕ), is_pell (pell_zd n) | 0 := rfl | (n+1) := let o := is_pell_one in by simp; exact pell.is_pell_mul (is_pell_pell_zd n) o @[simp] theorem pell_eqz (n : ℕ) : xz n * xz n - d * yz n * yz n = 1 := is_pell_pell_zd n @[simp] theorem pell_eq (n : ℕ) : xn n * xn n - d * yn n * yn n = 1 := let pn := pell_eqz n in have h : (↑(xn n * xn n) : ℤ) - ↑(d * yn n * yn n) = 1, by repeat {rw int.coe_nat_mul}; exact pn, have hl : d * yn n * yn n ≤ xn n * xn n, from int.le_of_coe_nat_le_coe_nat $ int.le.intro $ add_eq_of_eq_sub' $ eq.symm h, int.coe_nat_inj (by rw int.coe_nat_sub hl; exact h) instance dnsq : zsqrtd.nonsquare d := ⟨λn h, have n*n + 1 = a*a, by rw ← h; exact nat.succ_pred_eq_of_pos (asq_pos a1), have na : n < a, from nat.mul_self_lt_mul_self_iff.2 (by rw ← this; exact nat.lt_succ_self _), have (n+1)*(n+1) ≤ n*n + 1, by rw this; exact nat.mul_self_le_mul_self na, have n+n ≤ 0, from @nat.le_of_add_le_add_right (n*n + 1) _ _ (by simpa [mul_add, mul_comm, mul_left_comm]), ne_of_gt d_pos $ by rw nat.eq_zero_of_le_zero (le_trans (nat.le_add_left _ _) this) at h; exact h⟩ theorem xn_ge_a_pow : ∀ (n : ℕ), a^n ≤ xn n | 0 := le_refl 1 | (n+1) := by simp [nat.pow_succ]; exact le_trans (nat.mul_le_mul_right _ (xn_ge_a_pow n)) (nat.le_add_right _ _) theorem n_lt_a_pow : ∀ (n : ℕ), n < a^n | 0 := nat.le_refl 1 | (n+1) := begin have IH := n_lt_a_pow n, have : a^n + a^n ≤ a^n * a, { rw ← mul_two, exact nat.mul_le_mul_left _ a1 }, simp [nat.pow_succ], refine lt_of_lt_of_le _ this, exact add_lt_add_of_lt_of_le IH (lt_of_le_of_lt (nat.zero_le _) IH) end theorem n_lt_xn (n) : n < xn n := lt_of_lt_of_le (n_lt_a_pow n) (xn_ge_a_pow n) theorem x_pos (n) : xn n > 0 := lt_of_le_of_lt (nat.zero_le n) (n_lt_xn n) lemma eq_pell_lem : ∀n (b:ℤ√d), 1 ≤ b → is_pell b → pell_zd n ≥ b → ∃n, b = pell_zd n | 0 b := λh1 hp hl, ⟨0, @zsqrtd.le_antisymm _ dnsq _ _ hl h1⟩ | (n+1) b := λh1 hp h, have a1p : (0:ℤ√d) ≤ ⟨a, 1⟩, from trivial, have am1p : (0:ℤ√d) ≤ ⟨a, -1⟩, from show (_:nat) ≤ _, by simp; exact nat.pred_le _, have a1m : (⟨a, 1⟩ * ⟨a, -1⟩ : ℤ√d) = 1, from is_pell_norm.1 is_pell_one, if ha : b ≥ ⟨↑a, 1⟩ then let ⟨m, e⟩ := eq_pell_lem n (b * ⟨a, -1⟩) (by rw ← a1m; exact mul_le_mul_of_nonneg_right ha am1p) (is_pell_mul hp (is_pell_conj.1 is_pell_one)) (by have t := mul_le_mul_of_nonneg_right h am1p; rwa [pell_zd_succ, mul_assoc, a1m, mul_one] at t) in ⟨m+1, by rw [show b = b * ⟨a, -1⟩ * ⟨a, 1⟩, by rw [mul_assoc, eq.trans (mul_comm _ _) a1m]; simp, pell_zd_succ, e]⟩ else suffices ¬1 < b, from ⟨0, show b = 1, from (or.resolve_left (lt_or_eq_of_le h1) this).symm⟩, λh1l, by cases b with x y; exact have bm : (_*⟨_,_⟩ :ℤ√(d a1)) = 1, from pell.is_pell_norm.1 hp, have y0l : (0:ℤ√(d a1)) < ⟨x - x, y - -y⟩, from sub_lt_sub h1l $ λ(hn : (1:ℤ√(d a1)) ≤ ⟨x, -y⟩), by have t := mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1); rw [bm, mul_one] at t; exact h1l t, have yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩, from show (⟨x, y⟩ - ⟨x, -y⟩ : ℤ√(d a1)) < ⟨a, 1⟩ - ⟨a, -1⟩, from sub_lt_sub (by exact ha) $ λ(hn : (⟨x, -y⟩ : ℤ√(d a1)) ≤ ⟨a, -1⟩), by have t := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left hn (le_trans zero_le_one h1)) a1p; rw [bm, one_mul, mul_assoc, eq.trans (mul_comm _ _) a1m, mul_one] at t; exact ha t, by simp at y0l; simp at yl2; exact match y, y0l, (yl2 : (⟨_, _⟩ : ℤ√_) < ⟨_, _⟩) with | 0, y0l, yl2 := y0l (le_refl 0) | (y+1 : ℕ), y0l, yl2 := yl2 (zsqrtd.le_of_le_le (le_refl 0) (let t := int.coe_nat_le_coe_nat_of_le (nat.succ_pos y) in add_le_add t t)) | -[1+y], y0l, yl2 := y0l trivial end theorem eq_pell_zd (b : ℤ√d) (b1 : 1 ≤ b) (hp : is_pell b) : ∃n, b = pell_zd n := let ⟨n, h⟩ := @zsqrtd.le_arch d b in eq_pell_lem n b b1 hp $ zsqrtd.le_trans h $ by rw zsqrtd.coe_nat_val; exact zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ le_of_lt $ n_lt_xn _ _) (int.coe_zero_le _) theorem eq_pell {x y : ℕ} (hp : x*x - d*y*y = 1) : ∃n, x = xn n ∧ y = yn n := have (1:ℤ√d) ≤ ⟨x, y⟩, from match x, hp with | 0, (hp : 0 - _ = 1) := by rw nat.zero_sub at hp; contradiction | (x+1), hp := zsqrtd.le_of_le_le (int.coe_nat_le_coe_nat_of_le $ nat.succ_pos x) (int.coe_zero_le _) end, let ⟨m, e⟩ := eq_pell_zd ⟨x, y⟩ this (is_pell_nat.2 hp) in ⟨m, match x, y, e with ._, ._, rfl := ⟨rfl, rfl⟩ end⟩ theorem pell_zd_add (m) : ∀ n, pell_zd (m + n) = pell_zd m * pell_zd n | 0 := (mul_one _).symm | (n+1) := by rw[← add_assoc, pell_zd_succ, pell_zd_succ, pell_zd_add n, ← mul_assoc] theorem xn_add (m n) : xn (m + n) = xn m * xn n + d * yn m * yn n := by injection (pell_zd_add _ m n) with h _; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem yn_add (m n) : yn (m + n) = xn m * yn n + yn m * xn n := by injection (pell_zd_add _ m n) with _ h; repeat {rw ← int.coe_nat_add at h <|> rw ← int.coe_nat_mul at h}; exact int.coe_nat_inj h theorem pell_zd_sub {m n} (h : n ≤ m) : pell_zd (m - n) = pell_zd m * (pell_zd n).conj := let t := pell_zd_add n (m - n) in by rw [nat.add_sub_of_le h] at t; rw [t, mul_comm (pell_zd _ n) _, mul_assoc, (is_pell_norm _).1 (is_pell_pell_zd _ _), mul_one] theorem xz_sub {m n} (h : n ≤ m) : xz (m - n) = xz m * xz n - d * yz m * yz n := by injection (pell_zd_sub _ h) with h _; repeat {rw ← neg_mul_eq_mul_neg at h}; exact h theorem yz_sub {m n} (h : n ≤ m) : yz (m - n) = xz n * yz m - xz m * yz n := by injection (pell_zd_sub a1 h) with _ h; repeat {rw ← neg_mul_eq_mul_neg at h}; rw [add_comm, mul_comm] at h; exact h theorem xy_coprime (n) : (xn n).coprime (yn n) := nat.coprime_of_dvd' $ λk kx ky, let p := pell_eq n in by rw ← p; exact nat.dvd_sub (le_of_lt $ nat.lt_of_sub_eq_succ p) (dvd_mul_of_dvd_right kx _) (dvd_mul_of_dvd_right ky _) theorem y_increasing {m} : Π {n}, m < n → yn m < yn n | 0 h := absurd h $ nat.not_lt_zero _ | (n+1) h := have yn m ≤ yn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ y_increasing hl) (λe, by rw e), by simp; refine lt_of_le_of_lt _ (nat.lt_add_of_pos_left $ x_pos a1 n); rw ← mul_one (yn a1 m); exact mul_le_mul this (le_of_lt a1) (nat.zero_le _) (nat.zero_le _) theorem x_increasing {m} : Π {n}, m < n → xn m < xn n | 0 h := absurd h $ nat.not_lt_zero _ | (n+1) h := have xn m ≤ xn n, from or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ h) (λhl, le_of_lt $ x_increasing hl) (λe, by rw e), by simp; refine lt_of_lt_of_le (lt_of_le_of_lt this _) (nat.le_add_right _ _); have t := nat.mul_lt_mul_of_pos_left a1 (x_pos a1 n); rwa mul_one at t theorem yn_ge_n : Π n, n ≤ yn n | 0 := nat.zero_le _ | (n+1) := show n < yn (n+1), from lt_of_le_of_lt (yn_ge_n n) (y_increasing $ nat.lt_succ_self n) theorem y_mul_dvd (n) : ∀k, yn n ∣ yn (n * k) | 0 := dvd_zero _ | (k+1) := by rw [nat.mul_succ, yn_add]; exact dvd_add (dvd_mul_left _ _) (dvd_mul_of_dvd_left (y_mul_dvd k) _) theorem y_dvd_iff (m n) : yn m ∣ yn n ↔ m ∣ n := ⟨λh, nat.dvd_of_mod_eq_zero $ (nat.eq_zero_or_pos _).resolve_right $ λhp, have co : nat.coprime (yn m) (xn (m * (n / m))), from nat.coprime.symm $ (xy_coprime _).coprime_dvd_right (y_mul_dvd m (n / m)), have m0 : m > 0, from m.eq_zero_or_pos.resolve_left $ λe, by rw [e, nat.mod_zero] at hp; rw [e] at h; exact have 0 < yn a1 n, from y_increasing _ hp, ne_of_lt (y_increasing a1 hp) (eq_zero_of_zero_dvd h).symm, by rw [← nat.mod_add_div n m, yn_add] at h; exact not_le_of_gt (y_increasing _ $ nat.mod_lt n m0) (nat.le_of_dvd (y_increasing _ hp) $ co.dvd_of_dvd_mul_right $ (nat.dvd_add_iff_right $ dvd_mul_of_dvd_right (y_mul_dvd _ _ _) _).2 h), λ⟨k, e⟩, by rw e; apply y_mul_dvd⟩ theorem xy_modeq_yn (n) : ∀k, xn (n * k) ≡ (xn n)^k [MOD (yn n)^2] ∧ yn (n * k) ≡ k * (xn n)^(k-1) * yn n [MOD (yn n)^3] | 0 := by constructor; simp | (k+1) := let ⟨hx, hy⟩ := xy_modeq_yn k in have L : xn (n * k) * xn n + d * yn (n * k) * yn n ≡ xn n^k * xn n + 0 [MOD yn n^2], from modeq.modeq_add (modeq.modeq_mul_right _ hx) $ modeq.modeq_zero_iff.2 $ by rw nat.pow_succ; exact mul_dvd_mul_right (dvd_mul_of_dvd_right (modeq.modeq_zero_iff.1 $ (hy.modeq_of_dvd_of_modeq $ by simp [nat.pow_succ]).trans $ modeq.modeq_zero_iff.2 $ by simp [-mul_comm, -mul_assoc]) _) _, have R : xn (n * k) * yn n + yn (n * k) * xn n ≡ xn n^k * yn n + k * xn n^k * yn n [MOD yn n^3], from modeq.modeq_add (by rw nat.pow_succ; exact modeq.modeq_mul_right' _ hx) $ have k * xn n^(k - 1) * yn n * xn n = k * xn n^k * yn n, by clear _let_match; cases k with k; simp [nat.pow_succ, mul_comm, mul_left_comm], by rw ← this; exact modeq.modeq_mul_right _ hy, by rw [nat.add_sub_cancel, nat.mul_succ, xn_add, yn_add, nat.pow_succ (xn _ n), nat.succ_mul, add_comm (k * xn _ n^k) (xn _ n^k), right_distrib]; exact ⟨L, R⟩ theorem ysq_dvd_yy (n) : yn n * yn n ∣ yn (n * yn n) := modeq.modeq_zero_iff.1 $ ((xy_modeq_yn n (yn n)).right.modeq_of_dvd_of_modeq $ by simp [nat.pow_succ]).trans (modeq.modeq_zero_iff.2 $ by simp [mul_dvd_mul_left, mul_assoc]) theorem dvd_of_ysq_dvd {n t} (h : yn n * yn n ∣ yn t) : yn n ∣ t := have nt : n ∣ t, from (y_dvd_iff n t).1 $ dvd_of_mul_left_dvd h, n.eq_zero_or_pos.elim (λn0, by rw n0; rw n0 at nt; exact nt) $ λ(n0l : n > 0), let ⟨k, ke⟩ := nt in have yn n ∣ k * (xn n)^(k-1), from nat.dvd_of_mul_dvd_mul_right (y_increasing n0l) $ modeq.modeq_zero_iff.1 $ by have xm := (xy_modeq_yn a1 n k).right; rw ← ke at xm; exact (xm.modeq_of_dvd_of_modeq $ by simp [nat.pow_succ]).symm.trans (modeq.modeq_zero_iff.2 h), by rw ke; exact dvd_mul_of_dvd_right (((xy_coprime _ _).pow_left _).symm.dvd_of_dvd_mul_right this) _ theorem pell_zd_succ_succ (n) : pell_zd (n + 2) + pell_zd n = (2 * a : ℕ) * pell_zd (n + 1) := have (1:ℤ√d) + ⟨a, 1⟩ * ⟨a, 1⟩ = ⟨a, 1⟩ * (2 * a), by rw zsqrtd.coe_nat_val; change (⟨_,_⟩:ℤ√(d a1))=⟨_,_⟩; rw dz_val; change az a1 with a; simp [mul_add, add_mul], by simpa [mul_add, mul_comm, mul_left_comm] using congr_arg (* pell_zd a1 n) this theorem xy_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) ∧ yn (n + 2) + yn n = (2 * a) * yn (n + 1) := begin have := pell_zd_succ_succ a1 n, unfold pell_zd at this, rw [← int.cast_coe_nat, zsqrtd.smul_val] at this, injection this with h₁ h₂, split; apply int.coe_nat_inj; [simpa using h₁, simpa using h₂] end theorem xn_succ_succ (n) : xn (n + 2) + xn n = (2 * a) * xn (n + 1) := (xy_succ_succ n).1 theorem yn_succ_succ (n) : yn (n + 2) + yn n = (2 * a) * yn (n + 1) := (xy_succ_succ n).2 theorem xz_succ_succ (n) : xz (n + 2) = (2 * a : ℕ) * xz (n + 1) - xz n := eq_sub_of_add_eq $ by delta xz; rw [← int.coe_nat_add, ← int.coe_nat_mul, xn_succ_succ] theorem yz_succ_succ (n) : yz (n + 2) = (2 * a : ℕ) * yz (n + 1) - yz n := eq_sub_of_add_eq $ by delta yz; rw [← int.coe_nat_add, ← int.coe_nat_mul, yn_succ_succ] theorem yn_modeq_a_sub_one : ∀ n, yn n ≡ n [MOD a-1] | 0 := by simp | 1 := by simp | (n+2) := modeq.modeq_add_cancel_right (yn_modeq_a_sub_one n) $ have 2*(n+1) = n+2+n, by simp [two_mul], by rw [yn_succ_succ, ← this]; refine modeq.modeq_mul (modeq.modeq_mul_left 2 (_ : a ≡ 1 [MOD a-1])) (yn_modeq_a_sub_one (n+1)); exact (modeq.modeq_of_dvd $ by rw [int.coe_nat_sub $ le_of_lt a1]; apply dvd_refl).symm theorem yn_modeq_two : ∀ n, yn n ≡ n [MOD 2] | 0 := by simp | 1 := by simp | (n+2) := modeq.modeq_add_cancel_right (yn_modeq_two n) $ have 2*(n+1) = n+2+n, by simp [two_mul], by rw [yn_succ_succ, ← this]; refine modeq.modeq_mul _ (yn_modeq_two (n+1)); exact modeq.trans (modeq.modeq_zero_iff.2 $ by simp) (modeq.modeq_zero_iff.2 $ by simp).symm -- TODO(Mario): Hopefully a tactic will be able to dispense this lemma lemma x_sub_y_dvd_pow_lem (y2 y1 y0 yn1 yn0 xn1 xn0 ay a2 : ℤ) : (a2 * yn1 - yn0) * ay + y2 - (a2 * xn1 - xn0) = y2 - a2 * y1 + y0 + a2 * (yn1 * ay + y1 - xn1) - (yn0 * ay + y0 - xn0) := calc (a2 * yn1 - yn0) * ay + y2 - (a2 * xn1 - xn0) = a2 * yn1 * ay - yn0 * ay + y2 - (a2 * xn1 - xn0) : by rw [mul_sub_right_distrib] ... = y2 + a2 * (yn1 * ay) - a2 * xn1 - yn0 * ay + xn0 : by simp [mul_comm, mul_left_comm] ... = y2 + a2 * (yn1 * ay) - a2 * y1 + a2 * y1 - a2 * xn1 - yn0 * ay + y0 - y0 + xn0 : by rw [add_sub_cancel, sub_add_cancel] ... = y2 - a2 * y1 + y0 + a2 * (yn1 * ay + y1 - xn1) - (yn0 * ay + y0 - xn0) : by simp [mul_add] theorem x_sub_y_dvd_pow (y : ℕ) : ∀ n, (2*a*y - y*y - 1 : ℤ) ∣ yz n * (a - y) + ↑(y^n) - xz n | 0 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | 1 := by simp [xz, yz, int.coe_nat_zero, int.coe_nat_one] | (n+2) := have (2*a*y - y*y - 1 : ℤ) ∣ ↑(y^(n + 2)) - ↑(2 * a) * ↑(y^(n + 1)) + ↑(y^n), from ⟨-↑(y^n), by simp [nat.pow_succ, mul_add, int.coe_nat_mul, show ((2:ℕ):ℤ) = 2, from rfl, mul_comm, mul_left_comm]⟩, by rw [xz_succ_succ, yz_succ_succ, x_sub_y_dvd_pow_lem a1 ↑(y^(n+2)) ↑(y^(n+1)) ↑(y^n)]; exact dvd_sub (dvd_add this $ dvd_mul_of_dvd_right (x_sub_y_dvd_pow (n+1)) _) (x_sub_y_dvd_pow n) theorem xn_modeq_x2n_add_lem (n j) : xn n ∣ d * yn n * (yn n * xn j) + xn j := have h1 : d * yn n * (yn n * xn j) + xn j = (d * yn n * yn n + 1) * xn j, by simp [add_mul, mul_assoc], have h2 : d * yn n * yn n + 1 = xn n * xn n, by apply int.coe_nat_inj; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; exact add_eq_of_eq_sub' (eq.symm $ pell_eqz _ _), by rw h2 at h1; rw [h1, mul_assoc]; exact dvd_mul_right _ _ theorem xn_modeq_x2n_add (n j) : xn (2 * n + j) + xn j ≡ 0 [MOD xn n] := by rw [two_mul, add_assoc, xn_add, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_right (xn a1 n) (xn a1 (n + j))) $ by rw [yn_add, left_distrib, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_of_dvd_right (dvd_mul_right _ _) _) $ modeq.modeq_zero_iff.2 $ xn_modeq_x2n_add_lem _ _ _ lemma xn_modeq_x2n_sub_lem {n j} (h : j ≤ n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := have h1 : xz n ∣ ↑d * yz n * yz (n - j) + xz j, by rw [yz_sub _ h, mul_sub_left_distrib, sub_add_eq_add_sub]; exact dvd_sub (by delta xz; delta yz; repeat {rw ← int.coe_nat_add <|> rw ← int.coe_nat_mul}; rw mul_comm (xn a1 j) (yn a1 n); exact int.coe_nat_dvd.2 (xn_modeq_x2n_add_lem _ _ _)) (dvd_mul_of_dvd_right (dvd_mul_right _ _) _), by rw [two_mul, nat.add_sub_assoc h, xn_add, add_assoc]; exact show _ ≡ 0+0 [MOD xn a1 n], from modeq.modeq_add (modeq.modeq_zero_iff.2 $ dvd_mul_right _ _) $ modeq.modeq_zero_iff.2 $ int.coe_nat_dvd.1 $ by simpa [xz, yz] using h1 theorem xn_modeq_x2n_sub {n j} (h : j ≤ 2 * n) : xn (2 * n - j) + xn j ≡ 0 [MOD xn n] := (le_total j n).elim xn_modeq_x2n_sub_lem (λjn, have 2 * n - j + j ≤ n + j, by rw [nat.sub_add_cancel h, two_mul]; exact nat.add_le_add_left jn _, let t := xn_modeq_x2n_sub_lem (nat.le_of_add_le_add_right this) in by rwa [nat.sub_sub_self h, add_comm] at t) theorem xn_modeq_x4n_add (n j) : xn (4 * n + j) ≡ xn j [MOD xn n] := modeq.modeq_add_cancel_right (modeq.refl $ xn (2 * n + j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_add _ _ _).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, add_assoc]; apply xn_modeq_x2n_add theorem xn_modeq_x4n_sub {n j} (h : j ≤ 2 * n) : xn (4 * n - j) ≡ xn j [MOD xn n] := have h' : j ≤ 2*n, from le_trans h (by rw nat.succ_mul; apply nat.le_add_left), modeq.modeq_add_cancel_right (modeq.refl $ xn (2 * n - j)) $ by refine @modeq.trans _ _ 0 _ _ (by rw add_comm; exact (xn_modeq_x2n_sub _ h).symm); rw [show 4*n = 2*n + 2*n, from right_distrib 2 2 n, nat.add_sub_assoc h']; apply xn_modeq_x2n_add theorem eq_of_xn_modeq_lem1 {i n} (npos : n > 0) : Π {j}, i < j → j < n → xn i % xn n < xn j % xn n | 0 ij _ := absurd ij (nat.not_lt_zero _) | (j+1) ij jn := suffices xn j % xn n < xn (j + 1) % xn n, from (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem1 h (le_of_lt jn)) this) (λh, by rw h; exact this), by rw [nat.mod_eq_of_lt (x_increasing _ (nat.lt_of_succ_lt jn)), nat.mod_eq_of_lt (x_increasing _ jn)]; exact x_increasing _ (nat.lt_succ_self _) theorem eq_of_xn_modeq_lem2 {n} (h : 2 * xn n = xn (n + 1)) : a = 2 ∧ n = 0 := by rw [xn_succ, mul_comm] at h; exact have n = 0, from n.eq_zero_or_pos.resolve_right $ λnp, ne_of_lt (lt_of_le_of_lt (nat.mul_le_mul_left _ a1) (nat.lt_add_of_pos_right $ mul_pos (d_pos a1) (y_increasing a1 np))) h, by cases this; simp at h; exact ⟨h.symm, rfl⟩ theorem eq_of_xn_modeq_lem3 {i n} (npos : n > 0) : Π {j}, i < j → j ≤ 2 * n → j ≠ n → ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2) → xn i % xn n < xn j % xn n | 0 ij _ _ _ := absurd ij (nat.not_lt_zero _) | (j+1) ij j2n jnn ntriv := have lem2 : ∀k > n, k ≤ 2*n → (↑(xn k % xn n) : ℤ) = xn n - xn (2 * n - k), from λk kn k2n, let k2nl := lt_of_add_lt_add_right $ show 2*n-k+k < n+k, by {rw nat.sub_add_cancel, rw two_mul; exact (add_lt_add_left kn n), exact k2n } in have xle : xn (2 * n - k) ≤ xn n, from le_of_lt $ x_increasing k2nl, suffices xn k % xn n = xn n - xn (2 * n - k), by rw [this, int.coe_nat_sub xle], by { rw ← nat.mod_eq_of_lt (nat.sub_lt (x_pos a1 n) (x_pos a1 (2 * n - k))), apply modeq.modeq_add_cancel_right (modeq.refl (xn a1 (2 * n - k))), rw [nat.sub_add_cancel xle], have t := xn_modeq_x2n_sub_lem a1 (le_of_lt k2nl), rw nat.sub_sub_self k2n at t, exact t.trans (modeq.modeq_zero_iff.2 $ dvd_refl _).symm }, (lt_trichotomy j n).elim (λ (jn : j < n), eq_of_xn_modeq_lem1 npos ij (lt_of_le_of_ne jn jnn)) $ λo, o.elim (λ (jn : j = n), by { cases jn, apply int.lt_of_coe_nat_lt_coe_nat, rw [lem2 (n+1) (nat.lt_succ_self _) j2n, show 2 * n - (n + 1) = n - 1, by rw[two_mul, ← nat.sub_sub, nat.add_sub_cancel]], refine lt_sub_left_of_add_lt (int.coe_nat_lt_coe_nat_of_lt _), cases (lt_or_eq_of_le $ nat.le_of_succ_le_succ ij) with lin ein, { rw nat.mod_eq_of_lt (x_increasing _ lin), have ll : xn a1 (n-1) + xn a1 (n-1) ≤ xn a1 n, { rw [← two_mul, mul_comm, show xn a1 n = xn a1 (n-1+1), by rw [nat.sub_add_cancel npos], xn_succ], exact le_trans (nat.mul_le_mul_left _ a1) (nat.le_add_right _ _) }, have npm : (n-1).succ = n := nat.succ_pred_eq_of_pos npos, have il : i ≤ n - 1 := by apply nat.le_of_succ_le_succ; rw npm; exact lin, cases lt_or_eq_of_le il with ill ile, { exact lt_of_lt_of_le (nat.add_lt_add_left (x_increasing a1 ill) _) ll }, { rw ile, apply lt_of_le_of_ne ll, rw ← two_mul, exact λe, ntriv $ let ⟨a2, s1⟩ := @eq_of_xn_modeq_lem2 _ a1 (n-1) (by rw[nat.sub_add_cancel npos]; exact e) in have n1 : n = 1, from le_antisymm (nat.le_of_sub_eq_zero s1) npos, by rw [ile, a2, n1]; exact ⟨rfl, rfl, rfl, rfl⟩ } }, { rw [ein, nat.mod_self, add_zero], exact x_increasing _ (nat.pred_lt $ ne_of_gt npos) } }) (λ (jn : j > n), have lem1 : j ≠ n → xn j % xn n < xn (j + 1) % xn n → xn i % xn n < xn (j + 1) % xn n, from λjn s, (lt_or_eq_of_le (nat.le_of_succ_le_succ ij)).elim (λh, lt_trans (eq_of_xn_modeq_lem3 h (le_of_lt j2n) jn $ λ⟨a1, n1, i0, j2⟩, by rw [n1, j2] at j2n; exact absurd j2n dec_trivial) s) (λh, by rw h; exact s), lem1 (ne_of_gt jn) $ int.lt_of_coe_nat_lt_coe_nat $ by { rw [lem2 j jn (le_of_lt j2n), lem2 (j+1) (nat.le_succ_of_le jn) j2n], refine sub_lt_sub_left (int.coe_nat_lt_coe_nat_of_lt $ x_increasing _ _) _, rw [nat.sub_succ], exact nat.pred_lt (ne_of_gt $ nat.sub_pos_of_lt j2n) }) theorem eq_of_xn_modeq_le {i j n} (npos : n > 0) (ij : i ≤ j) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : ¬(a = 2 ∧ n = 1 ∧ i = 0 ∧ j = 2)) : i = j := (lt_or_eq_of_le ij).resolve_left $ λij', if jn : j = n then by { refine ne_of_gt _ h, rw [jn, nat.mod_self], have x0 : xn a1 0 % xn a1 n > 0 := by rw [nat.mod_eq_of_lt (x_increasing a1 npos)]; exact dec_trivial, cases i with i, exact x0, rw jn at ij', exact lt_trans x0 (eq_of_xn_modeq_lem3 _ npos (nat.succ_pos _) (le_trans ij j2n) (ne_of_lt ij') $ λ⟨a1, n1, _, i2⟩, by rw [n1, i2] at ij'; exact absurd ij' dec_trivial) } else ne_of_lt (eq_of_xn_modeq_lem3 npos ij' j2n jn ntriv) h theorem eq_of_xn_modeq {i j n} (npos : n > 0) (i2n : i ≤ 2 * n) (j2n : j ≤ 2 * n) (h : xn i ≡ xn j [MOD xn n]) (ntriv : a = 2 → n = 1 → (i = 0 → j ≠ 2) ∧ (i = 2 → j ≠ 0)) : i = j := (le_total i j).elim (λij, eq_of_xn_modeq_le npos ij j2n h $ λ⟨a2, n1, i0, j2⟩, (ntriv a2 n1).left i0 j2) (λij, (eq_of_xn_modeq_le npos ij i2n h.symm $ λ⟨a2, n1, j0, i2⟩, (ntriv a2 n1).right i2 j0).symm) theorem eq_of_xn_modeq' {i j n} (ipos : i > 0) (hin : i ≤ n) (j4n : j ≤ 4 * n) (h : xn j ≡ xn i [MOD xn n]) : j = i ∨ j + i = 4 * n := have i2n : i ≤ 2*n, by apply le_trans hin; rw two_mul; apply nat.le_add_left, have npos : n > 0, from lt_of_lt_of_le ipos hin, (le_or_gt j (2 * n)).imp (λj2n : j ≤ 2*n, eq_of_xn_modeq npos j2n i2n h $ λa2 n1, ⟨λj0 i2, by rw [n1, i2] at hin; exact absurd hin dec_trivial, λj2 i0, ne_of_gt ipos i0⟩) (λj2n : j > 2*n, suffices i = 4*n - j, by rw [this, nat.add_sub_of_le j4n], have j42n : 4*n - j ≤ 2*n, from @nat.le_of_add_le_add_right j _ _ $ by rw [nat.sub_add_cancel j4n, show 4*n = 2*n + 2*n, from right_distrib 2 2 n]; exact nat.add_le_add_left (le_of_lt j2n) _, eq_of_xn_modeq npos i2n j42n (h.symm.trans $ let t := xn_modeq_x4n_sub j42n in by rwa [nat.sub_sub_self j4n] at t) (λa2 n1, ⟨λi0, absurd i0 (ne_of_gt ipos), λi2, by rw[n1, i2] at hin; exact absurd hin dec_trivial⟩)) theorem modeq_of_xn_modeq {i j n} (ipos : i > 0) (hin : i ≤ n) (h : xn j ≡ xn i [MOD xn n]) : j ≡ i [MOD 4 * n] ∨ j + i ≡ 0 [MOD 4 * n] := let j' := j % (4 * n) in have n4 : 4 * n > 0, from mul_pos dec_trivial (lt_of_lt_of_le ipos hin), have jl : j' < 4 * n, from nat.mod_lt _ n4, have jj : j ≡ j' [MOD 4 * n], by delta modeq; rw nat.mod_eq_of_lt jl, have ∀j q, xn (j + 4 * n * q) ≡ xn j [MOD xn n], begin intros j q, induction q with q IH, { simp }, rw[nat.mul_succ, ← add_assoc, add_comm], exact modeq.trans (xn_modeq_x4n_add _ _ _) IH end, or.imp (λ(ji : j' = i), by rwa ← ji) (λ(ji : j' + i = 4 * n), (modeq.modeq_add jj (modeq.refl _)).trans $ by rw ji; exact modeq.modeq_zero_iff.2 (dvd_refl _)) (eq_of_xn_modeq' ipos hin (le_of_lt jl) $ (modeq.symm (by rw ← nat.mod_add_div j (4*n); exact this j' _)).trans h) end theorem xy_modeq_of_modeq {a b c} (a1 : a > 1) (b1 : b > 1) (h : a ≡ b [MOD c]) : ∀ n, xn a1 n ≡ xn b1 n [MOD c] ∧ yn a1 n ≡ yn b1 n [MOD c] | 0 := by constructor; refl | 1 := by simp; exact ⟨h, modeq.refl 1⟩ | (n+2) := ⟨ modeq.modeq_add_cancel_right (xy_modeq_of_modeq n).left $ by rw [xn_succ_succ a1, xn_succ_succ b1]; exact modeq.modeq_mul (modeq.modeq_mul_left _ h) (xy_modeq_of_modeq (n+1)).left, modeq.modeq_add_cancel_right (xy_modeq_of_modeq n).right $ by rw [yn_succ_succ a1, yn_succ_succ b1]; exact modeq.modeq_mul (modeq.modeq_mul_left _ h) (xy_modeq_of_modeq (n+1)).right⟩ theorem matiyasevic {a k x y} : (∃ a1 : a > 1, xn a1 k = x ∧ yn a1 k = y) ↔ a > 1 ∧ k ≤ y ∧ (x = 1 ∧ y = 0 ∨ ∃ (u v s t b : ℕ), x * x - (a * a - 1) * y * y = 1 ∧ u * u - (a * a - 1) * v * v = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ b > 1 ∧ b ≡ 1 [MOD 4 * y] ∧ b ≡ a [MOD u] ∧ v > 0 ∧ y * y ∣ v ∧ s ≡ x [MOD u] ∧ t ≡ k [MOD 4 * y]) := ⟨λ⟨a1, hx, hy⟩, by rw [← hx, ← hy]; refine ⟨a1, (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact ⟨le_refl _, or.inl ⟨rfl, rfl⟩⟩) (λkpos, _)⟩; exact let x := xn a1 k, y := yn a1 k, m := 2 * (k * y), u := xn a1 m, v := yn a1 m in have ky : k ≤ y, from yn_ge_n a1 k, have yv : y * y ∣ v, from dvd_trans (ysq_dvd_yy a1 k) $ (y_dvd_iff _ _ _).2 $ dvd_mul_left _ _, have uco : nat.coprime u (4 * y), from have 2 ∣ v, from modeq.modeq_zero_iff.1 $ (yn_modeq_two _ _).trans $ modeq.modeq_zero_iff.2 (dvd_mul_right _ _), have nat.coprime u 2, from (xy_coprime a1 m).coprime_dvd_right this, (this.mul_right this).mul_right $ (xy_coprime _ _).coprime_dvd_right (dvd_of_mul_left_dvd yv), let ⟨b, ba, bm1⟩ := modeq.chinese_remainder uco a 1 in have m1 : 1 < m, from have 0 < k * y, from mul_pos kpos (y_increasing a1 kpos), nat.mul_le_mul_left 2 this, have vp : v > 0, from y_increasing a1 (lt_trans zero_lt_one m1), have b1 : b > 1, from have u > xn a1 1, from x_increasing a1 m1, have u > a, by simp at this; exact this, lt_of_lt_of_le a1 $ by delta modeq at ba; rw nat.mod_eq_of_lt this at ba; rw ← ba; apply nat.mod_le, let s := xn b1 k, t := yn b1 k in have sx : s ≡ x [MOD u], from (xy_modeq_of_modeq b1 a1 ba k).left, have tk : t ≡ k [MOD 4 * y], from have 4 * y ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact modeq.dvd_of_modeq bm1.symm, modeq.modeq_of_dvd_of_modeq this $ yn_modeq_a_sub_one _ _, ⟨ky, or.inr ⟨u, v, s, t, b, pell_eq _ _, pell_eq _ _, pell_eq _ _, b1, bm1, ba, vp, yv, sx, tk⟩⟩, λ⟨a1, ky, o⟩, ⟨a1, match o with | or.inl ⟨x1, y0⟩ := by rw y0 at ky; rw [nat.eq_zero_of_le_zero ky, x1, y0]; exact ⟨rfl, rfl⟩ | or.inr ⟨u, v, s, t, b, xy, uv, st, b1, rem⟩ := match x, y, eq_pell a1 xy, u, v, eq_pell a1 uv, s, t, eq_pell b1 st, rem, ky with | ._, ._, ⟨i, rfl, rfl⟩, ._, ._, ⟨n, rfl, rfl⟩, ._, ._, ⟨j, rfl, rfl⟩, ⟨(bm1 : b ≡ 1 [MOD 4 * yn a1 i]), (ba : b ≡ a [MOD xn a1 n]), (vp : yn a1 n > 0), (yv : yn a1 i * yn a1 i ∣ yn a1 n), (sx : xn b1 j ≡ xn a1 i [MOD xn a1 n]), (tk : yn b1 j ≡ k [MOD 4 * yn a1 i])⟩, (ky : k ≤ yn a1 i) := (nat.eq_zero_or_pos i).elim (λi0, by simp [i0] at ky; rw [i0, nat.eq_zero_of_le_zero ky]; exact ⟨rfl, rfl⟩) $ λipos, suffices i = k, by rw this; exact ⟨rfl, rfl⟩, by clear _x o rem xy uv st _match _match _fun_match; exact have iln : i ≤ n, from le_of_not_gt $ λhin, not_lt_of_ge (nat.le_of_dvd vp (dvd_of_mul_left_dvd yv)) (y_increasing a1 hin), have yd : 4 * yn a1 i ∣ 4 * n, from mul_dvd_mul_left _ $ dvd_of_ysq_dvd a1 yv, have jk : j ≡ k [MOD 4 * yn a1 i], from have 4 * yn a1 i ∣ b - 1, from int.coe_nat_dvd.1 $ by rw int.coe_nat_sub (le_of_lt b1); exact modeq.dvd_of_modeq bm1.symm, (modeq.modeq_of_dvd_of_modeq this (yn_modeq_a_sub_one b1 _)).symm.trans tk, have ki : k + i < 4 * yn a1 i, from lt_of_le_of_lt (add_le_add ky (yn_ge_n a1 i)) $ by rw ← two_mul; exact nat.mul_lt_mul_of_pos_right dec_trivial (y_increasing a1 ipos), have ji : j ≡ i [MOD 4 * n], from have xn a1 j ≡ xn a1 i [MOD xn a1 n], from (xy_modeq_of_modeq b1 a1 ba j).left.symm.trans sx, (modeq_of_xn_modeq a1 ipos iln this).resolve_right $ λ (ji : j + i ≡ 0 [MOD 4 * n]), not_le_of_gt ki $ nat.le_of_dvd (lt_of_lt_of_le ipos $ nat.le_add_left _ _) $ modeq.modeq_zero_iff.1 $ (modeq.modeq_add jk.symm (modeq.refl i)).trans $ modeq.modeq_of_dvd_of_modeq yd ji, by have : i % (4 * yn a1 i) = k % (4 * yn a1 i) := (modeq.modeq_of_dvd_of_modeq yd ji).symm.trans jk; rwa [nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_left _ _) ki), nat.mod_eq_of_lt (lt_of_le_of_lt (nat.le_add_right _ _) ki)] at this end end⟩⟩ lemma eq_pow_of_pell_lem {a y k} (a1 : 1 < a) (ypos : y > 0) : k > 0 → a > y^k → (↑(y^k) : ℤ) < 2*a*y - y*y - 1 := have y < a → 2*a*y ≥ a + (y*y + 1), begin intro ya, induction y with y IH, exact absurd ypos (lt_irrefl _), cases nat.eq_zero_or_pos y with y0 ypos, { rw y0, simp [two_mul], apply add_le_add_left, exact a1 }, { rw [nat.mul_succ, nat.mul_succ, nat.succ_mul y], have : 2 * a ≥ y + nat.succ y, { change y + y < 2 * a, rw ← two_mul, exact mul_lt_mul_of_pos_left (nat.lt_of_succ_lt ya) dec_trivial }, have := add_le_add (IH ypos (nat.lt_of_succ_lt ya)) this, simp at this, simp, exact this } end, λk0 yak, lt_of_lt_of_le (int.coe_nat_lt_coe_nat_of_lt yak) $ by rw sub_sub; apply le_sub_right_of_add_le; apply int.coe_nat_le_coe_nat_of_le; have y1 := nat.pow_le_pow_of_le_right ypos k0; simp at y1; exact this (lt_of_le_of_lt y1 yak) theorem eq_pow_of_pell {m n k} : (n^k = m ↔ k = 0 ∧ m = 1 ∨ k > 0 ∧ (n = 0 ∧ m = 0 ∨ n > 0 ∧ ∃ (w a t z : ℕ) (a1 : a > 1), xn a1 k ≡ yn a1 k * (a - n) + m [MOD t] ∧ 2 * a * n = t + (n * n + 1) ∧ m < t ∧ n ≤ w ∧ k ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)) := ⟨λe, by rw ← e; refine (nat.eq_zero_or_pos k).elim (λk0, by rw k0; exact or.inl ⟨rfl, rfl⟩) (λkpos, or.inr ⟨kpos, _⟩); refine (nat.eq_zero_or_pos n).elim (λn0, by rw [n0, nat.zero_pow kpos]; exact or.inl ⟨rfl, rfl⟩) (λnpos, or.inr ⟨npos, _⟩); exact let w := _root_.max n k in have nw : n ≤ w, from le_max_left _ _, have kw : k ≤ w, from le_max_right _ _, have wpos : w > 0, from lt_of_lt_of_le npos nw, have w1 : w + 1 > 1, from nat.succ_lt_succ wpos, let a := xn w1 w in have a1 : a > 1, from x_increasing w1 wpos, let x := xn a1 k, y := yn a1 k in let ⟨z, ze⟩ := show w ∣ yn w1 w, from modeq.modeq_zero_iff.1 $ modeq.trans (yn_modeq_a_sub_one w1 w) (modeq.modeq_zero_iff.2 $ dvd_refl _) in have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^w : nat.pow_le_pow_of_le_right npos kw ... < (w + 1)^w : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) wpos ... ≤ a : xn_ge_a_pow w1 w, let ⟨t, te⟩ := int.eq_coe_of_zero_le $ le_trans (int.coe_zero_le _) $ le_of_lt nt in have na : n ≤ a, from le_trans nw $ le_of_lt $ n_lt_xn w1 w, have tm : x ≡ y * (a - n) + n^k [MOD t], begin apply modeq.modeq_of_dvd, rw [int.coe_nat_add, int.coe_nat_mul, int.coe_nat_sub na, ← te], exact x_sub_y_dvd_pow a1 n k end, have ta : 2 * a * n = t + (n * n + 1), from int.coe_nat_inj $ by rw [int.coe_nat_add, ← te, sub_sub]; repeat {rw int.coe_nat_add <|> rw int.coe_nat_mul}; rw [int.coe_nat_one, sub_add_cancel]; refl, have mt : n^k < t, from int.lt_of_coe_nat_lt_coe_nat $ by rw ← te; exact nt, have zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1, by rw ← ze; exact pell_eq w1 w, ⟨w, a, t, z, a1, tm, ta, mt, nw, kw, zp⟩, λo, match o with | or.inl ⟨k0, m1⟩ := by rw [k0, m1]; refl | or.inr ⟨kpos, or.inl ⟨n0, m0⟩⟩ := by rw [n0, m0, nat.zero_pow kpos] | or.inr ⟨kpos, or.inr ⟨npos, w, a, t, z, (a1 : a > 1), (tm : xn a1 k ≡ yn a1 k * (a - n) + m [MOD t]), (ta : 2 * a * n = t + (n * n + 1)), (mt : m < t), (nw : n ≤ w), (kw : k ≤ w), (zp : a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)⟩⟩ := have wpos : w > 0, from lt_of_lt_of_le npos nw, have w1 : w + 1 > 1, from nat.succ_lt_succ wpos, let ⟨j, xj, yj⟩ := eq_pell w1 zp in by clear _match o _let_match; exact have jpos : j > 0, from (nat.eq_zero_or_pos j).resolve_left $ λj0, have a1 : a = 1, by rw j0 at xj; exact xj, have 2 * n = t + (n * n + 1), by rw a1 at ta; exact ta, have n1 : n = 1, from have n * n < n * 2, by rw [mul_comm n 2, this]; apply nat.le_add_left, have n ≤ 1, from nat.le_of_lt_succ $ lt_of_mul_lt_mul_left this (nat.zero_le _), le_antisymm this npos, by rw n1 at this; rw ← @nat.add_right_cancel 0 2 t this at mt; exact nat.not_lt_zero _ mt, have wj : w ≤ j, from nat.le_of_dvd jpos $ modeq.modeq_zero_iff.1 $ (yn_modeq_a_sub_one w1 j).symm.trans $ modeq.modeq_zero_iff.2 ⟨z, yj.symm⟩, have nt : (↑(n^k) : ℤ) < 2 * a * n - n * n - 1, from eq_pow_of_pell_lem a1 npos kpos $ calc n^k ≤ n^j : nat.pow_le_pow_of_le_right npos (le_trans kw wj) ... < (w + 1)^j : nat.pow_lt_pow_of_lt_left (nat.lt_succ_of_le nw) jpos ... ≤ xn w1 j : xn_ge_a_pow w1 j ... = a : xj.symm, have na : n ≤ a, by rw xj; exact le_trans (le_trans nw wj) (le_of_lt $ n_lt_xn _ _), have te : (t : ℤ) = 2 * ↑a * ↑n - ↑n * ↑n - 1, by rw sub_sub; apply eq_sub_of_add_eq; apply (int.coe_nat_eq_coe_nat_iff _ _).2; exact ta.symm, have xn a1 k ≡ yn a1 k * (a - n) + n^k [MOD t], by have := x_sub_y_dvd_pow a1 n k; rw [← te, ← int.coe_nat_sub na] at this; exact modeq.modeq_of_dvd this, have n^k % t = m % t, from modeq.modeq_add_cancel_left (modeq.refl _) (this.symm.trans tm), by rw ← te at nt; rwa [nat.mod_eq_of_lt (int.lt_of_coe_nat_lt_coe_nat nt), nat.mod_eq_of_lt mt] at this end⟩ end pell
6b938d678a396801e655c9bd3e470faae657e0fb
74d9d5f45c6ce5c4f2faf215c04a68eab55fe525
/src/operator_norm.lean
3770ec19943047093e3b42063d94f1594da8559d
[]
no_license
joshpoll/differential_geometry
290bb8a934ca3b3b6b707d810e6d4b941710b710
57e00a7e37b7c4c73c847429171ff63d3a48def5
refs/heads/master
1,584,551,626,391
1,527,747,643,000
1,527,747,643,000
135,014,993
1
0
null
null
null
null
UTF-8
Lean
false
false
2,359
lean
/- The operator norm is the natural norm for linear operators between normed vector spaces. One can think of it as how much a map stretches unit vectors or as the smallest value that guarantees Cauchy-Schwarz (i.e. ∥L v∥ ≤ ∥L∥ * ∥v∥). The derivative of f : E → F is f' : E → continuous_linear_map E F. We need the operator norm both to define continuity for the definition of Caratheodory derivative and to take higher-order derivatives. -/ -- TODO: We'd like op_norm to return an ennreal, but be able to restrict it to nonnegative reals when needed for a norm. Not sure how to do that yet. We can prove that the op_norm is finite for continuous/bounded linear maps. Should norm operate over nonnegative reals? import differentiability.normed_space linear_algebra.linear_map_module analysis.ennreal order.complete_lattice open lattice ennreal noncomputable theory universes u v w x /- extended norm -/ -- TODO: of_real or of_nonneg_real? def op_norm {k : Type u} {E : Type v} {F : Type w} [normed_field k] [normed_space k E] [normed_space k F] : linear_map E F → ennreal := λ L, Inf { M : ennreal | ∀ v : E, (of_nonneg_real ∥L v∥ norm_nonneg) ≤ M * (of_nonneg_real ∥v∥ norm_nonneg) } section op_norm variables {k : Type u} {E : Type v} {F : Type w} variables [normed_field k] [normed_space k E] [normed_space k F] variables {L M : linear_map E F} include k theorem op_norm_nonneg : op_norm L ≥ 0 := sorry theorem op_norm_zero_iff_zero : op_norm L = 0 ↔ L = 0 := sorry theorem op_norm_pos_homo : ∀ c (L : linear_map E F), op_norm (c•L) = (of_real ∥c∥) * op_norm L := sorry theorem op_norm_triangle : op_norm (L + M) ≤ op_norm L + op_norm M := sorry end op_norm def op_dist {k : Type u} {E : Type v} {F : Type w} [normed_field k] [normed_space k E] [normed_space k F] : linear_map E F → linear_map E F → ennreal := λ L M, op_norm (L - M) section op_dist variables {k : Type u} {E : Type v} {F : Type w} variables [normed_field k] [normed_space k E] [normed_space k F] variables {L M N : linear_map E F} include k theorem op_dist_self : op_dist L L = 0 := sorry theorem op_dist_eq_of_dist_eq_zero : op_dist L M = 0 → L = M := sorry theorem op_dist_comm : op_dist L M = op_dist M L := sorry theorem op_dist_triangle : op_dist L N ≤ op_dist L M + op_dist M N := sorry end op_dist
3e1474a36c3201f415b11a0b6638c07881d55e54
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/deprecated/ring_auto.lean
b775db0a6c6a1229f9c099c0108522cca4cbfa48
[]
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,229
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.deprecated.group import Mathlib.PostPort universes u v l u_1 u_2 namespace Mathlib /-! # Unbundled semiring and ring homomorphisms (deprecated) This file defines typeclasses for unbundled semiring and ring homomorphisms. Though these classes are deprecated, they are still widely used in mathlib, and probably will not go away before Lean 4 because Lean 3 often fails to coerce a bundled homomorphism to a function. ## main definitions is_semiring_hom (deprecated), is_ring_hom (deprecated) ## Tags is_semiring_hom, is_ring_hom -/ /-- Predicate for semiring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ class is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) where map_zero : f 0 = 0 map_one : f 1 = 1 map_add : ∀ {x y : α}, f (x + y) = f x + f y map_mul : ∀ {x y : α}, f (x * y) = f x * f y namespace is_semiring_hom /-- The identity map is a semiring homomorphism. -/ protected instance id {α : Type u} [semiring α] : is_semiring_hom id := mk (Eq.refl (id 0)) (Eq.refl (id 1)) (fun (x y : α) => Eq.refl (id (x + y))) fun (x y : α) => Eq.refl (id (x * y)) /-- The composition of two semiring homomorphisms is a semiring homomorphism. -/ -- see Note [no instance on morphisms] theorem comp {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) [is_semiring_hom f] {γ : Type u_1} [semiring γ] (g : β → γ) [is_semiring_hom g] : is_semiring_hom (g ∘ f) := sorry /-- A semiring homomorphism is an additive monoid homomorphism. -/ protected instance is_add_monoid_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) [is_semiring_hom f] : is_add_monoid_hom f := is_add_monoid_hom.mk (map_zero f) /-- A semiring homomorphism is a monoid homomorphism. -/ protected instance is_monoid_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) [is_semiring_hom f] : is_monoid_hom f := is_monoid_hom.mk (map_one f) end is_semiring_hom /-- Predicate for ring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) where map_one : f 1 = 1 map_mul : ∀ {x y : α}, f (x * y) = f x * f y map_add : ∀ {x y : α}, f (x + y) = f x + f y namespace is_ring_hom /-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/ theorem of_semiring {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) [H : is_semiring_hom f] : is_ring_hom f := mk (is_semiring_hom.map_one f) (is_semiring_hom.map_mul f) (is_semiring_hom.map_add f) /-- Ring homomorphisms map zero to zero. -/ theorem map_zero {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) [is_ring_hom f] : f 0 = 0 := sorry /-- Ring homomorphisms preserve additive inverses. -/ theorem map_neg {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) [is_ring_hom f] {x : α} : f (-x) = -f x := sorry /-- Ring homomorphisms preserve subtraction. -/ theorem map_sub {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) [is_ring_hom f] {x : α} {y : α} : f (x - y) = f x - f y := sorry /-- The identity map is a ring homomorphism. -/ protected instance id {α : Type u} [ring α] : is_ring_hom id := mk (Eq.refl (id 1)) (fun (x y : α) => Eq.refl (id (x * y))) fun (x y : α) => Eq.refl (id (x + y)) /-- The composition of two ring homomorphisms is a ring homomorphism. -/ -- see Note [no instance on morphisms] theorem comp {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) [is_ring_hom f] {γ : Type u_1} [ring γ] (g : β → γ) [is_ring_hom g] : is_ring_hom (g ∘ f) := sorry /-- A ring homomorphism is also a semiring homomorphism. -/ protected instance is_semiring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) [is_ring_hom f] : is_semiring_hom f := is_semiring_hom.mk (map_zero f) (map_one f) (map_add f) (map_mul f) protected instance is_add_group_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) [is_ring_hom f] : is_add_group_hom f := is_add_group_hom.mk end is_ring_hom namespace ring_hom /-- Interpret `f : α → β` with `is_semiring_hom f` as a ring homomorphism. -/ def of {α : Type u} {β : Type v} [rα : semiring α] [rβ : semiring β] (f : α → β) [is_semiring_hom f] : α →+* β := mk f sorry sorry sorry sorry @[simp] theorem coe_of {α : Type u} {β : Type v} [rα : semiring α] [rβ : semiring β] (f : α → β) [is_semiring_hom f] : ⇑(of f) = f := rfl protected instance is_semiring_hom {α : Type u} {β : Type v} [rα : semiring α] [rβ : semiring β] (f : α →+* β) : is_semiring_hom ⇑f := is_semiring_hom.mk (map_zero f) (map_one f) (map_add f) (map_mul f) protected instance is_ring_hom {α : Type u_1} {γ : Type u_2} [ring α] [ring γ] (g : α →+* γ) : is_ring_hom ⇑g := is_ring_hom.of_semiring ⇑g end Mathlib
81aca9961e46f6714b1473b7f1a5fa8a0b2e4f06
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/init/path.hlean
e8030805000e2f5acfb91e3f22d09c6caf2191c0
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
31,657
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .function .tactic open function eq /- Path equality -/ namespace eq variables {A B C : Type} {P : A → Type} {a a' x y z t : A} {b b' : B} --notation a = b := eq a b notation x = y `:>`:50 A:49 := @eq A x y definition idp [reducible] [constructor] {a : A} := refl a definition idpath [reducible] [constructor] (a : A) := refl a -- unbased path induction definition rec_unbased [reducible] [unfold 6] {P : Π (a b : A), (a = b) → Type} (H : Π (a : A), P a a idp) {a b : A} (p : a = b) : P a b p := eq.rec (H a) p definition rec_on_unbased [reducible] [unfold 5] {P : Π (a b : A), (a = b) → Type} {a b : A} (p : a = b) (H : Π (a : A), P a a idp) : P a b p := eq.rec (H a) p /- Concatenation and inverse -/ definition concat [trans] [unfold 6] (p : x = y) (q : y = z) : x = z := by induction q; exact p definition inverse [symm] [unfold 4] (p : x = y) : y = x := by induction p; reflexivity infix ⬝ := concat postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing_only] `⁻¹ᵖ`:std.prec.max_plus := inverse /- The 1-dimensional groupoid structure -/ -- The identity path is a right unit. definition con_idp [unfold_full] (p : x = y) : p ⬝ idp = p := idp -- The identity path is a left unit. definition idp_con [unfold 4] (p : x = y) : idp ⬝ p = p := by induction p; reflexivity -- Concatenation is associative. definition con.assoc' [unfold 8] (p : x = y) (q : y = z) (r : z = t) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := by induction r; reflexivity definition con.assoc [unfold 8] (p : x = y) (q : y = z) (r : z = t) : (p ⬝ q) ⬝ r = p ⬝ (q ⬝ r) := by induction r; reflexivity definition con.assoc5 {a₁ a₂ a₃ a₄ a₅ a₆ : A} (p₁ : a₁ = a₂) (p₂ : a₂ = a₃) (p₃ : a₃ = a₄) (p₄ : a₄ = a₅) (p₅ : a₅ = a₆) : p₁ ⬝ (p₂ ⬝ p₃ ⬝ p₄) ⬝ p₅ = (p₁ ⬝ p₂) ⬝ p₃ ⬝ (p₄ ⬝ p₅) := by induction p₅; induction p₄; induction p₃; reflexivity -- The right inverse law. definition con.right_inv [unfold 4] (p : x = y) : p ⬝ p⁻¹ = idp := by induction p; reflexivity -- The left inverse law. definition con.left_inv [unfold 4] (p : x = y) : p⁻¹ ⬝ p = idp := by induction p; reflexivity /- Several auxiliary theorems about canceling inverses across associativity. These are somewhat redundant, following from earlier theorems. -/ definition inv_con_cancel_left (p : x = y) (q : y = z) : p⁻¹ ⬝ (p ⬝ q) = q := by induction q; induction p; reflexivity definition con_inv_cancel_left (p : x = y) (q : x = z) : p ⬝ (p⁻¹ ⬝ q) = q := by induction q; induction p; reflexivity definition con_inv_cancel_right (p : x = y) (q : y = z) : (p ⬝ q) ⬝ q⁻¹ = p := by induction q; reflexivity definition inv_con_cancel_right (p : x = z) (q : y = z) : (p ⬝ q⁻¹) ⬝ q = p := by induction q; reflexivity -- Inverse distributes over concatenation definition con_inv (p : x = y) (q : y = z) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ := by induction q; induction p; reflexivity definition inv_con_inv_left (p : y = x) (q : y = z) : (p⁻¹ ⬝ q)⁻¹ = q⁻¹ ⬝ p := by induction q; induction p; reflexivity definition inv_con_inv_right (p : x = y) (q : z = y) : (p ⬝ q⁻¹)⁻¹ = q ⬝ p⁻¹ := by induction q; induction p; reflexivity definition inv_con_inv_inv (p : y = x) (q : z = y) : (p⁻¹ ⬝ q⁻¹)⁻¹ = q ⬝ p := by induction q; induction p; reflexivity -- Inverse is an involution. definition inv_inv [unfold 4] (p : x = y) : p⁻¹⁻¹ = p := by induction p; reflexivity -- auxiliary definition used by 'cases' tactic definition elim_inv_inv [unfold 5] {A : Type} {a b : A} {C : a = b → Type} (H₁ : a = b) (H₂ : C (H₁⁻¹⁻¹)) : C H₁ := eq.rec_on (inv_inv H₁) H₂ definition eq.rec_symm {A : Type} {a₀ : A} {P : Π⦃a₁⦄, a₁ = a₀ → Type} (H : P idp) ⦃a₁ : A⦄ (p : a₁ = a₀) : P p := begin cases p, exact H end /- Theorems for moving things around in equations -/ definition con_eq_of_eq_inv_con {p : x = z} {q : y = z} {r : y = x} : p = r⁻¹ ⬝ q → r ⬝ p = q := begin induction r, intro h, exact !idp_con ⬝ h ⬝ !idp_con end definition con_eq_of_eq_con_inv [unfold 5] {p : x = z} {q : y = z} {r : y = x} : r = q ⬝ p⁻¹ → r ⬝ p = q := by induction p; exact id definition inv_con_eq_of_eq_con {p : x = z} {q : y = z} {r : x = y} : p = r ⬝ q → r⁻¹ ⬝ p = q := by induction r; intro h; exact !idp_con ⬝ h ⬝ !idp_con definition con_inv_eq_of_eq_con [unfold 5] {p : z = x} {q : y = z} {r : y = x} : r = q ⬝ p → r ⬝ p⁻¹ = q := by induction p; exact id definition eq_con_of_inv_con_eq {p : x = z} {q : y = z} {r : y = x} : r⁻¹ ⬝ q = p → q = r ⬝ p := by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹ definition eq_con_of_con_inv_eq [unfold 5] {p : x = z} {q : y = z} {r : y = x} : q ⬝ p⁻¹ = r → q = r ⬝ p := by induction p; exact id definition eq_inv_con_of_con_eq {p : x = z} {q : y = z} {r : x = y} : r ⬝ q = p → q = r⁻¹ ⬝ p := by induction r; intro h; exact !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹ definition eq_con_inv_of_con_eq [unfold 5] {p : z = x} {q : y = z} {r : y = x} : q ⬝ p = r → q = r ⬝ p⁻¹ := by induction p; exact id definition eq_of_con_inv_eq_idp [unfold 5] {p q : x = y} : p ⬝ q⁻¹ = idp → p = q := by induction q; exact id definition eq_of_inv_con_eq_idp {p q : x = y} : q⁻¹ ⬝ p = idp → p = q := by induction q; intro h; exact !idp_con⁻¹ ⬝ h definition eq_inv_of_con_eq_idp' [unfold 5] {p : x = y} {q : y = x} : p ⬝ q = idp → p = q⁻¹ := by induction q; exact id definition eq_inv_of_con_eq_idp {p : x = y} {q : y = x} : q ⬝ p = idp → p = q⁻¹ := by induction q; intro h; exact !idp_con⁻¹ ⬝ h definition eq_of_idp_eq_inv_con {p q : x = y} : idp = p⁻¹ ⬝ q → p = q := by induction p; intro h; exact h ⬝ !idp_con definition eq_of_idp_eq_con_inv [unfold 4] {p q : x = y} : idp = q ⬝ p⁻¹ → p = q := by induction p; exact id definition inv_eq_of_idp_eq_con [unfold 4] {p : x = y} {q : y = x} : idp = q ⬝ p → p⁻¹ = q := by induction p; exact id definition inv_eq_of_idp_eq_con' {p : x = y} {q : y = x} : idp = p ⬝ q → p⁻¹ = q := by induction p; intro h; exact h ⬝ !idp_con definition con_inv_eq_idp [unfold 6] {p q : x = y} (r : p = q) : p ⬝ q⁻¹ = idp := by cases r; apply con.right_inv definition inv_con_eq_idp [unfold 6] {p q : x = y} (r : p = q) : q⁻¹ ⬝ p = idp := by cases r; apply con.left_inv definition con_eq_idp {p : x = y} {q : y = x} (r : p = q⁻¹) : p ⬝ q = idp := by cases q; exact r definition idp_eq_inv_con {p q : x = y} (r : p = q) : idp = p⁻¹ ⬝ q := by cases r; exact !con.left_inv⁻¹ definition idp_eq_con_inv {p q : x = y} (r : p = q) : idp = q ⬝ p⁻¹ := by cases r; exact !con.right_inv⁻¹ definition idp_eq_con {p : x = y} {q : y = x} (r : p⁻¹ = q) : idp = q ⬝ p := by cases p; exact r definition eq_idp_of_con_right {p : x = x} {q : x = y} (r : p ⬝ q = q) : p = idp := by cases q; exact r definition eq_idp_of_con_left {p : x = x} {q : y = x} (r : q ⬝ p = q) : p = idp := by cases q; exact (idp_con p)⁻¹ ⬝ r definition idp_eq_of_con_right {p : x = x} {q : x = y} (r : q = p ⬝ q) : idp = p := by cases q; exact r definition idp_eq_of_con_left {p : x = x} {q : y = x} (r : q = q ⬝ p) : idp = p := by cases q; exact r ⬝ idp_con p /- Transport -/ definition transport [subst] [reducible] [unfold 5] (P : A → Type) {x y : A} (p : x = y) (u : P x) : P y := by induction p; exact u -- This idiom makes the operation right associative. infixr ` ▸ ` := transport _ definition cast [reducible] [unfold 3] {A B : Type} (p : A = B) (a : A) : B := p ▸ a definition cast_def [reducible] [unfold_full] {A B : Type} (p : A = B) (a : A) : cast p a = p ▸ a := idp definition tr_rev [reducible] [unfold 6] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition ap [unfold 6] ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x = y) : f x = f y := by induction p; reflexivity abbreviation ap01 [parsing_only] := ap definition homotopy [reducible] (f g : Πx, P x) : Type := Πx : A, f x = g x infix ~ := homotopy protected definition homotopy.refl [refl] [reducible] [unfold_full] (f : Πx, P x) : f ~ f := λ x, idp protected definition homotopy.rfl [reducible] [unfold_full] {f : Πx, P x} : f ~ f := homotopy.refl f protected definition homotopy.symm [symm] [reducible] [unfold_full] {f g : Πx, P x} (H : f ~ g) : g ~ f := λ x, (H x)⁻¹ protected definition homotopy.trans [trans] [reducible] [unfold_full] {f g h : Πx, P x} (H1 : f ~ g) (H2 : g ~ h) : f ~ h := λ x, H1 x ⬝ H2 x infix ` ⬝hty `:75 := homotopy.trans postfix `⁻¹ʰᵗʸ`:(max+1) := homotopy.symm definition hwhisker_left [unfold_full] (g : B → C) {f f' : A → B} (H : f ~ f') : g ∘ f ~ g ∘ f' := λa, ap g (H a) definition hwhisker_right [unfold_full] (f : A → B) {g g' : B → C} (H : g ~ g') : g ∘ f ~ g' ∘ f := λa, H (f a) definition compose_id (f : A → B) : f ∘ id ~ f := by reflexivity definition id_compose (f : A → B) : id ∘ f ~ f := by reflexivity definition compose2 {A B C : Type} {g g' : B → C} {f f' : A → B} (p : g ~ g') (q : f ~ f') : g ∘ f ~ g' ∘ f' := hwhisker_right f p ⬝hty hwhisker_left g' q definition hassoc {A B C D : Type} (h : C → D) (g : B → C) (f : A → B) : (h ∘ g) ∘ f ~ h ∘ (g ∘ f) := λa, idp definition homotopy_of_eq {f g : Πx, P x} (H1 : f = g) : f ~ g := H1 ▸ homotopy.refl f definition apd10 [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g := λx, by induction H; reflexivity --the next theorem is useful if you want to write "apply (apd10' a)" definition apd10' [unfold 6] {f g : Πx, P x} (a : A) (H : f = g) : f a = g a := by induction H; reflexivity --apd10 is also ap evaluation definition apd10_eq_ap_eval {f g : Πx, P x} (H : f = g) (a : A) : apd10 H a = ap (λs : Πx, P x, s a) H := by induction H; reflexivity definition ap10 [reducible] [unfold 5] {f g : A → B} (H : f = g) : f ~ g := apd10 H definition ap11 {f g : A → B} (H : f = g) {x y : A} (p : x = y) : f x = g y := by induction H; exact ap f p -- [apd] is defined in init.pathover using pathover instead of an equality with transport. definition apdt [unfold 6] (f : Πa, P a) {x y : A} (p : x = y) : p ▸ f x = f y := by induction p; reflexivity definition ap011 [unfold 9] (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := by cases Ha; exact ap (f a) Hb /- More theorems for moving things around in equations -/ definition tr_eq_of_eq_inv_tr {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : u = p⁻¹ ▸ v → p ▸ u = v := by induction p; exact id definition inv_tr_eq_of_eq_tr {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : u = p ▸ v → p⁻¹ ▸ u = v := by induction p; exact id definition eq_inv_tr_of_tr_eq {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : p ▸ u = v → u = p⁻¹ ▸ v := by induction p; exact id definition eq_tr_of_inv_tr_eq {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : p⁻¹ ▸ u = v → u = p ▸ v := by induction p; exact id /- Transporting along the diagonal of a type family -/ definition tr_diag_eq_tr_tr {A : Type} (P : A → A → Type) {x y : A} (p : x = y) (a : P x x) : transport (λ x, P x x) p a = transport (λ x, P _ x) p (transport (λ x, P x _) p a) := by induction p; reflexivity /- Functoriality of functions -/ -- Here we prove that functions behave like functors between groupoids, and that [ap] itself is -- functorial. -- Functions take identity paths to identity paths definition ap_idp [unfold_full] (x : A) (f : A → B) : ap f idp = idp :> (f x = f x) := idp -- Functions commute with concatenation. definition ap_con [unfold 8] (f : A → B) {x y z : A} (p : x = y) (q : y = z) : ap f (p ⬝ q) = ap f p ⬝ ap f q := by induction q; reflexivity definition con_ap_con_eq_con_ap_con_ap (f : A → B) {w x y z : A} (r : f w = f x) (p : x = y) (q : y = z) : r ⬝ ap f (p ⬝ q) = (r ⬝ ap f p) ⬝ ap f q := by induction q; induction p; reflexivity definition ap_con_con_eq_ap_con_ap_con (f : A → B) {w x y z : A} (p : x = y) (q : y = z) (r : f z = f w) : ap f (p ⬝ q) ⬝ r = ap f p ⬝ (ap f q ⬝ r) := by induction q; induction p; apply con.assoc -- Functions commute with path inverses. definition ap_inv' [unfold 6] (f : A → B) {x y : A} (p : x = y) : (ap f p)⁻¹ = ap f p⁻¹ := by induction p; reflexivity definition ap_inv [unfold 6] (f : A → B) {x y : A} (p : x = y) : ap f p⁻¹ = (ap f p)⁻¹ := by induction p; reflexivity -- [ap] itself is functorial in the first argument. definition ap_id [unfold 4] (p : x = y) : ap id p = p := by induction p; reflexivity definition ap_compose [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (g ∘ f) p = ap g (ap f p) := by induction p; reflexivity -- Sometimes we don't have the actual function [compose]. definition ap_compose' [unfold 8] (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (λa, g (f a)) p = ap g (ap f p) := by induction p; reflexivity -- The action of constant maps. definition ap_constant [unfold 5] (p : x = y) (z : B) : ap (λu, z) p = idp := by induction p; reflexivity -- Naturality of [ap]. -- see also natural_square in cubical.square definition ap_con_eq_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ ap g q := by induction q; apply idp_con -- Naturality of [ap] at identity. definition ap_con_eq_con {f : A → A} (p : Πx, f x = x) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ q := by induction q; apply idp_con definition con_ap_eq_con {f : A → A} (p : Πx, x = f x) {x y : A} (q : x = y) : p x ⬝ ap f q = q ⬝ p y := by induction q; exact !idp_con⁻¹ -- Naturality of [ap] with constant function definition ap_con_eq {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q ⬝ p y = p x := by induction q; apply idp_con -- Naturality with other paths hanging around. definition con_ap_con_con_eq_con_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w z : B} (r : w = f x) (s : g y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (ap g q ⬝ s) := by induction s; induction q; reflexivity definition con_ap_con_eq_con_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w : B} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ ap g q := by induction q; reflexivity -- TODO: try this using the simplifier, and compare proofs definition ap_con_con_eq_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {z : B} (s : g y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (ap g q ⬝ s) := begin induction s, induction q, apply idp_con end definition con_ap_con_con_eq_con_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w z : A} (r : w = f x) (s : y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (q ⬝ s) := by induction s; induction q; reflexivity definition con_con_ap_con_eq_con_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w z : A} (r : w = x) (s : g y = z) : (r ⬝ p x) ⬝ (ap g q ⬝ s) = (r ⬝ q) ⬝ (p y ⬝ s) := by induction s; induction q; reflexivity definition con_ap_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w : A} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ q := by induction q; reflexivity definition ap_con_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {z : A} (s : y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (q ⬝ s) := by induction s; induction q; apply idp_con definition con_con_ap_eq_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w : A} (r : w = x) : (r ⬝ p x) ⬝ ap g q = (r ⬝ q) ⬝ p y := begin cases q, exact idp end definition con_ap_con_eq_con_con' {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {z : A} (s : g y = z) : p x ⬝ (ap g q ⬝ s) = q ⬝ (p y ⬝ s) := by induction s; induction q; exact !idp_con⁻¹ /- Action of [apd10] and [ap10] on paths -/ -- Application of paths between functions preserves the groupoid structure definition apd10_idp (f : Πx, P x) (x : A) : apd10 (refl f) x = idp := idp definition apd10_con {f f' f'' : Πx, P x} (h : f = f') (h' : f' = f'') (x : A) : apd10 (h ⬝ h') x = apd10 h x ⬝ apd10 h' x := by induction h; induction h'; reflexivity definition apd10_inv {f g : Πx : A, P x} (h : f = g) (x : A) : apd10 h⁻¹ x = (apd10 h x)⁻¹ := by induction h; reflexivity definition ap10_idp {f : A → B} (x : A) : ap10 (refl f) x = idp := idp definition ap10_con {f f' f'' : A → B} (h : f = f') (h' : f' = f'') (x : A) : ap10 (h ⬝ h') x = ap10 h x ⬝ ap10 h' x := apd10_con h h' x definition ap10_inv {f g : A → B} (h : f = g) (x : A) : ap10 h⁻¹ x = (ap10 h x)⁻¹ := apd10_inv h x -- [ap10] also behaves nicely on paths produced by [ap] definition ap_ap10 (f g : A → B) (h : B → C) (p : f = g) (a : A) : ap h (ap10 p a) = ap10 (ap (λ f', h ∘ f') p) a:= by induction p; reflexivity /- some lemma's about ap011 -/ definition ap_eq_ap011_left (f : A → B → C) (Ha : a = a') (b : B) : ap (λa, f a b) Ha = ap011 f Ha idp := by induction Ha; reflexivity definition ap_eq_ap011_right (f : A → B → C) (a : A) (Hb : b = b') : ap (f a) Hb = ap011 f idp Hb := by reflexivity definition ap_ap011 {A B C D : Type} (g : C → D) (f : A → B → C) {a a' : A} {b b' : B} (p : a = a') (q : b = b') : ap g (ap011 f p q) = ap011 (λa b, g (f a b)) p q := begin induction p, exact (ap_compose g (f a) q)⁻¹ end /- Transport and the groupoid structure of paths -/ definition idp_tr {P : A → Type} {x : A} (u : P x) : idp ▸ u = u := idp definition con_tr [unfold 7] {P : A → Type} {x y z : A} (p : x = y) (q : y = z) (u : P x) : p ⬝ q ▸ u = q ▸ p ▸ u := by induction q; reflexivity definition tr_inv_tr {P : A → Type} {x y : A} (p : x = y) (z : P y) : p ▸ p⁻¹ ▸ z = z := (con_tr p⁻¹ p z)⁻¹ ⬝ ap (λr, transport P r z) (con.left_inv p) definition inv_tr_tr {P : A → Type} {x y : A} (p : x = y) (z : P x) : p⁻¹ ▸ p ▸ z = z := (con_tr p p⁻¹ z)⁻¹ ⬝ ap (λr, transport P r z) (con.right_inv p) definition cast_cast_inv {A : Type} {P : A → Type} {x y : A} (p : x = y) (z : P y) : cast (ap P p) (cast (ap P p⁻¹) z) = z := by induction p; reflexivity definition cast_inv_cast {A : Type} {P : A → Type} {x y : A} (p : x = y) (z : P x) : cast (ap P p⁻¹) (cast (ap P p) z) = z := by induction p; reflexivity definition fn_tr_eq_tr_fn {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (p ▸ z) = p ▸ f x z := by induction p; reflexivity definition fn_cast_eq_cast_fn {A : Type} {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (cast (ap P p) z) = cast (ap Q p) (f x z) := by induction p; reflexivity definition con_con_tr {P : A → Type} {x y z w : A} (p : x = y) (q : y = z) (r : z = w) (u : P x) : ap (λe, e ▸ u) (con.assoc' p q r) ⬝ (con_tr (p ⬝ q) r u) ⬝ ap (transport P r) (con_tr p q u) = (con_tr p (q ⬝ r) u) ⬝ (con_tr q r (p ▸ u)) :> ((p ⬝ (q ⬝ r)) ▸ u = r ▸ q ▸ p ▸ u) := by induction r; induction q; induction p; reflexivity -- Here is another coherence lemma for transport. definition tr_inv_tr_lemma {P : A → Type} {x y : A} (p : x = y) (z : P x) : tr_inv_tr p (transport P p z) = ap (transport P p) (inv_tr_tr p z) := by induction p; reflexivity /- some properties for apdt -/ definition apdt_idp (x : A) (f : Πx, P x) : apdt f idp = idp :> (f x = f x) := idp definition apdt_con (f : Πx, P x) {x y z : A} (p : x = y) (q : y = z) : apdt f (p ⬝ q) = con_tr p q (f x) ⬝ ap (transport P q) (apdt f p) ⬝ apdt f q := by cases p; cases q; apply idp definition apdt_inv (f : Πx, P x) {x y : A} (p : x = y) : apdt f p⁻¹ = (eq_inv_tr_of_tr_eq (apdt f p))⁻¹ := by cases p; apply idp -- Dependent transport in a doubly dependent type. -- This is a special case of transporto in init.pathover definition transportD [unfold 6] {P : A → Type} (Q : Πa, P a → Type) {a a' : A} (p : a = a') (b : P a) (z : Q a b) : Q a' (p ▸ b) := by induction p; exact z -- In Coq the variables P, Q and b are explicit, but in Lean we can probably have them implicit -- using the following notation notation p ` ▸D `:65 x:64 := transportD _ p _ x -- transporting over 2 one-dimensional paths -- This is a special case of transporto in init.pathover definition transport11 {A B : Type} (P : A → B → Type) {a a' : A} {b b' : B} (p : a = a') (q : b = b') (z : P a b) : P a' b' := transport (P a') q (p ▸ z) -- Transporting along higher-dimensional paths definition transport2 [unfold 7] (P : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : P x) : p ▸ z = q ▸ z := ap (λp', p' ▸ z) r notation p ` ▸2 `:65 x:64 := transport2 _ p _ x -- An alternative definition. definition tr2_eq_ap10 (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r z = ap10 (ap (transport Q) r) z := by induction r; reflexivity definition tr2_con {P : A → Type} {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) (z : P x) : transport2 P (r1 ⬝ r2) z = transport2 P r1 z ⬝ transport2 P r2 z := by induction r1; induction r2; reflexivity definition tr2_inv (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r⁻¹ z = (transport2 Q r z)⁻¹ := by induction r; reflexivity definition transportD2 [unfold 7] {B C : A → Type} (D : Π(a:A), B a → C a → Type) {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z) : D x2 (p ▸ y) (p ▸ z) := by induction p; exact w notation p ` ▸D2 `:65 x:64 := transportD2 _ p _ _ x definition ap_tr_con_tr2 (P : A → Type) {x y : A} {p q : x = y} {z w : P x} (r : p = q) (s : z = w) : ap (transport P p) s ⬝ transport2 P r w = transport2 P r z ⬝ ap (transport P q) s := by induction r; exact !idp_con⁻¹ /- Transporting in particular fibrations -/ /- From the Coq HoTT library: One frequently needs lemmas showing that transport in a certain dependent type is equal to some more explicitly defined operation, defined according to the structure of that dependent type. For most dependent types, we prove these lemmas in the appropriate file in the types/ subdirectory. Here we consider only the most basic cases. -/ -- Transporting in a constant fibration. definition tr_constant (p : x = y) (z : B) : transport (λx, B) p z = z := by induction p; reflexivity definition tr2_constant {p q : x = y} (r : p = q) (z : B) : tr_constant p z = transport2 (λu, B) r z ⬝ tr_constant q z := by induction r; exact !idp_con⁻¹ -- Transporting in a pulled back fibration. definition tr_compose (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport (P ∘ f) p z = transport P (ap f p) z := by induction p; reflexivity definition tr_ap (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport P (ap f p) z = transport (P ∘ f) p z := (tr_compose P f p z)⁻¹ definition ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : ap (λh, h ∘ f) p = transport (λh : B → C, g ∘ f = h ∘ f) p idp := by induction p; reflexivity definition apd10_ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : apd10 (ap (λh : B → C, h ∘ f) p) = λa, apd10 p (f a) := by induction p; reflexivity definition apd10_ap_precompose_dependent {C : B → Type} (f : A → B) {g g' : Πb : B, C b} (p : g = g') : apd10 (ap (λ(h : (Πb : B, C b))(a : A), h (f a)) p) = λa, apd10 p (f a) := by induction p; reflexivity definition apd10_ap_postcompose (f : B → C) (g g' : A → B) (p : g = g') : apd10 (ap (λh : A → B, f ∘ h) p) = λa, ap f (apd10 p a) := by induction p; reflexivity -- A special case of [tr_compose] which seems to come up a lot. definition tr_eq_cast_ap {P : A → Type} {x y} (p : x = y) (u : P x) : p ▸ u = cast (ap P p) u := by induction p; reflexivity definition tr_eq_cast_ap_fn {P : A → Type} {x y} (p : x = y) : transport P p = cast (ap P p) := by induction p; reflexivity /- The behavior of [ap] and [apdt] -/ -- In a constant fibration, [apdt] reduces to [ap], modulo [transport_const]. definition apdt_eq_tr_constant_con_ap (f : A → B) (p : x = y) : apdt f p = tr_constant p (f x) ⬝ ap f p := by induction p; reflexivity /- The 2-dimensional groupoid structure -/ -- Horizontal composition of 2-dimensional paths. definition concat2 [unfold 9 10] {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q') : p ⬝ q = p' ⬝ q' := ap011 concat h h' -- 2-dimensional path inversion definition inverse2 [unfold 6] {p q : x = y} (h : p = q) : p⁻¹ = q⁻¹ := ap inverse h infixl ` ◾ `:80 := concat2 postfix [parsing_only] `⁻²`:(max+10) := inverse2 --this notation is abusive, should we use it? /- Whiskering -/ definition whisker_left [unfold 8] (p : x = y) {q r : y = z} (h : q = r) : p ⬝ q = p ⬝ r := idp ◾ h definition whisker_right [unfold 8] {p q : x = y} (r : y = z) (h : p = q) : p ⬝ r = q ⬝ r := h ◾ idp -- Unwhiskering, a.k.a. cancelling definition cancel_left {x y z : A} (p : x = y) {q r : y = z} : (p ⬝ q = p ⬝ r) → (q = r) := λs, !inv_con_cancel_left⁻¹ ⬝ whisker_left p⁻¹ s ⬝ !inv_con_cancel_left definition cancel_right {x y z : A} {p q : x = y} (r : y = z) : (p ⬝ r = q ⬝ r) → (p = q) := λs, !con_inv_cancel_right⁻¹ ⬝ whisker_right r⁻¹ s ⬝ !con_inv_cancel_right -- Whiskering and identity paths. definition whisker_right_idp {p q : x = y} (h : p = q) : whisker_right idp h = h := by induction h; induction p; reflexivity definition whisker_right_idp_left [unfold_full] (p : x = y) (q : y = z) : whisker_right q idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp_right [unfold_full] (p : x = y) (q : y = z) : whisker_left p idp = idp :> (p ⬝ q = p ⬝ q) := idp definition whisker_left_idp {p q : x = y} (h : p = q) : (idp_con p)⁻¹ ⬝ whisker_left idp h ⬝ idp_con q = h := by induction h; induction p; reflexivity definition whisker_left_idp2 {A : Type} {a : A} (p : idp = idp :> a = a) : whisker_left idp p = p := begin refine _ ⬝ whisker_left_idp p, exact !idp_con⁻¹ end definition con2_idp [unfold_full] {p q : x = y} (h : p = q) : h ◾ idp = whisker_right idp h :> (p ⬝ idp = q ⬝ idp) := idp definition idp_con2 [unfold_full] {p q : x = y} (h : p = q) : idp ◾ h = whisker_left idp h :> (idp ⬝ p = idp ⬝ q) := idp definition inv2_con2 {p p' : x = y} (h : p = p') : h⁻² ◾ h = con.left_inv p ⬝ (con.left_inv p')⁻¹ := by induction h; induction p; reflexivity -- The interchange law for concatenation. definition con2_con_con2 {p p' p'' : x = y} {q q' q'' : y = z} (a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') : a ◾ c ⬝ b ◾ d = (a ⬝ b) ◾ (c ⬝ d) := by induction d; induction c; induction b;induction a; reflexivity definition con2_eq_rl {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : a ◾ b = whisker_right q a ⬝ whisker_left p' b := by induction b; induction a; reflexivity definition con2_eq_lf {A : Type} {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : a ◾ b = whisker_left p b ⬝ whisker_right q' a := by induction b; induction a; reflexivity definition whisker_right_con_whisker_left {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : (whisker_right q a) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right q' a) := by induction b; induction a; reflexivity -- Structure corresponding to the coherence equations of a bicategory. -- The "pentagonator": the 3-cell witnessing the associativity pentagon. definition pentagon {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z) : whisker_left p (con.assoc' q r s) ⬝ con.assoc' p (q ⬝ r) s ⬝ whisker_right s (con.assoc' p q r) = con.assoc' p q (r ⬝ s) ⬝ con.assoc' (p ⬝ q) r s := by induction s;induction r;induction q;induction p;reflexivity -- The 3-cell witnessing the left unit triangle. definition triangulator (p : x = y) (q : y = z) : con.assoc' p idp q ⬝ whisker_right q (con_idp p) = whisker_left p (idp_con q) := by induction q; induction p; reflexivity definition eckmann_hilton (p q : idp = idp :> a = a) : p ⬝ q = q ⬝ p := begin refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _, refine !whisker_right_con_whisker_left ⬝ _, refine !whisker_left_idp2 ◾ !whisker_right_idp end definition con_eq_con2 (p q : idp = idp :> a = a) : p ⬝ q = p ◾ q := begin refine (whisker_right_idp p ◾ whisker_left_idp2 q)⁻¹ ⬝ _, exact !con2_eq_rl⁻¹ end definition inv_eq_inv2 (p : idp = idp :> a = a) : p⁻¹ = p⁻² := begin apply eq.cancel_right p, refine !con.left_inv ⬝ _, refine _ ⬝ !con_eq_con2⁻¹, exact !inv2_con2⁻¹, end -- The action of functions on 2-dimensional paths definition ap02 [unfold 8] [reducible] (f : A → B) {x y : A} {p q : x = y} (r : p = q) : ap f p = ap f q := ap (ap f) r definition ap02_con (f : A → B) {x y : A} {p p' p'' : x = y} (r : p = p') (r' : p' = p'') : ap02 f (r ⬝ r') = ap02 f r ⬝ ap02 f r' := by induction r; induction r'; reflexivity definition ap02_con2 (f : A → B) {x y z : A} {p p' : x = y} {q q' :y = z} (r : p = p') (s : q = q') : ap02 f (r ◾ s) = ap_con f p q ⬝ (ap02 f r ◾ ap02 f s) ⬝ (ap_con f p' q')⁻¹ := by induction r; induction s; induction q; induction p; reflexivity definition apdt02 [unfold 8] {p q : x = y} (f : Π x, P x) (r : p = q) : apdt f p = transport2 P r (f x) ⬝ apdt f q := by induction r; exact !idp_con⁻¹ end eq /- an auxillary namespace for concatenation and inversion for homotopies. We put this is a separate namespace because ⁻¹ʰ is also used as the inverse of a homomorphism -/ open eq namespace homotopy infix ` ⬝h `:75 := homotopy.trans postfix `⁻¹ʰ`:(max+1) := homotopy.symm end homotopy
eb0c211689177d77d8e61a60530ed5a18bb8ce7f
1dd482be3f611941db7801003235dc84147ec60a
/test/linarith.lean
bbd989a049ae90f60ace9f36fb232bda6359754a
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
3,593
lean
import tactic.linarith example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) : v0 + 5 + (v1 - 3) + (c - 2) = 10 := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε := by linarith example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0) (h3 : 12*y - z < 0) : false := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε := by linarith example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε := by linarith example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith {discharger := `[ring SOP]} example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false := by linarith example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false := by linarith {restrict_type := ℚ} example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0) (h5 : 0 ≤ c) (h6 : c < 1) : v ≤ V := by linarith example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z)) (h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) (h3 : 12*y - 4* z < 0) : false := by linarith example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) : ¬ 12*y - 4* z < 0 := by linarith example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0) (h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false := by linarith example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10) (h4 : a + b - c < 3) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false := by linarith example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 := by linarith {exfalso := ff} example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false := by linarith using [rat.num_pos_iff_pos.mpr hx] example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y := by linarith example (h1 : (1 : ℕ) < 1) : false := by linarith example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 := by linarith example (a b c : ℕ) : a + b ≥ a := by linarith example (a b c : ℕ) : ¬ a + b < a := by linarith example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0) (h'' : (6 + 3 * y) * y ≥ 0) : false := by linarith example (x y : ℕ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) : false := by linarith example (a b i : ℕ) (h1 : ¬ a < i) (h2 : b < i) (h3 : a ≤ b) : false := by linarith example (a b c : ℚ) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c := by linarith example (N : ℕ) (n : ℕ) (Hirrelevant : n > N) (A : ℚ) (l : ℚ) (h : A - l ≤ -(A - l)) (h_1 : ¬A ≤ -A) (h_2 : ¬l ≤ -l) (h_3 : -(A - l) < 1) : A < l + 1 := by linarith example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : d ≤ ((q : ℚ) - 1)*n := by linarith example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) : ((q : ℚ) - 1)*n - d = 1/3 * (((q : ℚ) - 1)*n) := by linarith
3692e2a4dc411c388b70476eab364b3374730c57
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/tactic/lean_core_docs.lean
ab5bb8aeab04131c20fc617ecbe88efb39ab3e94
[ "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
22,847
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Bryan Gin-ge Chen, Robert Y. Lewis, Scott Morrison -/ import tactic.doc_commands /-! # Core tactic documentation This file adds the majority of the interactive tactics from core Lean (i.e. pre-mathlib) to the API documentation. ## TODO * Make a PR to core changing core docstrings to the docstrings below, and also changing the docstrings of `cc`, `simp` and `conv` to the ones already in the API docs. * SMT tactics are currently not documented. * `rsimp` and `constructor_matching` are currently not documented. * `dsimp` deserves better documentation. -/ add_tactic_doc { name := "abstract", category := doc_category.tactic, decl_names := [`tactic.interactive.abstract], tags := ["core", "proof extraction"] } /-- Proves a goal of the form `s = t` when `s` and `t` are expressions built up out of a binary operation, and equality can be proved using associativity and commutativity of that operation. -/ add_tactic_doc { name := "ac_refl", category := doc_category.tactic, decl_names := [`tactic.interactive.ac_refl, `tactic.interactive.ac_reflexivity], tags := ["core", "lemma application", "finishing"] } add_tactic_doc { name := "all_goals", category := doc_category.tactic, decl_names := [`tactic.interactive.all_goals], tags := ["core", "goal management"] } add_tactic_doc { name := "any_goals", category := doc_category.tactic, decl_names := [`tactic.interactive.any_goals], tags := ["core", "goal management"] } add_tactic_doc { name := "apply", category := doc_category.tactic, decl_names := [`tactic.interactive.apply], tags := ["core", "basic", "lemma application"] } add_tactic_doc { name := "apply_auto_param", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_auto_param], tags := ["core", "lemma application"] } add_tactic_doc { name := "apply_instance", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_instance], tags := ["core", "type class"] } add_tactic_doc { name := "apply_opt_param", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_opt_param], tags := ["core", "lemma application"] } add_tactic_doc { name := "apply_with", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_with], tags := ["core", "lemma application"] } add_tactic_doc { name := "assume", category := doc_category.tactic, decl_names := [`tactic.interactive.assume], tags := ["core", "logic"] } add_tactic_doc { name := "assumption", category := doc_category.tactic, decl_names := [`tactic.interactive.assumption], tags := ["core", "basic", "finishing"] } add_tactic_doc { name := "assumption'", category := doc_category.tactic, decl_names := [`tactic.interactive.assumption'], tags := ["core", "goal management"] } add_tactic_doc { name := "async", category := doc_category.tactic, decl_names := [`tactic.interactive.async], tags := ["core", "goal management", "combinator", "proof extraction"] } /-- `by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax `by_cases h : p`. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `open_locale classical` (or `local attribute [instance, priority 10] classical.prop_decidable` if you are not using mathlib). -/ add_tactic_doc { name := "by_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.by_cases], tags := ["core", "basic", "logic", "case bashing"] } /-- If the target of the main goal is a proposition `p`, `by_contra h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `open_locale classical` (or `local attribute [instance, priority 10] classical.prop_decidable` if you are not using mathlib). -/ add_tactic_doc { name := "by_contra / by_contradiction", category := doc_category.tactic, decl_names := [`tactic.interactive.by_contra, `tactic.interactive.by_contradiction], tags := ["core", "logic"] } add_tactic_doc { name := "case", category := doc_category.tactic, decl_names := [`tactic.interactive.case], tags := ["core", "goal management"] } add_tactic_doc { name := "cases", category := doc_category.tactic, decl_names := [`tactic.interactive.cases], tags := ["core", "basic", "induction"] } /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` is a more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. `casesm` is shorthand for `cases_matching`. Example: The following tactic destructs all conjunctions and disjunctions in the current context. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ add_tactic_doc { name := "cases_matching / casesm", category := doc_category.tactic, decl_names := [`tactic.interactive.cases_matching, `tactic.interactive.casesm], tags := ["core", "induction", "context management"] } /-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current context. ``` cases_type* or and ``` -/ add_tactic_doc { name := "cases_type", category := doc_category.tactic, decl_names := [`tactic.interactive.cases_type], tags := ["core", "induction", "context management"] } add_tactic_doc { name := "change", category := doc_category.tactic, decl_names := [`tactic.interactive.change], tags := ["core", "basic", "renaming"] } add_tactic_doc { name := "clear", category := doc_category.tactic, decl_names := [`tactic.interactive.clear], tags := ["core", "context management"] } /-- Close goals of the form `n ≠ m` when `n` and `m` have type `nat`, `char`, `string`, `int` or `fin sz`, and they are literals. It also closes goals of the form `n < m`, `n > m`, `n ≤ m` and `n ≥ m` for `nat`. If the goal is of the form `n = m`, then it tries to close it using reflexivity. In mathlib, consider using `norm_num` instead for numeric types. -/ add_tactic_doc { name := "comp_val", category := doc_category.tactic, decl_names := [`tactic.interactive.comp_val], tags := ["core", "arithmetic"] } /-- The `congr` tactic attempts to identify both sides of an equality goal `A = B`, leaving as new goals the subterms of `A` and `B` which are not definitionally equal. Example: suppose the goal is `x * f y = g w * f z`. Then `congr` will produce two goals: `x = g w` and `y = z`. Note that `congr` can be over-aggressive at times; the `congr'` tactic in mathlib provides a more refined approach, by taking a parameter that limits the recursion depth. -/ add_tactic_doc { name := "congr", category := doc_category.tactic, decl_names := [`tactic.interactive.congr], tags := ["core", "congruence"] } add_tactic_doc { name := "constructor", category := doc_category.tactic, decl_names := [`tactic.interactive.constructor], tags := ["core", "logic"] } add_tactic_doc { name := "contradiction", category := doc_category.tactic, decl_names := [`tactic.interactive.contradiction], tags := ["core", "basic", "finishing"] } add_tactic_doc { name := "delta", category := doc_category.tactic, decl_names := [`tactic.interactive.delta], tags := ["core", "simplification"] } add_tactic_doc { name := "destruct", category := doc_category.tactic, decl_names := [`tactic.interactive.destruct], tags := ["core", "induction"] } add_tactic_doc { name := "done", category := doc_category.tactic, decl_names := [`tactic.interactive.done], tags := ["core", "goal management"] } add_tactic_doc { name := "dsimp", category := doc_category.tactic, decl_names := [`tactic.interactive.dsimp], tags := ["core", "simplification"] } add_tactic_doc { name := "dunfold", category := doc_category.tactic, decl_names := [`tactic.interactive.dunfold], tags := ["core", "simplification"] } add_tactic_doc { name := "eapply", category := doc_category.tactic, decl_names := [`tactic.interactive.eapply], tags := ["core", "lemma application"] } add_tactic_doc { name := "econstructor", category := doc_category.tactic, decl_names := [`tactic.interactive.econstructor], tags := ["core", "logic"] } /-- A variant of `rw` that uses the unifier more aggressively, unfolding semireducible definitions. -/ add_tactic_doc { name := "erewrite / erw", category := doc_category.tactic, decl_names := [`tactic.interactive.erewrite, `tactic.interactive.erw], tags := ["core", "rewriting"] } add_tactic_doc { name := "exact", category := doc_category.tactic, decl_names := [`tactic.interactive.exact], tags := ["core", "basic", "finishing"] } add_tactic_doc { name := "exacts", category := doc_category.tactic, decl_names := [`tactic.interactive.exacts], tags := ["core", "finishing"] } add_tactic_doc { name := "exfalso", category := doc_category.tactic, decl_names := [`tactic.interactive.exfalso], tags := ["core", "basic", "logic"] } /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. Note: in mathlib, the `use` tactic is an equivalent tactic which sometimes is smarter with unification. -/ add_tactic_doc { name := "existsi", category := doc_category.tactic, decl_names := [`tactic.interactive.existsi], tags := ["core", "logic"] } add_tactic_doc { name := "fail_if_success", category := doc_category.tactic, decl_names := [`tactic.interactive.fail_if_success], tags := ["core", "testing", "combinator"] } add_tactic_doc { name := "fapply", category := doc_category.tactic, decl_names := [`tactic.interactive.fapply], tags := ["core", "lemma application"] } add_tactic_doc { name := "focus", category := doc_category.tactic, decl_names := [`tactic.interactive.focus], tags := ["core", "goal management", "combinator"] } add_tactic_doc { name := "from", category := doc_category.tactic, decl_names := [`tactic.interactive.from], tags := ["core", "finishing"] } /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. Note also the mathlib tactic `ext`, which applies as many extensionality lemmas as possible. -/ add_tactic_doc { name := "funext", category := doc_category.tactic, decl_names := [`tactic.interactive.funext], tags := ["core", "logic"] } add_tactic_doc { name := "generalize", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize], tags := ["core", "context management"] } add_tactic_doc { name := "guard_hyp", category := doc_category.tactic, decl_names := [`tactic.interactive.guard_hyp], tags := ["core", "testing", "context management"] } add_tactic_doc { name := "guard_target", category := doc_category.tactic, decl_names := [`tactic.interactive.guard_target], tags := ["core", "testing", "goal management"] } add_tactic_doc { name := "have", category := doc_category.tactic, decl_names := [`tactic.interactive.have], tags := ["core", "basic", "context management"] } add_tactic_doc { name := "induction", category := doc_category.tactic, decl_names := [`tactic.interactive.induction], tags := ["core", "basic", "induction"] } add_tactic_doc { name := "injection", category := doc_category.tactic, decl_names := [`tactic.interactive.injection], tags := ["core", "structures", "induction"] } add_tactic_doc { name := "injections", category := doc_category.tactic, decl_names := [`tactic.interactive.injections], tags := ["core", "structures", "induction"] } /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. The variant `intro z` uses the identifier `z` to name the new hypothesis. The variant `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ add_tactic_doc { name := "intro / intros", category := doc_category.tactic, decl_names := [`tactic.interactive.intro, `tactic.interactive.intros], tags := ["core", "basic", "logic"] } add_tactic_doc { name := "introv", category := doc_category.tactic, decl_names := [`tactic.interactive.introv], tags := ["core", "logic"] } add_tactic_doc { name := "iterate", category := doc_category.tactic, decl_names := [`tactic.interactive.iterate], tags := ["core", "combinator"] } /-- `left` applies the first constructor when the type of the target is an inductive data type with two constructors. Similarly, `right` applies the second constructor. -/ add_tactic_doc { name := "left / right", category := doc_category.tactic, decl_names := [`tactic.interactive.left, `tactic.interactive.right], tags := ["core", "basic", "logic"] } /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. Note the related mathlib tactic `set a := t with h`, which adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. -/ add_tactic_doc { name := "let", category := doc_category.tactic, decl_names := [`tactic.interactive.let], tags := ["core", "basic", "logic", "context management"] } add_tactic_doc { name := "mapply", category := doc_category.tactic, decl_names := [`tactic.interactive.mapply], tags := ["core", "lemma application"] } add_tactic_doc { name := "match_target", category := doc_category.tactic, decl_names := [`tactic.interactive.match_target], tags := ["core", "testing", "goal management"] } add_tactic_doc { name := "refine", category := doc_category.tactic, decl_names := [`tactic.interactive.refine], tags := ["core", "basic", "lemma application"] } /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ add_tactic_doc { name := "refl / reflexivity", category := doc_category.tactic, decl_names := [`tactic.interactive.refl, `tactic.interactive.reflexivity], tags := ["core", "basic", "finishing"] } add_tactic_doc { name := "rename", category := doc_category.tactic, decl_names := [`tactic.interactive.rename], tags := ["core", "renaming"] } add_tactic_doc { name := "repeat", category := doc_category.tactic, decl_names := [`tactic.interactive.repeat], tags := ["core", "combinator"] } add_tactic_doc { name := "revert", category := doc_category.tactic, decl_names := [`tactic.interactive.revert], tags := ["core", "context management", "goal management"] } /-- `rw e` applies an equation or iff `e` as a rewrite rule to the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rw [e₁, ..., eₙ]` applies the given rules sequentially. `rw e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. `rewrite` is synonymous with `rw`. -/ add_tactic_doc { name := "rw / rewrite", category := doc_category.tactic, decl_names := [`tactic.interactive.rw, `tactic.interactive.rewrite], tags := ["core", "basic", "rewriting"] } add_tactic_doc { name := "rwa", category := doc_category.tactic, decl_names := [`tactic.interactive.rwa], tags := ["core", "rewriting"] } add_tactic_doc { name := "show", category := doc_category.tactic, decl_names := [`tactic.interactive.show], tags := ["core", "goal management", "renaming"] } add_tactic_doc { name := "simp_intros", category := doc_category.tactic, decl_names := [`tactic.interactive.simp_intros], tags := ["core", "simplification"] } add_tactic_doc { name := "skip", category := doc_category.tactic, decl_names := [`tactic.interactive.skip], tags := ["core", "combinator"] } add_tactic_doc { name := "solve1", category := doc_category.tactic, decl_names := [`tactic.interactive.solve1], tags := ["core", "combinator", "goal management"] } add_tactic_doc { name := "sorry / admit", category := doc_category.tactic, decl_names := [`tactic.interactive.sorry, `tactic.interactive.admit], inherit_description_from := `tactic.interactive.sorry, tags := ["core", "testing", "debugging"] } add_tactic_doc { name := "specialize", category := doc_category.tactic, decl_names := [`tactic.interactive.specialize], tags := ["core", "hypothesis management", "lemma application"] } add_tactic_doc { name := "split", category := doc_category.tactic, decl_names := [`tactic.interactive.split], tags := ["core", "basic", "logic"] } add_tactic_doc { name := "subst", category := doc_category.tactic, decl_names := [`tactic.interactive.subst], tags := ["core", "rewriting"] } add_tactic_doc { name := "subst_vars", category := doc_category.tactic, decl_names := [`tactic.interactive.subst_vars], tags := ["core", "rewriting"] } add_tactic_doc { name := "success_if_fail", category := doc_category.tactic, decl_names := [`tactic.interactive.success_if_fail], tags := ["core", "testing", "combinator"] } add_tactic_doc { name := "suffices", category := doc_category.tactic, decl_names := [`tactic.interactive.suffices], tags := ["core", "basic", "goal management"] } add_tactic_doc { name := "symmetry", category := doc_category.tactic, decl_names := [`tactic.interactive.symmetry], tags := ["core", "basic", "lemma application"] } add_tactic_doc { name := "trace", category := doc_category.tactic, decl_names := [`tactic.interactive.trace], tags := ["core", "debugging", "testing"] } add_tactic_doc { name := "trace_simp_set", category := doc_category.tactic, decl_names := [`tactic.interactive.trace_simp_set], tags := ["core", "debugging", "testing"] } add_tactic_doc { name := "trace_state", category := doc_category.tactic, decl_names := [`tactic.interactive.trace_state], tags := ["core", "debugging", "testing"] } add_tactic_doc { name := "transitivity", category := doc_category.tactic, decl_names := [`tactic.interactive.transitivity], tags := ["core", "lemma application"] } add_tactic_doc { name := "trivial", category := doc_category.tactic, decl_names := [`tactic.interactive.trivial], tags := ["core", "finishing"] } add_tactic_doc { name := "try", category := doc_category.tactic, decl_names := [`tactic.interactive.try], tags := ["core", "combinator"] } add_tactic_doc { name := "type_check", category := doc_category.tactic, decl_names := [`tactic.interactive.type_check], tags := ["core", "debugging", "testing"] } add_tactic_doc { name := "unfold", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold], tags := ["core", "basic", "rewriting"] } add_tactic_doc { name := "unfold1", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold1], tags := ["core", "rewriting"] } add_tactic_doc { name := "unfold_projs", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold_projs], tags := ["core", "rewriting"] } add_tactic_doc { name := "with_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.with_cases], tags := ["core", "combinator"] }
9a84302db9d0c67c8d59168f8f7bf52786abf1a2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Config/FacetConfig.lean
36632967ed4bc0e37a7dfaea7b88824b34278346
[ "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,714
lean
/- Copyright (c) 2022 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone, Mario Carneiro -/ import Lake.Build.Info import Lake.Build.Store namespace Lake /-- A facet's declarative configuration. -/ structure FacetConfig (DataFam : Name → Type) (ι : Type) (name : Name) : Type where /-- The facet's build (function). -/ build : ι → IndexBuildM (DataFam name) /-- Does this facet produce an associated asynchronous job? -/ getJob? : Option (DataFam name → BuildJob Unit) deriving Inhabited protected abbrev FacetConfig.name (_ : FacetConfig DataFam ι name) := name /-- A smart constructor for facet configurations that are not known to generate targets. -/ @[inline] def mkFacetConfig (build : ι → IndexBuildM α) [h : FamilyOut Fam facet α] : FacetConfig Fam ι facet where build := cast (by rw [← h.family_key_eq_type]) build getJob? := none /-- A smart constructor for facet configurations that generate jobs for the CLI. This is for small jobs that do not the increase the progress counter. -/ @[inline] def mkFacetJobConfigSmall (build : ι → IndexBuildM (BuildJob α)) [h : FamilyOut Fam facet (BuildJob α)] : FacetConfig Fam ι facet where build := cast (by rw [← h.family_key_eq_type]) build getJob? := some fun data => discard <| ofFamily data /-- A smart constructor for facet configurations that generate jobs for the CLI. -/ @[inline] def mkFacetJobConfig (build : ι → IndexBuildM (BuildJob α)) [FamilyOut Fam facet (BuildJob α)] : FacetConfig Fam ι facet := mkFacetJobConfigSmall fun i => do let ctx ← readThe BuildContext ctx.startedBuilds.modify (·+1) let job ← build i job.bindSync (prio := .default + 1) fun a trace => do ctx.finishedBuilds.modify (·+1) return (a, trace) /-- A dependently typed configuration based on its registered name. -/ structure NamedConfigDecl (β : Name → Type u) where name : Name config : β name /-- A module facet's declarative configuration. -/ abbrev ModuleFacetConfig := FacetConfig ModuleData Module /-- A module facet declaration from a configuration file. -/ abbrev ModuleFacetDecl := NamedConfigDecl ModuleFacetConfig /-- A package facet's declarative configuration. -/ abbrev PackageFacetConfig := FacetConfig PackageData Package /-- A package facet declaration from a configuration file. -/ abbrev PackageFacetDecl := NamedConfigDecl PackageFacetConfig /-- A library facet's declarative configuration. -/ abbrev LibraryFacetConfig := FacetConfig LibraryData LeanLib /-- A library facet declaration from a configuration file. -/ abbrev LibraryFacetDecl := NamedConfigDecl LibraryFacetConfig
0e234423fa5017f83bbe98f36fcb1b46c0ab355e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/ideal/over.lean
9d4b4d8eab0a12aca569bc5725e0a35ce39ffd92
[ "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,588
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.algebraic import ring_theory.localization /-! # Ideals over/under ideals This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ variables {R : Type*} [comm_ring R] namespace ideal open polynomial open submodule section comm_ring variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma coeff_zero_mem_comap_of_root_mem_of_eval_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r ∈ I) : p.coeff 0 ∈ I.comap f := begin rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp, refine mem_comap.mpr ((I.add_mem_iff_right _).mp hp), exact I.mul_mem_left _ hr end lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (hp.symm ▸ I.zero_mem) lemma exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {r : S} (r_non_zero_divisor : ∀ {x}, x * r = 0 → x = 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := begin refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp, refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩, simp [coeff_eq_zero, a_ne_zero] }, { intros p p_nonzero ih mul_nonzero hp, rw [eval₂_mul, eval₂_X] at hp, obtain ⟨i, hi, mem⟩ := ih p_nonzero (r_non_zero_divisor hp), refine ⟨i + 1, _, _⟩; simp [hi, mem] } end /-- Let `P` be an ideal in `R[x]`. The map `R[x]/P → (R / (P ∩ R))[x] / (P / (P ∩ R))` is injective. -/ lemma injective_quotient_le_comap_map (P : ideal (polynomial R)) : function.injective ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map) := begin refine quotient_map_injective' (le_of_eq _), rw comap_map_of_surjective (map_ring_hom (quotient.mk (P.comap C))) (map_surjective _ quotient.mk_surjective), refine le_antisymm (sup_le le_rfl _) (le_sup_of_le_left le_rfl), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using ext_iff.mp (ideal.mem_bot.mp (mem_comap.mp hp)) n, end /-- The identity in this lemma asserts that the "obvious" square ``` R → (R / (P ∩ R)) ↓ ↓ R[x] / P → (R / (P ∩ R))[x] / (P / (P ∩ R)) ``` commutes. It is used, for instance, in the proof of `quotient_mk_comp_C_is_integral_of_jacobson`, in the file `ring_theory/jacobson`. -/ lemma quotient_mk_maps_eq (P : ideal (polynomial R)) : ((quotient.mk (map (map_ring_hom (quotient.mk (P.comap C))) P)).comp C).comp (quotient.mk (P.comap C)) = ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map).comp ((quotient.mk P).comp C) := begin refine ring_hom.ext (λ x, _), repeat { rw [ring_hom.coe_comp, function.comp_app] }, rw [quotient_map_mk, coe_map_ring_hom, map_C], end /-- This technical lemma asserts the existence of a polynomial `p` in an ideal `P ⊂ R[x]` that is non-zero in the quotient `R / (P ∩ R) [x]`. The assumptions are equivalent to `P ≠ 0` and `P ∩ R = (0)`. -/ lemma exists_nonzero_mem_of_ne_bot {P : ideal (polynomial R)} (Pb : P ≠ ⊥) (hP : ∀ (x : R), C x ∈ P → x = 0) : ∃ p : polynomial R, p ∈ P ∧ (polynomial.map (quotient.mk (P.comap C)) p) ≠ 0 := begin obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr Pb), refine ⟨m, submodule.coe_mem m, λ pp0, hm (submodule.coe_eq_zero.mp _)⟩, refine (is_add_group_hom.injective_iff (polynomial.map (quotient.mk (P.comap C)))).mp _ _ pp0, refine map_injective _ ((quotient.mk (P.comap C)).injective_iff_ker_eq_bot.mpr _), rw [mk_ker], exact (submodule.eq_bot_iff _).mpr (λ x hx, hP x (mem_comap.mp hx)), end end comm_ring section integral_domain variables {S : Type*} [integral_domain S] {f : R →+* S} {I J : ideal S} lemma exists_coeff_ne_zero_mem_comap_of_root_mem {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (λ _ h, or.resolve_right (mul_eq_zero.mp h) r_ne_zero) hr lemma exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hpI : p.eval₂ f r ∈ I) : ∃ i, p.coeff i ∈ (J.comap f : set R) \ (I.comap f) := begin obtain ⟨hrJ, hrI⟩ := hr, have rbar_ne_zero : quotient.mk I r ≠ 0 := mt (quotient.mk_eq_zero I).mp hrI, have rbar_mem_J : quotient.mk I r ∈ J.map (quotient.mk I) := mem_map_of_mem _ hrJ, have quotient_f : ∀ x ∈ I.comap f, (quotient.mk I).comp f x = 0, { simp [quotient.eq_zero_iff_mem] }, have rbar_root : (p.map (quotient.mk (I.comap f))).eval₂ (quotient.lift (I.comap f) _ quotient_f) (quotient.mk I r) = 0, { convert quotient.eq_zero_iff_mem.mpr hpI, exact trans (eval₂_map _ _ _) (hom_eval₂ p f (quotient.mk I) r).symm }, obtain ⟨i, ne_zero, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem rbar_ne_zero rbar_mem_J p_ne_zero rbar_root, rw coeff_map at ne_zero mem, refine ⟨i, (mem_quotient_iff_mem hIJ).mp _, mt _ ne_zero⟩, { simpa using mem }, simp [quotient.eq_zero_iff_mem], end lemma comap_ne_bot_of_root_mem {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) : I.comap f ≠ ⊥ := λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in absurd (mem_bot.mp (eq_bot_iff.mp h mem)) hi lemma comap_lt_comap_of_root_mem_sdiff [I.is_prime] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hp : p.eval₂ f r ∈ I) : I.comap f < J.comap f := let ⟨i, hJ, hI⟩ := exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff hIJ hr p_ne_zero hp in set_like.lt_iff_le_and_exists.mpr ⟨comap_mono hIJ, p.coeff i, hJ, hI⟩ variables [algebra R S] lemma comap_ne_bot_of_algebraic_mem {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ := let ⟨p, p_ne_zero, hp⟩ := hx in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp lemma comap_ne_bot_of_integral_mem [nontrivial R] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R) lemma eq_bot_of_comap_eq_bot [nontrivial R] (hRS : algebra.is_integral R S) (hI : I.comap (algebra_map R S) = ⊥) : I = ⊥ := begin refine eq_bot_iff.2 (λ x hx, _), by_cases hx0 : x = 0, { exact hx0.symm ▸ ideal.zero_mem ⊥ }, { exact absurd hI (comap_ne_bot_of_integral_mem hx0 hx (hRS x)) } end lemma mem_of_one_mem (h : (1 : S) ∈ I) (x) : x ∈ I := (I.eq_top_iff_one.mpr h).symm ▸ mem_top lemma comap_lt_comap_of_integral_mem_sdiff [hI : I.is_prime] (hIJ : I ≤ J) {x : S} (mem : x ∈ (J : set S) \ I) (integral : is_integral R x) : I.comap (algebra_map R S) < J.comap (algebra_map _ _) := begin obtain ⟨p, p_monic, hpx⟩ := integral, refine comap_lt_comap_of_root_mem_sdiff hIJ mem _ _, swap, { apply map_monic_ne_zero p_monic, apply quotient.nontrivial, apply mt comap_eq_top_iff.mp, apply hI.1 }, convert I.zero_mem end lemma is_maximal_of_is_integral_of_is_maximal_comap (hRS : algebra.is_integral R S) (I : ideal S) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R S))) : is_maximal I := ⟨⟨mt comap_eq_top_iff.mpr hI.1.1, λ J I_lt_J, let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_eq_top_iff.1 $ hI.1.2 _ (comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (hRS x))⟩⟩ lemma is_maximal_of_is_integral_of_is_maximal_comap' {R S : Type*} [comm_ring R] [integral_domain S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) [hI' : I.is_prime] (hI : is_maximal (I.comap f)) : is_maximal I := @is_maximal_of_is_integral_of_is_maximal_comap R _ S _ f.to_algebra hf I hI' hI lemma is_maximal_comap_of_is_integral_of_is_maximal (hRS : algebra.is_integral R S) (I : ideal S) [hI : I.is_maximal] : is_maximal (I.comap (algebra_map R S)) := begin refine quotient.maximal_of_is_field _ _, haveI : is_prime (I.comap (algebra_map R S)) := comap_is_prime _ _, exact is_field_of_is_integral_of_is_field (is_integral_quotient_of_is_integral hRS) algebra_map_quotient_injective (by rwa ← quotient.maximal_ideal_iff_is_field_quotient), end lemma is_maximal_comap_of_is_integral_of_is_maximal' {R S : Type*} [comm_ring R] [integral_domain S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) (hI : I.is_maximal) : is_maximal (I.comap f) := @is_maximal_comap_of_is_integral_of_is_maximal R _ S _ f.to_algebra hf I hI lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ := let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in comap_ne_bot_of_integral_mem x_ne_zero x_mem (integral_closure.is_integral x) lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} : I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ := imp_of_not_imp_not _ _ integral_closure.comap_ne_bot lemma integral_closure.comap_lt_comap {I J : ideal (integral_closure R S)} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R (integral_closure R S)) < J.comap (algebra_map _ _) := let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (integral_closure.is_integral x) lemma integral_closure.is_maximal_of_is_maximal_comap (I : ideal (integral_closure R S)) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R (integral_closure R S)))) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (λ x, integral_closure.is_integral x) I hI /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_prime_of_is_integral' (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ Q.comap (algebra_map R S) = P := begin have hP0 : (0 : S) ∉ algebra.algebra_map_submonoid S P.prime_compl, { rintro ⟨x, ⟨hx, x0⟩⟩, exact absurd (hP x0) hx }, let Rₚ := localization P.prime_compl, let f := localization.of P.prime_compl, let Sₚ := localization (algebra.algebra_map_submonoid S P.prime_compl), let g := localization.of (algebra.algebra_map_submonoid S P.prime_compl), letI : integral_domain (localization (algebra.algebra_map_submonoid S P.prime_compl)) := localization_map.integral_domain_localization (le_non_zero_divisors_of_domain hP0), obtain ⟨Qₚ : ideal Sₚ, Qₚ_maximal⟩ := exists_maximal Sₚ, haveI Qₚ_max : is_maximal (comap _ Qₚ) := @is_maximal_comap_of_is_integral_of_is_maximal Rₚ _ Sₚ _ (localization_algebra P.prime_compl f g) (is_integral_localization f g H) _ Qₚ_maximal, refine ⟨comap g.to_map Qₚ, ⟨comap_is_prime g.to_map Qₚ, _⟩⟩, convert localization.at_prime.comap_maximal_ideal, rw [comap_comap, ← local_ring.eq_maximal_ideal Qₚ_max, ← f.map_comp _], refl end /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : I.comap (algebra_map R S) ≤ P) : ∃ Q ≥ I, is_prime Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q' : ideal I.quotient, ⟨Q'_prime, hQ'⟩⟩ := @exists_ideal_over_prime_of_is_integral' (I.comap (algebra_map R S)).quotient _ I.quotient _ ideal.quotient_algebra (is_integral_quotient_of_is_integral H) (map (quotient.mk (I.comap (algebra_map R S))) P) (map_is_prime_of_surjective quotient.mk_surjective (by simp [hIP])) (le_trans (le_of_eq ((ring_hom.injective_iff_ker_eq_bot _).1 algebra_map_quotient_injective)) bot_le), haveI := Q'_prime, refine ⟨Q'.comap _, le_trans (le_of_eq mk_ker.symm) (ker_le_comap _), ⟨comap_is_prime _ Q', _⟩⟩, rw comap_comap, refine trans _ (trans (congr_arg (comap (quotient.mk (comap (algebra_map R S) I))) hQ') _), { simpa [comap_comap] }, { refine trans (comap_map_of_surjective _ quotient.mk_surjective _) (sup_eq_left.2 _), simpa [← ring_hom.ker_eq_comap_bot] using hIP}, end /-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_maximal_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [P_max : is_maximal P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_maximal Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q, ⟨Q_prime, hQ⟩⟩ := exists_ideal_over_prime_of_is_integral' H P hP, haveI : Q.is_prime := Q_prime, exact ⟨Q, is_maximal_of_is_integral_of_is_maximal_comap H _ (hQ.symm ▸ P_max), hQ⟩, end end integral_domain end ideal
3f03f873b8deb98a7bc16dbcae4c351f9d60ba26
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo1994_q1.lean
89b584ee3ebce936a67af877a5aa5309682efc16
[ "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
4,287
lean
/- Copyright (c) 2021 Antoine Labelle. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Labelle -/ import algebra.big_operators.basic import algebra.big_operators.order import data.fintype.big_operators import data.finset.sort import data.fin.interval import tactic.linarith import tactic.by_contra /-! # IMO 1994 Q1 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `m` and `n` be two positive integers. Let `a₁, a₂, ..., aₘ` be `m` different numbers from the set `{1, 2, ..., n}` such that for any two indices `i` and `j` with `1 ≤ i ≤ j ≤ m` and `aᵢ + aⱼ ≤ n`, there exists an index `k` such that `aᵢ + aⱼ = aₖ`. Show that `(a₁+a₂+...+aₘ)/m ≥ (n+1)/2` # Sketch of solution We can order the numbers so that `a₁ ≤ a₂ ≤ ... ≤ aₘ`. The key idea is to pair the numbers in the sum and show that `aᵢ + aₘ₊₁₋ᵢ ≥ n+1`. Indeed, if we had `aᵢ + aₘ₊₁₋ᵢ ≤ n`, then `a₁ + aₘ₊₁₋ᵢ, a₂ + aₘ₊₁₋ᵢ, ..., aᵢ + aₘ₊₁₋ᵢ` would be `m` elements of the set of `aᵢ`'s all larger than `aₘ₊₁₋ᵢ`, which is impossible. -/ open_locale big_operators open finset namespace imo1994_q1 lemma tedious (m : ℕ) (k : fin (m+1)) : m - (m + (m + 1 - ↑k)) % (m + 1) = ↑k := begin cases k with k hk, rw [nat.lt_succ_iff, le_iff_exists_add] at hk, rcases hk with ⟨c, rfl⟩, have : k + c + (k + c + 1 - k) = c + (k + c + 1), { simp only [add_assoc, add_tsub_cancel_left, add_left_comm] }, rw [fin.coe_mk, this, nat.add_mod_right, nat.mod_eq_of_lt, nat.add_sub_cancel], linarith end end imo1994_q1 open imo1994_q1 theorem imo1994_q1 (n : ℕ) (m : ℕ) (A : finset ℕ) (hm : A.card = m + 1) (hrange : ∀ a ∈ A, 0 < a ∧ a ≤ n) (hadd : ∀ (a b ∈ A), a + b ≤ n → a + b ∈ A) : (m + 1) * (n + 1) ≤ 2 * ∑ x in A, x := begin set a := order_emb_of_fin A hm, -- We sort the elements of `A` have ha : ∀ i, a i ∈ A := λ i, order_emb_of_fin_mem A hm i, set rev := equiv.sub_left (fin.last m), -- `i ↦ m-i` -- We reindex the sum by fin (m+1) have : ∑ x in A, x = ∑ i : fin (m+1), a i, { convert sum_image (λ x hx y hy, (order_embedding.eq_iff_eq a).1), rw ←coe_inj, simp }, rw this, clear this, -- The main proof is a simple calculation by rearranging one of the two sums suffices hpair : ∀ k ∈ univ, a k + a (rev k) ≥ n+1, calc 2 * ∑ i : fin (m+1), a i = ∑ i : fin (m+1), a i + ∑ i : fin (m+1), a i : two_mul _ ... = ∑ i : fin (m+1), a i + ∑ i : fin (m+1), a (rev i) : by rw equiv.sum_comp rev ... = ∑ i : fin (m+1), (a i + a (rev i)) : sum_add_distrib.symm ... ≥ ∑ i : fin (m+1), (n+1) : sum_le_sum hpair ... = (m+1) * (n+1) : by rw [sum_const, card_fin, nat.nsmul_eq_mul], -- It remains to prove the key inequality, by contradiction rintros k -, by_contra' h : a k + a (rev k) < n + 1, -- We exhibit `k+1` elements of `A` greater than `a (rev k)` set f : fin (m+1) ↪ ℕ := ⟨λ i, a i + a (rev k), begin apply injective_of_le_imp_le, intros i j hij, rwa [add_le_add_iff_right, a.map_rel_iff] at hij, end⟩, -- Proof that the `f i` are greater than `a (rev k)` for `i ≤ k` have hf : map f (Icc 0 k) ⊆ map a.to_embedding (Ioc (rev k) (fin.last m)), { intros x hx, simp only [equiv.sub_left_apply] at h, simp only [mem_map, f, mem_Icc, mem_Ioc, fin.zero_le, true_and, equiv.sub_left_apply, function.embedding.coe_fn_mk, exists_prop, rel_embedding.coe_fn_to_embedding] at hx ⊢, rcases hx with ⟨i, ⟨hi, rfl⟩⟩, have h1 : a i + a (fin.last m - k) ≤ n, { linarith only [h, a.monotone hi] }, have h2 : a i + a (fin.last m - k) ∈ A := hadd _ (ha _) _ (ha _) h1, rw [←mem_coe, ←range_order_emb_of_fin A hm, set.mem_range] at h2, cases h2 with j hj, refine ⟨j, ⟨_, fin.le_last j⟩, hj⟩, rw [← a.strict_mono.lt_iff_lt, hj], simpa using (hrange (a i) (ha i)).1 }, -- A set of size `k+1` embed in one of size `k`, which yields a contradiction simpa [fin.coe_sub, tedious] using card_le_of_subset hf, end
fd84d0a4479426e5c5f39848beb5051a25c760ce
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/polynomial/basic.lean
95d18e95b496f15e3c5c8573505963c9bb8eeff2
[ "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
43,802
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p.basic import data.mv_polynomial.comm_ring import data.mv_polynomial.equiv import ring_theory.principal_ideal_domain import ring_theory.polynomial.content /-! # Ring-theoretic supplement of data.polynomial. ## Main results * `mv_polynomial.integral_domain`: If a ring is an integral domain, then so is its polynomial ring over finitely many variables. * `polynomial.is_noetherian_ring`: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. * `polynomial.wf_dvd_monoid`: If an integral domain is a `wf_dvd_monoid`, then so is its polynomial ring. * `polynomial.unique_factorization_monoid`: If an integral domain is a `unique_factorization_monoid`, then so is its polynomial ring. -/ noncomputable theory open_locale classical big_operators universes u v w namespace polynomial instance {R : Type u} [semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p := let ⟨h⟩ := h in ⟨λ n, by rw [← C.map_nat_cast, ← C_0, C_inj, h]⟩ variables (R : Type u) [comm_ring R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker /-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/ def degree_lt (n : ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl @[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, (X : polynomial R)^n)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← polynomial.sum_monomial_eq p, polynomial.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [monomial_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, exact (degree_X_pow_le _).trans (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end theorem mem_degree_lt {n : ℕ} {f : polynomial R} : f ∈ degree_lt R n ↔ degree f < n := by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl } @[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) : degree_lt R m ≤ degree_lt R n := λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H) theorem degree_lt_eq_span_X_pow {n : ℕ} : degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_lt.1 hp, rw [← polynomial.sum_monomial_eq p, polynomial.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk), rw [monomial_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_lt.2, exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk) end /-- The first `n` coefficients on `degree_lt n` form a linear equivalence with `fin n → F`. -/ def degree_lt_equiv (F : Type*) [field F] (n : ℕ) : degree_lt F n ≃ₗ[F] (fin n → F) := { to_fun := λ p n, (↑p : polynomial F).coeff n, inv_fun := λ f, ⟨∑ i : fin n, monomial i (f i), (degree_lt F n).sum_mem (λ i _, mem_degree_lt.mpr (lt_of_le_of_lt (degree_monomial_le i (f i)) (with_bot.coe_lt_coe.mpr i.is_lt)))⟩, map_add' := λ p q, by { ext, rw [submodule.coe_add, coeff_add], refl }, map_smul' := λ x p, by { ext, rw [submodule.coe_smul, coeff_smul], refl }, left_inv := begin rintro ⟨p, hp⟩, ext1, simp only [submodule.coe_mk], by_cases hp0 : p = 0, { subst hp0, simp only [coeff_zero, linear_map.map_zero, finset.sum_const_zero] }, rw [mem_degree_lt, degree_eq_nat_degree hp0, with_bot.coe_lt_coe] at hp, conv_rhs { rw [p.as_sum_range' n hp, ← fin.sum_univ_eq_sum_range] }, end, right_inv := begin intro f, ext i, simp only [finset_sum_coeff, submodule.coe_mk], rw [finset.sum_eq_single i, coeff_monomial, if_pos rfl], { rintro j - hji, rw [coeff_monomial, if_neg], rwa [← subtype.ext_iff] }, { intro h, exact (h (finset.mem_univ _)).elim } end } /-- The finset of nonzero coefficients of a polynomial. -/ def frange (p : polynomial R) : finset R := finset.image (λ n, p.coeff n) p.support lemma frange_zero : frange (0 : polynomial R) = ∅ := rfl lemma mem_frange_iff {p : polynomial R} {c : R} : c ∈ p.frange ↔ ∃ n ∈ p.support, c = p.coeff n := by simp [frange, eq_comm] lemma frange_one : frange (1 : polynomial R) ⊆ {1} := begin simp [frange, finset.image_subset_iff], simp only [← C_1, coeff_C], assume n hn, simp only [exists_prop, ite_eq_right_iff, not_forall] at hn, simp [hn], end lemma coeff_mem_frange (p : polynomial R) (n : ℕ) (h : p.coeff n ≠ 0) : p.coeff n ∈ p.frange := begin simp only [frange, exists_prop, mem_support_iff, finset.mem_image, ne.def], exact ⟨n, h, rfl⟩, end /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (subring.closure (↑p.frange : set R)) := ∑ i in p.support, monomial i (⟨p.coeff i, if H : p.coeff i = 0 then H.symm ▸ (subring.closure _).zero_mem else subring.subset_closure (p.coeff_mem_frange _ H)⟩ : (subring.closure (↑p.frange : set R))) @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := begin simp only [restriction, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ne.def, ite_not], split_ifs, { rw h, refl }, { refl } end @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := coeff_restriction @[simp] lemma support_restriction (p : polynomial R) : support (restriction p) = support p := begin ext i, simp only [mem_support_iff, not_iff_not, ne.def], conv_rhs { rw [← coeff_restriction] }, exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem map_restriction (p : polynomial R) : p.restriction.map (algebra_map _ _) = p := ext $ λ n, by rw [coeff_map, algebra.algebra_map_of_subring_apply, coeff_restriction] @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := by simp [degree] @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := by simp [nat_degree] @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := begin simp only [monic, leading_coeff, nat_degree_restriction], rw [←@coeff_restriction _ _ p], exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := by simp only [restriction, finset.sum_empty, support_zero] @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [ring S] {f : R →+* S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f.comp (subring.subtype _)) x p.restriction := begin simp only [eval₂_eq_sum, sum, support_restriction, ←@coeff_restriction _ _ p], refl, end section to_subring variables (p : polynomial R) (T : subring R) /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : (↑p.frange : set R) ⊆ T) : polynomial T := ∑ i in p.support, monomial i (⟨p.coeff i, if H : p.coeff i = 0 then H.symm ▸ T.zero_mem else hp (p.coeff_mem_frange _ H)⟩ : T) variables (hp : (↑p.frange : set R) ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := begin simp only [to_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ne.def, ite_not], split_ifs, { rw h, refl }, { refl } end @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := coeff_to_subring _ _ hp @[simp] lemma support_to_subring : support (to_subring p T hp) = support p := begin ext i, simp only [mem_support_iff, not_iff_not, ne.def], conv_rhs { rw [← coeff_to_subring p T hp] }, exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := by simp [degree] @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := by simp [nat_degree] @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := begin simp_rw [monic, leading_coeff, nat_degree_to_subring, ← coeff_to_subring p T hp], exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (by simp [frange_zero]) = 0 := by { ext i, simp } @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans frange_one $finset.singleton_subset_set_iff.2 T.one_mem) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl @[simp] theorem map_to_subring : (p.to_subring T hp).map (subring.subtype T) = p := by { ext n, simp [coeff_map] } end to_subring variables (T : subring R) /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefficients are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ∑ i in p.support, monomial i (p.coeff i : R) lemma coeff_of_subring (p : polynomial T) (n : ℕ) : coeff (of_subring T p) n = (coeff p n : T) := begin simp only [of_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ite_eq_right_iff, ne.def, ite_not, not_not, ite_eq_left_iff], assume h, rw h, refl end @[simp] theorem frange_of_subring {p : polynomial T} : (↑(p.of_subring T).frange : set R) ⊆ T := begin assume i hi, simp only [frange, set.mem_image, mem_support_iff, ne.def, finset.mem_coe, finset.coe_image] at hi, rcases hi with ⟨n, hn, h'n⟩, rw [← h'n, coeff_of_subring], exact subtype.mem (coeff p n : T) end section mod_by_monic variables {q : polynomial R} lemma mem_ker_mod_by_monic [nontrivial R] (hq : q.monic) {p : polynomial R} : p ∈ (mod_by_monic_hom hq).ker ↔ q ∣ p := linear_map.mem_ker.trans (dvd_iff_mod_by_monic_eq_zero hq) @[simp] lemma ker_mod_by_monic_hom [nontrivial R] (hq : q.monic) : (polynomial.mod_by_monic_hom hq).ker = (ideal.span {q}).restrict_scalars R := submodule.ext (λ f, (mem_ker_mod_by_monic hq).trans ideal.mem_span_singleton.symm) end mod_by_monic end polynomial variables {R : Type u} {σ : Type v} {M : Type w} [comm_ring R] [add_comm_group M] [module R M] namespace ideal open polynomial /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself -/ lemma polynomial_mem_ideal_of_coeff_mem_ideal (I : ideal (polynomial R)) (p : polynomial R) (hp : ∀ (n : ℕ), (p.coeff n) ∈ I.comap C) : p ∈ I := sum_C_mul_X_eq p ▸ submodule.sum_mem I (λ n hn, I.mul_mem_right _ (hp n)) /-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : polynomial R} : f ∈ (ideal.map C I : ideal (polynomial R)) ↔ ∀ n : ℕ, f.coeff n ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw ← sum_monomial_eq f, refine (I.map C : ideal (polynomial R)).sum_mem (λ n hn, _), simp [monomial_eq_C_mul_X], rw mul_comm, exact (I.map C : ideal (polynomial R)).mul_mem_left _ (mem_map_of_mem _ (hf n)) } end lemma quotient_map_C_eq_zero {I : ideal R} : ∀ a ∈ I, ((quotient.mk (map C I : ideal (polynomial R))).comp C) a = 0 := begin intros a ha, rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem], exact mem_map_of_mem _ ha, end lemma eval₂_C_mk_eq_zero {I : ideal R} : ∀ f ∈ (map C I : ideal (polynomial R)), eval₂_ring_hom (C.comp (quotient.mk I)) X f = 0 := begin intros a ha, rw ← sum_monomial_eq a, dsimp, rw eval₂_sum, refine finset.sum_eq_zero (λ n hn, _), dsimp, rw eval₂_monomial (C.comp (quotient.mk I)) X, refine mul_eq_zero_of_left (polynomial.ext (λ m, _)) (X ^ n), erw coeff_C, by_cases h : m = 0, { simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) }, { simp [h] } end /-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is isomorphic to the quotient of `polynomial R` by the ideal `map C I`, where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/ def polynomial_quotient_equiv_quotient_polynomial (I : ideal R) : polynomial (I.quotient) ≃+* (map C I : ideal (polynomial R)).quotient := { to_fun := eval₂_ring_hom (quotient.lift I ((quotient.mk (map C I : ideal (polynomial R))).comp C) quotient_map_C_eq_zero) ((quotient.mk (map C I : ideal (polynomial R)) X)), inv_fun := quotient.lift (map C I : ideal (polynomial R)) (eval₂_ring_hom (C.comp (quotient.mk I)) X) eval₂_C_mk_eq_zero, map_mul' := λ f g, by simp only [coe_eval₂_ring_hom, eval₂_mul], map_add' := λ f g, by simp only [eval₂_add, coe_eval₂_ring_hom], left_inv := begin intro f, apply polynomial.induction_on' f, { intros p q hp hq, simp only [coe_eval₂_ring_hom] at hp, simp only [coe_eval₂_ring_hom] at hq, simp only [coe_eval₂_ring_hom, hp, hq, ring_hom.map_add] }, { rintros n ⟨x⟩, simp only [monomial_eq_smul_X, C_mul', quotient.lift_mk, submodule.quotient.quot_mk_eq_mk, quotient.mk_eq_mk, eval₂_X_pow, eval₂_smul, coe_eval₂_ring_hom, ring_hom.map_pow, eval₂_C, ring_hom.coe_comp, ring_hom.map_mul, eval₂_X] } end, right_inv := begin rintro ⟨f⟩, apply polynomial.induction_on' f, { simp_intros p q hp hq, rw [hp, hq] }, { intros n a, simp only [monomial_eq_smul_X, ← C_mul' a (X ^ n), quotient.lift_mk, submodule.quotient.quot_mk_eq_mk, quotient.mk_eq_mk, eval₂_X_pow, eval₂_smul, coe_eval₂_ring_hom, ring_hom.map_pow, eval₂_C, ring_hom.coe_comp, ring_hom.map_mul, eval₂_X] }, end, } @[simp] lemma polynomial_quotient_equiv_quotient_polynomial_symm_mk (I : ideal R) (f : polynomial R) : I.polynomial_quotient_equiv_quotient_polynomial.symm (quotient.mk _ f) = f.map (quotient.mk I) := by rw [polynomial_quotient_equiv_quotient_polynomial, ring_equiv.symm_mk, ring_equiv.coe_mk, ideal.quotient.lift_mk, coe_eval₂_ring_hom, eval₂_eq_eval_map, ←polynomial.map_map, ←eval₂_eq_eval_map, polynomial.eval₂_C_X] @[simp] lemma polynomial_quotient_equiv_quotient_polynomial_map_mk (I : ideal R) (f : polynomial R) : I.polynomial_quotient_equiv_quotient_polynomial (f.map I^.quotient.mk) = quotient.mk _ f := begin apply (polynomial_quotient_equiv_quotient_polynomial I).symm.injective, rw [ring_equiv.symm_apply_apply, polynomial_quotient_equiv_quotient_polynomial_symm_mk], end /-- If `P` is a prime ideal of `R`, then `R[x]/(P)` is an integral domain. -/ lemma is_integral_domain_map_C_quotient {P : ideal R} (H : is_prime P) : is_integral_domain (quotient (map C P : ideal (polynomial R))) := ring_equiv.is_integral_domain (polynomial (quotient P)) (integral_domain.to_is_integral_domain (polynomial (quotient P))) (polynomial_quotient_equiv_quotient_polynomial P).symm /-- If `P` is a prime ideal of `R`, then `P.R[x]` is a prime ideal of `R[x]`. -/ lemma is_prime_map_C_of_is_prime {P : ideal R} (H : is_prime P) : is_prime (map C P : ideal (polynomial R)) := (quotient.is_integral_domain_iff_prime (map C P : ideal (polynomial R))).mp (is_integral_domain_map_C_quotient H) /-- Given any ring `R` and an ideal `I` of `polynomial R`, we get a map `R → R[x] → R[x]/I`. If we let `R` be the image of `R` in `R[x]/I` then we also have a map `R[x] → R'[x]`. In particular we can map `I` across this map, to get `I'` and a new map `R' → R'[x] → R'[x]/I`. This theorem shows `I'` will not contain any non-zero constant polynomials -/ lemma eq_zero_of_polynomial_mem_map_range (I : ideal (polynomial R)) (x : ((quotient.mk I).comp C).range) (hx : C x ∈ (I.map (polynomial.map_ring_hom ((quotient.mk I).comp C).range_restrict))) : x = 0 := begin let i := ((quotient.mk I).comp C).range_restrict, have hi' : (polynomial.map_ring_hom i).ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), rw [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], rw [ring_hom.mem_ker, coe_map_ring_hom] at hf, replace hf := congr_arg (λ (f : polynomial _), f.coeff n) hf, simp only [coeff_map, coeff_zero] at hf, rwa [subtype.ext_iff, ring_hom.coe_range_restrict] at hf }, obtain ⟨x, hx'⟩ := x, obtain ⟨y, rfl⟩ := (ring_hom.mem_range).1 hx', refine subtype.eq _, simp only [ring_hom.comp_apply, quotient.eq_zero_iff_mem, subring.coe_zero, subtype.val_eq_coe], suffices : C (i y) ∈ (I.map (polynomial.map_ring_hom i)), { obtain ⟨f, hf⟩ := mem_image_of_mem_map_of_surjective (polynomial.map_ring_hom i) (polynomial.map_surjective _ (((quotient.mk I).comp C).range_restrict_surjective)) this, refine sub_add_cancel (C y) f ▸ I.add_mem (hi' _ : (C y - f) ∈ I) hf.1, rw [ring_hom.mem_ker, ring_hom.map_sub, hf.2, sub_eq_zero, coe_map_ring_hom, map_C] }, exact hx, end /-- `polynomial R` is never a field for any ring `R`. -/ lemma polynomial_not_is_field : ¬ is_field (polynomial R) := begin by_contradiction hR, by_cases hR' : ∃ (x y : R), x ≠ y, { haveI : nontrivial R := let ⟨x, y, hxy⟩ := hR' in nontrivial_of_ne x y hxy, obtain ⟨p, hp⟩ := hR.mul_inv_cancel X_ne_zero, by_cases hp0 : p = 0, { replace hp := congr_arg degree hp, rw [hp0, mul_zero, degree_zero, degree_one] at hp, contradiction }, { have : p.degree < (X * p).degree := (mul_comm p X) ▸ degree_lt_degree_mul_X hp0, rw [congr_arg degree hp, degree_one, nat.with_bot.lt_zero_iff, degree_eq_bot] at this, exact hp0 this } }, { push_neg at hR', exact let ⟨x, y, hxy⟩ := hR.exists_pair_ne in hxy (polynomial.ext (λ n, hR' _ _)) } end /-- The only constant in a maximal ideal over a field is `0`. -/ lemma eq_zero_of_constant_mem_of_maximal (hR : is_field R) (I : ideal (polynomial R)) [hI : I.is_maximal] (x : R) (hx : C x ∈ I) : x = 0 := begin refine classical.by_contradiction (λ hx0, hI.ne_top ((eq_top_iff_one I).2 _)), obtain ⟨y, hy⟩ := hR.mul_inv_cancel hx0, convert I.smul_mem (C y) hx, rw [smul_eq_mul, ← C.map_mul, mul_comm y x, hy, ring_hom.map_one], end /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero_mem' := I.zero_mem, add_mem' := λ _ _, I.add_mem, smul_mem' := λ c x H, by { rw [← C_mul'], exact I.mul_mem_left _ H } } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact add_sub_cancel_of_le (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right _ hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [set_like.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right _ hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, add_sub_cancel_of_le H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal namespace polynomial @[priority 100] instance {R : Type*} [comm_ring R] [integral_domain R] [wf_dvd_monoid R] : wf_dvd_monoid (polynomial R) := { well_founded_dvd_not_unit := begin classical, refine rel_hom.well_founded ⟨λ p, (if p = 0 then ⊤ else ↑p.degree, p.leading_coeff), _⟩ (prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf) _inst_6.well_founded_dvd_not_unit), rintros a b ⟨ane0, ⟨c, ⟨not_unit_c, rfl⟩⟩⟩, rw [polynomial.degree_mul, if_neg ane0], split_ifs with hac, { rw [hac, polynomial.leading_coeff_zero], apply prod.lex.left, exact lt_of_le_of_ne le_top with_top.coe_ne_top }, have cne0 : c ≠ 0 := right_ne_zero_of_mul hac, simp only [cne0, ane0, polynomial.leading_coeff_mul], by_cases hdeg : c.degree = 0, { simp only [hdeg, add_zero], refine prod.lex.right _ ⟨_, ⟨c.leading_coeff, (λ unit_c, not_unit_c _), rfl⟩⟩, { rwa [ne, polynomial.leading_coeff_eq_zero] }, rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg], use [c.leading_coeff, unit_c], rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] }, { apply prod.lex.left, rw polynomial.degree_eq_nat_degree cne0 at *, rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0, ← with_bot.coe_add, with_bot.coe_lt_coe], exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (λ h, hdeg (h.symm ▸ with_bot.coe_zero))) }, end } end polynomial /-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/ protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := is_noetherian_ring_iff.2 ⟨assume I : ideal (polynomial R), let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min (well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin have : submodule.span (polynomial R) ↑s = ideal.span ↑s, by refl, rw this, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, add_sub_cancel_of_le, hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _ _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right _ hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ attribute [instance] polynomial.is_noetherian_ring namespace polynomial theorem exists_irreducible_of_degree_pos {R : Type u} [comm_ring R] [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f := wf_dvd_monoid.exists_irreducible_factor (λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf) (λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _) theorem exists_irreducible_of_nat_degree_pos {R : Type u} [comm_ring R] [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf } theorem exists_irreducible_of_nat_degree_ne_zero {R : Type u} [comm_ring R] [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf lemma linear_independent_powers_iff_aeval (f : M →ₗ[R] M) (v : M) : linear_independent R (λ n : ℕ, (f ^ n) v) ↔ ∀ (p : polynomial R), aeval f p v = 0 → p = 0 := begin rw linear_independent_iff, simp only [finsupp.total_apply, aeval_endomorphism, forall_iff_forall_finsupp, sum, support, coeff, ← zero_to_finsupp], exact iff.rfl, end lemma disjoint_ker_aeval_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : disjoint (aeval f p).ker (aeval f q).ker := begin intros v hv, rcases hpq with ⟨p', q', hpq'⟩, simpa [linear_map.mem_ker.1 (submodule.mem_inf.1 hv).1, linear_map.mem_ker.1 (submodule.mem_inf.1 hv).2] using congr_arg (λ p : polynomial R, aeval f p v) hpq'.symm, end lemma sup_aeval_range_eq_top_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).range ⊔ (aeval f q).range = ⊤ := begin rw eq_top_iff, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, use aeval f (p * p') v, use linear_map.mem_range.2 ⟨aeval f p' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, use aeval f (q * q') v, use linear_map.mem_range.2 ⟨aeval f q' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, simpa only [mul_comm p p', mul_comm q q', aeval_one, aeval_add] using congr_arg (λ p : polynomial R, aeval f p v) hpq' end lemma sup_ker_aeval_le_ker_aeval_mul {f : M →ₗ[R] M} {p q : polynomial R} : (aeval f p).ker ⊔ (aeval f q).ker ≤ (aeval f (p * q)).ker := begin intros v hv, rcases submodule.mem_sup.1 hv with ⟨x, hx, y, hy, hxy⟩, have h_eval_x : aeval f (p * q) x = 0, { rw [mul_comm, aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hx, linear_map.map_zero] }, have h_eval_y : aeval f (p * q) y = 0, { rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hy, linear_map.map_zero] }, rw [linear_map.mem_ker, ←hxy, linear_map.map_add, h_eval_x, h_eval_y, add_zero], end lemma sup_ker_aeval_eq_ker_aeval_mul_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).ker ⊔ (aeval f q).ker = (aeval f (p * q)).ker := begin apply le_antisymm sup_ker_aeval_le_ker_aeval_mul, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, have h_eval₂_qpp' := calc aeval f (q * (p * p')) v = aeval f (p' * (p * q)) v : by rw [mul_comm, mul_assoc, mul_comm, mul_assoc, mul_comm q p] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], have h_eval₂_pqq' := calc aeval f (p * (q * q')) v = aeval f (q' * (p * q)) v : by rw [←mul_assoc, mul_comm] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], rw aeval_mul at h_eval₂_qpp' h_eval₂_pqq', refine ⟨aeval f (q * q') v, linear_map.mem_ker.1 h_eval₂_pqq', aeval f (p * p') v, linear_map.mem_ker.1 h_eval₂_qpp', _⟩, rw [add_comm, mul_comm p p', mul_comm q q'], simpa using congr_arg (λ p : polynomial R, aeval f p v) hpq' end end polynomial namespace mv_polynomial lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin 0) R) := is_noetherian_ring_of_ring_equiv R ((mv_polynomial.is_empty_ring_equiv R pempty).symm.trans (rename_equiv R fin_zero_equiv'.symm).to_ring_equiv) theorem is_noetherian_ring_fin [is_noetherian_ring R] : ∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R) | 0 := is_noetherian_ring_fin_0 | (n+1) := @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _ (mv_polynomial.fin_succ_equiv _ n).to_ring_equiv.symm (@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin)) /-- The multivariate polynomial ring in finitely many variables over a noetherian ring is itself a noetherian ring. -/ instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (rename_equiv R (fintype.equiv_fin σ).symm).to_ring_equiv is_noetherian_ring_fin lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial (fin 0) R) := ring_equiv.is_integral_domain R hR ((rename_equiv R fin_zero_equiv').to_ring_equiv.trans (mv_polynomial.is_empty_ring_equiv R pempty)) /-- Auxiliary lemma: Multivariate polynomials over an integral domain with variables indexed by `fin n` form an integral domain. This fact is proven inductively, and then used to prove the general case without any finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) : ∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R) | 0 := is_integral_domain_fin_zero R hR | (n+1) := ring_equiv.is_integral_domain (polynomial (mv_polynomial (fin n) R)) (is_integral_domain_fin n).polynomial (mv_polynomial.fin_succ_equiv _ n).to_ring_equiv lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) := @ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_integral_domain_fin _ hR _) (rename_equiv R (fintype.equiv_fin σ)).to_ring_equiv /-- Auxiliary definition: Multivariate polynomials in finitely many variables over an integral domain form an integral domain. This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`, and then used to prove the general case without finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ theorem integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [integral_domain R] [fintype σ] : integral_domain (mv_polynomial σ R) := @is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $ integral_domain.to_is_integral_domain R protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [comm_ring R] [integral_domain R] {σ : Type v} (p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 := begin obtain ⟨s, p, rfl⟩ := exists_finset_rename p, obtain ⟨t, q, rfl⟩ := exists_finset_rename q, have : rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) p * rename (subtype.map id (finset.subset_union_right s t) : {x // x ∈ t} → {x // x ∈ s ∪ t}) q = 0, { apply rename_injective _ subtype.val_injective, simpa using h }, letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)}, rw mul_eq_zero at this, cases this; [left, right], all_goals { simpa using congr_arg (rename subtype.val) this } end /-- The multivariate polynomial ring over an integral domain is an integral domain. -/ instance {R : Type u} {σ : Type v} [comm_ring R] [integral_domain R] : integral_domain (mv_polynomial σ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero, exists_pair_ne := ⟨0, 1, λ H, begin have : eval₂ (ring_hom.id _) (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ (ring_hom.id _) (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end⟩, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } lemma map_mv_polynomial_eq_eval₂ {S : Type*} [comm_ring S] [fintype σ] (ϕ : mv_polynomial σ R →+* S) (p : mv_polynomial σ R) : ϕ p = mv_polynomial.eval₂ (ϕ.comp mv_polynomial.C) (λ s, ϕ (mv_polynomial.X s)) p := begin refine trans (congr_arg ϕ (mv_polynomial.as_sum p)) _, rw [mv_polynomial.eval₂_eq', ϕ.map_sum], congr, ext, simp only [monomial_eq, ϕ.map_pow, ϕ.map_prod, ϕ.comp_apply, ϕ.map_mul, finsupp.prod_pow], end lemma quotient_map_C_eq_zero {I : ideal R} {i : R} (hi : i ∈ I) : (ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C i = 0 := begin simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient.eq_zero_iff_mem], exact ideal.mem_map_of_mem _ hi end /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself, multivariate version. -/ lemma mem_ideal_of_coeff_mem_ideal (I : ideal (mv_polynomial σ R)) (p : mv_polynomial σ R) (hcoe : ∀ (m : σ →₀ ℕ), p.coeff m ∈ I.comap C) : p ∈ I := begin rw as_sum p, suffices : ∀ m ∈ p.support, monomial m (mv_polynomial.coeff m p) ∈ I, { exact submodule.sum_mem I this }, intros m hm, rw [← mul_one (coeff m p), ← C_mul_monomial], suffices : C (coeff m p) ∈ I, { exact I.mul_mem_right (monomial m 1) this }, simpa [ideal.mem_comap] using hcoe m end /-- The push-forward of an ideal `I` of `R` to `mv_polynomial σ R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : mv_polynomial σ R} : f ∈ (ideal.map C I : ideal (mv_polynomial σ R)) ↔ ∀ (m : σ →₀ ℕ), f.coeff m ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [ne.symm h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw as_sum f, suffices : ∀ m ∈ f.support, monomial m (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact submodule.sum_mem _ this }, intros m hm, rw [← mul_one (coeff m f), ← C_mul_monomial], suffices : C (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact ideal.mul_mem_right _ _ this }, apply ideal.mem_map_of_mem _, exact hf m } end lemma eval₂_C_mk_eq_zero {I : ideal R} {a : mv_polynomial σ R} (ha : a ∈ (ideal.map C I : ideal (mv_polynomial σ R))) : eval₂_hom (C.comp (ideal.quotient.mk I)) X a = 0 := begin rw as_sum a, rw [coe_eval₂_hom, eval₂_sum], refine finset.sum_eq_zero (λ n hn, _), simp only [eval₂_monomial, function.comp_app, ring_hom.coe_comp], refine mul_eq_zero_of_left _ _, suffices : coeff n a ∈ I, { rw [← @ideal.mk_ker R _ I, ring_hom.mem_ker] at this, simp only [this, C_0] }, exact mem_map_C_iff.1 ha n end /-- If `I` is an ideal of `R`, then the ring `mv_polynomial σ I.quotient` is isomorphic as an `R`-algebra to the quotient of `mv_polynomial σ R` by the ideal generated by `I`. -/ def quotient_equiv_quotient_mv_polynomial (I : ideal R) : mv_polynomial σ I.quotient ≃ₐ[R] (ideal.map C I : ideal (mv_polynomial σ R)).quotient := { to_fun := eval₂_hom (ideal.quotient.lift I ((ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C) (λ i hi, quotient_map_C_eq_zero hi)) (λ i, ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R)) (X i)), inv_fun := ideal.quotient.lift (ideal.map C I : ideal (mv_polynomial σ R)) (eval₂_hom (C.comp (ideal.quotient.mk I)) X) (λ a ha, eval₂_C_mk_eq_zero ha), map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _, left_inv := begin intro f, apply induction_on f, { rintro ⟨r⟩, rw [coe_eval₂_hom, eval₂_C], simp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_C_right, ring_hom.coe_comp] }, { simp_intros p q hp hq only [ring_hom.map_add, mv_polynomial.coe_eval₂_hom, coe_eval₂_hom, mv_polynomial.eval₂_add, mv_polynomial.eval₂_hom_eq_bind₂, eval₂_hom_eq_bind₂], rw [hp, hq] }, { simp_intros p i hp only [eval₂_hom_eq_bind₂, coe_eval₂_hom], simp only [hp, eval₂_hom_eq_bind₂, coe_eval₂_hom, ideal.quotient.lift_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X] } end, right_inv := begin rintro ⟨f⟩, apply induction_on f, { intros r, simp only [submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, ring_hom.coe_comp, eval₂_hom_C] }, { simp_intros p q hp hq only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, eval₂_add, ring_hom.map_add, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk], rw [hp, hq] }, { simp_intros p i hp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X], simp only [hp] } end, commutes' := λ r, eval₂_hom_C _ _ (ideal.quotient.mk I r) } end mv_polynomial namespace polynomial open unique_factorization_monoid variables {D : Type u} [comm_ring D] [integral_domain D] [unique_factorization_monoid D] @[priority 100] instance unique_factorization_monoid : unique_factorization_monoid (polynomial D) := begin haveI := arbitrary (normalization_monoid D), haveI := to_normalized_gcd_monoid D, exact ufm_of_gcd_of_wf_dvd_monoid end end polynomial
dab2afe0a430a10e7ba9a977ff63be6a66c60f2a
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/src/builtin/specialfn.lean
95f4e4e714a00dbde073a1ba0bab5b94e5f5eb0d
[ "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
571
lean
import Real. variable exp : Real → Real. variable log : Real → Real. variable pi : Real. alias π : pi. variable sin : Real → Real. definition cos x := sin (x - π / 2). definition tan x := sin x / cos x. definition cot x := cos x / sin x. definition sec x := 1 / cos x. definition csc x := 1 / sin x. definition sinh x := (1 - exp (-2 * x)) / (2 * exp (- x)). definition cosh x := (1 + exp (-2 * x)) / (2 * exp (- x)). definition tanh x := sinh x / cosh x. definition coth x := cosh x / sinh x. definition sech x := 1 / cosh x. definition csch x := 1 / sinh x.
29caa1c13fe58dc08d2968e0a862f17144fef18a
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/revert1.lean
effc59863614e6ef5053430132d9f8d338b56e8a
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
310
lean
new_frontend theorem tst1 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 h2 h3; revert h2; intro h2; exact Eq.trans h3 h1 end theorem tst2 (x y z : Nat) : y = z → x = x → x = y → x = z := begin intros h1 h2 h3; revert y; intros y hb ha; exact Eq.trans ha hb end
1ff465bc6f1e61407a42427527e687aeaa66ef82
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/by_contra.lean
ddff6e807d1c944e2a8f060e96d1d8507efa203b
[ "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
606
lean
import tactic.by_contra import tactic.interactive example : 1 < 2 := begin by_contra' h, guard_hyp' h : 2 ≤ 1, revert h, exact dec_trivial end example : 1 < 2 := begin by_contra' h : 2 ≤ 1, guard_hyp' h : 2 ≤ 1, -- this is not defeq to `¬ 1 < 2` revert h, exact dec_trivial end example : 1 < 2 := begin by_contra' h : ¬ 1 < 2, guard_hyp' h : ¬ 1 < 2, -- this is not defeq to `2 ≤ 1` revert h, exact dec_trivial end example : 1 < 2 := begin by_contra' : 2 ≤ 1, guard_hyp' this : 2 ≤ 1, -- this is not defeq to `¬ 1 < 2` revert this, exact dec_trivial end
510b3e894605025efb2d55cc1cbb1e205053a898
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/conv_tac1.lean
583c14979c10fdc8e55f32105b98cdc0470bc1bb
[ "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
3,529
lean
local attribute [simp] nat.add_comm nat.add_left_comm example (a b : nat) : (λ x, a + x) 0 = b + 1 + a := begin conv in (_ + 1) { change nat.succ b }, guard_target (λ x, a + x) 0 = nat.succ b + a, admit end def Div : nat → nat → nat | x y := if h : 0 < y ∧ y ≤ x then have x - y < x, from sorry, Div (x - y) y + 1 else 0 example (x y : nat) : 0 < y → y ≤ x → Div x y = Div (x - y) y + 1 := begin intros h1 h2, -- Use conv to focus on the lhs conv { to_lhs, simp [Div] {single_pass := tt}, simp [h1, h2] }, guard_target 1 + Div (x - y) y = Div (x - y) y + 1, simp end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use conv to rewrite subterm of a hypothesis conv at h in (0 + _) { simp }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use conv to rewrite subterm of a hypothesis conv at h in (0 + x) { simp }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use congr primitive to find term to be modified conv at h { guard_lhs f (0 + x + y) = 0 + y, congr, { guard_lhs f (0 + x + y), congr, congr, simp }, { guard_lhs 0 + y } }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use congr primitive to find term to be modified conv at h { guard_lhs f (0 + x + y) = 0 + y, to_lhs, guard_lhs f (0 + x + y), congr, guard_lhs 0 + x + y, congr, simp, }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (x + y) = 0 + y := begin -- use conv to rewrite subterm of a hypothesis conv at h in (0 + _) { rw [nat.zero_add] }, assumption end example (x y : nat) (f : nat → nat) (h : f (0 + x + y) = 0 + y) : f (0 + x + y) = y := begin -- use conv to rewrite rhs a hypothesis conv at h { to_rhs, rw [nat.zero_add] }, assumption end example (x : nat) (f : nat → nat) (h₁ : x = 0) (h₂ : ∀ x, f x = x + x) : f x = x := begin conv { to_rhs, rw [h₁, <- nat.add_zero 0, <- h₁], }, exact h₂ x end lemma addz (x : nat) : x + 0 = x := rfl example (x : nat) (g : nat → nat) (f : nat → (nat → nat) → nat) (h : f (x + 0) (λ x, g x) = x) : f x g = x := begin conv at h {dsimp [addz] {eta := ff}}, conv at h {dsimp}, exact h, end example (x : nat) (g : nat → nat) (f : nat → (nat → nat) → nat) (h : f (x + 0) (λ x, g x) = x) : f x g = x := begin conv at h {dsimp [addz] {eta := ff}, guard_lhs f x (λ x, g x) = x, dsimp, guard_lhs f x g = x}, exact h, end def f (x y : nat) : nat := x + y + 1 example (x y : nat) : f x y + f x x + f y y = x + y + 1 + y + y + 1 + f x x := begin conv { -- execute `rw [f]` for 1st and 3rd occurrences of f-applications for (f _ _) [1, 3] { rw [f] }, guard_lhs (x + y + 1) + f x x + (y + y + 1) = x + y + 1 + y + y + 1 + f x x, simp } end example (x : nat) : f x x + f x x + f x x = f x x + x + x + x + x + 1 + 1 := begin conv { -- execute `rw [f]` for 1st and 3rd occurrences of f-applications for (f _ _) [1, 3] { rw [f] }, guard_lhs (x + x + 1) + f x x + (x + x + 1) = f x x + x + x + x + x + 1 + 1, simp } end example (x : nat) : f x x + f x x = f x x + x + x + 1 := begin conv in (f _ _) { rw [f] }, guard_target (x + x + 1) + f x x = f x x + x + x + 1, simp end
e4197a53ced1ddc4a525c344c148d63db3d773b1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Instances.lean
d3b784f965d6389cee5bfde0fb8564907c661c38
[ "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
11,813
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 -/ import Lean.ScopedEnvExtension import Lean.Meta.GlobalInstances import Lean.Meta.DiscrTree import Lean.Meta.CollectMVars namespace Lean.Meta register_builtin_option synthInstance.checkSynthOrder : Bool := { defValue := true descr := "check that instances do not introduce metavariable in non-out-params" } /- Note: we want to use iota reduction when indexing instaces. Otherwise, we cannot elaborate examples such as ``` inductive Ty where | int | bool @[reducible] def Ty.interp (ty : Ty) : Type := Ty.casesOn (motive := fun _ => Type) ty Int Bool def test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp := f x y def f (a b : Ty.bool.interp) : Ty.bool.interp := -- We want to synthesize `BEq Ty.bool.interp` here, and it will fail -- if we do not reduce `Ty.bool.interp` to `Bool`. test (.==.) a b ``` See comment at `DiscrTree`. -/ abbrev InstanceKey := DiscrTree.Key (simpleReduce := false) structure InstanceEntry where keys : Array InstanceKey val : Expr priority : Nat globalName? : Option Name := none /-- The order in which the instance's arguments are to be synthesized. -/ synthOrder : Array Nat /- We store the attribute kind to be able to implement the API `getInstanceAttrKind`. TODO: add better support for retrieving the `attrKind` of any attribute. The current implementation here works only for instances, but it is good enough for unblocking the implementation of `to_additive`. -/ attrKind : AttributeKind deriving Inhabited instance : BEq InstanceEntry where beq e₁ e₂ := e₁.val == e₂.val instance : ToFormat InstanceEntry where format e := match e.globalName? with | some n => format n | _ => "<local>" abbrev InstanceTree := DiscrTree InstanceEntry (simpleReduce := false) structure Instances where discrTree : InstanceTree := DiscrTree.empty instanceNames : PHashMap Name InstanceEntry := {} erased : PHashSet Name := {} deriving Inhabited def addInstanceEntry (d : Instances) (e : InstanceEntry) : Instances := match e.globalName? with | some n => { d with discrTree := d.discrTree.insertCore e.keys e, instanceNames := d.instanceNames.insert n e, erased := d.erased.erase n } | none => { d with discrTree := d.discrTree.insertCore e.keys e } def Instances.eraseCore (d : Instances) (declName : Name) : Instances := { d with erased := d.erased.insert declName, instanceNames := d.instanceNames.erase declName } def Instances.erase [Monad m] [MonadError m] (d : Instances) (declName : Name) : m Instances := do unless d.instanceNames.contains declName do throwError "'{declName}' does not have [instance] attribute" return d.eraseCore declName builtin_initialize instanceExtension : SimpleScopedEnvExtension InstanceEntry Instances ← registerSimpleScopedEnvExtension { initial := {} addEntry := addInstanceEntry } private def mkInstanceKey (e : Expr) : MetaM (Array InstanceKey) := do let type ← inferType e withNewMCtxDepth do let (_, _, type) ← forallMetaTelescopeReducing type DiscrTree.mkPath type /-- Compute the order the arguments of `inst` should by synthesized. The synthesization order makes sure that all mvars in non-out-params of the subgoals are assigned before we try to synthesize it. Otherwise it goes left to right. For example: - `[Add α] [Zero α] : Foo α` returns `[0, 1]` - `[Mul A] [Mul B] [MulHomClass F A B] : FunLike F A B` returns `[2, 0, 1]` (because A B are out-params and are only filled in once we synthesize 2) (The type of `inst` must not contain mvars.) -/ partial def computeSynthOrder (inst : Expr) : MetaM (Array Nat) := withReducible do let instTy ← inferType inst -- Gets positions of all out- and semi-out-params of `classTy` -- (where `classTy` is e.g. something like `Inhabited Nat`) let rec getSemiOutParamPositionsOf (classTy : Expr) : MetaM (Array Nat) := do if let .const className .. := classTy.getAppFn then forallTelescopeReducing (← inferType classTy.getAppFn) fun args _ => do let mut pos := (getOutParamPositions? (← getEnv) className).getD #[] for arg in args, i in [:args.size] do if (← inferType arg).isAppOf ``semiOutParam then pos := pos.push i return pos else return #[] -- Create both metavariables and free variables for the instance args -- We will successively pick subgoals where all non-out-params have been -- assigned already. After picking such a "ready" subgoal, we assign the -- mvars in its out-params by the corresponding fvars. let (argMVars, argBIs, ty) ← forallMetaTelescopeReducing instTy let ty ← whnf ty forallTelescopeReducing instTy fun argVars _ => do -- Assigns all mvars from argMVars in e by the corresponding fvar. let rec assignMVarsIn (e : Expr) : MetaM Unit := do for mvarId in ← getMVars e do if let some i := argMVars.findIdx? (·.mvarId! == mvarId) then mvarId.assign argVars[i]! assignMVarsIn (← inferType (.mvar mvarId)) -- We start by assigning all metavariables in non-out-params of the return value. -- These are assumed to not be mvars during TC search (or at least not assignable) let tyOutParams ← getSemiOutParamPositionsOf ty let tyArgs := ty.getAppArgs for tyArg in tyArgs, i in [:tyArgs.size] do unless tyOutParams.contains i do assignMVarsIn tyArg -- Now we successively try to find the next ready subgoal, where all -- non-out-params are mvar-free. let mut synthed := #[] let mut toSynth := List.range argMVars.size |>.filter (argBIs[·]! == .instImplicit) |>.toArray while !toSynth.isEmpty do let next? ← toSynth.findM? fun i => do forallTelescopeReducing (← instantiateMVars (← inferType argMVars[i]!)) fun _ argTy => do let argTy ← whnf argTy let argOutParams ← getSemiOutParamPositionsOf argTy let argTyArgs := argTy.getAppArgs for i in [:argTyArgs.size], argTyArg in argTyArgs do if !argOutParams.contains i && argTyArg.hasExprMVar then return false return true let next ← match next? with | some next => pure next | none => if synthInstance.checkSynthOrder.get (← getOptions) then let typeLines := ("" : MessageData).joinSep <| Array.toList <| ← toSynth.mapM fun i => do let ty ← instantiateMVars (← inferType argMVars[i]!) return indentExpr (ty.setPPExplicit true) logError m!"cannot find synthesization order for instance {inst} with type{indentExpr instTy}\nall remaining arguments have metavariables:{typeLines}" pure toSynth[0]! synthed := synthed.push next toSynth := toSynth.filter (· != next) assignMVarsIn (← inferType argMVars[next]!) assignMVarsIn argMVars[next]! if synthInstance.checkSynthOrder.get (← getOptions) then let ty ← instantiateMVars ty if ty.hasExprMVar then logError m!"instance does not provide concrete values for (semi-)out-params{indentExpr (ty.setPPExplicit true)}" trace[Meta.synthOrder] "synthesizing the arguments of {inst} in the order {synthed}:{("" : MessageData).joinSep (← synthed.mapM fun i => return indentExpr (← inferType argVars[i]!)).toList}" return synthed def addInstance (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let c ← mkConstWithLevelParams declName let keys ← mkInstanceKey c addGlobalInstance declName attrKind let synthOrder ← computeSynthOrder c instanceExtension.add { keys, val := c, priority := prio, globalName? := declName, attrKind, synthOrder } attrKind builtin_initialize registerBuiltinAttribute { name := `instance descr := "type class instance" add := fun declName stx attrKind => do let prio ← getAttrParamOptPrio stx[1] discard <| addInstance declName attrKind prio |>.run {} {} erase := fun declName => do let s := instanceExtension.getState (← getEnv) let s ← s.erase declName modifyEnv fun env => instanceExtension.modifyState env fun _ => s } def getGlobalInstancesIndex : CoreM (DiscrTree InstanceEntry (simpleReduce := false)) := return Meta.instanceExtension.getState (← getEnv) |>.discrTree def getErasedInstances : CoreM (PHashSet Name) := return Meta.instanceExtension.getState (← getEnv) |>.erased def isInstance (declName : Name) : CoreM Bool := return Meta.instanceExtension.getState (← getEnv) |>.instanceNames.contains declName def getInstancePriority? (declName : Name) : CoreM (Option Nat) := do let some entry := Meta.instanceExtension.getState (← getEnv) |>.instanceNames.find? declName | return none return entry.priority def getInstanceAttrKind? (declName : Name) : CoreM (Option AttributeKind) := do let some entry := Meta.instanceExtension.getState (← getEnv) |>.instanceNames.find? declName | return none return entry.attrKind /-! # Default instance support -/ structure DefaultInstanceEntry where className : Name instanceName : Name priority : Nat abbrev PrioritySet := RBTree Nat (fun x y => compare y x) structure DefaultInstances where defaultInstances : NameMap (List (Name × Nat)) := {} priorities : PrioritySet := {} deriving Inhabited def addDefaultInstanceEntry (d : DefaultInstances) (e : DefaultInstanceEntry) : DefaultInstances := let d := { d with priorities := d.priorities.insert e.priority } match d.defaultInstances.find? e.className with | some insts => { d with defaultInstances := d.defaultInstances.insert e.className <| (e.instanceName, e.priority) :: insts } | none => { d with defaultInstances := d.defaultInstances.insert e.className [(e.instanceName, e.priority)] } builtin_initialize defaultInstanceExtension : SimplePersistentEnvExtension DefaultInstanceEntry DefaultInstances ← registerSimplePersistentEnvExtension { addEntryFn := addDefaultInstanceEntry addImportedFn := fun es => (mkStateFromImportedEntries addDefaultInstanceEntry {} es) } def addDefaultInstance (declName : Name) (prio : Nat := 0) : MetaM Unit := do match (← getEnv).find? declName with | none => throwError "unknown constant '{declName}'" | some info => forallTelescopeReducing info.type fun _ type => do match type.getAppFn with | Expr.const className _ => unless isClass (← getEnv) className do throwError "invalid default instance '{declName}', it has type '({className} ...)', but {className}' is not a type class" setEnv <| defaultInstanceExtension.addEntry (← getEnv) { className := className, instanceName := declName, priority := prio } | _ => throwError "invalid default instance '{declName}', type must be of the form '(C ...)' where 'C' is a type class" builtin_initialize registerBuiltinAttribute { name := `default_instance descr := "type class default instance" add := fun declName stx kind => do let prio ← getAttrParamOptPrio stx[1] unless kind == AttributeKind.global do throwError "invalid attribute 'default_instance', must be global" discard <| addDefaultInstance declName prio |>.run {} {} } registerTraceClass `Meta.synthOrder def getDefaultInstancesPriorities [Monad m] [MonadEnv m] : m PrioritySet := return defaultInstanceExtension.getState (← getEnv) |>.priorities def getDefaultInstances [Monad m] [MonadEnv m] (className : Name) : m (List (Name × Nat)) := return defaultInstanceExtension.getState (← getEnv) |>.defaultInstances.find? className |>.getD [] end Lean.Meta
d5c90ec900a43aac2eb7d691dbfc7976354bf677
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/ack.lean
fd76f8e7cd13e5a3fe6252c550f8414a9fce4cbd
[ "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
488
lean
open nat definition iter (f : nat → nat) (n : nat) : nat := nat.rec_on n (f 1) (λ (n₁ : nat) (r : nat), f r) definition ack (m : nat) : nat → nat := nat.rec_on m nat.succ (λ (m₁ : nat) (r : nat → nat), iter r) theorem ack_0_n (n : nat) : ack 0 n = n + 1 := rfl theorem ack_m_0 (m : nat) : ack (m + 1) 0 = ack m 1 := rfl theorem ack_m_n (m n : nat) : ack (m + 1) (n + 1) = ack m (ack (m + 1) n) := rfl example : ack 3 2 = 29 := rfl example : ack 3 3 = 61 := rfl
537ce3db8fdcc479c2747bff62174c881750f0a4
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/morphism.lean
c37562e0f766639e351852e3fc8f51ea8c944935
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
1,648
lean
import .group_representation universe variables u v w w' w'' w''' open linear_map variables {G : Type u} [group G] {R : Type v}[ring R] namespace morphism variables {M : Type w} [add_comm_group M] [module R M] {M' : Type w'} [add_comm_group M'] [module R M'] /-- a morphism `f : ρ ⟶ π` between representation is a linear map `f.ℓ : M(ρ) →ₗ[R] M(π)` satisfying `f.ℓ ∘ ρ g = π g ∘ f.ℓ` has function on `set`. -/ structure morphism (ρ : group_representation G R M) (π : group_representation G R M') : Type (max w w') := (ℓ : M →ₗ[R] M') (commute : ∀(g : G), ℓ ∘ ρ g = π g ∘ ℓ) --- en terme d'élément ! variables (ρ : group_representation G R M) infixr ` ⟶ `:25 := morphism @[ext]lemma ext {ρ : group_representation G R M} {ρ' : group_representation G R M'} ( f g : ρ ⟶ ρ') : (f.ℓ) = g.ℓ → f = g := begin intros, cases f,cases g , congr'; try {assumption}, end variables (ρ' : group_representation G R M') instance : has_coe_to_fun (morphism ρ ρ') := ⟨_,λ f, f.ℓ.to_fun⟩ lemma coersion (f : ρ ⟶ ρ') : ⇑f = (f.ℓ) := rfl theorem commute_apply ( f : ρ ⟶ ρ') (x : M) (g : G) : f ( ρ g x) = ρ' g (f x ) := begin change (f.ℓ ∘ ρ g ) x = _, rw f.commute, exact rfl, end theorem 𝒞_o_e_r_s_i_o_n__s__ℓ( f : ρ ⟶ ρ')(g : G) : f.ℓ ∘ ρ g = ((linear_map.comp (f.ℓ) ((ρ g): M →ₗ[R]M ) : M → M')) := rfl def one (ρ : group_representation G R M) : ρ ⟶ ρ := { ℓ := linear_map.id, commute := λ g, rfl } notation `𝟙` := one end morphism
c6b8ef4fbaf1c825223cc7f337286d14a48d8967
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/lie/cartan_subalgebra.lean
296ff9f84ed19382a171e622b388dfab51c7b281
[ "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,257
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 algebra.lie.nilpotent import algebra.lie.centralizer /-! # Cartan subalgebras Cartan subalgebras are one of the most important concepts in Lie theory. We define them here. The standard example is the set of diagonal matrices in the Lie algebra of matrices. ## Main definitions * `lie_submodule.is_ucs_limit` * `lie_subalgebra.is_cartan_subalgebra` * `lie_subalgebra.is_cartan_subalgebra_iff_is_ucs_limit` ## Tags lie subalgebra, normalizer, idealizer, cartan subalgebra -/ universes u v w w₁ w₂ variables {R : Type u} {L : Type v} variables [comm_ring R] [lie_ring L] [lie_algebra R L] (H : lie_subalgebra R L) /-- Given a Lie module `M` of a Lie algebra `L`, `lie_submodule.is_ucs_limit` is the proposition that a Lie submodule `N ⊆ M` is the limiting value for the upper central series. This is a characteristic property of Cartan subalgebras with the roles of `L`, `M`, `N` played by `H`, `L`, `H`, respectively. See `lie_subalgebra.is_cartan_subalgebra_iff_is_ucs_limit`. -/ def lie_submodule.is_ucs_limit {M : Type*} [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] (N : lie_submodule R L M) : Prop := ∃ k, ∀ l, k ≤ l → (⊥ : lie_submodule R L M).ucs l = N namespace lie_subalgebra /-- A Cartan subalgebra is a nilpotent, self-normalizing subalgebra. -/ class is_cartan_subalgebra : Prop := (nilpotent : lie_algebra.is_nilpotent R H) (self_normalizing : H.normalizer = H) instance [H.is_cartan_subalgebra] : lie_algebra.is_nilpotent R H := is_cartan_subalgebra.nilpotent @[simp] lemma centralizer_eq_self_of_is_cartan_subalgebra (H : lie_subalgebra R L) [H.is_cartan_subalgebra] : H.to_lie_submodule.centralizer = H.to_lie_submodule := by rw [← lie_submodule.coe_to_submodule_eq_iff, coe_centralizer_eq_normalizer, is_cartan_subalgebra.self_normalizing, coe_to_lie_submodule] @[simp] lemma ucs_eq_self_of_is_cartan_subalgebra (H : lie_subalgebra R L) [H.is_cartan_subalgebra] (k : ℕ) : H.to_lie_submodule.ucs k = H.to_lie_submodule := begin induction k with k ih, { simp, }, { simp [ih], }, end lemma is_cartan_subalgebra_iff_is_ucs_limit : H.is_cartan_subalgebra ↔ H.to_lie_submodule.is_ucs_limit := begin split, { introsI h, have h₁ : _root_.lie_algebra.is_nilpotent R H := by apply_instance, obtain ⟨k, hk⟩ := H.to_lie_submodule.is_nilpotent_iff_exists_self_le_ucs.mp h₁, replace hk : H.to_lie_submodule = lie_submodule.ucs k ⊥ := le_antisymm hk (lie_submodule.ucs_le_of_centralizer_eq_self H.centralizer_eq_self_of_is_cartan_subalgebra k), refine ⟨k, λ l hl, _⟩, rw [← nat.sub_add_cancel hl, lie_submodule.ucs_add, ← hk, lie_subalgebra.ucs_eq_self_of_is_cartan_subalgebra], }, { rintros ⟨k, hk⟩, exact { nilpotent := begin dunfold lie_algebra.is_nilpotent, erw H.to_lie_submodule.is_nilpotent_iff_exists_lcs_eq_bot, use k, rw [_root_.eq_bot_iff, lie_submodule.lcs_le_iff, hk k (le_refl k)], exact le_refl _, end, self_normalizing := begin have hk' := hk (k + 1) k.le_succ, rw [lie_submodule.ucs_succ, hk k (le_refl k)] at hk', rw [← lie_subalgebra.coe_to_submodule_eq_iff, ← lie_subalgebra.coe_centralizer_eq_normalizer, hk', lie_subalgebra.coe_to_lie_submodule], end } }, end end lie_subalgebra @[simp] lemma lie_ideal.normalizer_eq_top {R : Type u} {L : Type v} [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) : (I : lie_subalgebra R L).normalizer = ⊤ := begin ext x, simpa only [lie_subalgebra.mem_normalizer_iff, lie_subalgebra.mem_top, iff_true] using λ y hy, I.lie_mem hy end open lie_ideal /-- A nilpotent Lie algebra is its own Cartan subalgebra. -/ instance lie_algebra.top_is_cartan_subalgebra_of_nilpotent [lie_algebra.is_nilpotent R L] : lie_subalgebra.is_cartan_subalgebra (⊤ : lie_subalgebra R L) := { nilpotent := infer_instance, self_normalizing := by { rw [← top_coe_lie_subalgebra, normalizer_eq_top, top_coe_lie_subalgebra], }, }
e966f4c9cb3fe15fe78b3712ad5a6ec03325e4c8
7cef822f3b952965621309e88eadf618da0c8ae9
/src/meta/expr.lean
4cd94956870b845d8dc2e22731bcd2b729555fad
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
25,483
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : inhabited binder := ⟨⟨default _, default _, default _⟩⟩ meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) namespace expr /-- Turns an expression into a positive natural number, assuming it is only built up from `has_one.one`, `bit0` and `bit1`. -/ protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1` and `has_zero.zero`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es library_note "open expressions" "Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x)." /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open.-/ meta def pi_codomain : expr → expr -- see note [open expressions] | (pi n bi d b) := pi_codomain b | e := e /-- Auxilliary defintion for `pi_binders`. -/ -- see note [open expressions] meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables -/ meta def pi_binders (e : expr) : list binder × expr := -- see note [open expressions] let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the retulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param end declaration
93e832b7f738faf5cc5f0b8ab62470dcffc0abaa
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/sparse.lean
6a61d6cb5ad7a239eda449f0e31d71c419aeb91e
[ "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
828
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.category /-! A sparse category is a category with at most one morphism between each pair of objects. Examples include posets, but many indexing categories (diagrams) for special shapes of (co)limits. To construct a category instance one only needs to specify the `category_struct` part, as the axioms hold for free. -/ universes u v namespace category_theory variables {C : Type u} [category_struct.{v} C] /-- Construct a category instance from a category_struct, using the fact that hom spaces are subsingletons to prove the axioms. -/ def sparse_category [∀ X Y : C, subsingleton (X ⟶ Y)] : category.{v} C := { } end category_theory
8a511fb9d78085ed8510524434c9eb3c8d222454
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/ODE/picard_lindelof.lean
4e6b3f6ab62321f61396949cc98dacb9ad1a8786
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
15,026
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 analysis.special_functions.integrals import topology.metric_space.contracting /-! # Picard-Lindelöf (Cauchy-Lipschitz) Theorem In this file we prove that an ordinary differential equation $\dot x=v(t, x)$ such that $v$ is Lipschitz continuous in $x$ and continuous in $t$ has a local solution, see `exists_forall_deriv_within_Icc_eq_of_lipschitz_of_continuous`. ## Implementation notes In order to split the proof into small lemmas, we introduce a structure `picard_lindelof` that holds all assumptions of the main theorem. This structure and lemmas in the `picard_lindelof` namespace should be treated as private implementation details. We only prove existence of a solution in this file. For uniqueness see `ODE_solution_unique` and related theorems in `analysis.ODE.gronwall`. ## Tags differential equation -/ open filter function set metric topological_space interval_integral measure_theory open measure_theory.measure_space (volume) open_locale filter topological_space nnreal ennreal nat interval noncomputable theory variables {E : Type*} [normed_group E] [normed_space ℝ E] /-- This structure holds arguments of the Picard-Lipschitz (Cauchy-Lipschitz) theorem. Unless you want to use one of the auxiliary lemmas, use `exists_forall_deriv_within_Icc_eq_of_lipschitz_of_continuous` instead of using this structure. -/ structure picard_lindelof (E : Type*) [normed_group E] [normed_space ℝ E] := (to_fun : ℝ → E → E) (t_min t_max : ℝ) (t₀ : Icc t_min t_max) (x₀ : E) (C R L : ℝ≥0) (lipschitz' : ∀ t ∈ Icc t_min t_max, lipschitz_on_with L (to_fun t) (closed_ball x₀ R)) (cont : ∀ x ∈ closed_ball x₀ R, continuous_on (λ t, to_fun t x) (Icc t_min t_max)) (norm_le' : ∀ (t ∈ Icc t_min t_max) (x ∈ closed_ball x₀ R), ∥to_fun t x∥ ≤ C) (C_mul_le_R : (C : ℝ) * max (t_max - t₀) (t₀ - t_min) ≤ R) namespace picard_lindelof variables (v : picard_lindelof E) instance : has_coe_to_fun (picard_lindelof E) (λ _, ℝ → E → E) := ⟨to_fun⟩ instance : inhabited (picard_lindelof E) := ⟨⟨0, 0, 0, ⟨0, le_rfl, le_rfl⟩, 0, 0, 0, 0, λ t ht, (lipschitz_with.const 0).lipschitz_on_with _, λ _ _, by simpa only [pi.zero_apply] using continuous_on_const, λ t ht x hx, norm_zero.le, (zero_mul _).le⟩⟩ lemma t_min_le_t_max : v.t_min ≤ v.t_max := v.t₀.2.1.trans v.t₀.2.2 protected lemma nonempty_Icc : (Icc v.t_min v.t_max).nonempty := nonempty_Icc.2 v.t_min_le_t_max protected lemma lipschitz_on_with {t} (ht : t ∈ Icc v.t_min v.t_max) : lipschitz_on_with v.L (v t) (closed_ball v.x₀ v.R) := v.lipschitz' t ht protected lemma continuous_on : continuous_on (uncurry v) (Icc v.t_min v.t_max ×ˢ closed_ball v.x₀ v.R) := have continuous_on (uncurry (flip v)) (closed_ball v.x₀ v.R ×ˢ Icc v.t_min v.t_max), from continuous_on_prod_of_continuous_on_lipschitz_on _ v.L v.cont v.lipschitz', this.comp continuous_swap.continuous_on preimage_swap_prod.symm.subset lemma norm_le {t : ℝ} (ht : t ∈ Icc v.t_min v.t_max) {x : E} (hx : x ∈ closed_ball v.x₀ v.R) : ∥v t x∥ ≤ v.C := v.norm_le' _ ht _ hx /-- The maximum of distances from `t₀` to the endpoints of `[t_min, t_max]`. -/ def t_dist : ℝ := max (v.t_max - v.t₀) (v.t₀ - v.t_min) lemma t_dist_nonneg : 0 ≤ v.t_dist := le_max_iff.2 $ or.inl $ sub_nonneg.2 v.t₀.2.2 lemma dist_t₀_le (t : Icc v.t_min v.t_max) : dist t v.t₀ ≤ v.t_dist := begin rw [subtype.dist_eq, real.dist_eq], cases le_total t v.t₀ with ht ht, { rw [abs_of_nonpos (sub_nonpos.2 $ subtype.coe_le_coe.2 ht), neg_sub], exact (sub_le_sub_left t.2.1 _).trans (le_max_right _ _) }, { rw [abs_of_nonneg (sub_nonneg.2 $ subtype.coe_le_coe.2 ht)], exact (sub_le_sub_right t.2.2 _).trans (le_max_left _ _) } end /-- Projection $ℝ → [t_{\min}, t_{\max}]$ sending $(-∞, t_{\min}]$ to $t_{\min}$ and $[t_{\max}, ∞)$ to $t_{\max}$. -/ def proj : ℝ → Icc v.t_min v.t_max := proj_Icc v.t_min v.t_max v.t_min_le_t_max lemma proj_coe (t : Icc v.t_min v.t_max) : v.proj t = t := proj_Icc_coe _ _ lemma proj_of_mem {t : ℝ} (ht : t ∈ Icc v.t_min v.t_max) : ↑(v.proj t) = t := by simp only [proj, proj_Icc_of_mem _ ht, subtype.coe_mk] @[continuity] lemma continuous_proj : continuous v.proj := continuous_proj_Icc /-- The space of curves $γ \colon [t_{\min}, t_{\max}] \to E$ such that $γ(t₀) = x₀$ and $γ$ is Lipschitz continuous with constant $C$. The map sending $γ$ to $\mathbf Pγ(t)=x₀ + ∫_{t₀}^{t} v(τ, γ(τ))\,dτ$ is a contracting map on this space, and its fixed point is a solution of the ODE $\dot x=v(t, x)$. -/ structure fun_space := (to_fun : Icc v.t_min v.t_max → E) (map_t₀' : to_fun v.t₀ = v.x₀) (lipschitz' : lipschitz_with v.C to_fun) namespace fun_space variables {v} (f : fun_space v) instance : has_coe_to_fun (fun_space v) (λ _, Icc v.t_min v.t_max → E) := ⟨to_fun⟩ instance : inhabited v.fun_space := ⟨⟨λ _, v.x₀, rfl, (lipschitz_with.const _).weaken (zero_le _)⟩⟩ protected lemma lipschitz : lipschitz_with v.C f := f.lipschitz' protected lemma continuous : continuous f := f.lipschitz.continuous /-- Each curve in `picard_lindelof.fun_space` is continuous. -/ def to_continuous_map : v.fun_space ↪ C(Icc v.t_min v.t_max, E) := ⟨λ f, ⟨f, f.continuous⟩, λ f g h, by { cases f, cases g, simpa using h }⟩ instance : metric_space v.fun_space := metric_space.induced to_continuous_map to_continuous_map.injective infer_instance lemma uniform_inducing_to_continuous_map : uniform_inducing (@to_continuous_map _ _ _ v) := ⟨rfl⟩ lemma range_to_continuous_map : range to_continuous_map = {f : C(Icc v.t_min v.t_max, E) | f v.t₀ = v.x₀ ∧ lipschitz_with v.C f} := begin ext f, split, { rintro ⟨⟨f, hf₀, hf_lip⟩, rfl⟩, exact ⟨hf₀, hf_lip⟩ }, { rcases f with ⟨f, hf⟩, rintro ⟨hf₀, hf_lip⟩, exact ⟨⟨f, hf₀, hf_lip⟩, rfl⟩ } end lemma map_t₀ : f v.t₀ = v.x₀ := f.map_t₀' protected lemma mem_closed_ball (t : Icc v.t_min v.t_max) : f t ∈ closed_ball v.x₀ v.R := calc dist (f t) v.x₀ = dist (f t) (f.to_fun v.t₀) : by rw f.map_t₀' ... ≤ v.C * dist t v.t₀ : f.lipschitz.dist_le_mul _ _ ... ≤ v.C * v.t_dist : mul_le_mul_of_nonneg_left (v.dist_t₀_le _) v.C.2 ... ≤ v.R : v.C_mul_le_R /-- Given a curve $γ \colon [t_{\min}, t_{\max}] → E$, `v_comp` is the function $F(t)=v(π t, γ(π t))$, where `π` is the projection $ℝ → [t_{\min}, t_{\max}]$. The integral of this function is the image of `γ` under the contracting map we are going to define below. -/ def v_comp (t : ℝ) : E := v (v.proj t) (f (v.proj t)) lemma v_comp_apply_coe (t : Icc v.t_min v.t_max) : f.v_comp t = v t (f t) := by simp only [v_comp, proj_coe] lemma continuous_v_comp : continuous f.v_comp := begin have := (continuous_subtype_coe.prod_mk f.continuous).comp v.continuous_proj, refine continuous_on.comp_continuous v.continuous_on this (λ x, _), exact ⟨(v.proj x).2, f.mem_closed_ball _⟩ end lemma norm_v_comp_le (t : ℝ) : ∥f.v_comp t∥ ≤ v.C := v.norm_le (v.proj t).2 $ f.mem_closed_ball _ lemma dist_apply_le_dist (f₁ f₂ : fun_space v) (t : Icc v.t_min v.t_max) : dist (f₁ t) (f₂ t) ≤ dist f₁ f₂ := @continuous_map.dist_apply_le_dist _ _ _ _ _ f₁.to_continuous_map f₂.to_continuous_map _ lemma dist_le_of_forall {f₁ f₂ : fun_space v} {d : ℝ} (h : ∀ t, dist (f₁ t) (f₂ t) ≤ d) : dist f₁ f₂ ≤ d := (@continuous_map.dist_le_iff_of_nonempty _ _ _ _ _ f₁.to_continuous_map f₂.to_continuous_map _ v.nonempty_Icc.to_subtype).2 h instance [complete_space E] : complete_space v.fun_space := begin refine (complete_space_iff_is_complete_range uniform_inducing_to_continuous_map).2 (is_closed.is_complete _), rw [range_to_continuous_map, set_of_and], refine (is_closed_eq (continuous_map.continuous_evalx _) continuous_const).inter _, have : is_closed {f : Icc v.t_min v.t_max → E | lipschitz_with v.C f} := is_closed_set_of_lipschitz_with v.C, exact this.preimage continuous_map.continuous_coe end variables [measurable_space E] [borel_space E] lemma interval_integrable_v_comp (t₁ t₂ : ℝ) : interval_integrable f.v_comp volume t₁ t₂ := (f.continuous_v_comp).interval_integrable _ _ variables [second_countable_topology E] [complete_space E] /-- The Picard-Lindelöf operator. This is a contracting map on `picard_lindelof.fun_space v` such that the fixed point of this map is the solution of the corresponding ODE. More precisely, some iteration of this map is a contracting map. -/ def next (f : fun_space v) : fun_space v := { to_fun := λ t, v.x₀ + ∫ τ : ℝ in v.t₀..t, f.v_comp τ, map_t₀' := by rw [integral_same, add_zero], lipschitz' := lipschitz_with.of_dist_le_mul $ λ t₁ t₂, begin rw [dist_add_left, dist_eq_norm, integral_interval_sub_left (f.interval_integrable_v_comp _ _) (f.interval_integrable_v_comp _ _)], exact norm_integral_le_of_norm_le_const (λ t ht, f.norm_v_comp_le _), end } lemma next_apply (t : Icc v.t_min v.t_max) : f.next t = v.x₀ + ∫ τ : ℝ in v.t₀..t, f.v_comp τ := rfl lemma has_deriv_within_at_next (t : Icc v.t_min v.t_max) : has_deriv_within_at (f.next ∘ v.proj) (v t (f t)) (Icc v.t_min v.t_max) t := begin haveI : fact ((t : ℝ) ∈ Icc v.t_min v.t_max) := ⟨t.2⟩, simp only [(∘), next_apply], refine has_deriv_within_at.const_add _ _, have : has_deriv_within_at (λ t : ℝ, ∫ τ in v.t₀..t, f.v_comp τ) (f.v_comp t) (Icc v.t_min v.t_max) t, from integral_has_deriv_within_at_right (f.interval_integrable_v_comp _ _) (f.continuous_v_comp.measurable_at_filter _ _) f.continuous_v_comp.continuous_within_at, rw v_comp_apply_coe at this, refine this.congr_of_eventually_eq_of_mem _ t.coe_prop, filter_upwards [self_mem_nhds_within] with _ ht', rw v.proj_of_mem ht' end lemma dist_next_apply_le_of_le {f₁ f₂ : fun_space v} {n : ℕ} {d : ℝ} (h : ∀ t, dist (f₁ t) (f₂ t) ≤ (v.L * |t - v.t₀|) ^ n / n! * d) (t : Icc v.t_min v.t_max) : dist (next f₁ t) (next f₂ t) ≤ (v.L * |t - v.t₀|) ^ (n + 1) / (n + 1)! * d := begin simp only [dist_eq_norm, next_apply, add_sub_add_left_eq_sub, ← interval_integral.integral_sub (interval_integrable_v_comp _ _ _) (interval_integrable_v_comp _ _ _), norm_integral_eq_norm_integral_Ioc] at *, calc ∥∫ τ in Ι (v.t₀ : ℝ) t, f₁.v_comp τ - f₂.v_comp τ∥ ≤ ∫ τ in Ι (v.t₀ : ℝ) t, v.L * ((v.L * |τ - v.t₀|) ^ n / n! * d) : begin refine norm_integral_le_of_norm_le (continuous.integrable_on_interval_oc _) _, { continuity }, { refine (ae_restrict_mem measurable_set_Ioc).mono (λ τ hτ, _), refine (v.lipschitz_on_with (v.proj τ).2).norm_sub_le_of_le (f₁.mem_closed_ball _) (f₂.mem_closed_ball _) ((h _).trans_eq _), rw v.proj_of_mem, exact (interval_subset_Icc v.t₀.2 t.2 $ Ioc_subset_Icc_self hτ) } end ... = (v.L * |t - v.t₀|) ^ (n + 1) / (n + 1)! * d : _, simp_rw [mul_pow, div_eq_mul_inv, mul_assoc, measure_theory.integral_mul_left, measure_theory.integral_mul_right, integral_pow_abs_sub_interval_oc, div_eq_mul_inv, pow_succ (v.L : ℝ), nat.factorial_succ, nat.cast_mul, nat.cast_succ, mul_inv₀, mul_assoc] end lemma dist_iterate_next_apply_le (f₁ f₂ : fun_space v) (n : ℕ) (t : Icc v.t_min v.t_max) : dist (next^[n] f₁ t) (next^[n] f₂ t) ≤ (v.L * |t - v.t₀|) ^ n / n! * dist f₁ f₂ := begin induction n with n ihn generalizing t, { rw [pow_zero, nat.factorial_zero, nat.cast_one, div_one, one_mul], exact dist_apply_le_dist f₁ f₂ t }, { rw [iterate_succ_apply', iterate_succ_apply'], exact dist_next_apply_le_of_le ihn _ } end lemma dist_iterate_next_le (f₁ f₂ : fun_space v) (n : ℕ) : dist (next^[n] f₁) (next^[n] f₂) ≤ (v.L * v.t_dist) ^ n / n! * dist f₁ f₂ := begin refine dist_le_of_forall (λ t, (dist_iterate_next_apply_le _ _ _ _).trans _), have : 0 ≤ dist f₁ f₂ := dist_nonneg, have : |(t - v.t₀ : ℝ)| ≤ v.t_dist := v.dist_t₀_le t, mono*; simp only [nat.cast_nonneg, mul_nonneg, nnreal.coe_nonneg, abs_nonneg, *] end end fun_space variables [second_countable_topology E] [complete_space E] section variables [measurable_space E] [borel_space E] lemma exists_contracting_iterate : ∃ (N : ℕ) K, contracting_with K ((fun_space.next : v.fun_space → v.fun_space)^[N]) := begin rcases ((real.tendsto_pow_div_factorial_at_top (v.L * v.t_dist)).eventually (gt_mem_nhds zero_lt_one)).exists with ⟨N, hN⟩, have : (0 : ℝ) ≤ (v.L * v.t_dist) ^ N / N!, from div_nonneg (pow_nonneg (mul_nonneg v.L.2 v.t_dist_nonneg) _) (nat.cast_nonneg _), exact ⟨N, ⟨_, this⟩, hN, lipschitz_with.of_dist_le_mul (λ f g, fun_space.dist_iterate_next_le f g N)⟩ end lemma exists_fixed : ∃ f : v.fun_space, f.next = f := let ⟨N, K, hK⟩ := exists_contracting_iterate v in ⟨_, hK.is_fixed_pt_fixed_point_iterate⟩ end /-- Picard-Lindelöf (Cauchy-Lipschitz) theorem. -/ lemma exists_solution : ∃ f : ℝ → E, f v.t₀ = v.x₀ ∧ ∀ t ∈ Icc v.t_min v.t_max, has_deriv_within_at f (v t (f t)) (Icc v.t_min v.t_max) t := begin letI : measurable_space E := borel E, haveI : borel_space E := ⟨rfl⟩, rcases v.exists_fixed with ⟨f, hf⟩, refine ⟨f ∘ v.proj, _, λ t ht, _⟩, { simp only [(∘), proj_coe, f.map_t₀] }, { simp only [(∘), v.proj_of_mem ht], lift t to Icc v.t_min v.t_max using ht, simpa only [hf, v.proj_coe] using f.has_deriv_within_at_next t } end end picard_lindelof /-- Picard-Lindelöf (Cauchy-Lipschitz) theorem. -/ lemma exists_forall_deriv_within_Icc_eq_of_lipschitz_of_continuous [complete_space E] [second_countable_topology E] {v : ℝ → E → E} {t_min t₀ t_max : ℝ} (ht₀ : t₀ ∈ Icc t_min t_max) (x₀ : E) {C R : ℝ} (hR : 0 ≤ R) {L : ℝ≥0} (Hlip : ∀ t ∈ Icc t_min t_max, lipschitz_on_with L (v t) (closed_ball x₀ R)) (Hcont : ∀ x ∈ closed_ball x₀ R, continuous_on (λ t, v t x) (Icc t_min t_max)) (Hnorm : ∀ (t ∈ Icc t_min t_max) (x ∈ closed_ball x₀ R), ∥v t x∥ ≤ C) (Hmul_le : C * max (t_max - t₀) (t₀ - t_min) ≤ R) : ∃ f : ℝ → E, f t₀ = x₀ ∧ ∀ t ∈ Icc t_min t_max, has_deriv_within_at f (v t (f t)) (Icc t_min t_max) t := begin lift C to ℝ≥0 using ((norm_nonneg _).trans $ Hnorm t₀ ht₀ x₀ (mem_closed_ball_self hR)), lift R to ℝ≥0 using hR, lift t₀ to Icc t_min t_max using ht₀, exact picard_lindelof.exists_solution ⟨v, t_min, t_max, t₀, x₀, C, R, L, Hlip, Hcont, Hnorm, Hmul_le⟩ end
e68316671e76503b9c7a499c2b404a4b48812331
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Data/Option/Instances.lean
a2eb044390c7f6e9acac1b3321086ff0ef9c7250
[ "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
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
660
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Option.Basic universe u v theorem Option.eq_of_eq_some {α : Type u} : ∀ {x y : Option α}, (∀z, x = some z ↔ y = some z) → x = y | none, none, h => rfl | none, some z, h => Option.noConfusion ((h z).2 rfl) | some z, none, h => Option.noConfusion ((h z).1 rfl) | some z, some w, h => Option.noConfusion ((h w).2 rfl) (congrArg some) theorem Option.eq_none_of_isNone {α : Type u} : ∀ {o : Option α}, o.isNone → o = none | none, h => rfl
372014f9933ffb53b4c1606d7bd13a2ce6f06c7e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/iterate.lean
1dfdb3b58f77d3e6e5afef28f5fdb11d66121d0a
[ "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,077
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 logic.function.iterate import order.monotone.basic /-! # Inequalities on iterates > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove some inequalities comparing `f^[n] x` and `g^[n] x` where `f` and `g` are two self-maps that commute with each other. Current selection of inequalities is motivated by formalization of the rotation number of a circle homeomorphism. -/ variables {α β : Type*} open function namespace monotone variables [preorder α] {f : α → α} {x y : ℕ → α} /-! ### Comparison of two sequences If $f$ is a monotone function, then $∀ k, x_{k+1} ≤ f(x_k)$ implies that $x_k$ grows slower than $f^k(x_0)$, and similarly for the reversed inequalities. If $x_k$ and $y_k$ are two sequences such that $x_{k+1} ≤ f(x_k)$ and $y_{k+1} ≥ f(y_k)$ for all $k < n$, then $x_0 ≤ y_0$ implies $x_n ≤ y_n$, see `monotone.seq_le_seq`. If some of the inequalities in this lemma are strict, then we have $x_n < y_n$. The rest of the lemmas in this section formalize this fact for different inequalities made strict. -/ lemma seq_le_seq (hf : monotone f) (n : ℕ) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n ≤ y n := begin induction n with n ihn, { exact h₀ }, { refine (hx _ n.lt_succ_self).trans ((hf $ ihn _ _).trans (hy _ n.lt_succ_self)), exact λ k hk, hx _ (hk.trans n.lt_succ_self), exact λ k hk, hy _ (hk.trans n.lt_succ_self) } end lemma seq_pos_lt_seq_of_lt_of_le (hf : monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n < y n := begin induction n with n ihn, { exact hn.false.elim }, suffices : x n ≤ y n, from (hx n n.lt_succ_self).trans_le ((hf this).trans $ hy n n.lt_succ_self), cases n, { exact h₀ }, refine (ihn n.zero_lt_succ (λ k hk, hx _ _) (λ k hk, hy _ _)).le; exact hk.trans n.succ.lt_succ_self end lemma seq_pos_lt_seq_of_le_of_lt (hf : monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) : x n < y n := hf.dual.seq_pos_lt_seq_of_lt_of_le hn h₀ hy hx lemma seq_lt_seq_of_lt_of_le (hf : monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) : x n < y n := by { cases n, exacts [h₀, hf.seq_pos_lt_seq_of_lt_of_le n.zero_lt_succ h₀.le hx hy] } lemma seq_lt_seq_of_le_of_lt (hf : monotone f) (n : ℕ) (h₀ : x 0 < y 0) (hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) : x n < y n := hf.dual.seq_lt_seq_of_lt_of_le n h₀ hy hx /-! ### Iterates of two functions In this section we compare the iterates of a monotone function `f : α → α` to iterates of any function `g : β → β`. If `h : β → α` satisfies `h ∘ g ≤ f ∘ h`, then `h (g^[n] x)` grows slower than `f^[n] (h x)`, and similarly for the reversed inequality. Then we specialize these two lemmas to the case `β = α`, `h = id`. -/ variables {g : β → β} {h : β → α} open function lemma le_iterate_comp_of_le (hf : monotone f) (H : h ∘ g ≤ f ∘ h) (n : ℕ) : h ∘ (g^[n]) ≤ (f^[n]) ∘ h := λ x, by refine hf.seq_le_seq n _ (λ k hk, _) (λ k hk, _); simp [iterate_succ', H _] lemma iterate_comp_le_of_le (hf : monotone f) (H : f ∘ h ≤ h ∘ g) (n : ℕ) : f^[n] ∘ h ≤ h ∘ (g^[n]) := hf.dual.le_iterate_comp_of_le H n /-- If `f ≤ g` and `f` is monotone, then `f^[n] ≤ g^[n]`. -/ lemma iterate_le_of_le {g : α → α} (hf : monotone f) (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := hf.iterate_comp_le_of_le h n /-- If `f ≤ g` and `g` is monotone, then `f^[n] ≤ g^[n]`. -/ lemma le_iterate_of_le {g : α → α} (hg : monotone g) (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := hg.dual.iterate_le_of_le h n end monotone /-! ### Comparison of iterations and the identity function If $f(x) ≤ x$ for all $x$ (we express this as `f ≤ id` in the code), then the same is true for any iterate of $f$, and similarly for the reversed inequality. -/ namespace function section preorder variables [preorder α] {f : α → α} /-- If $x ≤ f x$ for all $x$ (we write this as `id ≤ f`), then the same is true for any iterate `f^[n]` of `f`. -/ lemma id_le_iterate_of_id_le (h : id ≤ f) (n : ℕ) : id ≤ (f^[n]) := by simpa only [iterate_id] using monotone_id.iterate_le_of_le h n lemma iterate_le_id_of_le_id (h : f ≤ id) (n : ℕ) : (f^[n]) ≤ id := @id_le_iterate_of_id_le αᵒᵈ _ f h n lemma monotone_iterate_of_id_le (h : id ≤ f) : monotone (λ m, f^[m]) := monotone_nat_of_le_succ $ λ n x, by { rw iterate_succ_apply', exact h _ } lemma antitone_iterate_of_le_id (h : f ≤ id) : antitone (λ m, f^[m]) := λ m n hmn, @monotone_iterate_of_id_le αᵒᵈ _ f h m n hmn end preorder /-! ### Iterates of commuting functions If `f` and `g` are monotone and commute, then `f x ≤ g x` implies `f^[n] x ≤ g^[n] x`, see `function.commute.iterate_le_of_map_le`. We also prove two strict inequality versions of this lemma, as well as `iff` versions. -/ namespace commute section preorder variables [preorder α] {f g : α → α} lemma iterate_le_of_map_le (h : commute f g) (hf : monotone f) (hg : monotone g) {x} (hx : f x ≤ g x) (n : ℕ) : f^[n] x ≤ (g^[n]) x := by refine hf.seq_le_seq n _ (λ k hk, _) (λ k hk, _); simp [iterate_succ' f, h.iterate_right _ _, hg.iterate _ hx] lemma iterate_pos_lt_of_map_lt (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x} (hx : f x < g x) {n} (hn : 0 < n) : f^[n] x < (g^[n]) x := by refine hf.seq_pos_lt_seq_of_le_of_lt hn _ (λ k hk, _) (λ k hk, _); simp [iterate_succ' f, h.iterate_right _ _, hg.iterate _ hx] lemma iterate_pos_lt_of_map_lt' (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x} (hx : f x < g x) {n} (hn : 0 < n) : f^[n] x < (g^[n]) x := @iterate_pos_lt_of_map_lt αᵒᵈ _ g f h.symm hg.dual hf.dual x hx n hn end preorder variables [linear_order α] {f g : α → α} lemma iterate_pos_lt_iff_map_lt (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x n} (hn : 0 < n) : f^[n] x < (g^[n]) x ↔ f x < g x := begin rcases lt_trichotomy (f x) (g x) with H|H|H, { simp only [*, iterate_pos_lt_of_map_lt] }, { simp only [*, h.iterate_eq_of_map_eq, lt_irrefl] }, { simp only [lt_asymm H, lt_asymm (h.symm.iterate_pos_lt_of_map_lt' hg hf H hn)] } end lemma iterate_pos_lt_iff_map_lt' (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x n} (hn : 0 < n) : f^[n] x < (g^[n]) x ↔ f x < g x := @iterate_pos_lt_iff_map_lt αᵒᵈ _ _ _ h.symm hg.dual hf.dual x n hn lemma iterate_pos_le_iff_map_le (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x n} (hn : 0 < n) : f^[n] x ≤ (g^[n]) x ↔ f x ≤ g x := by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt' hg hf hn) lemma iterate_pos_le_iff_map_le' (h : commute f g) (hf : strict_mono f) (hg : monotone g) {x n} (hn : 0 < n) : f^[n] x ≤ (g^[n]) x ↔ f x ≤ g x := by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt hg hf hn) lemma iterate_pos_eq_iff_map_eq (h : commute f g) (hf : monotone f) (hg : strict_mono g) {x n} (hn : 0 < n) : f^[n] x = (g^[n]) x ↔ f x = g x := by simp only [le_antisymm_iff, h.iterate_pos_le_iff_map_le hf hg hn, h.symm.iterate_pos_le_iff_map_le' hg hf hn] end commute end function namespace monotone variables [preorder α] {f : α → α} {x : α} /-- If `f` is a monotone map and `x ≤ f x` at some point `x`, then the iterates `f^[n] x` form a monotone sequence. -/ lemma monotone_iterate_of_le_map (hf : monotone f) (hx : x ≤ f x) : monotone (λ n, f^[n] x) := monotone_nat_of_le_succ $ λ n, by { rw iterate_succ_apply, exact hf.iterate n hx } /-- If `f` is a monotone map and `f x ≤ x` at some point `x`, then the iterates `f^[n] x` form a antitone sequence. -/ lemma antitone_iterate_of_map_le (hf : monotone f) (hx : f x ≤ x) : antitone (λ n, f^[n] x) := hf.dual.monotone_iterate_of_le_map hx end monotone namespace strict_mono variables [preorder α] {f : α → α} {x : α} /-- If `f` is a strictly monotone map and `x < f x` at some point `x`, then the iterates `f^[n] x` form a strictly monotone sequence. -/ lemma strict_mono_iterate_of_lt_map (hf : strict_mono f) (hx : x < f x) : strict_mono (λ n, f^[n] x) := strict_mono_nat_of_lt_succ $ λ n, by { rw iterate_succ_apply, exact hf.iterate n hx } /-- If `f` is a strictly antitone map and `f x < x` at some point `x`, then the iterates `f^[n] x` form a strictly antitone sequence. -/ lemma strict_anti_iterate_of_map_lt (hf : strict_mono f) (hx : f x < x) : strict_anti (λ n, f^[n] x) := hf.dual.strict_mono_iterate_of_lt_map hx end strict_mono
90663c06a25e78ca3da2ee29d83ac3cd2e9b5b6a
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/ring_theory/valuation/integral.lean
a92c3437d8f20ff206b488d3da483cf41698005d
[ "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
2,069
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.integrally_closed import ring_theory.valuation.integers /-! # Integral elements over the ring of integers of a valution The ring of integers is integrally closed inside the original ring. -/ universes u v w open_locale big_operators namespace valuation namespace integers section comm_ring variables {R : Type u} {Γ₀ : Type v} [comm_ring R] [linear_ordered_comm_group_with_zero Γ₀] variables {v : valuation R Γ₀} {O : Type w} [comm_ring O] [algebra O R] (hv : integers v O) include hv open polynomial lemma mem_of_integral {x : R} (hx : is_integral O x) : x ∈ v.integer := let ⟨p, hpm, hpx⟩ := hx in le_of_not_lt $ λ hvx, begin rw [hpm.as_sum, eval₂_add, eval₂_pow, eval₂_X, eval₂_finset_sum, add_eq_zero_iff_eq_neg] at hpx, replace hpx := congr_arg v hpx, refine ne_of_gt _ hpx, rw [v.map_neg, v.map_pow], refine v.map_sum_lt' (zero_lt_one''.trans_le (one_le_pow_of_one_le' hvx.le _)) (λ i hi, _), rw [eval₂_mul, eval₂_pow, eval₂_C, eval₂_X, v.map_mul, v.map_pow, ← one_mul (v x ^ p.nat_degree)], cases (hv.2 $ p.coeff i).lt_or_eq with hvpi hvpi, { exact mul_lt_mul'''' hvpi (pow_lt_pow' hvx $ finset.mem_range.1 hi) }, { erw hvpi, rw [one_mul, one_mul], exact pow_lt_pow' hvx (finset.mem_range.1 hi) } end protected lemma integral_closure : integral_closure O R = ⊥ := bot_unique $ λ r hr, let ⟨x, hx⟩ := hv.3 (hv.mem_of_integral hr) in algebra.mem_bot.2 ⟨x, hx⟩ end comm_ring section fraction_field variables {K : Type u} {Γ₀ : Type v} [field K] [linear_ordered_comm_group_with_zero Γ₀] variables {v : valuation K Γ₀} {O : Type w} [integral_domain O] [algebra O K] [is_fraction_ring O K] variables (hv : integers v O) lemma integrally_closed : is_integrally_closed O := (is_integrally_closed.integral_closure_eq_bot_iff K).mp (valuation.integers.integral_closure hv) end fraction_field end integers end valuation
fb8048c51c836ccbe3b9c034dedc90e98147064e
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/rat/order.lean
eebc444d157a6fc5821e04751d61cddca6f77426
[ "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
8,397
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.basic /-! # Order for Rational Numbers ## Summary We define the order on `ℚ`, prove that `ℚ` is a discrete, linearly ordered field, and define functions such as `abs` and `sqrt` that depend on this order. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, order, ordering, sqrt, abs -/ namespace rat variables (a b c : ℚ) open_locale rat protected def nonneg : ℚ → Prop | ⟨n, d, h, c⟩ := 0 ≤ n @[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : 0 < b) : (a /. b).nonneg ↔ 0 ≤ a := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, simp [rat.nonneg], have d0 := int.coe_nat_lt.2 h₁, have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha, constructor; intro h₂, { apply nonneg_of_mul_nonneg_right _ d0, rw this, exact mul_nonneg h₂ (le_of_lt h) }, { apply nonneg_of_mul_nonneg_right _ h, rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) }, end protected lemma nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], intros n₁0 n₂0, apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}, end protected lemma nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0, mul_nonneg] { contextual := tt } end protected lemma nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 := num_denom_cases_on' a $ λ n d h, begin have d0 : 0 < (d:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h), simp [d0, h], exact λ h₁ h₂, le_antisymm h₂ h₁ end protected lemma nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) := by cases a with n; exact or.imp_right neg_nonneg_of_nonpos (le_total 0 n) instance decidable_nonneg : decidable (rat.nonneg a) := by cases a; unfold rat.nonneg; apply_instance protected def le (a b : ℚ) := rat.nonneg (b - a) instance : has_le ℚ := ⟨rat.le⟩ instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop) | a b := show decidable (rat.nonneg (b - a)), by apply_instance protected theorem le_def {a b c d : ℤ} (b0 : 0 < b) (d0 : 0 < d) : a /. b ≤ c /. d ↔ a * d ≤ c * b := begin show rat.nonneg _ ↔ _, rw ← sub_nonneg, simp [sub_eq_add_neg, ne_of_gt b0, ne_of_gt d0, mul_pos d0 b0] end protected theorem le_refl : a ≤ a := show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ) protected theorem le_total : a ≤ b ∨ b ≤ a := by have := rat.nonneg_total (b - a); rwa neg_sub at this protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b := by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa); rwa neg_neg at this protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc, by simpa [sub_eq_add_neg, add_comm, add_left_comm] instance : linear_order ℚ := { le := rat.le, le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := rat.le_total, decidable_eq := by apply_instance, decidable_le := assume a b, rat.decidable_nonneg (b - a) } /- Extra instances to short-circuit type class resolution -/ instance : has_lt ℚ := by apply_instance instance : distrib_lattice ℚ := by apply_instance instance : lattice ℚ := by apply_instance instance : semilattice_inf ℚ := by apply_instance instance : semilattice_sup ℚ := by apply_instance instance : has_inf ℚ := by apply_instance instance : has_sup ℚ := by apply_instance instance : partial_order ℚ := by apply_instance instance : preorder ℚ := by apply_instance protected lemma le_def' {p q : ℚ} : p ≤ q ↔ p.num * q.denom ≤ q.num * p.denom := begin rw [←(@num_denom q), ←(@num_denom p)], conv_rhs { simp only [num_denom] }, exact rat.le_def (by exact_mod_cast p.pos) (by exact_mod_cast q.pos) end protected lemma lt_def {p q : ℚ} : p < q ↔ p.num * q.denom < q.num * p.denom := begin rw [lt_iff_le_and_ne, rat.le_def'], suffices : p ≠ q ↔ p.num * q.denom ≠ q.num * p.denom, by { split; intro h, { exact lt_iff_le_and_ne.elim_right ⟨h.left, (this.elim_left h.right)⟩ }, { have tmp := lt_iff_le_and_ne.elim_left h, exact ⟨tmp.left, this.elim_right tmp.right⟩ }}, exact (not_iff_not.elim_right eq_iff_mul_eq_mul) end theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a := show rat.nonneg a ↔ rat.nonneg (a - 0), by simp theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a | ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩ protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b := by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb instance : linear_ordered_field ℚ := { zero_le_one := dec_trivial, add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab, mul_pos := assume a b ha hb, lt_of_le_of_ne (rat.mul_nonneg (le_of_lt ha) (le_of_lt hb)) (mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm, ..rat.field, ..rat.linear_order, ..rat.semiring } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_ring ℚ := by apply_instance instance : ordered_ring ℚ := by apply_instance instance : linear_ordered_semiring ℚ := by apply_instance instance : ordered_semiring ℚ := by apply_instance instance : linear_ordered_add_comm_group ℚ := by apply_instance instance : ordered_add_comm_group ℚ := by apply_instance instance : ordered_cancel_add_comm_monoid ℚ := by apply_instance instance : ordered_add_comm_monoid ℚ := by apply_instance attribute [irreducible] rat.le theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a := lt_iff_lt_of_le_iff_le $ by simpa [(by cases a; refl : (-a).num = -a.num)] using @num_nonneg_iff_zero_le (-a) lemma div_lt_div_iff_mul_lt_mul {a b c d : ℤ} (b_pos : 0 < b) (d_pos : 0 < d) : (a : ℚ) / b < c / d ↔ a * d < c * b := begin simp only [lt_iff_le_not_le], apply and_congr, { simp [div_num_denom, (rat.le_def b_pos d_pos)] }, { apply not_iff_not_of_iff, simp [div_num_denom, (rat.le_def d_pos b_pos)] } end lemma lt_one_iff_num_lt_denom {q : ℚ} : q < 1 ↔ q.num < q.denom := begin cases decidable.em (0 < q) with q_pos q_nonpos, { simp [rat.lt_def] }, { replace q_nonpos : q ≤ 0, from not_lt.elim_left q_nonpos, have : q.num < q.denom, by { have : ¬0 < q.num ↔ ¬0 < q, from not_iff_not.elim_right num_pos_iff_pos, simp only [not_lt] at this, exact lt_of_le_of_lt (this.elim_right q_nonpos) (by exact_mod_cast q.pos) }, simp only [this, (lt_of_le_of_lt q_nonpos zero_lt_one)] } end theorem abs_def (q : ℚ) : abs q = q.num.nat_abs /. q.denom := begin have hz : (0:ℚ) = 0 /. 1 := rfl, cases le_total q 0 with hq hq, { rw [abs_of_nonpos hq], rw [←(@num_denom q), hz, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one, mul_one, zero_mul] at hq, rw [int.of_nat_nat_abs_of_nonpos hq, ← neg_def, num_denom] }, { rw [abs_of_nonneg hq], rw [←(@num_denom q), hz, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos), mul_one, zero_mul] at hq, rw [int.nat_abs_of_nonneg hq, num_denom] } end end rat
0305ce9b52ea76e272b867f230d03e326025d287
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/algebra/ring.lean
c5c3b0100e52965d123dca4c0fcd5f7f30fe184b
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
3,777
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Theory of topological rings. -/ import topology.algebra.group ring_theory.ideals open classical set lattice filter topological_space open_locale classical section topological_ring universes u v w variables (α : Type u) [topological_space α] /-- A topological semiring is a semiring where addition and multiplication are continuous. -/ class topological_semiring [semiring α] extends topological_add_monoid α, topological_monoid α : Prop variables [ring α] /-- A topological ring is a ring where the ring operations are continuous. -/ class topological_ring extends topological_add_monoid α, topological_monoid α : Prop := (continuous_neg : continuous (λa:α, -a)) variables [t : topological_ring α] instance topological_ring.to_topological_semiring : topological_semiring α := {..t} instance topological_ring.to_topological_add_group : topological_add_group α := {..t} end topological_ring section topological_comm_ring variables {α : Type*} [topological_space α] [comm_ring α] [topological_ring α] def ideal.closure (S : ideal α) : ideal α := { carrier := closure S, zero := subset_closure S.zero_mem, add := assume x y hx hy, mem_closure2 continuous_add' hx hy $ assume a b, S.add_mem, smul := assume c x hx, have continuous (λx:α, c * x) := continuous_mul continuous_const continuous_id, mem_closure this hx $ assume a, S.mul_mem_left } @[simp] lemma ideal.coe_closure (S : ideal α) : (S.closure : set α) = closure S := rfl end topological_comm_ring section topological_ring variables {α : Type*} [topological_space α] [comm_ring α] (N : ideal α) open ideal.quotient instance topological_ring_quotient_topology : topological_space N.quotient := by dunfold ideal.quotient submodule.quotient; apply_instance lemma quotient_ring_saturate {α : Type*} [comm_ring α] (N : ideal α) (s : set α) : mk N ⁻¹' (mk N '' s) = (⋃ x : N, (λ y, x.1 + y) '' s) := begin ext x, simp only [mem_preimage, mem_image, mem_Union, ideal.quotient.eq], split, { exact assume ⟨a, a_in, h⟩, ⟨⟨_, N.neg_mem h⟩, a, a_in, by simp⟩ }, { exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by rw [← eq, sub_add_eq_sub_sub_swap, sub_self, zero_sub]; exact N.neg_mem hi⟩ } end variable [topological_ring α] lemma quotient_ring.is_open_map_coe : is_open_map (mk N) := begin assume s s_op, show is_open (mk N ⁻¹' (mk N '' s)), rw quotient_ring_saturate N s, exact is_open_Union (assume ⟨n, _⟩, is_open_map_add_left n s s_op) end lemma quotient_ring.quotient_map_coe_coe : quotient_map (λ p : α × α, (mk N p.1, mk N p.2)) := begin apply is_open_map.to_quotient_map, { exact is_open_map.prod (quotient_ring.is_open_map_coe N) (quotient_ring.is_open_map_coe N) }, { apply continuous.prod_mk, { exact continuous_quot_mk.comp continuous_fst }, { exact continuous_quot_mk.comp continuous_snd } }, { rintro ⟨⟨x⟩, ⟨y⟩⟩, exact ⟨(x, y), rfl⟩ } end instance topological_ring_quotient : topological_ring N.quotient := { continuous_add := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst + p.snd)) := continuous_quot_mk.comp continuous_add', (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).2 cont, continuous_neg := continuous_quotient_lift _ (continuous_quot_mk.comp continuous_neg'), continuous_mul := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul', (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).2 cont } end topological_ring
7ca6a8fa643d20bf564f104b21de4794d7538c50
94e33a31faa76775069b071adea97e86e218a8ee
/src/geometry/manifold/partition_of_unity.lean
76fec8fd69de3c58a3a18011427bf7a7348a0d32
[ "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
18,920
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 geometry.manifold.algebra.structures import geometry.manifold.bump_function import topology.paracompact import topology.partition_of_unity import topology.shrinking_lemma /-! # Smooth partition of unity In this file we define two structures, `smooth_bump_covering` and `smooth_partition_of_unity`. Both structures describe coverings of a set by a locally finite family of supports of smooth functions with some additional properties. The former structure is mostly useful as an intermediate step in the construction of a smooth partition of unity but some proofs that traditionally deal with a partition of unity can use a `smooth_bump_covering` as well. Given a real manifold `M` and its subset `s`, a `smooth_bump_covering ι I M s` is a collection of `smooth_bump_function`s `f i` indexed by `i : ι` such that * the center of each `f i` belongs to `s`; * the family of sets `support (f i)` is locally finite; * for each `x ∈ s`, there exists `i : ι` such that `f i =ᶠ[𝓝 x] 1`. In the same settings, a `smooth_partition_of_unity ι I M s` is a collection of smooth nonnegative functions `f i : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯`, `i : ι`, such that * the family of sets `support (f i)` is locally finite; * for each `x ∈ s`, the sum `∑ᶠ i, f i x` equals one; * for each `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. We prove that on a smooth finitely dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s` subordinate to `U`. Then we use this fact to prove a similar statement about smooth partitions of unity. ## Implementation notes ## TODO * Build a framework for to transfer local definitions to global using partition of unity and use it to define, e.g., the integral of a differential form over a manifold. ## Tags smooth bump function, partition of unity -/ universes uι uE uH uM open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory variables {ι : Type uι} {E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] (I : model_with_corners ℝ E H) {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] /-! ### Covering by supports of smooth bump functions In this section we define `smooth_bump_covering ι I M s` to be a collection of `smooth_bump_function`s such that their supports is a locally finite family of sets and for each `x ∈ s` some function `f i` from the collection is equal to `1` in a neighborhood of `x`. A covering of this type is useful to construct a smooth partition of unity and can be used instead of a partition of unity in some proofs. We prove that on a smooth finite dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s` subordinate to `U`. Then we use this fact to prove a version of the Whitney embedding theorem: any compact real manifold can be embedded into `ℝ^n` for large enough `n`. -/ variables (ι M) /-- We say that a collection of `smooth_bump_function`s is a `smooth_bump_covering` of a set `s` if * `(f i).c ∈ s` for all `i`; * the family `λ i, support (f i)` is locally finite; * for each point `x ∈ s` there exists `i` such that `f i =ᶠ[𝓝 x] 1`; in other words, `x` belongs to the interior of `{y | f i y = 1}`; If `M` is a finite dimensional real manifold which is a `σ`-compact Hausdorff topological space, then for every covering `U : M → set M`, `∀ x, U x ∈ 𝓝 x`, there exists a `smooth_bump_covering` subordinate to `U`, see `smooth_bump_covering.exists_is_subordinate`. This covering can be used, e.g., to construct a partition of unity and to prove the weak Whitney embedding theorem. -/ @[nolint has_inhabited_instance] structure smooth_bump_covering (s : set M := univ) := (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (c_mem' : ∀ i, c i ∈ s) (locally_finite' : locally_finite (λ i, support (to_fun i))) (eventually_eq_one' : ∀ x ∈ s, ∃ i, to_fun i =ᶠ[𝓝 x] 1) /-- We say that that a collection of functions form a smooth partition of unity on a set `s` if * all functions are infinitely smooth and nonnegative; * the family `λ i, support (f i)` is locally finite; * for all `x ∈ s` the sum `∑ᶠ i, f i x` equals one; * for all `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. -/ structure smooth_partition_of_unity (s : set M := univ) := (to_fun : ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) (locally_finite' : locally_finite (λ i, support (to_fun i))) (nonneg' : ∀ i x, 0 ≤ to_fun i x) (sum_eq_one' : ∀ x ∈ s, ∑ᶠ i, to_fun i x = 1) (sum_le_one' : ∀ x, ∑ᶠ i, to_fun i x ≤ 1) variables {ι I M} namespace smooth_partition_of_unity variables {s : set M} (f : smooth_partition_of_unity ι I M s) instance {s : set M} : has_coe_to_fun (smooth_partition_of_unity ι I M s) (λ _, ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) := ⟨smooth_partition_of_unity.to_fun⟩ protected lemma locally_finite : locally_finite (λ i, support (f i)) := f.locally_finite' lemma nonneg (i : ι) (x : M) : 0 ≤ f i x := f.nonneg' i x lemma sum_eq_one {x} (hx : x ∈ s) : ∑ᶠ i, f i x = 1 := f.sum_eq_one' x hx lemma sum_le_one (x : M) : ∑ᶠ i, f i x ≤ 1 := f.sum_le_one' x /-- Reinterpret a smooth partition of unity as a continuous partition of unity. -/ def to_partition_of_unity : partition_of_unity ι M s := { to_fun := λ i, f i, .. f } lemma smooth_sum : smooth I 𝓘(ℝ) (λ x, ∑ᶠ i, f i x) := smooth_finsum (λ i, (f i).smooth) f.locally_finite lemma le_one (i : ι) (x : M) : f i x ≤ 1 := f.to_partition_of_unity.le_one i x lemma sum_nonneg (x : M) : 0 ≤ ∑ᶠ i, f i x := f.to_partition_of_unity.sum_nonneg x /-- A smooth partition of unity `f i` is subordinate to a family of sets `U i` indexed by the same type if for each `i` the closure of the support of `f i` is a subset of `U i`. -/ def is_subordinate (f : smooth_partition_of_unity ι I M s) (U : ι → set M) := ∀ i, tsupport (f i) ⊆ U i @[simp] lemma is_subordinate_to_partition_of_unity {f : smooth_partition_of_unity ι I M s} {U : ι → set M} : f.to_partition_of_unity.is_subordinate U ↔ f.is_subordinate U := iff.rfl alias is_subordinate_to_partition_of_unity ↔ _ is_subordinate.to_partition_of_unity end smooth_partition_of_unity namespace bump_covering -- Repeat variables to drop [finite_dimensional ℝ E] and [smooth_manifold_with_corners I M] lemma smooth_to_partition_of_unity {E : Type uE} [normed_group E] [normed_space ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] {s : set M} (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) : smooth I 𝓘(ℝ) (f.to_partition_of_unity i) := (hf i).mul $ smooth_finprod_cond (λ j _, smooth_const.sub (hf j)) $ by { simp only [mul_support_one_sub], exact f.locally_finite } variables {s : set M} /-- A `bump_covering` such that all functions in this covering are smooth generates a smooth partition of unity. In our formalization, not every `f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`; instead, a `smooth_bump_covering` is a covering by supports of `smooth_bump_function`s. So, we define `bump_covering.to_smooth_partition_of_unity`, then reuse it in `smooth_bump_covering.to_smooth_partition_of_unity`. -/ def to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : smooth_partition_of_unity ι I M s := { to_fun := λ i, ⟨f.to_partition_of_unity i, f.smooth_to_partition_of_unity hf i⟩, .. f.to_partition_of_unity } @[simp] lemma to_smooth_partition_of_unity_to_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : (f.to_smooth_partition_of_unity hf).to_partition_of_unity = f.to_partition_of_unity := rfl @[simp] lemma coe_to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) : ⇑(f.to_smooth_partition_of_unity hf i) = f.to_partition_of_unity i := rfl lemma is_subordinate.to_smooth_partition_of_unity {f : bump_covering ι M s} {U : ι → set M} (h : f.is_subordinate U) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : (f.to_smooth_partition_of_unity hf).is_subordinate U := h.to_partition_of_unity end bump_covering namespace smooth_bump_covering variables {s : set M} {U : M → set M} (fs : smooth_bump_covering ι I M s) {I} instance : has_coe_to_fun (smooth_bump_covering ι I M s) (λ x, Π (i : ι), smooth_bump_function I (x.c i)) := ⟨to_fun⟩ @[simp] lemma coe_mk (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (h₁ h₂ h₃) : ⇑(mk c to_fun h₁ h₂ h₃ : smooth_bump_covering ι I M s) = to_fun := rfl /-- We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. -/ def is_subordinate {s : set M} (f : smooth_bump_covering ι I M s) (U : M → set M) := ∀ i, tsupport (f i) ⊆ U (f.c i) lemma is_subordinate.support_subset {fs : smooth_bump_covering ι I M s} {U : M → set M} (h : fs.is_subordinate U) (i : ι) : support (fs i) ⊆ U (fs.c i) := subset.trans subset_closure (h i) variable (I) /-- Let `M` be a smooth manifold with corners modelled on a finite dimensional real vector space. Suppose also that `M` is a Hausdorff `σ`-compact topological space. Let `s` be a closed set in `M` and `U : M → set M` be a collection of sets such that `U x ∈ 𝓝 x` for every `x ∈ s`. Then there exists a smooth bump covering of `s` that is subordinate to `U`. -/ lemma exists_is_subordinate [t2_space M] [sigma_compact_space M] (hs : is_closed s) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ (ι : Type uM) (f : smooth_bump_covering ι I M s), f.is_subordinate U := begin -- First we deduce some missing instances haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, -- Next we choose a covering by supports of smooth bump functions have hB := λ x hx, smooth_bump_function.nhds_basis_support I (hU x hx), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis_set hs hB with ⟨ι, c, f, hf, hsub', hfin⟩, choose hcs hfU using hf, /- Then we use the shrinking lemma to get a covering by smaller open -/ rcases exists_subset_Union_closed_subset hs (λ i, (f i).open_support) (λ x hx, hfin.point_finite x) hsub' with ⟨V, hsV, hVc, hVf⟩, choose r hrR hr using λ i, (f i).exists_r_pos_lt_subset_ball (hVc i) (hVf i), refine ⟨ι, ⟨c, λ i, (f i).update_r (r i) (hrR i), hcs, _, λ x hx, _⟩, λ i, _⟩, { simpa only [smooth_bump_function.support_update_r] }, { refine (mem_Union.1 $ hsV hx).imp (λ i hi, _), exact ((f i).update_r _ _).eventually_eq_one_of_dist_lt ((f i).support_subset_source $ hVf _ hi) (hr i hi).2 }, { simpa only [coe_mk, smooth_bump_function.support_update_r, tsupport] using hfU i } end variables {I M} protected lemma locally_finite : locally_finite (λ i, support (fs i)) := fs.locally_finite' protected lemma point_finite (x : M) : {i | fs i x ≠ 0}.finite := fs.locally_finite.point_finite x lemma mem_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) : x ∈ (chart_at H (fs.c i)).source := (fs i).support_subset_source $ by simp [h] lemma mem_ext_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) : x ∈ (ext_chart_at I (fs.c i)).source := by { rw ext_chart_at_source, exact fs.mem_chart_at_source_of_eq_one h } /-- Index of a bump function such that `fs i =ᶠ[𝓝 x] 1`. -/ def ind (x : M) (hx : x ∈ s) : ι := (fs.eventually_eq_one' x hx).some lemma eventually_eq_one (x : M) (hx : x ∈ s) : fs (fs.ind x hx) =ᶠ[𝓝 x] 1 := (fs.eventually_eq_one' x hx).some_spec lemma apply_ind (x : M) (hx : x ∈ s) : fs (fs.ind x hx) x = 1 := (fs.eventually_eq_one x hx).eq_of_nhds lemma mem_support_ind (x : M) (hx : x ∈ s) : x ∈ support (fs $ fs.ind x hx) := by simp [fs.apply_ind x hx] lemma mem_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (chart_at H (fs.c (fs.ind x hx))).source := fs.mem_chart_at_source_of_eq_one (fs.apply_ind x hx) lemma mem_ext_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (ext_chart_at I (fs.c (fs.ind x hx))).source := fs.mem_ext_chart_at_source_of_eq_one (fs.apply_ind x hx) /-- The index type of a `smooth_bump_covering` of a compact manifold is finite. -/ protected def fintype [compact_space M] : fintype ι := fs.locally_finite.fintype_of_compact $ λ i, (fs i).nonempty_support variable [t2_space M] /-- Reinterpret a `smooth_bump_covering` as a continuous `bump_covering`. Note that not every `f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`. -/ def to_bump_covering : bump_covering ι M s := { to_fun := λ i, ⟨fs i, (fs i).continuous⟩, locally_finite' := fs.locally_finite, nonneg' := λ i x, (fs i).nonneg, le_one' := λ i x, (fs i).le_one, eventually_eq_one' := fs.eventually_eq_one' } @[simp] lemma is_subordinate_to_bump_covering {f : smooth_bump_covering ι I M s} {U : M → set M} : f.to_bump_covering.is_subordinate (λ i, U (f.c i)) ↔ f.is_subordinate U := iff.rfl alias is_subordinate_to_bump_covering ↔ _ is_subordinate.to_bump_covering /-- Every `smooth_bump_covering` defines a smooth partition of unity. -/ def to_smooth_partition_of_unity : smooth_partition_of_unity ι I M s := fs.to_bump_covering.to_smooth_partition_of_unity (λ i, (fs i).smooth) lemma to_smooth_partition_of_unity_apply (i : ι) (x : M) : fs.to_smooth_partition_of_unity i x = fs i x * ∏ᶠ j (hj : well_ordering_rel j i), (1 - fs j x) := rfl lemma to_smooth_partition_of_unity_eq_mul_prod (i : ι) (x : M) (t : finset ι) (ht : ∀ j, well_ordering_rel j i → fs j x ≠ 0 → j ∈ t) : fs.to_smooth_partition_of_unity i x = fs i x * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j x) := fs.to_bump_covering.to_partition_of_unity_eq_mul_prod i x t ht lemma exists_finset_to_smooth_partition_of_unity_eventually_eq (i : ι) (x : M) : ∃ t : finset ι, fs.to_smooth_partition_of_unity i =ᶠ[𝓝 x] fs i * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j) := fs.to_bump_covering.exists_finset_to_partition_of_unity_eventually_eq i x lemma to_smooth_partition_of_unity_zero_of_zero {i : ι} {x : M} (h : fs i x = 0) : fs.to_smooth_partition_of_unity i x = 0 := fs.to_bump_covering.to_partition_of_unity_zero_of_zero h lemma support_to_smooth_partition_of_unity_subset (i : ι) : support (fs.to_smooth_partition_of_unity i) ⊆ support (fs i) := fs.to_bump_covering.support_to_partition_of_unity_subset i lemma is_subordinate.to_smooth_partition_of_unity {f : smooth_bump_covering ι I M s} {U : M → set M} (h : f.is_subordinate U) : f.to_smooth_partition_of_unity.is_subordinate (λ i, U (f.c i)) := h.to_bump_covering.to_partition_of_unity lemma sum_to_smooth_partition_of_unity_eq (x : M) : ∑ᶠ i, fs.to_smooth_partition_of_unity i x = 1 - ∏ᶠ i, (1 - fs i x) := fs.to_bump_covering.sum_to_partition_of_unity_eq x end smooth_bump_covering variable (I) /-- Given two disjoint closed sets in a Hausdorff σ-compact finite dimensional manifold, there exists an infinitely smooth function that is equal to `0` on one of them and is equal to one on the other. -/ lemma exists_smooth_zero_one_of_closed [t2_space M] [sigma_compact_space M] {s t : set M} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) : ∃ f : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯, eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := begin have : ∀ x ∈ t, sᶜ ∈ 𝓝 x, from λ x hx, hs.is_open_compl.mem_nhds (disjoint_right.1 hd hx), rcases smooth_bump_covering.exists_is_subordinate I ht this with ⟨ι, f, hf⟩, set g := f.to_smooth_partition_of_unity, refine ⟨⟨_, g.smooth_sum⟩, λ x hx, _, λ x, g.sum_eq_one, λ x, ⟨g.sum_nonneg x, g.sum_le_one x⟩⟩, suffices : ∀ i, g i x = 0, by simp only [this, cont_mdiff_map.coe_fn_mk, finsum_zero, pi.zero_apply], refine λ i, f.to_smooth_partition_of_unity_zero_of_zero _, exact nmem_support.1 (subset_compl_comm.1 (hf.support_subset i) hx) end variable {I} namespace smooth_partition_of_unity /-- A `smooth_partition_of_unity` that consists of a single function, uniformly equal to one, defined as an example for `inhabited` instance. -/ def single (i : ι) (s : set M) : smooth_partition_of_unity ι I M s := (bump_covering.single i s).to_smooth_partition_of_unity $ λ j, begin rcases eq_or_ne j i with rfl|h, { simp only [smooth_one, continuous_map.coe_one, bump_covering.coe_single, pi.single_eq_same] }, { simp only [smooth_zero, bump_covering.coe_single, pi.single_eq_of_ne h, continuous_map.coe_zero] } end instance [inhabited ι] (s : set M) : inhabited (smooth_partition_of_unity ι I M s) := ⟨single default s⟩ variables [t2_space M] [sigma_compact_space M] /-- If `X` is a paracompact normal topological space and `U` is an open covering of a closed set `s`, then there exists a `bump_covering ι X s` that is subordinate to `U`. -/ lemma exists_is_subordinate {s : set M} (hs : is_closed s) (U : ι → set M) (ho : ∀ i, is_open (U i)) (hU : s ⊆ ⋃ i, U i) : ∃ f : smooth_partition_of_unity ι I M s, f.is_subordinate U := begin haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, rcases bump_covering.exists_is_subordinate_of_prop (smooth I 𝓘(ℝ)) _ hs U ho hU with ⟨f, hf, hfU⟩, { exact ⟨f.to_smooth_partition_of_unity hf, hfU.to_smooth_partition_of_unity hf⟩ }, { intros s t hs ht hd, rcases exists_smooth_zero_one_of_closed I hs ht hd with ⟨f, hf⟩, exact ⟨f, f.smooth, hf⟩ } end end smooth_partition_of_unity
d25de66ea85dc6140d99dea939939ae1a965e596
83c8119e3298c0bfc53fc195c41a6afb63d01513
/library/init/data/int/order.lean
c27b969e86344c89c68f702af0217fa98304022b
[ "Apache-2.0" ]
permissive
anfelor/lean
584b91c4e87a6d95f7630c2a93fb082a87319ed0
31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1
refs/heads/master
1,610,067,141,310
1,585,992,232,000
1,585,992,232,000
251,683,543
0
0
Apache-2.0
1,585,676,570,000
1,585,676,569,000
null
UTF-8
Lean
false
false
11,814
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The order relation on the integers. -/ prelude import init.data.int.basic init.data.ordering.basic local attribute [simp] sub_eq_add_neg namespace int private def nonneg (a : ℤ) : Prop := int.cases_on a (assume n, true) (assume n, false) protected def le (a b : ℤ) : Prop := nonneg (b - a) instance : has_le int := ⟨int.le⟩ protected def lt (a b : ℤ) : Prop := (a + 1) ≤ b instance : has_lt int := ⟨int.lt⟩ private def decidable_nonneg (a : ℤ) : decidable (nonneg a) := int.cases_on a (assume a, decidable.true) (assume a, decidable.false) instance decidable_le (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _ instance decidable_lt (a b : ℤ) : decidable (a < b) := decidable_nonneg _ lemma lt_iff_add_one_le (a b : ℤ) : a < b ↔ a + 1 ≤ b := iff.refl _ private lemma nonneg.elim {a : ℤ} : nonneg a → ∃ n : ℕ, a = n := int.cases_on a (assume n H, exists.intro n rfl) (assume n', false.elim) private lemma nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) := int.cases_on a (assume n, or.inl trivial) (assume n, or.inr trivial) lemma le.intro_sub {a b : ℤ} {n : ℕ} (h : b - a = n) : a ≤ b := show nonneg (b - a), by rw h; trivial lemma le.intro {a b : ℤ} {n : ℕ} (h : a + n = b) : a ≤ b := le.intro_sub (by rw [← h, add_comm]; simp) lemma le.dest_sub {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, b - a = n := nonneg.elim h lemma le.dest {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, a + n = b := match (le.dest_sub h) with | ⟨n, h₁⟩ := exists.intro n begin rw [← h₁, add_comm], simp end end lemma le.elim {a b : ℤ} (h : a ≤ b) {P : Prop} (h' : ∀ n : ℕ, a + ↑n = b → P) : P := exists.elim (le.dest h) h' protected lemma le_total (a b : ℤ) : a ≤ b ∨ b ≤ a := or.imp_right (assume H : nonneg (-(b - a)), have -(b - a) = a - b, by simp, show nonneg (a - b), from this ▸ H) (nonneg_or_nonneg_neg (b - a)) lemma coe_nat_le_coe_nat_of_le {m n : ℕ} (h : m ≤ n) : (↑m : ℤ) ≤ ↑n := match nat.le.dest h with | ⟨k, (hk : m + k = n)⟩ := le.intro (begin rw [← hk], reflexivity end) end lemma le_of_coe_nat_le_coe_nat {m n : ℕ} (h : (↑m : ℤ) ≤ ↑n) : m ≤ n := le.elim h (assume k, assume hk : ↑m + ↑k = ↑n, have m + k = n, from int.coe_nat_inj ((int.coe_nat_add m k).trans hk), nat.le.intro this) lemma coe_nat_le_coe_nat_iff (m n : ℕ) : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := iff.intro le_of_coe_nat_le_coe_nat coe_nat_le_coe_nat_of_le lemma coe_zero_le (n : ℕ) : 0 ≤ (↑n : ℤ) := coe_nat_le_coe_nat_of_le n.zero_le lemma eq_coe_of_zero_le {a : ℤ} (h : 0 ≤ a) : ∃ n : ℕ, a = n := by have t := le.dest_sub h; simp at t; exact t lemma eq_succ_of_zero_lt {a : ℤ} (h : 0 < a) : ∃ n : ℕ, a = n.succ := let ⟨n, (h : ↑(1+n) = a)⟩ := le.dest h in ⟨n, by rw add_comm at h; exact h.symm⟩ lemma lt_add_succ (a : ℤ) (n : ℕ) : a < a + ↑(nat.succ n) := le.intro (show a + 1 + n = a + nat.succ n, begin simp [int.coe_nat_eq, add_comm, add_left_comm], reflexivity end) lemma lt.intro {a b : ℤ} {n : ℕ} (h : a + nat.succ n = b) : a < b := h ▸ lt_add_succ a n lemma lt.dest {a b : ℤ} (h : a < b) : ∃ n : ℕ, a + ↑(nat.succ n) = b := le.elim h (assume n, assume hn : a + 1 + n = b, exists.intro n begin rw [← hn, add_assoc, add_comm (1 : int)], reflexivity end) lemma lt.elim {a b : ℤ} (h : a < b) {P : Prop} (h' : ∀ n : ℕ, a + ↑(nat.succ n) = b → P) : P := exists.elim (lt.dest h) h' lemma coe_nat_lt_coe_nat_iff (n m : ℕ) : (↑n : ℤ) < ↑m ↔ n < m := begin rw [lt_iff_add_one_le, ← int.coe_nat_succ, coe_nat_le_coe_nat_iff], reflexivity end lemma lt_of_coe_nat_lt_coe_nat {m n : ℕ} (h : (↑m : ℤ) < ↑n) : m < n := (coe_nat_lt_coe_nat_iff _ _).mp h lemma coe_nat_lt_coe_nat_of_lt {m n : ℕ} (h : m < n) : (↑m : ℤ) < ↑n := (coe_nat_lt_coe_nat_iff _ _).mpr h /- show that the integers form an ordered additive group -/ protected lemma le_refl (a : ℤ) : a ≤ a := le.intro (add_zero a) protected lemma le_trans {a b c : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c := le.elim h₁ (assume n, assume hn : a + n = b, le.elim h₂ (assume m, assume hm : b + m = c, begin apply le.intro, rw [← hm, ← hn, add_assoc], reflexivity end)) protected lemma le_antisymm {a b : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b := le.elim h₁ (assume n, assume hn : a + n = b, le.elim h₂ (assume m, assume hm : b + m = a, have a + ↑(n + m) = a + 0, by rw [int.coe_nat_add, ← add_assoc, hn, hm, add_zero a], have (↑(n + m) : ℤ) = 0, from add_left_cancel this, have n + m = 0, from int.coe_nat_inj this, have n = 0, from nat.eq_zero_of_add_eq_zero_right this, show a = b, begin rw [← hn, this, int.coe_nat_zero, add_zero a] end)) protected lemma lt_irrefl (a : ℤ) : ¬ a < a := assume : a < a, lt.elim this (assume n, assume hn : a + nat.succ n = a, have a + nat.succ n = a + 0, by rw [hn, add_zero], have nat.succ n = 0, from int.coe_nat_inj (add_left_cancel this), show false, from nat.succ_ne_zero _ this) protected lemma ne_of_lt {a b : ℤ} (h : a < b) : a ≠ b := (assume : a = b, absurd (begin rewrite this at h, exact h end) (int.lt_irrefl b)) lemma le_of_lt {a b : ℤ} (h : a < b) : a ≤ b := lt.elim h (assume n, assume hn : a + nat.succ n = b, le.intro hn) protected lemma lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) := iff.intro (assume h, ⟨le_of_lt h, int.ne_of_lt h⟩) (assume ⟨aleb, aneb⟩, le.elim aleb (assume n, assume hn : a + n = b, have n ≠ 0, from (assume : n = 0, aneb begin rw [← hn, this, int.coe_nat_zero, add_zero] end), have n = nat.succ (nat.pred n), from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)), lt.intro (begin rewrite this at hn, exact hn end))) lemma lt_succ (a : ℤ) : a < a + 1 := int.le_refl (a + 1) protected lemma add_le_add_left {a b : ℤ} (h : a ≤ b) (c : ℤ) : c + a ≤ c + b := le.elim h (assume n, assume hn : a + n = b, le.intro (show c + a + n = c + b, begin rw [add_assoc, hn] end)) protected lemma add_lt_add_left {a b : ℤ} (h : a < b) (c : ℤ) : c + a < c + b := iff.mpr (int.lt_iff_le_and_ne _ _) (and.intro (int.add_le_add_left (le_of_lt h) _) (assume heq, int.lt_irrefl b begin rw add_left_cancel heq at h, exact h end)) protected lemma mul_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := le.elim ha (assume n, assume hn, le.elim hb (assume m, assume hm, le.intro (show 0 + ↑n * ↑m = a * b, begin rw [← hn, ← hm], simp [zero_add] end))) protected lemma mul_pos {a b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := lt.elim ha (assume n, assume hn, lt.elim hb (assume m, assume hm, lt.intro (show 0 + ↑(nat.succ (nat.succ n * m + n)) = a * b, begin rw [← hn, ← hm], simp [int.coe_nat_zero], rw [← int.coe_nat_mul], simp [nat.mul_succ, nat.succ_add] end))) protected lemma zero_lt_one : (0 : ℤ) < 1 := trivial protected lemma lt_iff_le_not_le {a b : ℤ} : a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := begin simp [int.lt_iff_le_and_ne], split; intro h, { cases h with hab hn, split, { assumption }, { intro hba, simp [int.le_antisymm hab hba] at *, contradiction } }, { cases h with hab hn, split, { assumption }, { intro h, simp [*] at * } } end instance : decidable_linear_ordered_comm_ring int := { le := int.le, le_refl := int.le_refl, le_trans := @int.le_trans, le_antisymm := @int.le_antisymm, lt := int.lt, lt_iff_le_not_le := @int.lt_iff_le_not_le, add_le_add_left := @int.add_le_add_left, zero_ne_one := int.zero_ne_one, mul_pos := @int.mul_pos, le_total := int.le_total, zero_lt_one := int.zero_lt_one, decidable_eq := int.decidable_eq, decidable_le := int.decidable_le, decidable_lt := int.decidable_lt, ..int.comm_ring } instance : decidable_linear_ordered_comm_group int := by apply_instance lemma eq_nat_abs_of_zero_le {a : ℤ} (h : 0 ≤ a) : a = nat_abs a := let ⟨n, e⟩ := eq_coe_of_zero_le h in by rw e; refl lemma le_nat_abs {a : ℤ} : a ≤ nat_abs a := or.elim (le_total 0 a) (λh, by rw eq_nat_abs_of_zero_le h; refl) (λh, le_trans h (coe_zero_le _)) lemma neg_succ_lt_zero (n : ℕ) : -[1+ n] < 0 := lt_of_not_ge $ λ h, let ⟨m, h⟩ := eq_coe_of_zero_le h in by contradiction lemma eq_neg_succ_of_lt_zero : ∀ {a : ℤ}, a < 0 → ∃ n : ℕ, a = -[1+ n] | (n : ℕ) h := absurd h (not_lt_of_ge (coe_zero_le _)) | -[1+ n] h := ⟨n, rfl⟩ /- more facts specific to int -/ theorem of_nat_nonneg (n : ℕ) : 0 ≤ of_nat n := trivial theorem coe_succ_pos (n : nat) : (nat.succ n : ℤ) > 0 := coe_nat_lt_coe_nat_of_lt (nat.succ_pos _) theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -n := let ⟨n, h⟩ := eq_coe_of_zero_le (neg_nonneg_of_nonpos H) in ⟨n, eq_neg_of_eq_neg h.symm⟩ theorem nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : (nat_abs a : ℤ) = a := match a, eq_coe_of_zero_le H with ._, ⟨n, rfl⟩ := rfl end theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : (nat_abs a : ℤ) = -a := by rw [← nat_abs_neg, nat_abs_of_nonneg (neg_nonneg_of_nonpos H)] theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := H theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := H theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 := add_le_add_right H 1 theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b := le_of_add_le_add_right H theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b := sub_right_lt_of_lt_add $ lt_add_one_of_le H theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b := le_of_lt_add_one $ lt_add_of_sub_right_lt H theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 := le_sub_right_of_add_le H theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b := add_le_of_le_sub_right H theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := rfl theorem sign_eq_one_of_pos {a : ℤ} (h : 0 < a) : sign a = 1 := match a, eq_succ_of_zero_lt h with ._, ⟨n, rfl⟩ := rfl end theorem sign_eq_neg_one_of_neg {a : ℤ} (h : a < 0) : sign a = -1 := match a, eq_neg_succ_of_lt_zero h with ._, ⟨n, rfl⟩ := rfl end lemma eq_zero_of_sign_eq_zero : Π {a : ℤ}, sign a = 0 → a = 0 | 0 _ := rfl theorem pos_of_sign_eq_one : ∀ {a : ℤ}, sign a = 1 → 0 < a | (n+1:ℕ) _ := coe_nat_lt_coe_nat_of_lt (nat.succ_pos _) theorem neg_of_sign_eq_neg_one : ∀ {a : ℤ}, sign a = -1 → a < 0 | (n+1:ℕ) h := match h with end | 0 h := match h with end | -[1+ n] _ := neg_succ_lt_zero _ theorem sign_eq_one_iff_pos (a : ℤ) : sign a = 1 ↔ 0 < a := ⟨pos_of_sign_eq_one, sign_eq_one_of_pos⟩ theorem sign_eq_neg_one_iff_neg (a : ℤ) : sign a = -1 ↔ a < 0 := ⟨neg_of_sign_eq_neg_one, sign_eq_neg_one_of_neg⟩ theorem sign_eq_zero_iff_zero (a : ℤ) : sign a = 0 ↔ a = 0 := ⟨eq_zero_of_sign_eq_zero, λ h, by rw [h, sign_zero]⟩ theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := eq_of_mul_eq_mul_right Hpos (by rw [one_mul, H]) theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := eq_of_mul_eq_mul_left Hpos (by rw [mul_one, H]) end int
547f0c82c6a324dd6cd35eb8c3eedda80b9634ab
3446e92e64a5de7ed1f2109cfb024f83cd904c34
/src/game/world1/level1.lean
896b7982ae5c4b19828780340af93e75f2325632
[]
no_license
kckennylau/natural_number_game
019f4a5f419c9681e65234ecd124c564f9a0a246
ad8c0adaa725975be8a9f978c8494a39311029be
refs/heads/master
1,598,784,137,722
1,571,905,156,000
1,571,905,156,000
218,354,686
0
0
null
1,572,373,319,000
1,572,373,318,000
null
UTF-8
Lean
false
false
4,484
lean
import mynat.definition -- Imports Peano's definition of the natural numbers. namespace mynat -- hide /- # The Natural Number Game, version 1.0beta. ## By Kevin Buzzard and Mohammad Pedramfar. Special thanks to Rob Lewis for tactic hackery, Sian Carey for power world (world 4), and, last but not least, the 2019-20 Imperial College 1st year maths beta tester students for countless suggestions and improvements. The natural number game is brought to you by the Xena project, a project based at Imperial College London whose aim is to get mathematics undergraduates using computer theorem provers. Lean is a computer theorem prover being developed at Microsoft Research. ## What is this game? Welcome to the natural number game -- a game which shows the power of induction. In this game, you get own version of the natural numbers, called `mynat`, in a programming language called Lean. Your version of the natural numbers satisfies induction, and a couple of other axioms (Peano's axioms). Unfortunately, nobody has proved any theorems about these natural numbers yet. For example, addition will be defined for you, but nobody has proved that `x + y = y + x` yet. This is your job. You're going to prove mathematical theorems using the Lean theorem prover. In other words, you're going to solve levels in a computer game. You're going to prove these theorems using *tactics*. This introductory world, Tutorial World, will take you through some of these tactics. During your proofs, your "goal" (i.e. what you're supposed to be proving) will be displayed with a `⊢` symbol in front of it. If the top left hand box reports "Theorem Proved!", you have closed all the goals in the level and can move on to the next level in the world you're in. # World 1: Tutorial World ## Level 1: the `refl` tactic. Let's start with the `refl` tactic. `refl` stands for "reflexivity", which is a fancy way of saying that it will prove any goal of the form `A = A`. It doesn't matter how complicated `A` is, all that matters is that the left hand side is *exactly equal* to the right hand side (a computer scientist would say "definitionally equal"). For example, `x * y + z = x * y + z` can be proved by `refl`, but `x + y = y + x` cannot. Let's see `refl` in action! At the bottom of the text in this box, there's a lemma, which says that if x is a natural number then x = x. Locate this lemma (if you can't see the lemma and these instructions, make this box wider by dragging the sides). Let's supply the proof. Click on the word `sorry` and then delete it. When the system finishes being busy, then in the box on the top right you can see your goal -- the objective of this level. Remember that the goal is the thing with the weird `⊢` thing just before it. The goal in this case is `x = x`, where `x` is one of your natural numbers. That's a pretty easy goal to prove -- you can just prove it with the `refl` tactic. Where it used to say `sorry`, write `refl,` **and don't forget the comma**. Then hit enter to go onto the next line. If all is well, Lean should tell you "Proof complete!" in the top right box, and there should be no errors in the bottom right box. You just did the first level of the tutorial! And you also learnt how to avoid by *far* the most common mistake that beginner users make -- **every line must end with a comma**. If things go weird and you don't understand why the top right box is empty, check for missing commas. For each level, the idea is to get Lean into this state: with the top right box saying "Proof complete!" and the bottom right box empty (i.e. with no errors in). If you want to be reminded about the `refl` tactic, you can click on the "Tactics" drop down menu on the left. Resize the window if it's too small. Now click on "next level" in the top right of your browser to go onto the second level of tutorial world, where we'll learn about the `exact` tactic. [NB don't click on "next world", we're not ready for addition world yet] -/ /- Lemma : no-side-bar For all natural numbers $x$, we have $x = x$. -/ lemma example1 (x : mynat) : x = x := begin [less_leaky] refl end /- Tactic : refl The `refl` tactic will close any goal of the form `A = B` where `A` and `B` are *exactly the same thing*. ### Example: If it looks like this in the top right hand box: ``` x y z : mynat ⊢ (x + y) * z = (x + y) * z ``` then `refl,` will close the goal and solve the level. Don't forget the comma. -/ end mynat -- hide
e9d5da71f1f175faf9f6b8c03caba1105003e5d5
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/meta/expr.lean
2b0df42f1b89f9ea18d1012ebd5243e7ab74da4d
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
36,514
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs import tactic.derive_inhabited /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind @[priority 100] meta instance has_reflect.has_to_pexpr {α} [has_reflect α] : has_to_pexpr α := ⟨λ b, pexpr.of_expr (reflect b)⟩ namespace binder_info /-! ### Declarations about `binder_info` -/ instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ meta def from_string (s : string) : name := from_components $ s.split (= '.') end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff /-- `l.fold_mvar f` folds a function `f : name → α → α` over each `n : name` appearing in a `level.mvar n` in `l`. -/ meta def fold_mvar {α} : level → (name → α → α) → α → α | zero f := id | (succ a) f := fold_mvar a f | (param a) f := id | (mvar a) f := f a | (max a b) f := fold_mvar a f ∘ fold_mvar b f | (imax a b) f := fold_mvar a f ∘ fold_mvar b f end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq, derive inhabited] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`. -/ meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero) := some 0 | `(has_one.one) := some 1 | `(bit0 %%e) := bit0 <$> e.to_nat | `(bit1 %%e) := bit1 <$> e.to_nat | `(nat.succ %%e) := (+1) <$> e.to_nat | `(nat.zero) := some 0 | _ := none /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff end expr /-! ### Declarations about `expr` -/ namespace expr open tactic /-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/ meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Clean an expression by removing `id`s listed in `clean_ids`. -/ meta def clean (e : expr) : expr := e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- Get the universe levels of a `const` expression -/ meta def univ_levels : expr → list level | (const n ls) := ls | _ := [] /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ meta def replace_mvars (e : expr) : expr := e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none) /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ meta def to_implicit_local_const : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ meta def list_univ_meta_vars (e : expr) : list name := native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s, match e' with | (sort u) := u.fold_mvar (flip native.rb_set.insert) s | (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s | _ := s end /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ meta def contains_expr_or_mvar (t : expr) (e : expr) : bool := -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. ¬ t.list_meta_vars.empty ∨ e.occurs t /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- Returns true if `e` contains a `sorry`. -/ meta def contains_sorry (e : expr) : bool := e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b) /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ meta def app_symbol_in (e : expr) (l : list name) : bool := match e.get_app_fn with | (expr.const n _) := n ∈ l | _ := ff end /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ meta def get_simp_args (e : expr) : tactic (list expr) := -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app if ¬ e.is_app then pure [] else do cgr ← mk_specialized_congr_lemma_simp e, pure $ do (arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args, guard $ arg_kind = congr_arg_kind.eq, pure arg /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- Repeatedly apply `expr.subst`. -/ meta def substs : expr → list expr → expr | e es := es.foldl expr.subst e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. This is very similar to `expr.substs`, but this also reduces head let-expressions. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" /-- Get the codomain/target of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def pi_codomain : expr → expr | (pi n bi d b) := pi_codomain b | e := e /-- Get the body/value of a lambda-expression. This definition doesn't instantiate bound variables, and therefore produces a term that is open. See note [open expressions]. -/ meta def lambda_body : expr → expr | (lam n bi d b) := lambda_body b | e := e /-- Auxilliary defintion for `pi_binders`. See note [open expressions]. -/ meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables. See note [open expressions]. -/ meta def pi_binders (e : expr) : list binder × expr := let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff /-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/ meta def has_local_constant (e l : expr) : bool := e.has_local_in $ mk_name_set.insert l.local_uniq_name /-- Turns a local constant into a binder -/ meta def to_binder : expr → binder | (local_const _ nm bi t) := ⟨nm, bi, t⟩ | _ := default binder /-- Strip-away the context-dependent unique id for the given local const and return: its friendly `name`, its `binder_info`, and its `type : expr`. -/ meta def get_local_const_kind : expr → name × binder_info × expr | (expr.local_const _ n bi e) := (n, bi, e) | _ := (name.anonymous, binder_info.default, expr.const name.anonymous []) /-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/ meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab | (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t | e new_t := e /-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to `expr tt` at the site of definition unnecessarily. DANGER: Unless you know exactly what you are doing, this is probably not the function you are looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/ meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast /-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever `f` is encountered in `e` verbatim, replace it with `t`". -/ meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) : expr elab := unsafe_cast $ e.unsafe_cast.replace $ λ e n, (mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd /-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of other `expr.local_const`s. It determines whether `e` should be considered "available in context" as a variable by virtue of the fact that the variables `vs` have been deemed such. 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. DANGER: It is possible that for `f : expr` another `expr.local_const`, we have `is_implicitly_included_variable f vs = ff` but `is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to iteratively add a list of local constants (usually, the `variables` declared in the local scope) which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables were added in a particular iteration. The function `all_implicitly_included_variables` below implements this behaviour. Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/ meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool := if ¬(e.local_pp_name.to_string.starts_with "_") then e ∈ vs else e.local_type.fold tt $ λ se _ b, if ¬b then ff else if ¬se.is_local_constant then tt else se ∈ vs /-- Private work function for `all_implicitly_included_variables`, performing the actual series of iterations, tracking with a boolean whether any updates occured this iteration. -/ private meta def all_implicitly_included_variables_aux : list expr → list expr → list expr → bool → list expr | [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff | [] vs rs ff := vs | (e :: rest) vs rs b := let (vs, rs, b) := if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in all_implicitly_included_variables_aux rest vs rs b /-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`, another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion of the variables in `vs` into the local context implies that `e` should also be included. See `is_implicitly_included_variable e vs` for the details. In particular, those elements of `vs` are included automatically. -/ meta def all_implicitly_included_variables (es vs : list expr) : list expr := all_implicitly_included_variables_aux es vs [] ff end expr /-! ### Declarations about `environment` -/ namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is a structure. -/ meta def is_structure (env : environment) (n : name) : bool := (env.structure_fields n).is_some /-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a structure. -/ meta def structure_fields_full (env : environment) (n : name) : option (list name) := (env.structure_fields n).map (list.map $ λ n', n ++ n') /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def filter (e : environment) (test : declaration → bool) : list declaration := e.fold [] $ λ d ds, if test d then d::ds else ds /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment /-! ### `is_eta_expansion` In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ namespace expr open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the resulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.structure_fields_full type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr /-! ### Declarations about `declaration` -/ namespace declaration open tactic /-- `declaration.update_with_fun f tgt decl` sets the name of the given `decl : declaration` to `tgt`, and applies `f` to the names of all `expr.const`s which appear in the value or type of `decl`. -/ protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns true iff `d` is an automatically-generated or internal declaration. -/ meta def is_auto_or_internal (env : environment) (d : declaration) : bool := d.to_name.is_internal || d.is_auto_generated env /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param /-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/ protected meta def reducibility_hints : declaration → reducibility_hints | (declaration.defn _ _ _ _ red _) := red | _ := _root_.reducibility_hints.opaque /-- formats the arguments of a `declaration.thm` -/ private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format := do tp ← pp tp, body ← pp body.get, return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.defn` -/ private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, body ← pp body, return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">" /-- formats the arguments of a `declaration.cnst` -/ private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format := do tp ← pp tp, return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- formats the arguments of a `declaration.ax` -/ private meta def print_ax (nm : name) (tp : expr) : tactic format := do tp ← pp tp, return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">" /-- pretty-prints a `declaration` object. -/ meta def to_tactic_format : declaration → tactic format | (declaration.thm nm _ tp bd) := print_thm nm tp bd | (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted | (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted | (declaration.ax nm _ tp) := print_ax nm tp meta instance : has_to_tactic_format declaration := ⟨to_tactic_format⟩ end declaration meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) := unchecked_cast expr.has_decidable_eq
78725d92e8f6f26b06d3a6443ffc7c91eb7564d1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/list/default_auto.lean
1a342b7ab43a1c28daf89997f0bc0ee505ddbd69
[]
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,016
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.alist import Mathlib.data.list.bag_inter import Mathlib.data.list.basic import Mathlib.data.list.chain import Mathlib.data.list.defs import Mathlib.data.list.erase_dup import Mathlib.data.list.forall2 import Mathlib.data.list.func import Mathlib.data.list.intervals import Mathlib.data.list.min_max import Mathlib.data.list.indexes import Mathlib.data.list.nat_antidiagonal import Mathlib.data.list.nodup import Mathlib.data.list.of_fn import Mathlib.data.list.pairwise import Mathlib.data.list.perm import Mathlib.data.list.range import Mathlib.data.list.rotate import Mathlib.data.list.sections import Mathlib.data.list.sigma import Mathlib.data.list.sort import Mathlib.data.list.tfae import Mathlib.data.list.zip import Mathlib.PostPort namespace Mathlib end Mathlib
6a7f5bcd08ed7f19d22d40e8d1ee6aedcca23ab5
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/instances/Top/limits.lean
52e5b899be9c98f591afee3fad47a9986ab866eb
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
2,811
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Patrick Massot, Scott Morrison, Mario Carneiro import category_theory.instances.Top.basic import category_theory.limits.types import category_theory.limits.preserves open category_theory open category_theory.instances open topological_space universe u namespace category_theory.instances.Top open category_theory.limits variables {J : Type u} [small_category J] def limit (F : J ⥤ Top.{u}) : cone F := { X := ⟨limit (F ⋙ forget), ⨆ j, (F.obj j).str.induced (limit.π (F ⋙ forget) j)⟩, π := { app := λ j, ⟨limit.π (F ⋙ forget) j, continuous_iff_induced_le.mpr (lattice.le_supr _ j)⟩, naturality' := λ j j' f, subtype.eq ((limit.cone (F ⋙ forget)).π.naturality f) } } def limit_is_limit (F : J ⥤ Top.{u}) : is_limit (limit F) := by refine is_limit.of_faithful forget (limit.is_limit _) (λ s, ⟨_, _⟩) (λ s, rfl); exact continuous_iff_le_coinduced.mpr (lattice.supr_le $ λ j, induced_le_iff_le_coinduced.mpr $ continuous_iff_le_coinduced.mp (s.π.app j).property) instance Top_has_limits : has_limits.{u} Top.{u} := { has_limits_of_shape := λ J 𝒥, { has_limit := λ F, by exactI { cone := limit F, is_limit := limit_is_limit F } } } instance forget_preserves_limits : preserves_limits (forget : Top.{u} ⥤ Type u) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by exactI preserves_limit_of_preserves_limit_cone (limit.is_limit F) (limit.is_limit (F ⋙ forget)) } } def colimit (F : J ⥤ Top.{u}) : cocone F := { X := ⟨colimit (F ⋙ forget), ⨅ j, (F.obj j).str.coinduced (colimit.ι (F ⋙ forget) j)⟩, ι := { app := λ j, ⟨colimit.ι (F ⋙ forget) j, continuous_iff_le_coinduced.mpr (lattice.infi_le _ j)⟩, naturality' := λ j j' f, subtype.eq ((colimit.cocone (F ⋙ forget)).ι.naturality f) } } def colimit_is_colimit (F : J ⥤ Top.{u}) : is_colimit (colimit F) := by refine is_colimit.of_faithful forget (colimit.is_colimit _) (λ s, ⟨_, _⟩) (λ s, rfl); exact continuous_iff_induced_le.mpr (lattice.le_infi $ λ j, induced_le_iff_le_coinduced.mpr $ continuous_iff_le_coinduced.mp (s.ι.app j).property) instance Top_has_colimits : has_colimits.{u} Top.{u} := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit F, is_colimit := colimit_is_colimit F } } } instance forget_preserves_colimits : preserves_colimits (forget : Top.{u} ⥤ Type u) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit F) (colimit.is_colimit (F ⋙ forget)) } } end category_theory.instances.Top
3484a0d790ba6f8b0b3853ff0338a1149804c40a
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/mazur_ulam.lean
862b9eb6145189be2e46d7e2217c793b0012782c
[ "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
6,828
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.instances.real_vector_space import analysis.normed_space.affine_isometry import linear_algebra.affine_space.midpoint /-! # Mazur-Ulam Theorem Mazur-Ulam theorem states that an isometric bijection between two normed affine spaces over `ℝ` is affine. We formalize it in three definitions: * `isometric.to_real_linear_isometry_equiv_of_map_zero` : given `E ≃ᵢ F` sending `0` to `0`, returns `E ≃ₗᵢ[ℝ] F` with the same `to_fun` and `inv_fun`; * `isometric.to_real_linear_isometry_equiv` : given `f : E ≃ᵢ F`, returns a linear isometry equivalence `g : E ≃ₗᵢ[ℝ] F` with `g x = f x - f 0`. * `isometric.to_real_affine_isometry_equiv` : given `f : PE ≃ᵢ PF`, returns an affine isometry equivalence `g : PE ≃ᵃⁱ[ℝ] PF` whose underlying `isometric` is `f` The formalization is based on [Jussi Väisälä, *A Proof of the Mazur-Ulam Theorem*][Vaisala_2003]. ## Tags isometry, affine map, linear map -/ variables {E PE : Type*} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {F PF : Type*} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF] open set affine_map affine_isometry_equiv noncomputable theory namespace isometric include E /-- If an isometric self-homeomorphism of a normed vector space over `ℝ` fixes `x` and `y`, then it fixes the midpoint of `[x, y]`. This is a lemma for a more general Mazur-Ulam theorem, see below. -/ lemma midpoint_fixed {x y : PE} : ∀ e : PE ≃ᵢ PE, e x = x → e y = y → e (midpoint ℝ x y) = midpoint ℝ x y := begin set z := midpoint ℝ x y, -- Consider the set of `e : E ≃ᵢ E` such that `e x = x` and `e y = y` set s := { e : PE ≃ᵢ PE | e x = x ∧ e y = y }, haveI : nonempty s := ⟨⟨isometric.refl PE, rfl, rfl⟩⟩, -- On the one hand, `e` cannot send the midpoint `z` of `[x, y]` too far have h_bdd : bdd_above (range $ λ e : s, dist (e z) z), { refine ⟨dist x z + dist x z, forall_range_iff.2 $ subtype.forall.2 _⟩, rintro e ⟨hx, hy⟩, calc dist (e z) z ≤ dist (e z) x + dist x z : dist_triangle (e z) x z ... = dist (e x) (e z) + dist x z : by rw [hx, dist_comm] ... = dist x z + dist x z : by erw [e.dist_eq x z] }, -- On the other hand, consider the map `f : (E ≃ᵢ E) → (E ≃ᵢ E)` -- sending each `e` to `R ∘ e⁻¹ ∘ R ∘ e`, where `R` is the point reflection in the -- midpoint `z` of `[x, y]`. set R : PE ≃ᵢ PE := (point_reflection ℝ z).to_isometric, set f : (PE ≃ᵢ PE) → (PE ≃ᵢ PE) := λ e, ((e.trans R).trans e.symm).trans R, -- Note that `f` doubles the value of ``dist (e z) z` have hf_dist : ∀ e, dist (f e z) z = 2 * dist (e z) z, { intro e, dsimp [f], rw [dist_point_reflection_fixed, ← e.dist_eq, e.apply_symm_apply, dist_point_reflection_self_real, dist_comm] }, -- Also note that `f` maps `s` to itself have hf_maps_to : maps_to f s s, { rintros e ⟨hx, hy⟩, split; simp [hx, hy, e.symm_apply_eq.2 hx.symm, e.symm_apply_eq.2 hy.symm], }, -- Therefore, `dist (e z) z = 0` for all `e ∈ s`. set c := ⨆ e : s, dist ((e : PE ≃ᵢ PE) z) z, have : c ≤ c / 2, { apply csupr_le, rintros ⟨e, he⟩, simp only [subtype.coe_mk, le_div_iff' (@zero_lt_two ℝ _ _), ← hf_dist], exact le_csupr h_bdd ⟨f e, hf_maps_to he⟩ }, replace : c ≤ 0, { linarith }, refine λ e hx hy, dist_le_zero.1 (le_trans _ this), exact le_csupr h_bdd ⟨e, hx, hy⟩ end include F /-- A bijective isometry sends midpoints to midpoints. -/ lemma map_midpoint (f : PE ≃ᵢ PF) (x y : PE) : f (midpoint ℝ x y) = midpoint ℝ (f x) (f y) := begin set e : PE ≃ᵢ PE := ((f.trans $ (point_reflection ℝ $ midpoint ℝ (f x) (f y)).to_isometric).trans f.symm).trans (point_reflection ℝ $ midpoint ℝ x y).to_isometric, have hx : e x = x, by simp, have hy : e y = y, by simp, have hm := e.midpoint_fixed hx hy, simp only [e, trans_apply] at hm, rwa [← eq_symm_apply, to_isometric_symm, point_reflection_symm, coe_to_isometric, coe_to_isometric, point_reflection_self, symm_apply_eq, point_reflection_fixed_iff] at hm end /-! Since `f : PE ≃ᵢ PF` sends midpoints to midpoints, it is an affine map. We define a conversion to a `continuous_linear_equiv` first, then a conversion to an `affine_map`. -/ /-- **Mazur-Ulam Theorem**: if `f` is an isometric bijection between two normed vector spaces over `ℝ` and `f 0 = 0`, then `f` is a linear isometry equivalence. -/ def to_real_linear_isometry_equiv_of_map_zero (f : E ≃ᵢ F) (h0 : f 0 = 0) : E ≃ₗᵢ[ℝ] F := { norm_map' := λ x, show ∥f x∥ = ∥x∥, by simp only [← dist_zero_right, ← h0, f.dist_eq], .. ((add_monoid_hom.of_map_midpoint ℝ ℝ f h0 f.map_midpoint).to_real_linear_map f.continuous), .. f } @[simp] lemma coe_to_real_linear_equiv_of_map_zero (f : E ≃ᵢ F) (h0 : f 0 = 0) : ⇑(f.to_real_linear_isometry_equiv_of_map_zero h0) = f := rfl @[simp] lemma coe_to_real_linear_equiv_of_map_zero_symm (f : E ≃ᵢ F) (h0 : f 0 = 0) : ⇑(f.to_real_linear_isometry_equiv_of_map_zero h0).symm = f.symm := rfl /-- **Mazur-Ulam Theorem**: if `f` is an isometric bijection between two normed vector spaces over `ℝ`, then `x ↦ f x - f 0` is a linear isometry equivalence. -/ def to_real_linear_isometry_equiv (f : E ≃ᵢ F) : E ≃ₗᵢ[ℝ] F := (f.trans (isometric.add_right (f 0)).symm).to_real_linear_isometry_equiv_of_map_zero (by simpa only [sub_eq_add_neg] using sub_self (f 0)) @[simp] lemma to_real_linear_equiv_apply (f : E ≃ᵢ F) (x : E) : (f.to_real_linear_isometry_equiv : E → F) x = f x - f 0 := (sub_eq_add_neg (f x) (f 0)).symm @[simp] lemma to_real_linear_isometry_equiv_symm_apply (f : E ≃ᵢ F) (y : F) : (f.to_real_linear_isometry_equiv.symm : F → E) y = f.symm (y + f 0) := rfl /-- **Mazur-Ulam Theorem**: if `f` is an isometric bijection between two normed add-torsors over normed vector spaces over `ℝ`, then `f` is an affine isometry equivalence. -/ def to_real_affine_isometry_equiv (f : PE ≃ᵢ PF) : PE ≃ᵃⁱ[ℝ] PF := affine_isometry_equiv.mk' f (((vadd_const (classical.arbitrary PE)).trans $ f.trans (vadd_const (f $ classical.arbitrary PE)).symm).to_real_linear_isometry_equiv) (classical.arbitrary PE) (λ p, by simp) @[simp] lemma coe_fn_to_real_affine_isometry_equiv (f : PE ≃ᵢ PF) : ⇑f.to_real_affine_isometry_equiv = f := rfl @[simp] lemma coe_to_real_affine_isometry_equiv (f : PE ≃ᵢ PF) : f.to_real_affine_isometry_equiv.to_isometric = f := by { ext, refl } end isometric
6d757c3d022cedd48a358c1ad2c699af881b4c76
9cba98daa30c0804090f963f9024147a50292fa0
/old/metrology/measurement.lean
09e3a45d9a73dfa4425aeee75326786964d72105
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
888
lean
import .dimensions import .unit namespace measurementSystem /- We define a measurement system to be a 7-tuple of units: one for length, one for mass, etc. -/ structure MeasurementSystem : Type := mk :: (length : unit.length) (mass : unit.mass) (time : unit.time) (current : unit.current) (temperature : unit.temperature) (quantity : unit.quantity) (intensity : unit.intensity) -- Examples def si_measurement_system : MeasurementSystem := MeasurementSystem.mk unit.length.meter unit.mass.kilogram unit.time.second unit.current.ampere unit.temperature.kelvin unit.quantity.mole unit.intensity.candela -- double check this and fix if necessary def imperial_measurement_system : MeasurementSystem := MeasurementSystem.mk unit.length.foot unit.mass.pound unit.time.second unit.current.ampere unit.temperature.fahrenheit unit.quantity.mole unit.intensity.candela end measurementSystem
ee79f4ebaa7ed461f7df1e2a36a1d92f16826d30
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/inner_product_space/adjoint.lean
768e5627ed4a4421e0e02d40e8907396e14f999f
[ "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
19,107
lean
/- Copyright (c) 2021 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis, Heather Macbeth -/ import analysis.inner_product_space.dual import analysis.inner_product_space.pi_L2 /-! # Adjoint of operators on Hilbert spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Given an operator `A : E →L[𝕜] F`, where `E` and `F` are Hilbert spaces, its adjoint `adjoint A : F →L[𝕜] E` is the unique operator such that `⟪x, A y⟫ = ⟪adjoint A x, y⟫` for all `x` and `y`. We then use this to put a C⋆-algebra structure on `E →L[𝕜] E` with the adjoint as the star operation. This construction is used to define an adjoint for linear maps (i.e. not continuous) between finite dimensional spaces. ## Main definitions * `continuous_linear_map.adjoint : (E →L[𝕜] F) ≃ₗᵢ⋆[𝕜] (F →L[𝕜] E)`: the adjoint of a continuous linear map, bundled as a conjugate-linear isometric equivalence. * `linear_map.adjoint : (E →ₗ[𝕜] F) ≃ₗ⋆[𝕜] (F →ₗ[𝕜] E)`: the adjoint of a linear map between finite-dimensional spaces, this time only as a conjugate-linear equivalence, since there is no norm defined on these maps. ## Implementation notes * The continuous conjugate-linear version `adjoint_aux` is only an intermediate definition and is not meant to be used outside this file. ## Tags adjoint -/ noncomputable theory open is_R_or_C open_locale complex_conjugate variables {𝕜 E F G : Type*} [is_R_or_C 𝕜] variables [normed_add_comm_group E] [normed_add_comm_group F] [normed_add_comm_group G] variables [inner_product_space 𝕜 E] [inner_product_space 𝕜 F] [inner_product_space 𝕜 G] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y /-! ### Adjoint operator -/ open inner_product_space namespace continuous_linear_map variables [complete_space E] [complete_space G] /-- The adjoint, as a continuous conjugate-linear map. This is only meant as an auxiliary definition for the main definition `adjoint`, where this is bundled as a conjugate-linear isometric equivalence. -/ def adjoint_aux : (E →L[𝕜] F) →L⋆[𝕜] (F →L[𝕜] E) := (continuous_linear_map.compSL _ _ _ _ _ ((to_dual 𝕜 E).symm : normed_space.dual 𝕜 E →L⋆[𝕜] E)).comp (to_sesq_form : (E →L[𝕜] F) →L[𝕜] F →L⋆[𝕜] normed_space.dual 𝕜 E) @[simp] lemma adjoint_aux_apply (A : E →L[𝕜] F) (x : F) : adjoint_aux A x = ((to_dual 𝕜 E).symm : (normed_space.dual 𝕜 E) → E) ((to_sesq_form A) x) := rfl lemma adjoint_aux_inner_left (A : E →L[𝕜] F) (x : E) (y : F) : ⟪adjoint_aux A y, x⟫ = ⟪y, A x⟫ := by { simp only [adjoint_aux_apply, to_dual_symm_apply, to_sesq_form_apply_coe, coe_comp', innerSL_apply_coe]} lemma adjoint_aux_inner_right (A : E →L[𝕜] F) (x : E) (y : F) : ⟪x, adjoint_aux A y⟫ = ⟪A x, y⟫ := by rw [←inner_conj_symm, adjoint_aux_inner_left, inner_conj_symm] variables [complete_space F] lemma adjoint_aux_adjoint_aux (A : E →L[𝕜] F) : adjoint_aux (adjoint_aux A) = A := begin ext v, refine ext_inner_left 𝕜 (λ w, _), rw [adjoint_aux_inner_right, adjoint_aux_inner_left], end @[simp] lemma adjoint_aux_norm (A : E →L[𝕜] F) : ‖adjoint_aux A‖ = ‖A‖ := begin refine le_antisymm _ _, { refine continuous_linear_map.op_norm_le_bound _ (norm_nonneg _) (λ x, _), rw [adjoint_aux_apply, linear_isometry_equiv.norm_map], exact to_sesq_form_apply_norm_le }, { nth_rewrite_lhs 0 [←adjoint_aux_adjoint_aux A], refine continuous_linear_map.op_norm_le_bound _ (norm_nonneg _) (λ x, _), rw [adjoint_aux_apply, linear_isometry_equiv.norm_map], exact to_sesq_form_apply_norm_le } end /-- The adjoint of a bounded operator from Hilbert space E to Hilbert space F. -/ def adjoint : (E →L[𝕜] F) ≃ₗᵢ⋆[𝕜] (F →L[𝕜] E) := linear_isometry_equiv.of_surjective { norm_map' := adjoint_aux_norm, ..adjoint_aux } (λ A, ⟨adjoint_aux A, adjoint_aux_adjoint_aux A⟩) localized "postfix (name := adjoint) `†`:1000 := continuous_linear_map.adjoint" in inner_product /-- The fundamental property of the adjoint. -/ lemma adjoint_inner_left (A : E →L[𝕜] F) (x : E) (y : F) : ⟪A† y, x⟫ = ⟪y, A x⟫ := adjoint_aux_inner_left A x y /-- The fundamental property of the adjoint. -/ lemma adjoint_inner_right (A : E →L[𝕜] F) (x : E) (y : F) : ⟪x, A† y⟫ = ⟪A x, y⟫ := adjoint_aux_inner_right A x y /-- The adjoint is involutive -/ @[simp] lemma adjoint_adjoint (A : E →L[𝕜] F) : A†† = A := adjoint_aux_adjoint_aux A /-- The adjoint of the composition of two operators is the composition of the two adjoints in reverse order. -/ @[simp] lemma adjoint_comp (A : F →L[𝕜] G) (B : E →L[𝕜] F) : (A ∘L B)† = B† ∘L A† := begin ext v, refine ext_inner_left 𝕜 (λ w, _), simp only [adjoint_inner_right, continuous_linear_map.coe_comp', function.comp_app], end lemma apply_norm_sq_eq_inner_adjoint_left (A : E →L[𝕜] E) (x : E) : ‖A x‖^2 = re ⟪(A† * A) x, x⟫ := have h : ⟪(A† * A) x, x⟫ = ⟪A x, A x⟫ := by { rw [←adjoint_inner_left], refl }, by rw [h, ←inner_self_eq_norm_sq _] lemma apply_norm_eq_sqrt_inner_adjoint_left (A : E →L[𝕜] E) (x : E) : ‖A x‖ = real.sqrt (re ⟪(A† * A) x, x⟫) := by rw [←apply_norm_sq_eq_inner_adjoint_left, real.sqrt_sq (norm_nonneg _)] lemma apply_norm_sq_eq_inner_adjoint_right (A : E →L[𝕜] E) (x : E) : ‖A x‖^2 = re ⟪x, (A† * A) x⟫ := have h : ⟪x, (A† * A) x⟫ = ⟪A x, A x⟫ := by { rw [←adjoint_inner_right], refl }, by rw [h, ←inner_self_eq_norm_sq _] lemma apply_norm_eq_sqrt_inner_adjoint_right (A : E →L[𝕜] E) (x : E) : ‖A x‖ = real.sqrt (re ⟪x, (A† * A) x⟫) := by rw [←apply_norm_sq_eq_inner_adjoint_right, real.sqrt_sq (norm_nonneg _)] /-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫` for all `x` and `y`. -/ lemma eq_adjoint_iff (A : E →L[𝕜] F) (B : F →L[𝕜] E) : A = B† ↔ (∀ x y, ⟪A x, y⟫ = ⟪x, B y⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩, ext x, exact ext_inner_right 𝕜 (λ y, by simp only [adjoint_inner_left, h x y]) end @[simp] lemma adjoint_id : (continuous_linear_map.id 𝕜 E).adjoint = continuous_linear_map.id 𝕜 E := begin refine eq.symm _, rw eq_adjoint_iff, simp, end lemma _root_.submodule.adjoint_subtypeL (U : submodule 𝕜 E) [complete_space U] : (U.subtypeL)† = orthogonal_projection U := begin symmetry, rw eq_adjoint_iff, intros x u, rw [U.coe_inner, inner_orthogonal_projection_left_eq_right, orthogonal_projection_mem_subspace_eq_self], refl end lemma _root_.submodule.adjoint_orthogonal_projection (U : submodule 𝕜 E) [complete_space U] : (orthogonal_projection U : E →L[𝕜] U)† = U.subtypeL := by rw [← U.adjoint_subtypeL, adjoint_adjoint] /-- `E →L[𝕜] E` is a star algebra with the adjoint as the star operation. -/ instance : has_star (E →L[𝕜] E) := ⟨adjoint⟩ instance : has_involutive_star (E →L[𝕜] E) := ⟨adjoint_adjoint⟩ instance : star_semigroup (E →L[𝕜] E) := ⟨adjoint_comp⟩ instance : star_ring (E →L[𝕜] E) := ⟨linear_isometry_equiv.map_add adjoint⟩ instance : star_module 𝕜 (E →L[𝕜] E) := ⟨linear_isometry_equiv.map_smulₛₗ adjoint⟩ lemma star_eq_adjoint (A : E →L[𝕜] E) : star A = A† := rfl /-- A continuous linear operator is self-adjoint iff it is equal to its adjoint. -/ lemma is_self_adjoint_iff' {A : E →L[𝕜] E} : is_self_adjoint A ↔ A.adjoint = A := iff.rfl instance : cstar_ring (E →L[𝕜] E) := ⟨begin intros A, rw [star_eq_adjoint], refine le_antisymm _ _, { calc ‖A† * A‖ ≤ ‖A†‖ * ‖A‖ : op_norm_comp_le _ _ ... = ‖A‖ * ‖A‖ : by rw [linear_isometry_equiv.norm_map] }, { rw [←sq, ←real.sqrt_le_sqrt_iff (norm_nonneg _), real.sqrt_sq (norm_nonneg _)], refine op_norm_le_bound _ (real.sqrt_nonneg _) (λ x, _), have := calc re ⟪(A† * A) x, x⟫ ≤ ‖(A† * A) x‖ * ‖x‖ : re_inner_le_norm _ _ ... ≤ ‖A† * A‖ * ‖x‖ * ‖x‖ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _), calc ‖A x‖ = real.sqrt (re ⟪(A† * A) x, x⟫) : by rw [apply_norm_eq_sqrt_inner_adjoint_left] ... ≤ real.sqrt (‖A† * A‖ * ‖x‖ * ‖x‖) : real.sqrt_le_sqrt this ... = real.sqrt (‖A† * A‖) * ‖x‖ : by rw [mul_assoc, real.sqrt_mul (norm_nonneg _), real.sqrt_mul_self (norm_nonneg _)] } end⟩ section real variables {E' : Type*} {F' : Type*} variables [normed_add_comm_group E'] [normed_add_comm_group F'] variables [inner_product_space ℝ E'] [inner_product_space ℝ F'] variables [complete_space E'] [complete_space F'] -- Todo: Generalize this to `is_R_or_C`. lemma is_adjoint_pair_inner (A : E' →L[ℝ] F') : linear_map.is_adjoint_pair (sesq_form_of_inner : E' →ₗ[ℝ] E' →ₗ[ℝ] ℝ) (sesq_form_of_inner : F' →ₗ[ℝ] F' →ₗ[ℝ] ℝ) A (A†) := λ x y, by simp only [sesq_form_of_inner_apply_apply, adjoint_inner_left, to_linear_map_eq_coe, coe_coe] end real end continuous_linear_map /-! ### Self-adjoint operators -/ namespace is_self_adjoint open continuous_linear_map variables [complete_space E] [complete_space F] lemma adjoint_eq {A : E →L[𝕜] E} (hA : is_self_adjoint A) : A.adjoint = A := hA /-- Every self-adjoint operator on an inner product space is symmetric. -/ lemma is_symmetric {A : E →L[𝕜] E} (hA : is_self_adjoint A) : (A : E →ₗ[𝕜] E).is_symmetric := λ x y, by rw_mod_cast [←A.adjoint_inner_right, hA.adjoint_eq] /-- Conjugating preserves self-adjointness -/ lemma conj_adjoint {T : E →L[𝕜] E} (hT : is_self_adjoint T) (S : E →L[𝕜] F) : is_self_adjoint (S ∘L T ∘L S.adjoint) := begin rw is_self_adjoint_iff' at ⊢ hT, simp only [hT, adjoint_comp, adjoint_adjoint], exact continuous_linear_map.comp_assoc _ _ _, end /-- Conjugating preserves self-adjointness -/ lemma adjoint_conj {T : E →L[𝕜] E} (hT : is_self_adjoint T) (S : F →L[𝕜] E) : is_self_adjoint (S.adjoint ∘L T ∘L S) := begin rw is_self_adjoint_iff' at ⊢ hT, simp only [hT, adjoint_comp, adjoint_adjoint], exact continuous_linear_map.comp_assoc _ _ _, end lemma _root_.continuous_linear_map.is_self_adjoint_iff_is_symmetric {A : E →L[𝕜] E} : is_self_adjoint A ↔ (A : E →ₗ[𝕜] E).is_symmetric := ⟨λ hA, hA.is_symmetric, λ hA, ext $ λ x, ext_inner_right 𝕜 $ λ y, (A.adjoint_inner_left y x).symm ▸ (hA x y).symm⟩ lemma _root_.linear_map.is_symmetric.is_self_adjoint {A : E →L[𝕜] E} (hA : (A : E →ₗ[𝕜] E).is_symmetric) : is_self_adjoint A := by rwa ←continuous_linear_map.is_self_adjoint_iff_is_symmetric at hA /-- The orthogonal projection is self-adjoint. -/ lemma _root_.orthogonal_projection_is_self_adjoint (U : submodule 𝕜 E) [complete_space U] : is_self_adjoint (U.subtypeL ∘L orthogonal_projection U) := (orthogonal_projection_is_symmetric U).is_self_adjoint lemma conj_orthogonal_projection {T : E →L[𝕜] E} (hT : is_self_adjoint T) (U : submodule 𝕜 E) [complete_space U] : is_self_adjoint (U.subtypeL ∘L orthogonal_projection U ∘L T ∘L U.subtypeL ∘L orthogonal_projection U) := begin rw ←continuous_linear_map.comp_assoc, nth_rewrite 0 ←(orthogonal_projection_is_self_adjoint U).adjoint_eq, refine hT.adjoint_conj _, end end is_self_adjoint namespace linear_map variables [complete_space E] variables {T : E →ₗ[𝕜] E} /-- The **Hellinger--Toeplitz theorem**: Construct a self-adjoint operator from an everywhere defined symmetric operator.-/ def is_symmetric.to_self_adjoint (hT : is_symmetric T) : self_adjoint (E →L[𝕜] E) := ⟨⟨T, hT.continuous⟩, continuous_linear_map.is_self_adjoint_iff_is_symmetric.mpr hT⟩ lemma is_symmetric.coe_to_self_adjoint (hT : is_symmetric T) : (hT.to_self_adjoint : E →ₗ[𝕜] E) = T := rfl lemma is_symmetric.to_self_adjoint_apply (hT : is_symmetric T) {x : E} : hT.to_self_adjoint x = T x := rfl end linear_map namespace linear_map variables [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] [finite_dimensional 𝕜 G] local attribute [instance, priority 20] finite_dimensional.complete /-- The adjoint of an operator from the finite-dimensional inner product space E to the finite- dimensional inner product space F. -/ def adjoint : (E →ₗ[𝕜] F) ≃ₗ⋆[𝕜] (F →ₗ[𝕜] E) := ((linear_map.to_continuous_linear_map : (E →ₗ[𝕜] F) ≃ₗ[𝕜] (E →L[𝕜] F)).trans continuous_linear_map.adjoint.to_linear_equiv).trans linear_map.to_continuous_linear_map.symm lemma adjoint_to_continuous_linear_map (A : E →ₗ[𝕜] F) : A.adjoint.to_continuous_linear_map = A.to_continuous_linear_map.adjoint := rfl lemma adjoint_eq_to_clm_adjoint (A : E →ₗ[𝕜] F) : A.adjoint = A.to_continuous_linear_map.adjoint := rfl /-- The fundamental property of the adjoint. -/ lemma adjoint_inner_left (A : E →ₗ[𝕜] F) (x : E) (y : F) : ⟪adjoint A y, x⟫ = ⟪y, A x⟫ := begin rw [←coe_to_continuous_linear_map A, adjoint_eq_to_clm_adjoint], exact continuous_linear_map.adjoint_inner_left _ x y, end /-- The fundamental property of the adjoint. -/ lemma adjoint_inner_right (A : E →ₗ[𝕜] F) (x : E) (y : F) : ⟪x, adjoint A y⟫ = ⟪A x, y⟫ := begin rw [←coe_to_continuous_linear_map A, adjoint_eq_to_clm_adjoint], exact continuous_linear_map.adjoint_inner_right _ x y, end /-- The adjoint is involutive -/ @[simp] lemma adjoint_adjoint (A : E →ₗ[𝕜] F) : A.adjoint.adjoint = A := begin ext v, refine ext_inner_left 𝕜 (λ w, _), rw [adjoint_inner_right, adjoint_inner_left], end /-- The adjoint of the composition of two operators is the composition of the two adjoints in reverse order. -/ @[simp] lemma adjoint_comp (A : F →ₗ[𝕜] G) (B : E →ₗ[𝕜] F) : (A ∘ₗ B).adjoint = B.adjoint ∘ₗ A.adjoint := begin ext v, refine ext_inner_left 𝕜 (λ w, _), simp only [adjoint_inner_right, linear_map.coe_comp, function.comp_app], end /-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫` for all `x` and `y`. -/ lemma eq_adjoint_iff (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) : A = B.adjoint ↔ (∀ x y, ⟪A x, y⟫ = ⟪x, B y⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩, ext x, exact ext_inner_right 𝕜 (λ y, by simp only [adjoint_inner_left, h x y]) end /-- The adjoint is unique: a map `A` is the adjoint of `B` iff it satisfies `⟪A x, y⟫ = ⟪x, B y⟫` for all basis vectors `x` and `y`. -/ lemma eq_adjoint_iff_basis {ι₁ : Type*} {ι₂ : Type*} (b₁ : basis ι₁ 𝕜 E) (b₂ : basis ι₂ 𝕜 F) (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) : A = B.adjoint ↔ (∀ (i₁ : ι₁) (i₂ : ι₂), ⟪A (b₁ i₁), b₂ i₂⟫ = ⟪b₁ i₁, B (b₂ i₂)⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩, refine basis.ext b₁ (λ i₁, _), exact ext_inner_right_basis b₂ (λ i₂, by simp only [adjoint_inner_left, h i₁ i₂]), end lemma eq_adjoint_iff_basis_left {ι : Type*} (b : basis ι 𝕜 E) (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) : A = B.adjoint ↔ (∀ i y, ⟪A (b i), y⟫ = ⟪b i, B y⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, basis.ext b (λ i, _)⟩, exact ext_inner_right 𝕜 (λ y, by simp only [h i, adjoint_inner_left]), end lemma eq_adjoint_iff_basis_right {ι : Type*} (b : basis ι 𝕜 F) (A : E →ₗ[𝕜] F) (B : F →ₗ[𝕜] E) : A = B.adjoint ↔ (∀ i x, ⟪A x, b i⟫ = ⟪x, B (b i)⟫) := begin refine ⟨λ h x y, by rw [h, adjoint_inner_left], λ h, _⟩, ext x, refine ext_inner_right_basis b (λ i, by simp only [h i, adjoint_inner_left]), end /-- `E →ₗ[𝕜] E` is a star algebra with the adjoint as the star operation. -/ instance : has_star (E →ₗ[𝕜] E) := ⟨adjoint⟩ instance : has_involutive_star (E →ₗ[𝕜] E) := ⟨adjoint_adjoint⟩ instance : star_semigroup (E →ₗ[𝕜] E) := ⟨adjoint_comp⟩ instance : star_ring (E →ₗ[𝕜] E) := ⟨linear_equiv.map_add adjoint⟩ instance : star_module 𝕜 (E →ₗ[𝕜] E) := ⟨linear_equiv.map_smulₛₗ adjoint⟩ lemma star_eq_adjoint (A : E →ₗ[𝕜] E) : star A = A.adjoint := rfl /-- A continuous linear operator is self-adjoint iff it is equal to its adjoint. -/ lemma is_self_adjoint_iff' {A : E →ₗ[𝕜] E} : is_self_adjoint A ↔ A.adjoint = A := iff.rfl lemma is_symmetric_iff_is_self_adjoint (A : E →ₗ[𝕜] E) : is_symmetric A ↔ is_self_adjoint A := by { rw [is_self_adjoint_iff', is_symmetric, ← linear_map.eq_adjoint_iff], exact eq_comm } section real variables {E' : Type*} {F' : Type*} variables [normed_add_comm_group E'] [normed_add_comm_group F'] variables [inner_product_space ℝ E'] [inner_product_space ℝ F'] variables [finite_dimensional ℝ E'] [finite_dimensional ℝ F'] -- Todo: Generalize this to `is_R_or_C`. lemma is_adjoint_pair_inner (A : E' →ₗ[ℝ] F') : is_adjoint_pair (sesq_form_of_inner : E' →ₗ[ℝ] E' →ₗ[ℝ] ℝ) (sesq_form_of_inner : F' →ₗ[ℝ] F' →ₗ[ℝ] ℝ) A A.adjoint := λ x y, by simp only [sesq_form_of_inner_apply_apply, adjoint_inner_left] end real /-- The Gram operator T†T is symmetric. -/ lemma is_symmetric_adjoint_mul_self (T : E →ₗ[𝕜] E) : is_symmetric (T.adjoint * T) := λ x y, by simp only [mul_apply, adjoint_inner_left, adjoint_inner_right] /-- The Gram operator T†T is a positive operator. -/ lemma re_inner_adjoint_mul_self_nonneg (T : E →ₗ[𝕜] E) (x : E) : 0 ≤ re ⟪ x, (T.adjoint * T) x ⟫ := by {simp only [mul_apply, adjoint_inner_right, inner_self_eq_norm_sq_to_K], norm_cast, exact sq_nonneg _} @[simp] lemma im_inner_adjoint_mul_self_eq_zero (T : E →ₗ[𝕜] E) (x : E) : im ⟪ x, linear_map.adjoint T (T x) ⟫ = 0 := by {simp only [mul_apply, adjoint_inner_right, inner_self_eq_norm_sq_to_K], norm_cast} end linear_map namespace matrix variables {m n : Type*} [fintype m] [decidable_eq m] [fintype n] [decidable_eq n] open_locale complex_conjugate /-- The adjoint of the linear map associated to a matrix is the linear map associated to the conjugate transpose of that matrix. -/ lemma to_euclidean_lin_conj_transpose_eq_adjoint (A : matrix m n 𝕜) : A.conj_transpose.to_euclidean_lin = A.to_euclidean_lin.adjoint := begin rw linear_map.eq_adjoint_iff, intros x y, simp_rw [euclidean_space.inner_eq_star_dot_product, pi_Lp_equiv_to_euclidean_lin, to_lin'_apply, star_mul_vec, conj_transpose_conj_transpose, dot_product_mul_vec], end end matrix
9b1546dd0e3f5afc5b90ddc81cfeac3a6d9d0016
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/subring/pointwise.lean
f4893695db3f51d17b175ccd7cce155a56230a2e
[ "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,479
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 ring_theory.subsemiring.pointwise import group_theory.subgroup.pointwise import ring_theory.subring.basic /-! # Pointwise instances on `subring`s This file provides the action `subring.pointwise_mul_action` which matches the action of `mul_action_set`. This actions is available in the `pointwise` locale. ## Implementation notes This file is almost identical to `ring_theory/subsemiring/pointwise.lean`. Where possible, try to keep them in sync. -/ variables {M R : Type*} namespace subring section monoid variables [monoid M] [ring R] [mul_semiring_action M R] /-- The action on a subring corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action M (subring R) := { smul := λ a S, S.map (mul_semiring_action.to_ring_hom _ _ a), one_smul := λ S, (congr_arg (λ f, S.map f) (ring_hom.ext $ by exact one_smul M)).trans S.map_id, mul_smul := λ a₁ a₂ S, (congr_arg (λ f, S.map f) (ring_hom.ext $ by exact mul_smul _ _)).trans (S.map_map _ _).symm } localized "attribute [instance] subring.pointwise_mul_action" in pointwise open_locale pointwise lemma pointwise_smul_def {a : M} (S : subring R) : a • S = S.map (mul_semiring_action.to_ring_hom _ _ a) := rfl @[simp] lemma coe_pointwise_smul (m : M) (S : subring R) : ↑(m • S) = m • (S : set R) := rfl @[simp] lemma pointwise_smul_to_add_subgroup (m : M) (S : subring R) : (m • S).to_add_subgroup = m • S.to_add_subgroup := rfl @[simp] lemma pointwise_smul_to_subsemiring (m : M) (S : subring R) : (m • S).to_subsemiring = m • S.to_subsemiring := rfl lemma smul_mem_pointwise_smul (m : M) (r : R) (S : subring R) : r ∈ S → m • r ∈ m • S := (set.smul_mem_smul_set : _ → _ ∈ m • (S : set R)) lemma mem_smul_pointwise_iff_exists (m : M) (r : R) (S : subring R) : r ∈ m • S ↔ ∃ (s : R), s ∈ S ∧ m • s = r := (set.mem_smul_set : r ∈ m • (S : set R) ↔ _) instance pointwise_central_scalar [mul_semiring_action Mᵐᵒᵖ R] [is_central_scalar M R] : is_central_scalar M (subring R) := ⟨λ a S, congr_arg (λ f, S.map f) $ ring_hom.ext $ by exact op_smul_eq_smul _⟩ end monoid section group variables [group M] [ring R] [mul_semiring_action M R] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff {a : M} {S : subring R} {x : R} : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff lemma mem_pointwise_smul_iff_inv_smul_mem {a : M} {S : subring R} {x : R} : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem lemma mem_inv_pointwise_smul_iff {a : M} {S : subring R} {x : R} : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff @[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : M} {S T : subring R} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff lemma pointwise_smul_subset_iff {a : M} {S T : subring R} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff lemma subset_pointwise_smul_iff {a : M} {S T : subring R} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff /-! TODO: add `equiv_smul` like we have for subgroup. -/ end group section group_with_zero variables [group_with_zero M] [ring R] [mul_semiring_action M R] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) (S : subring R) (x : R) : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff₀ ha (S : set R) x lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : M} (ha : a ≠ 0) (S : subring R) (x : R) : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem₀ ha (S : set R) x lemma mem_inv_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) (S : subring R) (x : R) : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff₀ ha (S : set R) x @[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) {S T : subring R} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff₀ ha lemma pointwise_smul_le_iff₀ {a : M} (ha : a ≠ 0) {S T : subring R} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff₀ ha lemma le_pointwise_smul_iff₀ {a : M} (ha : a ≠ 0) {S T : subring R} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff₀ ha end group_with_zero end subring
c7376e4baf5e6239ee20635243401aba26b172cc
471bedbd023d35c9d078c2f936dd577ace7f5813
/library/init/meta/simp_tactic.lean
3dfe7eb6422762e0b4cdfc8488b1b6952c4b81be
[ "Apache-2.0" ]
permissive
lambdaxymox/lean
e06f0fa503666df827edd9867d7f49ca017aae64
fc13c8c72a15dab71a2c2b31410c2cadc3526bd7
refs/heads/master
1,666,785,407,985
1,666,153,673,000
1,666,153,673,000
310,165,986
0
0
Apache-2.0
1,604,542,096,000
1,604,542,095,000
null
UTF-8
Lean
false
false
28,072
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 -/ prelude import init.meta.tactic init.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences import init.data.option.basic open tactic def tactic.id_tag.simp : unit := () def simp.default_max_steps := 10000000 /-- Prefix the given `attr_name` with `"simp_attr"`. -/ meta constant mk_simp_attr_decl_name (attr_name : name) : name /-- Simp lemmas are used by the "simplifier" family of tactics. `simp_lemmas` is essentially a pair of tables `rb_map (expr_type × name) (priority_list simp_lemma)`. One of the tables is for congruences and one is for everything else. An individual simp lemma is: - A kind which can be `Refl`, `Simp` or `Congr`. - A pair of `expr`s `l ~> r`. The rb map is indexed by the name of `get_app_fn(l)`. - A proof that `l = r` or `l ↔ r`. - A list of the metavariables that must be filled before the proof can be applied. - A priority number -/ meta constant simp_lemmas : Type /-- Make a new table of simp lemmas -/ meta constant simp_lemmas.mk : simp_lemmas /-- Merge the simp_lemma tables. -/ meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas /-- Remove the given lemmas from the table. Use the names of the lemmas. -/ meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas /-- Remove all simp lemmas from the table. -/ meta constant simp_lemmas.erase_simp_lemmas : simp_lemmas → simp_lemmas /-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/ meta constant simp_lemmas.mk_default : tactic simp_lemmas /-- Add a simplification lemma by an expression `p`. Some conditions on `p` must hold for it to be added, see list below. If your lemma is not being added, you can see the reasons by setting `set_option trace.simp_lemmas true`. - `p` must have the type `Π (h₁ : _) ... (hₙ : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`). - Any of the hypotheses `hᵢ` should either be present in `LHS` or otherwise a `Prop` or a typeclass instance. - `LHS` should not occur within `RHS`. - `LHS` should not occur within a hypothesis `hᵢ`. -/ meta constant simp_lemmas.add (s : simp_lemmas) (e : expr) (symm : bool := false) : tactic simp_lemmas /-- Add a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/ meta constant simp_lemmas.add_simp (s : simp_lemmas) (id : name) (symm : bool := false) : tactic simp_lemmas /-- Adds a congruence simp lemma to simp_lemmas. A congruence simp lemma is a lemma that breaks the simplification down into separate problems. For example, to simplify `a ∧ b` to `c ∧ d`, we should try to simp `a` to `c` and `b` to `d`. For examples of congruence simp lemmas look for lemmas with the `@[congr]` attribute. ```lean lemma if_simp_congr ... (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ... lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := ... lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := ... ``` -/ meta constant simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas /-- Add expressions to a set of simp lemmas using `simp_lemmas.add`. This is the new version of `simp_lemmas.append`, which also allows you to set the `symm` flag. -/ meta def simp_lemmas.append_with_symm (s : simp_lemmas) (hs : list (expr × bool)) : tactic simp_lemmas := hs.mfoldl (λ s h, simp_lemmas.add s h.fst h.snd) s /-- Add expressions to a set of simp lemmas using `simp_lemmas.add`. This is the backwards-compatibility version of `simp_lemmas.append_with_symm`, and sets all `symm` flags to `ff`. -/ meta def simp_lemmas.append (s : simp_lemmas) (hs : list expr) : tactic simp_lemmas := hs.mfoldl (λ s h, simp_lemmas.add s h ff) s /-- `simp_lemmas.rewrite s e prove R` apply a simplification lemma from 's' - 'e' is the expression to be "simplified" - 'prove' is used to discharge proof obligations. - 'r' is the equivalence relation being used (e.g., 'eq', 'iff') - 'md' is the transparency; how aggresively should the simplifier perform reductions. Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite (s : simp_lemmas) (e : expr) (prove : tactic unit := failed) (r : name := `eq) (md := reducible) : tactic (expr × expr) meta constant simp_lemmas.rewrites (s : simp_lemmas) (e : expr) (prove : tactic unit := failed) (r : name := `eq) (md := reducible) : tactic $ list (expr × expr) /-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite (s : simp_lemmas) (e : expr) (md := reducible) : tactic expr meta constant is_valid_simp_lemma_cnst : name → tactic bool meta constant is_valid_simp_lemma : expr → tactic bool meta constant simp_lemmas.pp : simp_lemmas → tactic format meta instance : has_to_tactic_format simp_lemmas := ⟨simp_lemmas.pp⟩ namespace tactic /- Remark: `transform` should not change the target. -/ /-- Revert a local constant, change its type using `transform`. -/ meta def revert_and_transform (transform : expr → tactic expr) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, t ← target, match t with | expr.pi n bi d b := do h_simp ← transform d, unsafe_change $ expr.pi n bi h_simp b | expr.elet n g e f := do h_simp ← transform g, unsafe_change $ expr.elet n h_simp e f | _ := fail "reverting hypothesis created neither a pi nor an elet expr (unreachable?)" end, intron num_reverted /-- `get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta def get_eqn_lemmas_for (deps : bool) (d : name) : tactic (list name) := do env ← get_env, pure $ if deps then env.get_ext_eqn_lemmas_for d else env.get_eqn_lemmas_for d structure dsimp_config := (md := reducible) -- reduction mode: how aggressively constants are replaced with their definitions. (max_steps : nat := simp.default_max_steps) -- The maximum number of steps allowed before failing. (canonize_instances : bool := tt) -- See the documentation in `src/library/defeq_canonizer.h` (single_pass : bool := ff) -- Visit each subterm no more than once. (fail_if_unchanged := tt) -- Don't throw if dsimp didn't do anything. (eta := tt) -- allow eta-equivalence: `(λ x, F $ x) ↝ F` (zeta : bool := tt) -- do zeta-reductions: `let x : a := b in c ↝ c[x/b]`. (beta : bool := tt) -- do beta-reductions: `(λ x, E) $ (y) ↝ E[x/y]`. (proj : bool := tt) -- reduce projections: `⟨a,b⟩.1 ↝ a`. (iota : bool := tt) -- reduce recursors for inductive datatypes: eg `nat.rec_on (succ n) Z R ↝ R n $ nat.rec_on n Z R` (unfold_reducible := ff) -- if tt, definitions with `reducible` transparency will be unfolded (delta-reduced) (memoize := tt) -- Perform caching of dsimps of subterms. end tactic /-- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. The list `u` contains defintions to be delta-reduced, and projections to be reduced.-/ meta constant simp_lemmas.dsimplify (s : simp_lemmas) (u : list name := []) (e : expr) (cfg : tactic.dsimp_config := {}) : tactic expr namespace tactic /- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/ meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) (e : expr) (cfg : dsimp_config := {}) : tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta def get_simp_lemmas_or_default : option simp_lemmas → tactic simp_lemmas | none := simp_lemmas.mk_default | (some s) := return s meta def dsimp_target (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit := do s ← get_simp_lemmas_or_default s, t ← target >>= instantiate_mvars, s.dsimplify u t cfg >>= unsafe_change meta def dsimp_hyp (h : expr) (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit := do s ← get_simp_lemmas_or_default s, revert_and_transform (λ e, s.dsimplify u e cfg) h /- Remark: we use transparency.instances by default to make sure that we can unfold projections of type classes. Example: (@has_add.add nat nat.has_add a b) -/ /-- Tries to unfold `e` if it is a constant or a constant application. Remark: this is not a recursive procedure. -/ meta constant dunfold_head (e : expr) (md := transparency.instances) : tactic expr structure dunfold_config extends dsimp_config := (md := transparency.instances) /- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for performance reasons. -/ meta constant dunfold (cs : list name) (e : expr) (cfg : dunfold_config := {}) : tactic expr meta def dunfold_target (cs : list name) (cfg : dunfold_config := {}) : tactic unit := do t ← target, dunfold cs t cfg >>= unsafe_change meta def dunfold_hyp (cs : list name) (h : expr) (cfg : dunfold_config := {}) : tactic unit := revert_and_transform (λ e, dunfold cs e cfg) h structure delta_config := (max_steps := simp.default_max_steps) (visit_instances := tt) private meta def is_delta_target (e : expr) (cs : list name) : bool := cs.any (λ c, if e.is_app_of c then tt /- Exact match -/ else let f := e.get_app_fn in /- f is an auxiliary constant generated when compiling c -/ f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c)) /-- Delta reduce the given constant names -/ meta def delta (cs : list name) (e : expr) (cfg : delta_config := {}) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (is_delta_target e cs), (expr.const f_name f_lvls) ← return e.get_app_fn, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, new_e ← head_beta (expr.mk_app new_f e.get_app_args), return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () (λ c e, failed) unfold e {max_steps := cfg.max_steps, canonize_instances := cfg.visit_instances}, return new_e meta def delta_target (cs : list name) (cfg : delta_config := {}) : tactic unit := do t ← target, delta cs t cfg >>= unsafe_change meta def delta_hyp (cs : list name) (h : expr) (cfg : delta_config := {}) :tactic unit := revert_and_transform (λ e, delta cs e cfg) h structure unfold_proj_config extends dsimp_config := (md := transparency.instances) /-- If `e` is a projection application, try to unfold it, otherwise fail. -/ meta constant unfold_proj (e : expr) (md := transparency.instances) : tactic expr meta def unfold_projs (e : expr) (cfg : unfold_proj_config := {}) : tactic expr := let unfold (changed : bool) (e : expr) : tactic (bool × expr × bool) := do new_e ← unfold_proj e cfg.md, return (tt, new_e, tt) in do (tt, new_e) ← dsimplify_core ff (λ c e, failed) unfold e cfg.to_dsimp_config | fail "no projections to unfold", return new_e meta def unfold_projs_target (cfg : unfold_proj_config := {}) : tactic unit := do t ← target, unfold_projs t cfg >>= unsafe_change meta def unfold_projs_hyp (h : expr) (cfg : unfold_proj_config := {}) : tactic unit := revert_and_transform (λ e, unfold_projs e cfg) h structure simp_config := (max_steps : nat := simp.default_max_steps) (contextual : bool := ff) (lift_eq : bool := tt) (canonize_instances : bool := tt) (canonize_proofs : bool := ff) (use_axioms : bool := tt) (zeta : bool := tt) (beta : bool := tt) (eta : bool := tt) (proj : bool := tt) -- reduce projections (iota : bool := tt) (iota_eqn : bool := ff) -- reduce using all equation lemmas generated by equation/pattern-matching compiler (constructor_eq : bool := tt) (single_pass : bool := ff) (fail_if_unchanged := tt) (memoize := tt) (trace_lemmas := ff) /-- `simplify s e cfg r prove` simplify `e` using `s` using bottom-up traversal. `discharger` is a tactic for dischaging new subgoals created by the simplifier. If it fails, the simplifier tries to discharge the subgoal by simplifying it to `true`. The parameter `to_unfold` specifies definitions that should be delta-reduced, and projection applications that should be unfolded. -/ meta constant simplify (s : simp_lemmas) (to_unfold : list name := []) (e : expr) (cfg : simp_config := {}) (r : name := `eq) (discharger : tactic unit := failed) : tactic (expr × expr × name_set) meta def simp_target (s : simp_lemmas) (to_unfold : list name := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic name_set := do t ← target >>= instantiate_mvars, (new_t, pr, lms) ← simplify s to_unfold t cfg `eq discharger, replace_target new_t pr ``id_tag.simp, return lms meta def simp_hyp (s : simp_lemmas) (to_unfold : list name := []) (h : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic (expr × name_set) := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, (h_new_type, pr, lms) ← simplify s to_unfold htype cfg `eq discharger, new_hyp ← replace_hyp h h_new_type pr ``id_tag.simp, return (new_hyp, lms) /-- `ext_simplify_core a c s discharger pre post r e`: - `a : α` - initial user data - `c : simp_config` - simp configuration options - `s : simp_lemmas` - the set of simp_lemmas to use. Remark: the simplification lemmas are not applied automatically like in the simplify tactic. The caller must use them at pre/post. - `discharger : α → tactic α` - tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user data. - `pre a s r p e` is invoked before visiting the children of subterm 'e'. + arguments: - `a` is the current user data - `s` is the updated set of lemmas if 'contextual' is `tt`, - `r` is the simplification relation being used, - `p` is the "parent" expression (if there is one). - `e` is the current subexpression in question. + if it succeeds the result is `(new_a, new_e, new_pr, flag)` where - `new_a` is the new value for the user data - `new_e` is a new expression s.t. `r e new_e` - `new_pr` is a proof for `r e new_e`, If it is none, the proof is assumed to be by reflexivity - `flag` if tt `new_e` children should be visited, and `post` invoked. - `(post a s r p e)` is invoked after visiting the children of subterm `e`, The output is similar to `(pre a r s p e)`, but the 'flag' indicates whether the new expression should be revisited or not. - `r` is the simplification relation. Usually `=` or `↔`. - `e` is the input expression to be simplified. The method returns `(a,e,pr)` where - `a` is the final user data - `e` is the new expression - `pr` is the proof that the given expression equals the input expression. Note that `ext_simplify_core` will succeed even if `pre` and `post` fail, as failures are used to indicate that the method should move on to the next subterm. If it is desirable to propagate errors from `pre`, they can be propagated through the "user data". An easy way to do this is to call `tactic.capture (do ...)` in the parts of `pre`/`post` where errors matter, and then use `tactic.unwrap a` on the result. Additionally, `ext_simplify_core` does not propagate changes made to the tactic state by `pre` and `post. If it is desirable to propagate changes to the tactic state in addition to errors, use `tactic.resume` instead of `tactic.unwrap`. -/ meta constant ext_simplify_core {α : Type} (a : α) (c : simp_config) (s : simp_lemmas) (discharger : α → tactic α) (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) (r : name) : expr → tactic (α × expr × expr) private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end meta def collect_ctx_simps : tactic (list expr) := local_context section simp_intros meta def intro1_aux : bool → list name → tactic expr | ff _ := intro1 | tt (n::ns) := intro n | _ _ := failed structure simp_intros_config extends simp_config := (use_hyps := ff) meta def simp_intros_aux (cfg : simp_config) (use_hyps : bool) (to_unfold : list name) : simp_lemmas → bool → list name → tactic simp_lemmas | S tt [] := try (simp_target S to_unfold cfg) >> return S | S use_ns ns := do t ← target, if t.is_napp_of `not 1 then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail else if t.is_arrow then do { d ← return t.binding_domain, (new_d, h_d_eq_new_d, lms) ← simplify S to_unfold d cfg, h_d ← intro1_aux use_ns ns, h_new_d ← mk_eq_mp h_d_eq_new_d h_d, assertv_core h_d.local_pp_name new_d h_new_d, clear h_d, h_new ← intro1, new_S ← if use_hyps then mcond (is_prop new_d) (S.add h_new ff) (return S) else return S, simp_intros_aux new_S use_ns ns.tail } <|> -- failed to simplify... we just introduce and continue (intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail) else if t.is_pi || t.is_let then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail else do new_t ← whnf t reducible, if new_t.is_pi then unsafe_change new_t >> simp_intros_aux S use_ns ns else try (simp_target S to_unfold cfg) >> mcond (expr.is_pi <$> target) (simp_intros_aux S use_ns ns) (if use_ns ∧ ¬ns.empty then failed else return S) meta def simp_intros (s : simp_lemmas) (to_unfold : list name := []) (ids : list name := []) (cfg : simp_intros_config := {}) : tactic unit := step $ simp_intros_aux cfg.to_simp_config cfg.use_hyps to_unfold s (bnot ids.empty) ids end simp_intros meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← (has_attribute `congr n >> S.add_congr n) <|> S.add_simp n ff, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) (attr_deps : list name := []) : command := do let t := `(user_attribute simp_lemmas), let v := `({name := attr_name, descr := "simplifier attribute", cache_cfg := { mk_cache := λ ns, do { s ← tactic.to_simp_lemmas simp_lemmas.mk ns, s ← attr_deps.mfoldl (λ s attr_name, do ns ← attribute.get_instances attr_name, to_simp_lemmas s ns) s, return s }, dependencies := `reducibility :: attr_deps}} : user_attribute simp_lemmas), let n := mk_simp_attr_decl_name attr_name, add_decl (declaration.defn n [] t v reducibility_hints.abbrev ff), attribute.register n /-- ### Example usage: ```lean -- make a new simp attribute called "my_reduction" run_cmd mk_simp_attr `my_reduction -- Add "my_reduction" attributes to these if-reductions attribute [my_reduction] if_pos if_neg dif_pos dif_neg -- will return the simp_lemmas with the `my_reduction` attribute. #eval get_user_simp_lemmas `my_reduction ``` -/ meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else get_attribute_cache_dyn (mk_simp_attr_decl_name attr_name) meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R meta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas := do s ← simp_lemmas.mk_default, let s := if no_dflt then s.erase_simp_lemmas else s, join_user_simp_lemmas_core s attrs meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) (λ _ _ _ _ _, failed) `eq e meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg, replace_target new_target pr ``id_tag.simp meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) `eq e meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg, replace_target new_target pr ``id_tag.simp private meta def remove_deps (s : name_set) (h : expr) : name_set := if s.empty then s else h.fold s (λ e o s, if e.is_local_constant then s.erase e.local_uniq_name else s) /- Return the list of hypothesis that are propositions and do not have forward dependencies. -/ meta def non_dep_prop_hyps : tactic (list expr) := do ctx ← local_context, s ← ctx.mfoldl (λ s h, do h_type ← infer_type h, let s := remove_deps s h_type, h_val ← head_zeta h, let s := if h_val =ₐ h then s else remove_deps s h_val, mcond (is_prop h_type) (return $ s.insert h.local_uniq_name) (return s)) mk_name_set, t ← target, let s := remove_deps s t, return $ ctx.filter (λ h, s.contains h.local_uniq_name) section simp_all meta structure simp_all_entry := (h : expr) -- hypothesis (new_type : expr) -- new type (pr : option expr) -- proof that type of h is equal to new_type (s : simp_lemmas) -- simplification lemmas for simplifying new_type private meta def update_simp_lemmas (es : list simp_all_entry) (h : expr) : tactic (list simp_all_entry) := es.mmap $ λ e, do new_s ← e.s.add h ff, return {s := new_s, ..e} /- Helper tactic for `init`. Remark: the following tactic is quadratic on the length of list expr (the list of non dependent propositions). We can make it more efficient as soon as we have an efficient simp_lemmas.erase. -/ private meta def init_aux : list expr → simp_lemmas → list simp_all_entry → tactic (simp_lemmas × list simp_all_entry) | [] s r := return (s, r) | (h::hs) s r := do new_r ← update_simp_lemmas r h, new_s ← s.add h ff, h_type ← infer_type h, init_aux hs new_s (⟨h, h_type, none, s⟩::new_r) private meta def init (s : simp_lemmas) (hs : list expr) : tactic (simp_lemmas × list simp_all_entry) := init_aux hs s [] private meta def add_new_hyps (es : list simp_all_entry) : tactic unit := es.mmap' $ λ e, match e.pr with | none := return () | some pr := assert e.h.local_pp_name e.new_type >> mk_eq_mp pr e.h >>= exact end private meta def clear_old_hyps (es : list simp_all_entry) : tactic unit := es.mmap' $ λ e, when (e.pr ≠ none) (try (clear e.h)) private meta def join_pr : option expr → expr → tactic expr | none pr₂ := return pr₂ | (some pr₁) pr₂ := mk_eq_trans pr₁ pr₂ private meta def loop (cfg : simp_config) (discharger : tactic unit) (to_unfold : list name) : list simp_all_entry → list simp_all_entry → simp_lemmas → bool → tactic name_set | [] r s m := if m then loop r [] s ff else do add_new_hyps r, (lms, target_changed) ← (simp_target s to_unfold cfg discharger >>= λ ns, return (ns, tt)) <|> (return (mk_name_set, ff)), guard (cfg.fail_if_unchanged = ff ∨ target_changed ∨ r.any (λ e, e.pr ≠ none)) <|> fail "simp_all tactic failed to simplify", clear_old_hyps r, return lms | (e::es) r s m := do let ⟨h, h_type, h_pr, s'⟩ := e, (new_h_type, new_pr, lms) ← simplify s' to_unfold h_type {fail_if_unchanged := ff, ..cfg} `eq discharger, if h_type =ₐ new_h_type then do new_lms ← loop es (e::r) s m, return (new_lms.fold lms (λ n ns, name_set.insert ns n)) else do new_pr ← join_pr h_pr new_pr, new_fact_pr ← mk_eq_mp new_pr h, if new_h_type = `(false) then do tgt ← target, to_expr ``(@false.rec %%tgt %%new_fact_pr) >>= exact, return (mk_name_set) else do h0_type ← infer_type h, let new_fact_pr := mk_tagged_proof new_h_type new_fact_pr ``id_tag.simp, new_es ← update_simp_lemmas es new_fact_pr, new_r ← update_simp_lemmas r new_fact_pr, let new_r := {new_type := new_h_type, pr := new_pr, ..e} :: new_r, new_s ← s.add new_fact_pr ff, new_lms ← loop new_es new_r new_s tt, return (new_lms.fold lms (λ n ns, name_set.insert ns n)) meta def simp_all (s : simp_lemmas) (to_unfold : list name) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic name_set := do hs ← non_dep_prop_hyps, (s, es) ← init s hs, loop cfg discharger to_unfold es [] s ff end simp_all /- debugging support for algebraic normalizer -/ meta constant trace_algebra_info : expr → tactic unit end tactic export tactic (mk_simp_attr) run_cmd mk_simp_attr `norm [`simp]
a351317a29015873f7132d66a9669f1682e5dc22
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/matrix/basic.lean
aa0fed9ddca7d16582c9823216485fcfac7501f7
[ "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
19,140
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin -/ import algebra.pi_instances /-! # Matrices -/ universes u v w open_locale big_operators @[nolint unused_arguments] def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) := m → n → α namespace matrix variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[ext] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext def transpose (M : matrix m n α) : matrix n m α | x y := M y x localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix def col (w : m → α) : matrix m punit α | x y := w x def row (v : n → α) : matrix punit n α | x y := v y instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _ instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl section diagonal variables [decidable_eq n] def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_val_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl @[simp] lemma diagonal_transpose [has_zero α] (v : n → α) : (diagonal v)ᵀ = diagonal v := begin ext i j, by_cases h : i = j, { simp [h, transpose] }, { simp [h, transpose, diagonal_val_ne' h] } end section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i @[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_val_ne theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_val_ne' end one end diagonal @[simp] theorem diagonal_add [decidable_eq n] [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases i = j; simp [h] section dot_product /-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/ def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α := ∑ i, v i * w i lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) : dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) := by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm lemma dot_product_comm [comm_semiring α] (v w : m → α) : dot_product v w = dot_product w v := by simp_rw [dot_product, mul_comm] @[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) : dot_product v w = v ⟨⟩ * w ⟨⟩ := by simp [dot_product] @[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 := by simp [dot_product] @[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 := dot_product_zero v @[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 := by simp [dot_product] @[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 := zero_dot_product v @[simp] lemma add_dot_product [semiring α] (u v w : m → α) : dot_product (u + v) w = dot_product u w + dot_product v w := by simp [dot_product, add_mul, finset.sum_add_distrib] @[simp] lemma dot_product_add [semiring α] (u v w : m → α) : dot_product u (v + w) = dot_product u v + dot_product u w := by simp [dot_product, mul_add, finset.sum_add_distrib] @[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product (diagonal v i) w = v i * w i := have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_val_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (diagonal w i) = v i * w i := have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_val_ne' hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) : dot_product v (λ j, diagonal w j i) = v i * w i := have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_val_ne hij], by convert finset.sum_eq_single i (λ j _, this j) _; simp @[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w := by simp [dot_product] @[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w := by simp [dot_product] @[simp] lemma smul_dot_product [semiring α] (x : α) (v w : m → α) : dot_product (x • v) w = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc] @[simp] lemma dot_product_smul [comm_semiring α] (x : α) (v w : m → α) : dot_product v (x • w) = x * dot_product v w := by simp [dot_product, finset.mul_sum, mul_assoc, mul_comm, mul_left_comm] end dot_product protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, dot_product (λ j, M i j) (λ j, N j k) localized "infixl ` ⬝ `:75 := matrix.mul" in matrix theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = ∑ j, M i j * N j k := rfl instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by { ext, apply dot_product_assoc } instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by { ext i j, apply dot_product_zero } @[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by { ext i j, apply zero_dot_product } protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by { ext i j, apply dot_product_add } protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by { ext i j, apply add_dot_product } @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := diagonal_dot_product _ _ _ @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by { rw ← diagonal_transpose, apply dot_product_diagonal } @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := matrix.mul_zero, zero_mul := matrix.zero_mul, left_distrib := matrix.mul_add, right_distrib := matrix.add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal _ _ lemma is_add_monoid_hom_mul_left (M : matrix l m α) : is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) := { to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ } lemma is_add_monoid_hom_mul_right (M : matrix m n α) : is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) := { to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ } protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α) (M : matrix m n α) : s.sum f ⬝ M = s.sum (λ a, f a ⬝ M) := (@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α) (M : matrix l m α) : M ⬝ s.sum f = s.sum (λ a, M ⬝ f a) := (@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x) /- This line does not type-check without `id` and `: _`. Lean did not recognize that two different `add_monoid` instances were def-eq -/ (id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm @[simp] lemma row_mul_col_val (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w := rfl end semiring section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by { ext, apply neg_dot_product } @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by { ext, apply dot_product_neg } end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.semiring, ..matrix.add_comm_group } instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar instance {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] : semimodule α (matrix m n β) := pi.semimodule _ _ _ instance {β : Type w} [ring α] [add_comm_group β] [module α β] : module α (matrix m n β) := { .. matrix.semimodule } @[simp] lemma smul_val [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl section comm_semiring variables [comm_semiring α] lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) : a • M = diagonal (λ _, a) ⬝ M := by { ext, simp } lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) : a • M = M ⬝ diagonal (λ _, a) := by { ext, simp [mul_comm] } @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := by { ext, apply dot_product_smul } @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := by { ext, apply smul_dot_product } end comm_semiring section semiring variables [semiring α] def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y def mul_vec (M : matrix m n α) (v : n → α) : m → α | i := dot_product (λ j, M i j) v def vec_mul (v : m → α) (M : matrix m n α) : n → α | j := dot_product v (λ i, M i j) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, apply add_dot_product end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := diagonal_dot_product v w x lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) : vec_mul v (diagonal w) x = v x * w x := dot_product_diagonal' v w x @[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v := by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] } @[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v := by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] } @[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 := by { ext, simp [mul_vec] } @[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 := by { ext, simp [vec_mul] } @[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) : vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) := by { ext, apply dot_product_assoc } @[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) : mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v := by { ext, symmetry, apply dot_product_assoc } lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by { ext i j, simp [vec_mul_vec, mul_val], refl } end semiring section ring variables [ring α] lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A := by { ext, apply neg_dot_product } lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A := by { ext, apply dot_product_neg } lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v := by { ext, apply neg_dot_product } lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v := by { ext, apply dot_product_neg } end ring section transpose open_locale matrix /-- Tell `simp` what the entries are in a transposed matrix. Compare with `mul_val`, `diagonal_val_eq`, etc. -/ @[simp] lemma transpose_val (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl @[simp] lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 := begin ext i j, unfold has_one.one transpose, by_cases i = j, { simp only [h, diagonal_val_eq] }, { simp only [diagonal_val_ne h, diagonal_val_ne (λ p, h (symm p))] } end @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := by { ext i j, simp } @[simp] lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, apply dot_product_comm end @[simp] lemma transpose_smul [comm_ring α] (c : α)(M : matrix m n α) : (c • M)ᵀ = c • Mᵀ := by { ext i j, refl } @[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl end transpose def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) section row_col /-! ### `row_col` section Simplification lemmas for `matrix.row` and `matrix.col`. -/ open_locale matrix @[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl } @[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl } @[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl } @[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl } @[simp] lemma col_val (v : m → α) (i j) : matrix.col v i j = v i := rfl @[simp] lemma row_val (v : m → α) (i j) : matrix.row v i j = v j := rfl @[simp] lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl} @[simp] lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl} lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl} lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) : matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl} lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl} lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) : matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl} end row_col end matrix
6f08be30883d4c44b8db2ab42d9a19be3b3cf2ce
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/inner_product_space/dual.lean
588dfa1ec932872371f5bc882d1c3f1975952c44
[ "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,607
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import analysis.inner_product_space.projection import analysis.normed_space.dual import analysis.normed_space.star.basic /-! # The Fréchet-Riesz representation theorem We consider an inner product space `E` over `𝕜`, which is either `ℝ` or `ℂ`. We define `to_dual_map`, a conjugate-linear isometric embedding of `E` into its dual, which maps an element `x` of the space to `λ y, ⟪x, y⟫`. Under the hypothesis of completeness (i.e., for Hilbert spaces), we upgrade this to `to_dual`, a conjugate-linear isometric *equivalence* of `E` onto its dual; that is, we establish the surjectivity of `to_dual_map`. This is the Fréchet-Riesz representation theorem: every element of the dual of a Hilbert space `E` has the form `λ u, ⟪x, u⟫` for some `x : E`. For a bounded sesquilinear form `B : E →L⋆[𝕜] E →L[𝕜] 𝕜`, we define a map `inner_product_space.continuous_linear_map_of_bilin B : E →L[𝕜] E`, given by substituting `E →L[𝕜] 𝕜` with `E` using `to_dual`. ## References * [M. Einsiedler and T. Ward, *Functional Analysis, Spectral Theory, and Applications*] [EinsiedlerWard2017] ## Tags dual, Fréchet-Riesz -/ noncomputable theory open_locale classical complex_conjugate universes u v namespace inner_product_space open is_R_or_C continuous_linear_map variables (𝕜 : Type*) variables (E : Type*) [is_R_or_C 𝕜] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local postfix `†`:90 := star_ring_end _ /-- An element `x` of an inner product space `E` induces an element of the dual space `dual 𝕜 E`, the map `λ y, ⟪x, y⟫`; moreover this operation is a conjugate-linear isometric embedding of `E` into `dual 𝕜 E`. If `E` is complete, this operation is surjective, hence a conjugate-linear isometric equivalence; see `to_dual`. -/ def to_dual_map : E →ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := { norm_map' := λ _, innerSL_apply_norm, ..innerSL } variables {E} @[simp] lemma to_dual_map_apply {x y : E} : to_dual_map 𝕜 E x y = ⟪x, y⟫ := rfl lemma innerSL_norm [nontrivial E] : ‖(innerSL : E →L⋆[𝕜] E →L[𝕜] 𝕜)‖ = 1 := show ‖(to_dual_map 𝕜 E).to_continuous_linear_map‖ = 1, from linear_isometry.norm_to_continuous_linear_map _ variable {𝕜} lemma ext_inner_left_basis {ι : Type*} {x y : E} (b : basis ι 𝕜 E) (h : ∀ i : ι, ⟪b i, x⟫ = ⟪b i, y⟫) : x = y := begin apply (to_dual_map 𝕜 E).map_eq_iff.mp, refine (function.injective.eq_iff continuous_linear_map.coe_injective).mp (basis.ext b _), intro i, simp only [to_dual_map_apply, continuous_linear_map.coe_coe], rw [←inner_conj_sym], nth_rewrite_rhs 0 [←inner_conj_sym], exact congr_arg conj (h i) end lemma ext_inner_right_basis {ι : Type*} {x y : E} (b : basis ι 𝕜 E) (h : ∀ i : ι, ⟪x, b i⟫ = ⟪y, b i⟫) : x = y := begin refine ext_inner_left_basis b (λ i, _), rw [←inner_conj_sym], nth_rewrite_rhs 0 [←inner_conj_sym], exact congr_arg conj (h i) end variables (𝕜) (E) [complete_space E] /-- Fréchet-Riesz representation: any `ℓ` in the dual of a Hilbert space `E` is of the form `λ u, ⟪y, u⟫` for some `y : E`, i.e. `to_dual_map` is surjective. -/ def to_dual : E ≃ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := linear_isometry_equiv.of_surjective (to_dual_map 𝕜 E) begin intros ℓ, set Y := linear_map.ker ℓ with hY, by_cases htriv : Y = ⊤, { have hℓ : ℓ = 0, { have h' := linear_map.ker_eq_top.mp htriv, rw [←coe_zero] at h', apply coe_injective, exact h' }, exact ⟨0, by simp [hℓ]⟩ }, { rw [← submodule.orthogonal_eq_bot_iff] at htriv, change Yᗮ ≠ ⊥ at htriv, rw [submodule.ne_bot_iff] at htriv, obtain ⟨z : E, hz : z ∈ Yᗮ, z_ne_0 : z ≠ 0⟩ := htriv, refine ⟨((ℓ z)† / ⟪z, z⟫) • z, _⟩, ext x, have h₁ : (ℓ z) • x - (ℓ x) • z ∈ Y, { rw [linear_map.mem_ker, map_sub, continuous_linear_map.map_smul, continuous_linear_map.map_smul, algebra.id.smul_eq_mul, algebra.id.smul_eq_mul, mul_comm], exact sub_self (ℓ x * ℓ z) }, have h₂ : (ℓ z) * ⟪z, x⟫ = (ℓ x) * ⟪z, z⟫, { have h₃ := calc 0 = ⟪z, (ℓ z) • x - (ℓ x) • z⟫ : by { rw [(Y.mem_orthogonal' z).mp hz], exact h₁ } ... = ⟪z, (ℓ z) • x⟫ - ⟪z, (ℓ x) • z⟫ : by rw [inner_sub_right] ... = (ℓ z) * ⟪z, x⟫ - (ℓ x) * ⟪z, z⟫ : by simp [inner_smul_right], exact sub_eq_zero.mp (eq.symm h₃) }, have h₄ := calc ⟪((ℓ z)† / ⟪z, z⟫) • z, x⟫ = (ℓ z) / ⟪z, z⟫ * ⟪z, x⟫ : by simp [inner_smul_left, conj_conj] ... = (ℓ z) * ⟪z, x⟫ / ⟪z, z⟫ : by rw [←div_mul_eq_mul_div] ... = (ℓ x) * ⟪z, z⟫ / ⟪z, z⟫ : by rw [h₂] ... = ℓ x : begin have : ⟪z, z⟫ ≠ 0, { change z = 0 → false at z_ne_0, rwa ←inner_self_eq_zero at z_ne_0 }, field_simp [this] end, exact h₄ } end variables {𝕜} {E} @[simp] lemma to_dual_apply {x y : E} : to_dual 𝕜 E x y = ⟪x, y⟫ := rfl @[simp] lemma to_dual_symm_apply {x : E} {y : normed_space.dual 𝕜 E} : ⟪(to_dual 𝕜 E).symm y, x⟫ = y x := begin rw ← to_dual_apply, simp only [linear_isometry_equiv.apply_symm_apply], end variables {E 𝕜} /-- Maps a bounded sesquilinear form to its continuous linear map, given by interpreting the form as a map `B : E →L⋆[𝕜] normed_space.dual 𝕜 E` and dualizing the result using `to_dual`. -/ def continuous_linear_map_of_bilin (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) : E →L[𝕜] E := comp (to_dual 𝕜 E).symm.to_continuous_linear_equiv.to_continuous_linear_map B local postfix `♯`:1025 := continuous_linear_map_of_bilin variables (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) @[simp] lemma continuous_linear_map_of_bilin_apply (v w : E) : ⟪(B♯ v), w⟫ = B v w := by simp [continuous_linear_map_of_bilin] lemma unique_continuous_linear_map_of_bilin {v f : E} (is_lax_milgram : (∀ w, ⟪f, w⟫ = B v w)) : f = B♯ v := begin refine ext_inner_right 𝕜 _, intro w, rw continuous_linear_map_of_bilin_apply, exact is_lax_milgram w, end end inner_product_space
15e5273e9a07434099f95e43b162d0b36fb70a05
874a8d2247ab9a4516052498f80da2e32d0e3a48
/ramsey_lb.lean
73122bd9164d9216715c50935463a91e7456626b
[]
no_license
AlexKontorovich/Spring2020Math492
378b36c643ee029f5ab91c1677889baa591f5e85
659108c5d864ff5c75b9b3b13b847aa5cff4348a
refs/heads/master
1,610,780,595,457
1,588,174,859,000
1,588,174,859,000
243,017,788
0
1
null
null
null
null
UTF-8
Lean
false
false
2,815
lean
import data.nat.basic import data.int.basic import data.rat.basic import algebra.field_power import tactic import data.finset import algebra.big_operators import data.real.basic import data.set.lattice open finset open nat local notation `edges_of `X := powerset_len 2 X universe u variables {α : Type u} (K : finset α) {n : ℕ} --[decidable_eq α] /- lemma number_of_colorings_of_K_with_monochromatic_K_subgraph (k : ℕ) (hn : card(K_1) = n) := card (colorings_of_K_with_monochromatic_K_subgraph k) = 2^(n.choose(2) - n.choose(k)) * 2 * n.choose(k) ---------- -/ /- The set of all two colorings of the complete graph -/ --Note: Present implementation only works with 2 colorings def colorings : finset (finset (finset α)) := powerset (edges_of K) /- The cardinality of colorings -/ lemma num_complete_colorings (hn : card K = n) : card (colorings K) = 2^(nat.choose n 2) := begin rw colorings, rw card_powerset, rw card_powerset_len, rw hn, end /- The set of all 2 colorings of the compelte graph such that the coloring is monochromatic on a complete subgraph of order k -/ def mono_sub_colorings (n : ℕ) (k : ℕ) : finset (finset (finset α)) := begin sorry, end /- The cardinality of mono_sub_colorings -/ lemma num_mono_sub_colorings (n k : ℕ) (h : n ≥ k) : (card (@mono_sub_colorings α n k) : ℚ) = ((2 : ℚ)^((n.choose(2)) - (k.choose(2))) : ℚ) * 2 * n.choose(k) := begin sorry, end /- Central inequality of the next theorem, except without binomial coefficients (for readability and convenience). -/ lemma core_ineq {a b c : ℕ} (h : ((2 : ℚ)^(1 - b : ℤ) * c : ℚ) < 1) : ((2 : ℚ)^(a - b : ℤ) * 2 * c : ℚ) < (2:ℚ)^(a : ℤ) := begin --rw fpow_add two_ne_zero a (-b), --fpow_add alt approach above rw @fpow_sub ℚ _ _ two_ne_zero 1 b at h, rw fpow_one (2: ℚ) at h, rw @fpow_sub ℚ _ _ two_ne_zero a b, rw div_mul_eq_mul_div_comm (2) ((2 : ℚ)^(a : ℤ)) ((2 : ℚ)^(b : ℤ)), rw mul_assoc ((2 : ℚ)^(a : ℤ)) (2 / 2 ^ ↑b) (↑c), rw mul_comm ((2 : ℚ) ^ ↑a) (2 / 2 ^ ↑b * ↑c), apply mul_lt_of_lt_div, exact nat.fpow_pos_of_pos (nat.pos_of_ne_zero(two_ne_zero)) (a : ℤ), rw div_self, exact h, apply fpow_ne_zero_of_ne_zero, exact dec_trivial, end /- Proof that the cardinality of colorings is strictly less than the cardinality of mono_sub_colorings given a certain hypothesis. -/ theorem card_strict_inequality (n k : ℕ) (hnk : n ≥ k) (hn : card (K) = n) (h : (2^(1 - k.choose(2) : ℤ) * n.choose(k) : ℚ) < 1) : (card (@mono_sub_colorings α n k) : ℚ) < (card (colorings K) : ℚ) := begin rw num_complete_colorings K hn, rw num_mono_sub_colorings n k hnk, exact @core_ineq (n.choose 2) (k.choose 2) (n.choose k) (h), end
12bf82a9cba3aa1e70f8293c995a75d653f25c95
a81826cfd4fd71c797ea79b8e827b03ccb332c17
/src/p_laplacian/basic.lean
1903fda607e378b98e8a3e4778d1e45b24bffc26
[ "Apache-2.0" ]
permissive
jamesa9283/Generalised-Trigonometric-Functions-for-Lean
0a0f4774363c3708be466526935c6d07f4b970f0
33775fb8286eacfc17397fe41af9d446cbdd78f3
refs/heads/master
1,669,337,232,958
1,597,061,947,000
1,597,061,947,000
276,104,804
0
0
null
1,593,540,795,000
1,593,523,262,000
Lean
UTF-8
Lean
false
false
4,647
lean
import tactic import data.real.basic import data.complex.exponential import analysis.special_functions.pow noncomputable theory open_locale classical open real notation `|`x`|` := abs x variables (a : ℝ) (b : ℝ) /-! ## p-GTFs This is my speciality but it _needs_ integration, so this won't be able to be filled in until somebody produces some sort of integration in lean or I prove it out of spite for not having it. I've actually remembered that we can define the πₚ function. -/ def pip (p : ℝ) := (2 * pi)/ (p * sin (pi / p)) -- def sinp (p : ℝ) := sorry -- def cosp (p : ℝ) := sorry example (h : a * b = 0) : a = 0 ∨ b = 0 := zero_eq_mul.mp (eq.symm h) private lemma lt_mul_eq_zero (fab : a < b) (fa : 0 < a) (fb : 0 < b) : 0 < a * b ↔ 0 < a ∨ 0 < b := begin split, intro famulb, left, exact fa, intro famulb, rw zero_lt_mul_left, exact fb, exact fa, end lemma pip_monotone_decreasing : strict_mono_decr_on pip {p : ℝ | 1 < p} := begin rintros a fa b fb fab, have one_lt_b : 1 < b, {apply fb}, have one_lt_a : 1 < a, {apply fa}, have a_pos : 0 < a := by linarith, have b_pos : 0 < b := by linarith, have two_pi_pos : 0 < 2 * pi, {norm_num, exact pi_pos}, have pi_a_lt_pi_b : pi/b < pi/a := by {apply div_lt_div', refl, exact fab, exact pi_pos, exact a_pos,}, have pi_on_b_pos : pi / b < pi := by {rw div_lt_iff b_pos, refine sub_pos.mp _, rw ←mul_one (pi), rw mul_assoc, rw one_mul (b), rw ←mul_sub, refine (div_lt_iff _).mp _, /- ⊢ 0 < b - 1 -/ { norm_num, exact one_lt_b,}, /- ⊢ 0 / (b - 1) < pi -/ {rw zero_div, exact pi_pos,}, }, have pi_on_a_pos : pi / a < pi := by {rw div_lt_iff a_pos, refine sub_pos.mp _, rw ←mul_one (pi), rw mul_assoc, rw one_mul (a), rw ←mul_sub, refine (div_lt_iff _).mp _, /- ⊢ 0 < b - 1 -/ { norm_num, exact one_lt_a,}, /- ⊢ 0 / (b - 1) < pi -/ {rw zero_div, exact pi_pos,}, }, have pi_b_pos : 0 < pi/b := by { refine div_pos _ b_pos, exact pi_pos,}, have pi_a_pos : 0 < pi/a := by { refine div_pos _ a_pos, exact pi_pos,}, have sin_pi_b_pos : 0 < sin(pi/b), {exact sin_pos_of_pos_of_lt_pi pi_b_pos pi_on_b_pos,}, have sin_pi_a_pos : 0 < sin(pi/a), {exact sin_pos_of_pos_of_lt_pi pi_a_pos pi_on_a_pos,}, have sin_fa_lt_sin_fb : sin (pi/a) < sin (pi/b) := sorry, /-/- This changes, depending on whether x ∈ (1, 2] or x ∈ (2, ∞). For x < 2, we get that f a < f b, however for 2 < x we get f b < f a -/ { apply sin_lt_sin_of_le_of_le_pi_div_two, linarith, { sorry }, -- pi/a < pi/b for all ∀ a < b : b > 2 which is false. So something else must be false sorry}, -/ unfold pip, rw div_eq_mul_one_div, rw div_eq_mul_one_div _ (a*sin(pi/a)), rw mul_lt_mul_left two_pi_pos, repeat {rw one_div_eq_inv}, rw inv_lt_inv, /- ⊢ a * sin (pi / a) < b * sin (pi / b) -/ {refine (div_lt_div_iff sin_pi_b_pos sin_pi_a_pos).mp _, refine div_lt_div' _ sin_fa_lt_sin_fb b_pos sin_pi_a_pos, exact le_of_lt fab,}, /- ⊢ 0 < b * sin (pi / b) -/ {refine mul_pos b_pos sin_pi_b_pos,}, /- ⊢ 0 < a * sin (pi / a) -/ {refine mul_pos a_pos sin_pi_a_pos,}, end #exit -- this is a mess. Please ignore below thiss example (p : ℝ) : pip p ≤ 16 / (pi ^ 2 - 8) := begin unfold pip, have H : p * sin(pi/p) ≠ 0, {intros f, --rw zero_eq_mul at f, sorry }, sorry end lemma pip_monotone (a b : ℝ) (ga : 1 < a) (gb : 1 < b) : a < b → pip b < pip a := begin have h : 0 < 2 * pi, {norm_num, exact pi_pos}, rintros fab, unfold pip, rw div_eq_mul_one_div, rw div_eq_mul_one_div _ (a*sin(pi/a)), rw mul_lt_mul_left h, repeat {rw one_div_eq_inv}, rw inv_lt_inv, { apply mul_lt_mul, {exact fab,}, { -- sin(π / a) ≤ sin(π / b) sorry }, { -- 0 < sin (π / a) sorry }, {linarith} }, { -- 0 < b * sin (π / b) have H : 0 < pi / b ∧ pi / b < pi, {split, { have pi_pos : 0 < pi := pi_pos, rw div_eq_inv_mul, --finish, sorry }, { have pi_pos : 0 < pi := pi_pos, rw div_eq_inv_mul, --apply lt_mul_of_inv_mul_lt_left, sorry },}, /- Basically this follows the proof that we know 0 < π/b < π as b > 1 → 0 < sin (π / b) < π and we know t ∈ [0, π] then 0 < sin t. -/ }, { -- 0 < a * sin (π / b) sorry } end --example (a b c : ℝ) (h : a = b⁻¹ * c) (g : b ≠ 0) : a * b = c := by library_search #exit
1c1773b0395e3f68eba01a8a70cebccff215cc3c
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/list/mem.lean
a6a0dbf04cff50d01689e7c1b6a7ab3b7bb2d965
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,659
lean
import galois.tactic universes u namespace list def mem_induction {A : Type u} (P : A → list A → Prop) (Phere : ∀ x xs, P x (x :: xs)) (Pthere : ∀ x y ys, P x ys → P x (y :: ys)) (x : A) (xs : list A) (H : x ∈ xs) : P x xs := begin induction xs, cases H, dsimp [has_mem.mem, list.mem] at H, induction H, subst a, apply Phere, apply Pthere, apply ih_1, assumption, end lemma mem_map' {A B} (f : A → B) (xs : list A) (x : A) (y : B) (H : f x = y) (H' : x ∈ xs) : y ∈ xs.map f := begin subst H, apply mem_induction _ _ _ _ _ H'; intros, left, reflexivity, right, assumption, end end list lemma list.mem_bind' {A B} (xs : list A) (f : A → list B) (y : B) (H : y ∈ xs >>= f) : ∃ x : A, x ∈ xs ∧ y ∈ f x := begin dsimp [(>>=), list.bind, list.join] at H, induction xs; dsimp [list.map, list.join] at H, rw list.mem_nil_iff at H, contradiction, rw list.mem_append at H, induction H with H H', existsi a, split, constructor, reflexivity, assumption, specialize (ih_1 H'), induction ih_1 with x H, induction H with H1 H2, existsi x, split, dsimp [has_mem.mem, list.mem], right, assumption, assumption, end lemma list.mem_bind_iff' {A B} (xs : list A) (f : A → list B) (y : B) : y ∈ xs >>= f ↔ ∃ x : A, x ∈ xs ∧ y ∈ f x := begin split; intros H, apply list.mem_bind', assumption, induction H with x Hx, induction Hx with H1 H2, dsimp [(>>=), list.bind, list.join], induction xs; dsimp [list.map, list.join], rw list.mem_nil_iff at H1, contradiction, rw list.mem_append, dsimp [has_mem.mem, list.mem] at H1, induction H1 with H1 H1, subst a, left, assumption, right, apply ih_1, assumption, end
26bb86b30be3a14b91ae67d084a97479c1570514
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/uniform_space/complete_separated.lean
5364e04cb70554b8f5e59891ffaae76606427279
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
852
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 Theory of complete separated uniform spaces. This file is for elementary lemmas that depend on both Cauchy filters and separation. -/ import topology.uniform_space.cauchy topology.uniform_space.separation open filter variables {α : Type*} [uniform_space α] /-In a separated space, a complete set is closed -/ lemma is_closed_of_is_complete [separated α] {s : set α} (h : is_complete s) : is_closed s := is_closed_iff_nhds.2 $ λ a ha, begin let f := nhds a ⊓ principal s, have : cauchy f := cauchy_downwards (cauchy_nhds) ha (lattice.inf_le_left), rcases h f this (lattice.inf_le_right) with ⟨y, ys, fy⟩, rwa (tendsto_nhds_unique ha lattice.inf_le_left fy : a = y) end
8183b4c21333c01c35abe786ab5073d0a5eacd9b
a537b538f2bea3181e24409d8a52590603d1ddd9
/examples/knot_isotopy.lean
7e8bb22b3cc0ff2673ce6da3af162f6348a3a27e
[]
no_license
rwbarton/lean-tidy
6134813ded72b275d19d4d32514dba80c21708e3
fe1125d32adb60decda7a77d0f679614ba9f6fbb
refs/heads/master
1,585,549,718,705
1,538,120,619,000
1,538,120,624,000
150,864,330
0
0
null
1,538,225,790,000
1,538,225,790,000
null
UTF-8
Lean
false
false
6,386
lean
import tidy.tidy inductive slice | pos : ℕ → slice | neg : ℕ → slice | cup : ℕ → slice | cap : ℕ → slice open slice inductive diagram | nil | cons : slice → diagram → diagram infixr ` ~~ `:80 := diagram.cons notation `t[` l:(foldr `, ` (h t, diagram.cons h t) diagram.nil `]`) := l namespace isotopy variable (d : diagram) axiom commute_pos_pos (n m) (h : n ≥ m + 2) : (pos n) ~~ (pos m) ~~ d = (pos m) ~~ (pos n) ~~ d axiom commute_pos_neg (n m) (h : n ≥ m + 2) : (pos n) ~~ (neg m) ~~ d = (neg m) ~~ (pos n) ~~ d axiom commute_neg_pos (n m) (h : n ≥ m + 2) : (neg n) ~~ (pos m) ~~ d = (pos m) ~~ (neg n) ~~ d axiom commute_neg_neg (n m) (h : n ≥ m + 2) : (neg n) ~~ (neg m) ~~ d = (neg m) ~~ (neg n) ~~ d axiom commute_cup_pos (n m) (h : n ≥ m + 2) : (cup n) ~~ (pos m) ~~ d = (pos m) ~~ (cup n) ~~ d axiom commute_cup_neg (n m) (h : n ≥ m + 2) : (cup n) ~~ (neg m) ~~ d = (neg m) ~~ (cup n) ~~ d axiom commute_cap_pos (n m) (h : n ≥ m + 2) : (cap n) ~~ (pos m) ~~ d = (pos m) ~~ (cap n) ~~ d axiom commute_cap_neg (n m) (h : n ≥ m + 2) : (cap n) ~~ (neg m) ~~ d = (neg m) ~~ (cap n) ~~ d axiom commute_pos_cup (n m) (h : n ≥ m) : (pos n) ~~ (cup m) ~~ d = (cup m) ~~ (pos (n+2)) ~~ d axiom commute_pos_cap (n m) (h : n ≥ m + 2) : (pos n) ~~ (cap m) ~~ d = (cap m) ~~ (pos (n-2)) ~~ d axiom commute_neg_cup (n m) (h : n ≥ m) : (neg n) ~~ (cup m) ~~ d = (cup m) ~~ (neg (n+2)) ~~ d axiom commute_neg_cap (n m) (h : n ≥ m + 2) : (neg n) ~~ (cap m) ~~ d = (cap m) ~~ (neg (n-2)) ~~ d axiom commute_cup_cup (n m) (h : n ≥ m) : (cup n) ~~ (cup m) ~~ d = (cup m) ~~ (cup (n+2)) ~~ d axiom commute_cup_cap (n m) (h : n ≥ m + 2) : (cup n) ~~ (cap m) ~~ d = (cap m) ~~ (cup (n-2)) ~~ d axiom commute_cap_cup (n m) (h : n ≥ m) : (cap n) ~~ (cup m) ~~ d = (cup m) ~~ (cap (n+2)) ~~ d axiom commute_cap_cap (n m) (h : n ≥ m + 2) : (cap n) ~~ (cap m) ~~ d = (cap m) ~~ (cap (n-2)) ~~ d axiom zigzag_left (n : ℕ) : (cup n) ~~ (cap (n+1)) ~~ d = d axiom zigzag_right (n : ℕ) : (cup (n+1)) ~~ (cap n) ~~ d = d axiom R2_east (n : ℕ) : (neg n) ~~ (pos n) ~~ d = d axiom R2_west (n : ℕ) : (pos n) ~~ (neg n) ~~ d = d axiom R2_north (n : ℕ) : (cup (n+1)) ~~ (pos n) ~~ (neg (n+2)) ~~ cap(n+1) ~~ d = (cap n) ~~ (cup n) ~~ d axiom R2_south (n : ℕ) : (cup (n+1)) ~~ (neg n) ~~ (pos (n+2)) ~~ cap(n+1) ~~ d = (cap n) ~~ (cup n) ~~ d axiom R1_pos_east (n : ℕ) : (cup (n+1)) ~~ (pos n) ~~ (cap (n+1)) ~~ d = d axiom R1_neg_east (n : ℕ) : (cup (n+1)) ~~ (neg n) ~~ (cap (n+1)) ~~ d = d axiom R1_pos_west (n : ℕ) : (cup n) ~~ (pos (n+1)) ~~ (cap n) ~~ d = d axiom R1_neg_west (n : ℕ) : (cup n) ~~ (neg (n+1)) ~~ (cap n) ~~ d = d axiom R1_pos_north (n : ℕ) : (pos n) ~~ (cap n) ~~ d = (cap n) ~~ d axiom R1_neg_north (n : ℕ) : (neg n) ~~ (cap n) ~~ d = (cap n) ~~ d axiom R1_pos_south (n : ℕ) : (cup n) ~~ (pos n) ~~ d = (cup n) ~~ d axiom R1_neg_south (n : ℕ) : (cup n) ~~ (neg n) ~~ d = (cup n) ~~ d axiom R3_pos_pos_pos (n : ℕ) : (pos n) ~~ (pos (n+1)) ~~ (pos n) ~~ d = (pos (n+1)) ~~ (pos n) ~~ (pos (n+1)) ~~ d axiom R3_pos_pos_neg (n : ℕ) : (pos n) ~~ (pos (n+1)) ~~ (neg n) ~~ d = (neg (n+1)) ~~ (pos n) ~~ (pos (n+1)) ~~ d axiom R3_pos_neg_neg (n : ℕ) : (pos n) ~~ (neg (n+1)) ~~ (neg n) ~~ d = (neg (n+1)) ~~ (neg n) ~~ (pos (n+1)) ~~ d axiom R3_neg_pos_pos (n : ℕ) : (neg n) ~~ (pos (n+1)) ~~ (pos n) ~~ d = (pos (n+1)) ~~ (pos n) ~~ (neg (n+1)) ~~ d axiom R3_neg_neg_pos (n : ℕ) : (neg n) ~~ (neg (n+1)) ~~ (pos n) ~~ d = (pos (n+1)) ~~ (neg n) ~~ (neg (n+1)) ~~ d axiom R3_neg_neg_neg (n : ℕ) : (neg n) ~~ (neg (n+1)) ~~ (neg n) ~~ d = (neg (n+1)) ~~ (neg n) ~~ (neg (n+1)) ~~ d axiom cap_over (n : ℕ) : (pos n) ~~ (cap (n+1)) ~~ d = (neg (n+1)) ~~ (cap n) ~~ d axiom cap_under (n : ℕ) : (neg n) ~~ (cap (n+1)) ~~ d = (pos (n+1)) ~~ (cap n) ~~ d axiom cup_over (n : ℕ) : (cup (n+1)) ~~ (neg n) ~~ d = (cup n) ~~ (pos (n+1)) ~~ d axiom cup_under (n : ℕ) : (cup (n+1)) ~~ (pos n) ~~ d = (cup n) ~~ (neg (n+1)) ~~ d -- axiom rotate_pos_clockwise (n : ℕ) : (cup n) ~~ (pos (n+1)) ~~ (cap (n+2)) ~~ d = (neg n) ~~ d -- axiom rotate_neg_clockwise (n : ℕ) : (cup n) ~~ (neg (n+1)) ~~ (cap (n+2)) ~~ d = (pos n) ~~ d -- axiom rotate_pos_widdershins (n : ℕ) : (cup (n+2)) ~~ (pos (n+1)) ~~ (cap n) ~~ d = (neg n) ~~ d -- axiom rotate_neg_widdershins (n : ℕ) : (cup (n+2)) ~~ (neg (n+1)) ~~ (cap n) ~~ d = (pos n) ~~ d attribute [search] commute_pos_pos commute_pos_neg commute_neg_pos commute_neg_neg attribute [search] commute_cup_pos commute_cup_neg commute_cap_pos commute_cap_neg attribute [search] commute_pos_cup commute_pos_cap commute_neg_cup commute_neg_cap attribute [search] commute_cup_cup commute_cup_cap commute_cap_cup commute_cap_cap attribute [search] zigzag_left zigzag_right attribute [search] cap_over cap_under cup_over cup_under attribute [search] R1_pos_east R1_neg_east R1_pos_west R1_neg_west R1_pos_north R1_neg_north R1_pos_south R1_neg_south attribute [search] R2_east R2_west R2_north R2_south attribute [search] R3_pos_pos_pos R3_pos_pos_neg R3_pos_neg_neg R3_neg_pos_pos R3_neg_neg_pos R3_neg_neg_neg -- attribute [search] rotate_pos_clockwise rotate_neg_clockwise rotate_pos_widdershins rotate_neg_widdershins end isotopy open isotopy open tactic meta def isotopy := `[rewrite_search_using [`search] { discharger := `[norm_num], simplifier := norm_num.derive, trace_result := tt }] meta def isotopy' := `[rewrite_search_using [`search] { discharger := `[norm_num], simplifier := norm_num.derive, trace := tt, view := visualiser, trace_result := tt }] lemma commute_1 : t[pos 0, neg 2, pos 4] = t[pos 4, neg 2, pos 0] := by isotopy lemma commute_2 : t[cup 0, pos 2] = t[pos 0, cup 0] := by isotopy lemma commute_3 : t[cup 2, cap 0] = t[cup 0, cap 2] := by isotopy lemma bulge : t[cup 1, cap 0, cup 0, cap 1] = t[] := by isotopy lemma R2_north : t[cup 1, pos 0, neg 2, cap 1] = t[cap 0, cup 0] := by isotopy lemma twists : t[cup 0, cup 2, pos 0, pos 2, cap 1, cap 0] = t[cup 0, cap 0] := by isotopy -- begin -- rw commute_cup_pos, -- rw R1_pos_south, -- rw R1_pos_south, -- rw zigzag_right, -- norm_num -- end lemma rotate : t[cup 0, pos 1, cap 2] = t[neg 0] := by isotopy -- lemma recognise_trefoil : t[cup 0, cup 1, pos 0, pos 0, pos 0, cap 1, cap 0] = t[cup 0, cup 2, neg 1, pos 0, pos 2, cap 1, cap 0] := by isotopy
1b1b8ed1946818127d9e315a5276e556f3928dd4
3aad12fe82645d2d3173fbedc2e5c2ba945a4d75
/src/data/equiv/nursery.lean
ef7559d0ebad09f274e37f559df660d5efe76884
[]
no_license
seanpm2001/LeanProver-Community_MathLIB-Nursery
4f88d539cb18d73a94af983092896b851e6640b5
0479b31fa5b4d39f41e89b8584c9f5bf5271e8ec
refs/heads/master
1,688,730,786,645
1,572,070,026,000
1,572,070,026,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
232
lean
import data.equiv.basic lemma equiv.forall_iff_forall {α β} {p : α → Prop} (f : α ≃ β) : (∀ x, p x) ↔ (∀ x, p $ f.symm x) := iff.intro (assume h x, h _) (assume h x, by { specialize h (f x), revert h, simp })
b7cea61dbe90acdc4b930ef7debac55a683b89e5
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/order/lattice.lean
1022d57cd1387a175cfe71920e24b7bba006bc01
[ "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
42,104
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.monotone import order.rel_classes import tactic.simps import tactic.pi_instances /-! # (Semi-)lattices Semilattices are partially ordered sets with join (greatest lower bound, or `sup`) or meet (least upper bound, or `inf`) operations. Lattices are posets that are both join-semilattices and meet-semilattices. Distributive lattices are lattices which satisfy any of four equivalent distributivity properties, of `sup` over `inf`, on the left or on the right. ## Main declarations * `semilattice_sup`: a type class for join semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_sup` via proofs that `⊔` is commutative, associative and idempotent. * `semilattice_inf`: a type class for meet semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_inf` via proofs that `⊓` is commutative, associative and idempotent. * `lattice`: a type class for lattices * `lattice.mk'`: an alternative constructor for `lattice` via profs that `⊔` and `⊓` are commutative, associative and satisfy a pair of "absorption laws". * `distrib_lattice`: a type class for distributive lattices. ## Notations * `a ⊔ b`: the supremum or join of `a` and `b` * `a ⊓ b`: the infimum or meet of `a` and `b` ## TODO * (Semi-)lattice homomorphisms * Alternative constructors for distributive lattices from the other distributive properties ## Tags semilattice, lattice -/ set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := @le_antisymm _ _ end /- TODO: automatic construction of dual definitions / theorems -/ /-! ### Join-semilattices -/ /-- A `semilattice_sup` is a join-semilattice, that is, a partial order with a join (a.k.a. lub / least upper bound, sup / supremum) operation `⊔` which is the least element larger than both factors. -/ class semilattice_sup (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) /-- A type with a commutative, associative and idempotent binary `sup` operation has the structure of a join-semilattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def semilattice_sup.mk' {α : Type*} [has_sup α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) : semilattice_sup α := { sup := (⊔), le := λ a b, a ⊔ b = b, le_refl := sup_idem, le_trans := λ a b c hab hbc, begin dsimp only [(≤)] at *, rwa [←hbc, ←sup_assoc, hab], end, le_antisymm := λ a b hab hba, begin dsimp only [(≤)] at *, rwa [←hba, sup_comm], end, le_sup_left := λ a b, show a ⊔ (a ⊔ b) = (a ⊔ b), by rw [←sup_assoc, sup_idem], le_sup_right := λ a b, show b ⊔ (a ⊔ b) = (a ⊔ b), by rw [sup_comm, sup_assoc, sup_idem], sup_le := λ a b c hac hbc, begin dsimp only [(≤), preorder.le] at *, rwa [sup_assoc, hbc], end } instance (α : Type*) [has_inf α] : has_sup αᵒᵈ := ⟨((⊓) : α → α → α)⟩ instance (α : Type*) [has_sup α] : has_inf αᵒᵈ := ⟨((⊔) : α → α → α)⟩ section semilattice_sup variables [semilattice_sup α] {a b c d : α} @[simp] theorem le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) := le_sup_left @[simp] theorem le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) := le_sup_right theorem le_sup_of_le_left (h : c ≤ a) : c ≤ a ⊔ b := le_trans h le_sup_left theorem le_sup_of_le_right (h : c ≤ b) : c ≤ a ⊔ b := le_trans h le_sup_right theorem lt_sup_of_lt_left (h : c < a) : c < a ⊔ b := h.trans_le le_sup_left theorem lt_sup_of_lt_right (h : c < b) : c < a ⊔ b := h.trans_le le_sup_right theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ @[simp] theorem sup_eq_left : a ⊔ b = a ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a := sup_eq_left.2 h @[simp] theorem left_eq_sup : a = a ⊔ b ↔ b ≤ a := eq_comm.trans sup_eq_left @[simp] theorem left_lt_sup : a < a ⊔ b ↔ ¬b ≤ a := le_sup_left.lt_iff_ne.trans $ not_congr left_eq_sup @[simp] theorem sup_eq_right : a ⊔ b = b ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b := sup_eq_right.2 h @[simp] theorem right_eq_sup : b = a ⊔ b ↔ a ≤ b := eq_comm.trans sup_eq_right @[simp] theorem right_lt_sup : b < a ⊔ b ↔ ¬a ≤ b := le_sup_right.lt_iff_ne.trans $ not_congr right_eq_sup lemma left_or_right_lt_sup (h : a ≠ b) : (a < a ⊔ b ∨ b < a ⊔ b) := h.not_le_or_not_le.symm.imp left_lt_sup.2 right_lt_sup.2 theorem le_iff_exists_sup : a ≤ b ↔ ∃ c, b = a ⊔ c := begin split, { intro h, exact ⟨b, (sup_eq_right.mpr h).symm⟩ }, { rintro ⟨c, (rfl : _ = _ ⊔ _)⟩, exact le_sup_left } end theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := sup_le (le_sup_of_le_left h₁) (le_sup_of_le_right h₂) theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b := sup_le_sup le_rfl h₁ theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c := sup_le_sup h₁ le_rfl theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by { rw ← h, simp } @[simp] theorem sup_idem : a ⊔ a = a := by apply le_antisymm; simp instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩ theorem sup_comm : a ⊔ b = b ⊔ a := by apply le_antisymm; simp instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := eq_of_forall_ge_iff $ λ x, by simp only [sup_le_iff, and_assoc] instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ lemma sup_left_right_swap (a b c : α) : a ⊔ b ⊔ c = c ⊔ b ⊔ a := by rw [sup_comm, @sup_comm _ _ a, sup_assoc] @[simp] lemma sup_left_idem : a ⊔ (a ⊔ b) = a ⊔ b := by rw [← sup_assoc, sup_idem] @[simp] lemma sup_right_idem : (a ⊔ b) ⊔ b = a ⊔ b := by rw [sup_assoc, sup_idem] lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) := by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a] lemma sup_right_comm (a b c : α) : a ⊔ b ⊔ c = a ⊔ c ⊔ b := by rw [sup_assoc, sup_assoc, @sup_comm _ _ b] lemma sup_sup_sup_comm (a b c d : α) : a ⊔ b ⊔ (c ⊔ d) = a ⊔ c ⊔ (b ⊔ d) := by rw [sup_assoc, sup_left_comm b, ←sup_assoc] lemma sup_sup_distrib_left (a b c : α) : a ⊔ (b ⊔ c) = (a ⊔ b) ⊔ (a ⊔ c) := by rw [sup_sup_sup_comm, sup_idem] lemma sup_sup_distrib_right (a b c : α) : (a ⊔ b) ⊔ c = (a ⊔ c) ⊔ (b ⊔ c) := by rw [sup_sup_sup_comm, sup_idem] lemma sup_congr_left (hb : b ≤ a ⊔ c) (hc : c ≤ a ⊔ b) : a ⊔ b = a ⊔ c := (sup_le le_sup_left hb).antisymm $ sup_le le_sup_left hc lemma sup_congr_right (ha : a ≤ b ⊔ c) (hb : b ≤ a ⊔ c) : a ⊔ c = b ⊔ c := (sup_le ha le_sup_right).antisymm $ sup_le hb le_sup_right lemma sup_eq_sup_iff_left : a ⊔ b = a ⊔ c ↔ b ≤ a ⊔ c ∧ c ≤ a ⊔ b := ⟨λ h, ⟨h ▸ le_sup_right, h.symm ▸ le_sup_right⟩, λ h, sup_congr_left h.1 h.2⟩ lemma sup_eq_sup_iff_right : a ⊔ c = b ⊔ c ↔ a ≤ b ⊔ c ∧ b ≤ a ⊔ c := ⟨λ h, ⟨h ▸ le_sup_left, h.symm ▸ le_sup_left⟩, λ h, sup_congr_right h.1 h.2⟩ /-- If `f` is monotone, `g` is antitone, and `f ≤ g`, then for all `a`, `b` we have `f a ≤ g b`. -/ theorem monotone.forall_le_of_antitone {β : Type*} [preorder β] {f g : α → β} (hf : monotone f) (hg : antitone g) (h : f ≤ g) (m n : α) : f m ≤ g n := calc f m ≤ f (m ⊔ n) : hf le_sup_left ... ≤ g (m ⊔ n) : h _ ... ≤ g n : hg le_sup_right theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y := eq_of_forall_ge_iff $ λ c, by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H] theorem semilattice_sup.ext {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x), casesI A, casesI B, injection this; congr' end lemma ite_le_sup (s s' : α) (P : Prop) [decidable P] : ite P s s' ≤ s ⊔ s' := if h : P then (if_pos h).trans_le le_sup_left else (if_neg h).trans_le le_sup_right end semilattice_sup /-! ### Meet-semilattices -/ /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) instance (α) [semilattice_inf α] : semilattice_sup αᵒᵈ := { le_sup_left := semilattice_inf.inf_le_left, le_sup_right := semilattice_inf.inf_le_right, sup_le := assume a b c hca hcb, @semilattice_inf.le_inf α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_sup α } instance (α) [semilattice_sup α] : semilattice_inf αᵒᵈ := { inf_le_left := @le_sup_left α _, inf_le_right := @le_sup_right α _, le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_inf α } theorem semilattice_sup.dual_dual (α : Type*) [H : semilattice_sup α] : order_dual.semilattice_sup αᵒᵈ = H := semilattice_sup.ext $ λ _ _, iff.rfl section semilattice_inf variables [semilattice_inf α] {a b c d : α} @[simp] theorem inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b @[simp] theorem inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c theorem inf_le_of_left_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h theorem inf_le_of_right_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h theorem inf_lt_of_left_lt (h : a < c) : a ⊓ b < c := lt_of_le_of_lt inf_le_left h theorem inf_lt_of_right_lt (h : b < c) : a ⊓ b < c := lt_of_le_of_lt inf_le_right h @[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := @sup_le_iff αᵒᵈ _ _ _ _ @[simp] theorem inf_eq_left : a ⊓ b = a ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] @[simp] theorem inf_lt_left : a ⊓ b < a ↔ ¬a ≤ b := @left_lt_sup αᵒᵈ _ _ _ theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a := inf_eq_left.2 h @[simp] theorem left_eq_inf : a = a ⊓ b ↔ a ≤ b := eq_comm.trans inf_eq_left @[simp] theorem inf_eq_right : a ⊓ b = b ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] @[simp] theorem inf_lt_right : a ⊓ b < b ↔ ¬b ≤ a := @right_lt_sup αᵒᵈ _ _ _ theorem inf_lt_left_or_right (h : a ≠ b) : a ⊓ b < a ∨ a ⊓ b < b := @left_or_right_lt_sup αᵒᵈ _ _ _ h theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b := inf_eq_right.2 h @[simp] theorem right_eq_inf : b = a ⊓ b ↔ b ≤ a := eq_comm.trans inf_eq_right theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := @sup_le_sup αᵒᵈ _ _ _ _ _ h₁ h₂ lemma inf_le_inf_right (a : α) {b c : α} (h : b ≤ c) : b ⊓ a ≤ c ⊓ a := inf_le_inf h le_rfl lemma inf_le_inf_left (a : α) {b c : α} (h : b ≤ c) : a ⊓ b ≤ a ⊓ c := inf_le_inf le_rfl h theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := inf_eq_left.1 h @[simp] lemma inf_idem : a ⊓ a = a := @sup_idem αᵒᵈ _ _ instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩ lemma inf_comm : a ⊓ b = b ⊓ a := @sup_comm αᵒᵈ _ _ _ instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ lemma inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := @sup_assoc αᵒᵈ _ a b c instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ lemma inf_left_right_swap (a b c : α) : a ⊓ b ⊓ c = c ⊓ b ⊓ a := @sup_left_right_swap αᵒᵈ _ _ _ _ @[simp] lemma inf_left_idem : a ⊓ (a ⊓ b) = a ⊓ b := @sup_left_idem αᵒᵈ _ a b @[simp] lemma inf_right_idem : (a ⊓ b) ⊓ b = a ⊓ b := @sup_right_idem αᵒᵈ _ a b lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := @sup_left_comm αᵒᵈ _ a b c lemma inf_right_comm (a b c : α) : a ⊓ b ⊓ c = a ⊓ c ⊓ b := @sup_right_comm αᵒᵈ _ a b c lemma inf_inf_inf_comm (a b c d : α) : a ⊓ b ⊓ (c ⊓ d) = a ⊓ c ⊓ (b ⊓ d) := @sup_sup_sup_comm αᵒᵈ _ _ _ _ _ lemma inf_inf_distrib_left (a b c : α) : a ⊓ (b ⊓ c) = (a ⊓ b) ⊓ (a ⊓ c) := @sup_sup_distrib_left αᵒᵈ _ _ _ _ lemma inf_inf_distrib_right (a b c : α) : (a ⊓ b) ⊓ c = (a ⊓ c) ⊓ (b ⊓ c) := @sup_sup_distrib_right αᵒᵈ _ _ _ _ lemma inf_congr_left (hb : a ⊓ c ≤ b) (hc : a ⊓ b ≤ c) : a ⊓ b = a ⊓ c := @sup_congr_left αᵒᵈ _ _ _ _ hb hc lemma inf_congr_right (h1 : b ⊓ c ≤ a) (h2 : a ⊓ c ≤ b) : a ⊓ c = b ⊓ c := @sup_congr_right αᵒᵈ _ _ _ _ h1 h2 lemma inf_eq_inf_iff_left : a ⊓ b = a ⊓ c ↔ a ⊓ c ≤ b ∧ a ⊓ b ≤ c := @sup_eq_sup_iff_left αᵒᵈ _ _ _ _ lemma inf_eq_inf_iff_right : a ⊓ c = b ⊓ c ↔ b ⊓ c ≤ a ∧ a ⊓ c ≤ b := @sup_eq_sup_iff_right αᵒᵈ _ _ _ _ theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H] theorem semilattice_inf.ext {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x), casesI A, casesI B, injection this; congr' end theorem semilattice_inf.dual_dual (α : Type*) [H : semilattice_inf α] : order_dual.semilattice_inf αᵒᵈ = H := semilattice_inf.ext $ λ _ _, iff.rfl lemma inf_le_ite (s s' : α) (P : Prop) [decidable P] : s ⊓ s' ≤ ite P s s' := @ite_le_sup αᵒᵈ _ _ _ _ _ end semilattice_inf /-- A type with a commutative, associative and idempotent binary `inf` operation has the structure of a meet-semilattice. The partial order is defined so that `a ≤ b` unfolds to `b ⊓ a = a`; cf. `inf_eq_right`. -/ def semilattice_inf.mk' {α : Type*} [has_inf α] (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) : semilattice_inf α := begin haveI : semilattice_sup αᵒᵈ := semilattice_sup.mk' inf_comm inf_assoc inf_idem, haveI i := order_dual.semilattice_inf αᵒᵈ, exact i, end /-! ### Lattices -/ /-- A lattice is a join-semilattice which is also a meet-semilattice. -/ @[protect_proj] class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α instance (α) [lattice α] : lattice αᵒᵈ := { .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α } /-- The partial orders from `semilattice_sup_mk'` and `semilattice_inf_mk'` agree if `sup` and `inf` satisfy the lattice absorption laws `sup_inf_self` (`a ⊔ a ⊓ b = a`) and `inf_sup_self` (`a ⊓ (a ⊔ b) = a`). -/ lemma semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : @semilattice_sup.to_partial_order _ (semilattice_sup.mk' sup_comm sup_assoc sup_idem) = @semilattice_inf.to_partial_order _ (semilattice_inf.mk' inf_comm inf_assoc inf_idem) := partial_order.ext $ λ a b, show a ⊔ b = b ↔ b ⊓ a = a, from ⟨λ h, by rw [←h, inf_comm, inf_sup_self], λ h, by rw [←h, sup_comm, sup_inf_self]⟩ /-- A type with a pair of commutative and associative binary operations which satisfy two absorption laws relating the two operations has the structure of a lattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def lattice.mk' {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : lattice α := have sup_idem : ∀ (b : α), b ⊔ b = b := λ b, calc b ⊔ b = b ⊔ b ⊓ (b ⊔ b) : by rw inf_sup_self ... = b : by rw sup_inf_self, have inf_idem : ∀ (b : α), b ⊓ b = b := λ b, calc b ⊓ b = b ⊓ (b ⊔ b ⊓ b) : by rw sup_inf_self ... = b : by rw inf_sup_self, let semilatt_inf_inst := semilattice_inf.mk' inf_comm inf_assoc inf_idem, semilatt_sup_inst := semilattice_sup.mk' sup_comm sup_assoc sup_idem, -- here we help Lean to see that the two partial orders are equal partial_order_inst := @semilattice_sup.to_partial_order _ semilatt_sup_inst in have partial_order_eq : partial_order_inst = @semilattice_inf.to_partial_order _ semilatt_inf_inst := semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order _ _ _ _ _ _ sup_inf_self inf_sup_self, { inf_le_left := λ a b, by { rw partial_order_eq, apply inf_le_left }, inf_le_right := λ a b, by { rw partial_order_eq, apply inf_le_right }, le_inf := λ a b c, by { rw partial_order_eq, apply le_inf }, ..partial_order_inst, ..semilatt_sup_inst, ..semilatt_inf_inst, } section lattice variables [lattice α] {a b c d : α} lemma inf_le_sup : a ⊓ b ≤ a ⊔ b := inf_le_left.trans le_sup_left @[simp] lemma inf_lt_sup : a ⊓ b < a ⊔ b ↔ a ≠ b := begin split, { rintro H rfl, simpa using H }, { refine λ Hne, lt_iff_le_and_ne.2 ⟨inf_le_sup, λ Heq, Hne _⟩, refine le_antisymm _ _, exacts [le_sup_left.trans (Heq.symm.trans_le inf_le_right), le_sup_right.trans (Heq.symm.trans_le inf_le_left)] } end /-! #### Distributivity laws -/ /- TODO: better names? -/ theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := le_inf (sup_le_sup_left inf_le_left _) (sup_le_sup_left inf_le_right _) theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := sup_le (inf_le_inf_left _ le_sup_left) (inf_le_inf_left _ le_sup_right) theorem inf_sup_self : a ⊓ (a ⊔ b) = a := by simp theorem sup_inf_self : a ⊔ (a ⊓ b) = a := by simp theorem sup_eq_iff_inf_eq : a ⊔ b = b ↔ a ⊓ b = a := by rw [sup_eq_right, ←inf_eq_left] theorem lattice.ext {α} {A B : lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have SS : @lattice.to_semilattice_sup α A = @lattice.to_semilattice_sup α B := semilattice_sup.ext H, have II := semilattice_inf.ext H, casesI A, casesI B, injection SS; injection II; congr' end end lattice /-! ### Distributive lattices -/ /-- A distributive lattice is a lattice that satisfies any of four equivalent distributive properties (of `sup` over `inf` or `inf` over `sup`, on the left or right). The definition here chooses `le_sup_inf`: `(x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)`. To prove distributivity from the dual law, use `distrib_lattice.of_inf_sup_le`. A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) section distrib_lattice variables [distrib_lattice α] {x y z : α} theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true] theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] instance (α : Type*) [distrib_lattice α] : distrib_lattice αᵒᵈ := { le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm, .. order_dual.lattice α } theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true] lemma le_of_inf_le_sup_le (h₁ : x ⊓ z ≤ y ⊓ z) (h₂ : x ⊔ z ≤ y ⊔ z) : x ≤ y := calc x ≤ (y ⊓ z) ⊔ x : le_sup_right ... = (y ⊔ x) ⊓ (x ⊔ z) : by rw [sup_inf_right, @sup_comm _ _ x] ... ≤ (y ⊔ x) ⊓ (y ⊔ z) : inf_le_inf_left _ h₂ ... = y ⊔ (x ⊓ z) : sup_inf_left.symm ... ≤ y ⊔ (y ⊓ z) : sup_le_sup_left h₁ _ ... ≤ _ : sup_le (le_refl y) inf_le_left lemma eq_of_inf_eq_sup_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (le_of_inf_le_sup_le (le_of_eq h₁) (le_of_eq h₂)) (le_of_inf_le_sup_le (le_of_eq h₁.symm) (le_of_eq h₂.symm)) end distrib_lattice /-- Prove distributivity of an existing lattice from the dual distributive law. -/ @[reducible] -- See note [reducible non-instances] def distrib_lattice.of_inf_sup_le [lattice α] (inf_sup_le : ∀ a b c : α, a ⊓ (b ⊔ c) ≤ (a ⊓ b) ⊔ (a ⊓ c)) : distrib_lattice α := { ..‹lattice α›, ..@order_dual.distrib_lattice αᵒᵈ { le_sup_inf := inf_sup_le, ..order_dual.lattice _ } } /-! ### Lattices derived from linear orders -/ @[priority 100] -- see Note [lower instance priority] instance linear_order.to_lattice {α : Type u} [o : linear_order α] : lattice α := { sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min, ..o } section linear_order variables [linear_order α] {a b c : α} lemma sup_eq_max : a ⊔ b = max a b := rfl lemma inf_eq_min : a ⊓ b = min a b := rfl lemma sup_ind (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊔ b) := (is_total.total a b).elim (λ h : a ≤ b, by rwa sup_eq_right.2 h) (λ h, by rwa sup_eq_left.2 h) @[simp] lemma le_sup_iff : a ≤ b ⊔ c ↔ a ≤ b ∨ a ≤ c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim le_sup_of_le_left le_sup_of_le_right⟩ @[simp] lemma lt_sup_iff : a < b ⊔ c ↔ a < b ∨ a < c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim lt_sup_of_lt_left lt_sup_of_lt_right⟩ @[simp] lemma sup_lt_iff : b ⊔ c < a ↔ b < a ∧ c < a := ⟨λ h, ⟨le_sup_left.trans_lt h, le_sup_right.trans_lt h⟩, λ h, sup_ind b c h.1 h.2⟩ lemma inf_ind (a b : α) {p : α → Prop} : p a → p b → p (a ⊓ b) := @sup_ind αᵒᵈ _ _ _ _ @[simp] lemma inf_le_iff : b ⊓ c ≤ a ↔ b ≤ a ∨ c ≤ a := @le_sup_iff αᵒᵈ _ _ _ _ @[simp] lemma inf_lt_iff : b ⊓ c < a ↔ b < a ∨ c < a := @lt_sup_iff αᵒᵈ _ _ _ _ @[simp] lemma lt_inf_iff : a < b ⊓ c ↔ a < b ∧ a < c := @sup_lt_iff αᵒᵈ _ _ _ _ end linear_order lemma sup_eq_max_default [semilattice_sup α] [decidable_rel ((≤) : α → α → Prop)] [is_total α (≤)] : (⊔) = (max_default : α → α → α) := begin ext x y, dunfold max_default, split_ifs with h', exacts [sup_of_le_left h', sup_of_le_right $ (total_of (≤) x y).resolve_right h'] end lemma inf_eq_min_default [semilattice_inf α] [decidable_rel ((≤) : α → α → Prop)] [is_total α (≤)] : (⊓) = (min_default : α → α → α) := @sup_eq_max_default αᵒᵈ _ _ _ /-- A lattice with total order is a linear order. See note [reducible non-instances]. -/ @[reducible] def lattice.to_linear_order (α : Type u) [lattice α] [decidable_eq α] [decidable_rel ((≤) : α → α → Prop)] [decidable_rel ((<) : α → α → Prop)] [is_total α (≤)] : linear_order α := { decidable_le := ‹_›, decidable_eq := ‹_›, decidable_lt := ‹_›, le_total := total_of (≤), max := (⊔), max_def := sup_eq_max_default, min := (⊓), min_def := inf_eq_min_default, ..‹lattice α› } @[priority 100] -- see Note [lower instance priority] instance linear_order.to_distrib_lattice {α : Type u} [o : linear_order α] : distrib_lattice α := { le_sup_inf := assume a b c, match le_total b c with | or.inl h := inf_le_of_left_le $ sup_le_sup_left (le_inf (le_refl b) h) _ | or.inr h := inf_le_of_right_le $ sup_le_sup_left (le_inf h (le_refl c)) _ end, ..linear_order.to_lattice } instance nat.distrib_lattice : distrib_lattice ℕ := by apply_instance /-! ### Dual order -/ open order_dual @[simp] lemma of_dual_inf [has_sup α] (a b: αᵒᵈ) : of_dual (a ⊓ b) = of_dual a ⊔ of_dual b := rfl @[simp] lemma of_dual_sup [has_inf α] (a b : αᵒᵈ) : of_dual (a ⊔ b) = of_dual a ⊓ of_dual b := rfl @[simp] lemma to_dual_inf [has_inf α] (a b : α) : to_dual (a ⊓ b) = to_dual a ⊔ to_dual b := rfl @[simp] lemma to_dual_sup [has_sup α] (a b : α) : to_dual (a ⊔ b) = to_dual a ⊓ to_dual b := rfl section linear_order variables [linear_order α] @[simp] lemma of_dual_min (a b : αᵒᵈ) : of_dual (min a b) = max (of_dual a) (of_dual b) := rfl @[simp] lemma of_dual_max (a b : αᵒᵈ) : of_dual (max a b) = min (of_dual a) (of_dual b) := rfl @[simp] lemma to_dual_min (a b : α) : to_dual (min a b) = max (to_dual a) (to_dual b) := rfl @[simp] lemma to_dual_max (a b : α) : to_dual (max a b) = min (to_dual a) (to_dual b) := rfl end linear_order /-! ### Function lattices -/ namespace pi variables {ι : Type*} {α' : ι → Type*} instance [Π i, has_sup (α' i)] : has_sup (Π i, α' i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply [Π i, has_sup (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl lemma sup_def [Π i, has_sup (α' i)] (f g : Π i, α' i) : f ⊔ g = λ i, f i ⊔ g i := rfl instance [Π i, has_inf (α' i)] : has_inf (Π i, α' i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply [Π i, has_inf (α' i)] (f g : Π i, α' i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl lemma inf_def [Π i, has_inf (α' i)] (f g : Π i, α' i) : f ⊓ g = λ i, f i ⊓ g i := rfl instance [Π i, semilattice_sup (α' i)] : semilattice_sup (Π i, α' i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance [Π i, semilattice_inf (α' i)] : semilattice_inf (Π i, α' i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance [Π i, lattice (α' i)] : lattice (Π i, α' i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance [Π i, distrib_lattice (α' i)] : distrib_lattice (Π i, α' i) := by refine_struct { .. pi.lattice }; tactic.pi_instance_derive_field end pi /-! ### Monotone functions and lattices -/ namespace monotone /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (f ⊔ g) := λ x y h, sup_le_sup (hf h) (hg h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (f ⊓ g) := λ x y h, inf_le_inf (hf h) (hg h) /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (λ x, max (f x) (g x)) := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : monotone f) (hg : monotone g) : monotone (λ x, min (f x) (g x)) := hf.inf hg lemma le_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : monotone f) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := sup_le (h le_sup_left) (h le_sup_right) lemma map_inf_le [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : monotone f) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := le_inf (h inf_le_left) (h inf_le_right) lemma of_map_inf [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : ∀ x y, f (x ⊓ y) = f x ⊓ f y) : monotone f := λ x y hxy, inf_eq_left.1 $ by rw [← h, inf_eq_left.2 hxy] lemma of_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : ∀ x y, f (x ⊔ y) = f x ⊔ f y) : monotone f := (@of_map_inf (order_dual α) (order_dual β) _ _ _ h).dual variables [linear_order α] lemma map_sup [semilattice_sup β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (is_total.total x y).elim (λ h : x ≤ y, by simp only [h, hf h, sup_of_le_right]) (λ h, by simp only [h, hf h, sup_of_le_left]) lemma map_inf [semilattice_inf β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := hf.dual.map_sup _ _ end monotone namespace monotone_on /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} {s : set α} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (f ⊔ g) s := λ x hx y hy h, sup_le_sup (hf hx hy h) (hg hx hy h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} {s : set α} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (f ⊓ g) s := (hf.dual.sup hg.dual).dual /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} {s : set α} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, max (f x) (g x)) s := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} {s : set α} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, min (f x) (g x)) s := hf.inf hg end monotone_on namespace antitone /-- Pointwise supremum of two monotone functions is a monotone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (f ⊔ g) := λ x y h, sup_le_sup (hf h) (hg h) /-- Pointwise infimum of two monotone functions is a monotone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (f ⊓ g) := λ x y h, inf_le_inf (hf h) (hg h) /-- Pointwise maximum of two monotone functions is a monotone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (λ x, max (f x) (g x)) := hf.sup hg /-- Pointwise minimum of two monotone functions is a monotone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} (hf : antitone f) (hg : antitone g) : antitone (λ x, min (f x) (g x)) := hf.inf hg lemma map_sup_le [semilattice_sup α] [semilattice_inf β] {f : α → β} (h : antitone f) (x y : α) : f (x ⊔ y) ≤ f x ⊓ f y := h.dual_right.le_map_sup x y lemma le_map_inf [semilattice_inf α] [semilattice_sup β] {f : α → β} (h : antitone f) (x y : α) : f x ⊔ f y ≤ f (x ⊓ y) := h.dual_right.map_inf_le x y variables [linear_order α] lemma map_sup [semilattice_inf β] {f : α → β} (hf : antitone f) (x y : α) : f (x ⊔ y) = f x ⊓ f y := hf.dual_right.map_sup x y lemma map_inf [semilattice_sup β] {f : α → β} (hf : antitone f) (x y : α) : f (x ⊓ y) = f x ⊔ f y := hf.dual_right.map_inf x y end antitone namespace antitone_on /-- Pointwise supremum of two antitone functions is a antitone function. -/ protected lemma sup [preorder α] [semilattice_sup β] {f g : α → β} {s : set α} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (f ⊔ g) s := λ x hx y hy h, sup_le_sup (hf hx hy h) (hg hx hy h) /-- Pointwise infimum of two antitone functions is a antitone function. -/ protected lemma inf [preorder α] [semilattice_inf β] {f g : α → β} {s : set α} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (f ⊓ g) s := (hf.dual.sup hg.dual).dual /-- Pointwise maximum of two antitone functions is a antitone function. -/ protected lemma max [preorder α] [linear_order β] {f g : α → β} {s : set α} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, max (f x) (g x)) s := hf.sup hg /-- Pointwise minimum of two antitone functions is a antitone function. -/ protected lemma min [preorder α] [linear_order β] {f g : α → β} {s : set α} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, min (f x) (g x)) s := hf.inf hg end antitone_on /-! ### Products of (semi-)lattices -/ namespace prod variables (α β) instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩ instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩ instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) := { sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩, le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩, le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩, .. prod.partial_order α β, .. prod.has_sup α β } instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) := { le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩, inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩, inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩, .. prod.partial_order α β, .. prod.has_inf α β } instance [lattice α] [lattice β] : lattice (α × β) := { .. prod.semilattice_inf α β, .. prod.semilattice_sup α β } instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) := { le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩, .. prod.lattice α β } end prod /-! ### Subtypes of (semi-)lattices -/ namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } @[simp, norm_cast] lemma coe_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (x y : subtype P) : (by {haveI := subtype.semilattice_sup Psup, exact (x ⊔ y : subtype P)} : α) = x ⊔ y := rfl @[simp, norm_cast] lemma coe_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) (x y : subtype P) : (by {haveI := subtype.semilattice_inf Pinf, exact (x ⊓ y : subtype P)} : α) = x ⊓ y := rfl @[simp] lemma mk_sup_mk [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) {x y : α} (hx : P x) (hy : P y) : (by {haveI := subtype.semilattice_sup Psup, exact (⟨x, hx⟩ ⊔ ⟨y, hy⟩ : subtype P)}) = ⟨x ⊔ y, Psup hx hy⟩ := rfl @[simp] lemma mk_inf_mk [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) {x y : α} (hx : P x) (hy : P y) : (by {haveI := subtype.semilattice_inf Pinf, exact (⟨x, hx⟩ ⊓ ⟨y, hy⟩ : subtype P)}) = ⟨x ⊓ y, Pinf hx hy⟩ := rfl end subtype section lift /-- A type endowed with `⊔` is a `semilattice_sup`, if it admits an injective map that preserves `⊔` to a `semilattice_sup`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.semilattice_sup [has_sup α] [semilattice_sup β] (f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) : semilattice_sup α := { sup := has_sup.sup, le_sup_left := λ a b, by { change f a ≤ f (a ⊔ b), rw map_sup, exact le_sup_left, }, le_sup_right := λ a b, by { change f b ≤ f (a ⊔ b), rw map_sup, exact le_sup_right, }, sup_le := λ a b c ha hb, by { change f (a ⊔ b) ≤ f c, rw map_sup, exact sup_le ha hb, }, ..partial_order.lift f hf_inj} /-- A type endowed with `⊓` is a `semilattice_inf`, if it admits an injective map that preserves `⊓` to a `semilattice_inf`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.semilattice_inf [has_inf α] [semilattice_inf β] (f : α → β) (hf_inj : function.injective f) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) : semilattice_inf α := { inf := has_inf.inf, inf_le_left := λ a b, by { change f (a ⊓ b) ≤ f a, rw map_inf, exact inf_le_left, }, inf_le_right := λ a b, by { change f (a ⊓ b) ≤ f b, rw map_inf, exact inf_le_right, }, le_inf := λ a b c ha hb, by { change f a ≤ f (b ⊓ c), rw map_inf, exact le_inf ha hb, }, ..partial_order.lift f hf_inj} /-- A type endowed with `⊔` and `⊓` is a `lattice`, if it admits an injective map that preserves `⊔` and `⊓` to a `lattice`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.lattice [has_sup α] [has_inf α] [lattice β] (f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) : lattice α := { ..hf_inj.semilattice_sup f map_sup, ..hf_inj.semilattice_inf f map_inf} /-- A type endowed with `⊔` and `⊓` is a `distrib_lattice`, if it admits an injective map that preserves `⊔` and `⊓` to a `distrib_lattice`. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_lattice [has_sup α] [has_inf α] [distrib_lattice β] (f : α → β) (hf_inj : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) : distrib_lattice α := { le_sup_inf := λ a b c, by { change f ((a ⊔ b) ⊓ (a ⊔ c)) ≤ f (a ⊔ b ⊓ c), rw [map_inf, map_sup, map_sup, map_sup, map_inf], exact le_sup_inf, }, ..hf_inj.lattice f map_sup map_inf, } end lift --To avoid noncomputability poisoning from `bool.complete_boolean_algebra` instance : distrib_lattice bool := linear_order.to_distrib_lattice
455292ecb80db677706cd12efb610640ab477b71
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/pack_unpack1.lean
b552e302b57aba4005ccddce8e7d63644d1252d8
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
2,273
lean
inductive tree_core (A : Type*) : bool → Type* | leaf' : A → tree_core ff | node' : tree_core tt → tree_core ff | nil' {} : tree_core tt | cons' : tree_core ff → tree_core tt → tree_core tt attribute [reducible] definition tree (A : Type*) := tree_core A ff attribute [reducible] definition tree_list (A : Type*) := tree_core A tt open tree_core definition pack {A : Type*} : list (tree A) → tree_core A tt | [] := nil' | (a::l) := cons' a (pack l) definition unpack {A : Type*} : ∀ {b}, tree_core A b → list (tree A) | .tt nil' := [] | .tt (cons' a t) := a :: unpack t | .ff (leaf' a) := [] | .ff (node' l) := [] attribute [inverse] lemma unpack_pack {A : Type*} : ∀ (l : list (tree A)), unpack (pack l) = l | [] := rfl | (a::l) := show a :: unpack (pack l) = a :: l, from congr_arg (λ x, a :: x) (unpack_pack l) attribute [inverse] lemma pack_unpack {A : Type*} : ∀ t : tree_core A tt, pack (unpack t) = t := λ t, @tree_core.rec_on A (λ b, bool.cases_on b (λ t, true) (λ t, pack (unpack t) = t)) tt t (λ a, trivial) (λ t ih, trivial) rfl (λ h t ih1 ih2, show cons' h (pack (unpack t)) = cons' h t, from congr_arg (λ x, cons' h x) ih2) attribute [pattern] definition tree.node {A : Type*} (l : list (tree A)) : tree A := tree_core.node' (pack l) attribute [pattern] definition tree.leaf {A : Type*} : A → tree A := tree_core.leaf' set_option trace.eqn_compiler true definition sz {A : Type*} : tree A → nat | (tree.leaf a) := 1 | (tree.node l) := list.length l + 1 constant P {A : Type*} : tree A → Type 1 constant mk1 {A : Type*} (a : A) : P (tree.leaf a) constant mk2 {A : Type*} (l : list (tree A)) : P (tree.node l) noncomputable definition bla {A : Type*} : ∀ n : tree A, P n | (tree.leaf a) := mk1 a | (tree.node l) := mk2 l check bla._main.equations._eqn_1 check bla._main.equations._eqn_2 definition foo {A : Type*} : nat → tree A → nat | 0 _ := 0 | (n+1) (tree.leaf a) := 0 | (n+1) (tree.node []) := foo n (tree.node []) | (n+1) (tree.node (x::xs)) := foo n x check @foo._main.equations._eqn_1 check @foo._main.equations._eqn_2 check @foo._main.equations._eqn_3 check @foo._main.equations._eqn_4
5ca40b7251929e7cf9e076ed14c16caacc5bee27
342425037bb9207ebcc87b62ab094d311b0787bb
/src/exercises/07_first_negations.lean
294c5880d39ccc94da42669fa3d71575554d5826
[ "Apache-2.0" ]
permissive
Denglihua/tutorials
6d4c219784f34acaa0bfcdfc388e980fd04b0cc2
6449169303de57d5f1799c25ac2a51af7062931d
refs/heads/master
1,673,009,657,280
1,604,880,270,000
1,604,880,270,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,794
lean
import tuto_lib import data.int.parity /- Negations, proof by contradiction and contraposition. This file introduces the logical rules and tactics related to negation: exfalso, by_contradiction, contrapose, by_cases and push_neg. There is a special statement denoted by `false` which, by definition, has no proof. So `false` implies everything. Indeed `false → P` means any proof of `false` could be turned into a proof of P. This fact is known by its latin name "ex falso quod libet" (from false follows whatever you want). Hence Lean's tactic to invoke this is called `exfalso`. -/ example : false → 0 = 1 := begin intro h, exfalso, exact h, end /- The preceding example suggests that this definition of `false` isn't very useful. But actually it allows us to define the negation of a statement P as "P implies false" that we can read as "if P were true, we would get a contradiction". Lean denotes this by `¬ P`. One can prove that (¬ P) ↔ (P ↔ false). But in practice we directly use the definition of `¬ P`. -/ example {x : ℝ} : ¬ x < x := begin intro hyp, rw lt_iff_le_and_ne at hyp, cases hyp with hyp_inf hyp_non, clear hyp_inf, -- we won't use that one, so let's discard it change x = x → false at hyp_non, -- Lean doesn't need this psychological line apply hyp_non, refl, end open int -- 0045 example (n : ℤ) (h_pair : even n) (h_non_pair : ¬ even n) : 0 = 1 := begin sorry end -- 0046 example (P Q : Prop) (h₁ : P ∨ Q) (h₂ : ¬ (P ∧ Q)) : ¬ P ↔ Q := begin sorry end /- The definition of negation easily implies that, for every statement P, P → ¬ ¬ P The excluded middle axiom, which asserts P ∨ ¬ P allows us to prove the converse implication. Together those two implications form the principle of double negation elimination. not_not {P : Prop} : (¬ ¬ P) ↔ P The implication `¬ ¬ P → P` is the basis for proofs by contradiction: in order to prove P, it suffices to prove ¬¬ P, ie `¬ P → false`. Of course there is no need to keep explaining all this. The tactic `by_contradiction Hyp` will transform any goal P into `false` and add Hyp : ¬ P to the local context. Let's return to a proof from the 5th file: uniqueness of limits for a sequence. This cannot be proved without using some version of the excluded middle axiom. We used it secretely in eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y (we'll prove a variation on this lemma below). -/ example (u : ℕ → ℝ) (l l' : ℝ) : seq_limit u l → seq_limit u l' → l = l' := begin intros hl hl', by_contradiction H, change l ≠ l' at H, -- Lean does not need this line have ineg : |l-l'| > 0, exact abs_pos_of_ne_zero (sub_ne_zero_of_ne H), cases hl ( |l-l'|/4 ) (by linarith) with N hN, cases hl' ( |l-l'|/4 ) (by linarith) with N' hN', let N₀ := max N N', -- this is a new tactic, whose effect should be clear specialize hN N₀ (le_max_left _ _), specialize hN' N₀ (le_max_right _ _), have clef : |l-l'| < |l-l'|, calc |l - l'| = |(l-u N₀) + (u N₀ -l')| : by ring ... ≤ |l - u N₀| + |u N₀ - l'| : by apply abs_add ... = |u N₀ - l| + |u N₀ - l'| : by rw abs_sub ... < |l-l'| : by linarith, linarith, -- linarith can also find simple numerical contradictions end /- Another incarnation of the excluded middle axiom is the principle of contraposition: in order to prove P ⇒ Q, it suffices to prove non Q ⇒ non P. -/ -- Using a proof by contradiction, let's prove the contraposition principle -- 0047 example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q := begin sorry end /- Again Lean doesn't need to be explain this principle. We can use the `contrapose` tactic. -/ example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q := begin contrapose, exact h, end /- In the next exercise, we'll use odd n : ∃ k, n = 2*k + 1 int.odd_iff_not_even {n : ℤ} : odd n ↔ ¬ even n -/ -- 0048 example (n : ℤ) : even (n^2) ↔ even n := begin sorry end /- As a last step on our law of the excluded middle tour, let's notice that, especially in pure logic exercises, it can sometimes be useful to use the excluded middle axiom in its original form: classical.em : ∀ P, P ∨ ¬ P Instead of applying this lemma and then using the `cases` tactic, we have the shortcut by_cases h : P, combining both steps to create two proof branches: one assuming h : P, and the other assuming h : ¬ P For instance, let's prove a reformulation of this implication relation, which is sometimes used as a definition in other logical foundations, especially those based on truth tables (hence very strongly using excluded middle from the very beginning). -/ variables (P Q : Prop) example : (P → Q) ↔ (¬ P ∨ Q) := begin split, { intro h, by_cases hP : P, { right, exact h hP }, { left, exact hP } }, { intros h hP, cases h with hnP hQ, { exfalso, exact hnP hP }, { exact hQ } }, end -- 0049 example : ¬ (P ∧ Q) ↔ ¬ P ∨ ¬ Q := begin sorry end /- It is crucial to understand negation of quantifiers. Let's do it by hand for a little while. In the first exercise, only the definition of negation is needed. -/ -- 0050 example (n : ℤ) : ¬ (∃ k, n = 2*k) ↔ ∀ k, n ≠ 2*k := begin sorry end /- Contrary to negation of the existential quantifier, negation of the universal quantifier requires excluded middle for the first implication. In order to prove this, we can use either * a double proof by contradiction * a contraposition, not_not : (¬ ¬ P) ↔ P) and a proof by contradiction. -/ def even_fun (f : ℝ → ℝ) := ∀ x, f (-x) = f x -- 0051 example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x := begin sorry end /- Of course we can't keep repeating the above proofs, especially the second one. So we use the `push_neg` tactic. -/ example : ¬ even_fun (λ x, 2*x) := begin unfold even_fun, -- Here unfolding is important because push_neg won't do it. push_neg, use 42, linarith, end -- 0052 example (f : ℝ → ℝ) : ¬ even_fun f ↔ ∃ x, f (-x) ≠ f x := begin sorry end def bounded_above (f : ℝ → ℝ) := ∃ M, ∀ x, f x ≤ M example : ¬ bounded_above (λ x, x) := begin unfold bounded_above, push_neg, intro M, use M + 1, linarith, end -- Let's contrapose -- 0053 example (x : ℝ) : (∀ ε > 0, x ≤ ε) → x ≤ 0 := begin sorry end /- The "contrapose, push_neg" combo is so common that we can abreviate it to `contrapose!` Let's use this trick, together with: eq_or_lt_of_le : a ≤ b → a = b ∨ a < b -/ -- 0054 example (f : ℝ → ℝ) : (∀ x y, x < y → f x < f y) ↔ (∀ x y, (x ≤ y ↔ f x ≤ f y)) := begin sorry end
277c912b4e7078d3ccc31ace3ee785c2580d5dbb
302b541ac2e998a523ae04da7673fd0932ded126
/tests/bench/treemap.lean
d63789a5fc1380608f9d9d2485c3ca6e11bb4bf7
[]
no_license
mattweingarten/lambdapure
4aeff69e8e3b8e78ea3c0a2b9b61770ef5a689b1
f920a4ad78e6b1e3651f30bf8445c9105dfa03a8
refs/heads/master
1,680,665,168,790
1,618,420,180,000
1,618,420,180,000
310,816,264
2
1
null
null
null
null
UTF-8
Lean
false
false
330
lean
set_option trace.compiler.ir.init true inductive Tree | Nil : Tree | Node : Nat -> Tree -> Tree -> Tree open Tree partial def make : Nat -> Tree | 0 => Leaf | n => Node n (make (n-1)) (make (n-1)) def mapTree : (Nat -> Nat) -> Tree -> Tree | _, Nil => Nil | f, Node n l r => Node (f n) (mapTree f l) (mapTree f r)
d5bc59bb5637f6744ab1a12b900f1738b39b1def
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/measure_theory/measurable_space.lean
1eaa86b0ad7c0ecd7bc5dfe0cfb227e385e68bcf
[]
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
62,510
lean
/- Copyright (c) 2017 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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.disjointed import Mathlib.data.set.countable import Mathlib.data.indicator_function import Mathlib.data.equiv.encodable.lattice import Mathlib.data.tprod import Mathlib.order.filter.lift import Mathlib.PostPort universes u_7 l u_1 u_2 u_3 u_6 u_4 u_8 u_5 namespace Mathlib /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `filter.eventually`. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. ## Notation * We write `α ≃ᵐ β` for measurable equivalences between the measurable spaces `α` and `β`. This should not be confused with `≃ₘ` which is used for diffeomorphisms between manifolds. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function, measurable equivalence, dynkin system, π-λ theorem, π-system -/ /-- A measurable space is a space equipped with a σ-algebra. -/ class measurable_space (α : Type u_7) where is_measurable' : set α → Prop is_measurable_empty : is_measurable' ∅ is_measurable_compl : ∀ (s : set α), is_measurable' s → is_measurable' (sᶜ) is_measurable_Union : ∀ (f : ℕ → set α), (∀ (i : ℕ), is_measurable' (f i)) → is_measurable' (set.Union fun (i : ℕ) => f i) protected instance order_dual.measurable_space {α : Type u_1} [h : measurable_space α] : measurable_space (order_dual α) := h /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable {α : Type u_1} [measurable_space α] : set α → Prop := measurable_space.is_measurable' _inst_1 @[simp] theorem is_measurable.empty {α : Type u_1} [measurable_space α] : is_measurable ∅ := measurable_space.is_measurable_empty _inst_1 theorem is_measurable.compl {α : Type u_1} {s : set α} [measurable_space α] : is_measurable s → is_measurable (sᶜ) := measurable_space.is_measurable_compl _inst_1 s theorem is_measurable.of_compl {α : Type u_1} {s : set α} [measurable_space α] (h : is_measurable (sᶜ)) : is_measurable s := compl_compl s ▸ is_measurable.compl h @[simp] theorem is_measurable.compl_iff {α : Type u_1} {s : set α} [measurable_space α] : is_measurable (sᶜ) ↔ is_measurable s := { mp := is_measurable.of_compl, mpr := is_measurable.compl } @[simp] theorem is_measurable.univ {α : Type u_1} [measurable_space α] : is_measurable set.univ := eq.mpr (id (Eq.refl (is_measurable set.univ))) (eq.mp ((fun (ᾰ ᾰ_1 : set α) (e_2 : ᾰ = ᾰ_1) => congr_arg is_measurable e_2) (∅ᶜ) set.univ set.compl_empty) (is_measurable.compl is_measurable.empty)) theorem subsingleton.is_measurable {α : Type u_1} [measurable_space α] [subsingleton α] {s : set α} : is_measurable s := subsingleton.set_cases is_measurable.empty is_measurable.univ s theorem is_measurable.congr {α : Type u_1} [measurable_space α] {s : set α} {t : set α} (hs : is_measurable s) (h : s = t) : is_measurable t := eq.mpr (id (Eq._oldrec (Eq.refl (is_measurable t)) (Eq.symm h))) hs theorem is_measurable.bUnion_decode2 {α : Type u_1} {β : Type u_2} [measurable_space α] [encodable β] {f : β → set α} (h : ∀ (b : β), is_measurable (f b)) (n : ℕ) : is_measurable (set.Union fun (b : β) => set.Union fun (H : b ∈ encodable.decode2 β n) => f b) := encodable.Union_decode2_cases is_measurable.empty h theorem is_measurable.Union {α : Type u_1} {β : Type u_2} [measurable_space α] [encodable β] {f : β → set α} (h : ∀ (b : β), is_measurable (f b)) : is_measurable (set.Union fun (b : β) => f b) := sorry theorem is_measurable.bUnion {α : Type u_1} {β : Type u_2} [measurable_space α] {f : β → set α} {s : set β} (hs : set.countable s) (h : ∀ (b : β), b ∈ s → is_measurable (f b)) : is_measurable (set.Union fun (b : β) => set.Union fun (H : b ∈ s) => f b) := sorry theorem set.finite.is_measurable_bUnion {α : Type u_1} {β : Type u_2} [measurable_space α] {f : β → set α} {s : set β} (hs : set.finite s) (h : ∀ (b : β), b ∈ s → is_measurable (f b)) : is_measurable (set.Union fun (b : β) => set.Union fun (H : b ∈ s) => f b) := is_measurable.bUnion (set.finite.countable hs) h theorem finset.is_measurable_bUnion {α : Type u_1} {β : Type u_2} [measurable_space α] {f : β → set α} (s : finset β) (h : ∀ (b : β), b ∈ s → is_measurable (f b)) : is_measurable (set.Union fun (b : β) => set.Union fun (H : b ∈ s) => f b) := set.finite.is_measurable_bUnion (finset.finite_to_set s) h theorem is_measurable.sUnion {α : Type u_1} [measurable_space α] {s : set (set α)} (hs : set.countable s) (h : ∀ (t : set α), t ∈ s → is_measurable t) : is_measurable (⋃₀s) := eq.mpr (id (Eq._oldrec (Eq.refl (is_measurable (⋃₀s))) set.sUnion_eq_bUnion)) (is_measurable.bUnion hs h) theorem set.finite.is_measurable_sUnion {α : Type u_1} [measurable_space α] {s : set (set α)} (hs : set.finite s) (h : ∀ (t : set α), t ∈ s → is_measurable t) : is_measurable (⋃₀s) := is_measurable.sUnion (set.finite.countable hs) h theorem is_measurable.Union_Prop {α : Type u_1} [measurable_space α] {p : Prop} {f : p → set α} (hf : ∀ (b : p), is_measurable (f b)) : is_measurable (set.Union fun (b : p) => f b) := sorry theorem is_measurable.Inter {α : Type u_1} {β : Type u_2} [measurable_space α] [encodable β] {f : β → set α} (h : ∀ (b : β), is_measurable (f b)) : is_measurable (set.Inter fun (b : β) => f b) := sorry theorem is_measurable.Union_fintype {α : Type u_1} {β : Type u_2} [measurable_space α] [fintype β] {f : β → set α} (h : ∀ (b : β), is_measurable (f b)) : is_measurable (set.Union fun (b : β) => f b) := is_measurable.Union h theorem is_measurable.Inter_fintype {α : Type u_1} {β : Type u_2} [measurable_space α] [fintype β] {f : β → set α} (h : ∀ (b : β), is_measurable (f b)) : is_measurable (set.Inter fun (b : β) => f b) := is_measurable.Inter h theorem is_measurable.bInter {α : Type u_1} {β : Type u_2} [measurable_space α] {f : β → set α} {s : set β} (hs : set.countable s) (h : ∀ (b : β), b ∈ s → is_measurable (f b)) : is_measurable (set.Inter fun (b : β) => set.Inter fun (H : b ∈ s) => f b) := sorry theorem set.finite.is_measurable_bInter {α : Type u_1} {β : Type u_2} [measurable_space α] {f : β → set α} {s : set β} (hs : set.finite s) (h : ∀ (b : β), b ∈ s → is_measurable (f b)) : is_measurable (set.Inter fun (b : β) => set.Inter fun (H : b ∈ s) => f b) := is_measurable.bInter (set.finite.countable hs) h theorem finset.is_measurable_bInter {α : Type u_1} {β : Type u_2} [measurable_space α] {f : β → set α} (s : finset β) (h : ∀ (b : β), b ∈ s → is_measurable (f b)) : is_measurable (set.Inter fun (b : β) => set.Inter fun (H : b ∈ s) => f b) := set.finite.is_measurable_bInter (finset.finite_to_set s) h theorem is_measurable.sInter {α : Type u_1} [measurable_space α] {s : set (set α)} (hs : set.countable s) (h : ∀ (t : set α), t ∈ s → is_measurable t) : is_measurable (⋂₀s) := eq.mpr (id (Eq._oldrec (Eq.refl (is_measurable (⋂₀s))) set.sInter_eq_bInter)) (is_measurable.bInter hs h) theorem set.finite.is_measurable_sInter {α : Type u_1} [measurable_space α] {s : set (set α)} (hs : set.finite s) (h : ∀ (t : set α), t ∈ s → is_measurable t) : is_measurable (⋂₀s) := is_measurable.sInter (set.finite.countable hs) h theorem is_measurable.Inter_Prop {α : Type u_1} [measurable_space α] {p : Prop} {f : p → set α} (hf : ∀ (b : p), is_measurable (f b)) : is_measurable (set.Inter fun (b : p) => f b) := sorry @[simp] theorem is_measurable.union {α : Type u_1} [measurable_space α] {s₁ : set α} {s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := eq.mpr (id (Eq._oldrec (Eq.refl (is_measurable (s₁ ∪ s₂))) set.union_eq_Union)) (is_measurable.Union (iff.mpr bool.forall_bool { left := h₂, right := h₁ })) @[simp] theorem is_measurable.inter {α : Type u_1} [measurable_space α] {s₁ : set α} {s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := eq.mpr (id (Eq._oldrec (Eq.refl (is_measurable (s₁ ∩ s₂))) (set.inter_eq_compl_compl_union_compl s₁ s₂))) (is_measurable.compl (is_measurable.union (is_measurable.compl h₁) (is_measurable.compl h₂))) @[simp] theorem is_measurable.diff {α : Type u_1} [measurable_space α] {s₁ : set α} {s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := is_measurable.inter h₁ (is_measurable.compl h₂) @[simp] theorem is_measurable.disjointed {α : Type u_1} [measurable_space α] {f : ℕ → set α} (h : ∀ (i : ℕ), is_measurable (f i)) (n : ℕ) : is_measurable (set.disjointed f n) := set.disjointed_induct (h n) fun (t : set α) (i : ℕ) (ht : is_measurable t) => is_measurable.diff ht (h i) @[simp] theorem is_measurable.const {α : Type u_1} [measurable_space α] (p : Prop) : is_measurable (set_of fun (a : α) => p) := sorry /-- Every set has a measurable superset. Declare this as local instance as needed. -/ theorem nonempty_measurable_superset {α : Type u_1} [measurable_space α] (s : set α) : Nonempty (Subtype fun (t : set α) => s ⊆ t ∧ is_measurable t) := Nonempty.intro { val := set.univ, property := { left := set.subset_univ s, right := is_measurable.univ } } theorem measurable_space.ext {α : Type u_1} {m₁ : measurable_space α} {m₂ : measurable_space α} : (∀ (s : set α), measurable_space.is_measurable' m₁ s ↔ measurable_space.is_measurable' m₂ s) → m₁ = m₂ := sorry theorem measurable_space.ext_iff {α : Type u_1} {m₁ : measurable_space α} {m₂ : measurable_space α} : m₁ = m₂ ↔ ∀ (s : set α), measurable_space.is_measurable' m₁ s ↔ measurable_space.is_measurable' m₂ s := { mp := fun (ᾰ : m₁ = m₂) => Eq._oldrec (fun (s : set α) => iff.refl (measurable_space.is_measurable' m₁ s)) ᾰ, mpr := measurable_space.ext } /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type u_7) [measurable_space α] where is_measurable_singleton : ∀ (x : α), is_measurable (singleton x) theorem is_measurable_eq {α : Type u_1} [measurable_space α] [measurable_singleton_class α] {a : α} : is_measurable (set_of fun (x : α) => x = a) := is_measurable_singleton a theorem is_measurable.insert {α : Type u_1} [measurable_space α] [measurable_singleton_class α] {s : set α} (hs : is_measurable s) (a : α) : is_measurable (insert a s) := is_measurable.union (is_measurable_singleton a) hs @[simp] theorem is_measurable_insert {α : Type u_1} [measurable_space α] [measurable_singleton_class α] {a : α} {s : set α} : is_measurable (insert a s) ↔ is_measurable s := sorry theorem set.finite.is_measurable {α : Type u_1} [measurable_space α] [measurable_singleton_class α] {s : set α} (hs : set.finite s) : is_measurable s := set.finite.induction_on hs is_measurable.empty fun (a : α) (s : set α) (ha : ¬a ∈ s) (hsf : set.finite s) (hsm : is_measurable s) => is_measurable.insert hsm a protected theorem finset.is_measurable {α : Type u_1} [measurable_space α] [measurable_singleton_class α] (s : finset α) : is_measurable ↑s := set.finite.is_measurable (finset.finite_to_set s) namespace measurable_space protected instance partial_order {α : Type u_1} : partial_order (measurable_space α) := partial_order.mk (fun (m₁ m₂ : measurable_space α) => is_measurable' m₁ ≤ is_measurable' m₂) (preorder.lt._default fun (m₁ m₂ : measurable_space α) => is_measurable' m₁ ≤ is_measurable' m₂) sorry sorry sorry /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable {α : Type u_1} (s : set (set α)) : set α → Prop where | basic : ∀ (u : set α), u ∈ s → generate_measurable s u | empty : generate_measurable s ∅ | compl : ∀ (s_1 : set α), generate_measurable s s_1 → generate_measurable s (s_1ᶜ) | union : ∀ (f : ℕ → set α), (∀ (n : ℕ), generate_measurable s (f n)) → generate_measurable s (set.Union fun (i : ℕ) => f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from {α : Type u_1} (s : set (set α)) : measurable_space α := mk (generate_measurable s) generate_measurable.empty generate_measurable.compl generate_measurable.union theorem is_measurable_generate_from {α : Type u_1} {s : set (set α)} {t : set α} (ht : t ∈ s) : is_measurable' (generate_from s) t := generate_measurable.basic t ht theorem generate_from_le {α : Type u_1} {s : set (set α)} {m : measurable_space α} (h : ∀ (t : set α), t ∈ s → is_measurable' m t) : generate_from s ≤ m := sorry theorem generate_from_le_iff {α : Type u_1} {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ set_of fun (t : set α) => is_measurable' m t := { mp := fun (h : generate_from s ≤ m) (u : set α) (hu : u ∈ s) => h u (is_measurable_generate_from hu), mpr := fun (h : s ⊆ set_of fun (t : set α) => is_measurable' m t) => generate_from_le h } @[simp] theorem generate_from_is_measurable {α : Type u_1} [measurable_space α] : generate_from (set_of fun (s : set α) => is_measurable s) = _inst_1 := le_antisymm (generate_from_le fun (_x : set α) => id) fun (s : set α) => is_measurable_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure {α : Type u_1} (g : set (set α)) (hg : (set_of fun (t : set α) => is_measurable' (generate_from g) t) = g) : measurable_space α := mk (fun (s : set α) => s ∈ g) sorry sorry sorry theorem mk_of_closure_sets {α : Type u_1} {s : set (set α)} {hs : (set_of fun (t : set α) => is_measurable' (generate_from s) t) = s} : measurable_space.mk_of_closure s hs = generate_from s := sorry /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from {α : Type u_1} : galois_insertion generate_from fun (m : measurable_space α) => set_of fun (t : set α) => is_measurable t := galois_insertion.mk (fun (g : set (set α)) (hg : (set_of fun (t : set α) => is_measurable t) ≤ g) => measurable_space.mk_of_closure g sorry) sorry sorry sorry protected instance complete_lattice {α : Type u_1} : complete_lattice (measurable_space α) := galois_insertion.lift_complete_lattice gi_generate_from protected instance inhabited {α : Type u_1} : Inhabited (measurable_space α) := { default := ⊤ } theorem is_measurable_bot_iff {α : Type u_1} {s : set α} : is_measurable s ↔ s = ∅ ∨ s = set.univ := sorry @[simp] theorem is_measurable_top {α : Type u_1} {s : set α} : is_measurable s := trivial @[simp] theorem is_measurable_inf {α : Type u_1} {m₁ : measurable_space α} {m₂ : measurable_space α} {s : set α} : is_measurable s ↔ is_measurable s ∧ is_measurable s := iff.rfl @[simp] theorem is_measurable_Inf {α : Type u_1} {ms : set (measurable_space α)} {s : set α} : is_measurable s ↔ ∀ (m : measurable_space α), m ∈ ms → is_measurable s := sorry @[simp] theorem is_measurable_infi {α : Type u_1} {ι : Sort u_2} {m : ι → measurable_space α} {s : set α} : is_measurable s ↔ ι → is_measurable s := sorry theorem is_measurable_sup {α : Type u_1} {m₁ : measurable_space α} {m₂ : measurable_space α} {s : set α} : is_measurable s ↔ generate_measurable (is_measurable' m₁ ∪ is_measurable' m₂) s := iff.refl (is_measurable s) theorem is_measurable_Sup {α : Type u_1} {ms : set (measurable_space α)} {s : set α} : is_measurable s ↔ generate_measurable (set_of fun (s : set α) => ∃ (m : measurable_space α), ∃ (H : m ∈ ms), is_measurable s) s := sorry theorem is_measurable_supr {α : Type u_1} {ι : Sort u_2} {m : ι → measurable_space α} {s : set α} : is_measurable s ↔ generate_measurable (set_of fun (s : set α) => ∃ (i : ι), is_measurable s) s := sorry /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map {α : Type u_1} {β : Type u_2} (f : α → β) (m : measurable_space α) : measurable_space β := mk (fun (s : set β) => is_measurable' m (f ⁻¹' s)) (is_measurable_empty m) sorry sorry @[simp] theorem map_id {α : Type u_1} {m : measurable_space α} : measurable_space.map id m = m := ext fun (s : set α) => iff.rfl @[simp] theorem map_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {m : measurable_space α} {f : α → β} {g : β → γ} : measurable_space.map g (measurable_space.map f m) = measurable_space.map (g ∘ f) m := ext fun (s : set γ) => iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap {α : Type u_1} {β : Type u_2} (f : α → β) (m : measurable_space β) : measurable_space α := mk (fun (s : set α) => ∃ (s' : set β), is_measurable' m s' ∧ f ⁻¹' s' = s) sorry sorry sorry @[simp] theorem comap_id {α : Type u_1} {m : measurable_space α} : measurable_space.comap id m = m := sorry @[simp] theorem comap_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {m : measurable_space α} {f : β → α} {g : γ → β} : measurable_space.comap g (measurable_space.comap f m) = measurable_space.comap (f ∘ g) m := sorry theorem comap_le_iff_le_map {α : Type u_1} {β : Type u_2} {m : measurable_space α} {m' : measurable_space β} {f : α → β} : measurable_space.comap f m' ≤ m ↔ m' ≤ measurable_space.map f m := sorry theorem gc_comap_map {α : Type u_1} {β : Type u_2} (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := fun (f_1 : measurable_space β) (g : measurable_space α) => comap_le_iff_le_map theorem map_mono {α : Type u_1} {β : Type u_2} {m₁ : measurable_space α} {m₂ : measurable_space α} {f : α → β} (h : m₁ ≤ m₂) : measurable_space.map f m₁ ≤ measurable_space.map f m₂ := galois_connection.monotone_u (gc_comap_map f) h theorem monotone_map {α : Type u_1} {β : Type u_2} {f : α → β} : monotone (measurable_space.map f) := fun (a b : measurable_space α) (h : a ≤ b) => map_mono h theorem comap_mono {α : Type u_1} {β : Type u_2} {m₁ : measurable_space α} {m₂ : measurable_space α} {g : β → α} (h : m₁ ≤ m₂) : measurable_space.comap g m₁ ≤ measurable_space.comap g m₂ := galois_connection.monotone_l (gc_comap_map g) h theorem monotone_comap {α : Type u_1} {β : Type u_2} {g : β → α} : monotone (measurable_space.comap g) := fun (a b : measurable_space α) (h : a ≤ b) => comap_mono h @[simp] theorem comap_bot {α : Type u_1} {β : Type u_2} {g : β → α} : measurable_space.comap g ⊥ = ⊥ := galois_connection.l_bot (gc_comap_map g) @[simp] theorem comap_sup {α : Type u_1} {β : Type u_2} {m₁ : measurable_space α} {m₂ : measurable_space α} {g : β → α} : measurable_space.comap g (m₁ ⊔ m₂) = measurable_space.comap g m₁ ⊔ measurable_space.comap g m₂ := galois_connection.l_sup (gc_comap_map g) @[simp] theorem comap_supr {α : Type u_1} {β : Type u_2} {ι : Sort u_6} {g : β → α} {m : ι → measurable_space α} : measurable_space.comap g (supr fun (i : ι) => m i) = supr fun (i : ι) => measurable_space.comap g (m i) := galois_connection.l_supr (gc_comap_map g) @[simp] theorem map_top {α : Type u_1} {β : Type u_2} {f : α → β} : measurable_space.map f ⊤ = ⊤ := galois_connection.u_top (gc_comap_map f) @[simp] theorem map_inf {α : Type u_1} {β : Type u_2} {m₁ : measurable_space α} {m₂ : measurable_space α} {f : α → β} : measurable_space.map f (m₁ ⊓ m₂) = measurable_space.map f m₁ ⊓ measurable_space.map f m₂ := galois_connection.u_inf (gc_comap_map f) @[simp] theorem map_infi {α : Type u_1} {β : Type u_2} {ι : Sort u_6} {f : α → β} {m : ι → measurable_space α} : measurable_space.map f (infi fun (i : ι) => m i) = infi fun (i : ι) => measurable_space.map f (m i) := galois_connection.u_infi (gc_comap_map f) theorem comap_map_le {α : Type u_1} {β : Type u_2} {m : measurable_space α} {f : α → β} : measurable_space.comap f (measurable_space.map f m) ≤ m := galois_connection.l_u_le (gc_comap_map f) m theorem le_map_comap {α : Type u_1} {β : Type u_2} {m : measurable_space α} {g : β → α} : m ≤ measurable_space.map g (measurable_space.comap g m) := galois_connection.le_u_l (gc_comap_map g) m theorem generate_from_le_generate_from {α : Type u_1} {s : set (set α)} {t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := galois_connection.monotone_l (galois_insertion.gc gi_generate_from) h theorem generate_from_sup_generate_from {α : Type u_1} {s : set (set α)} {t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := Eq.symm (galois_connection.l_sup (galois_insertion.gc gi_generate_from)) theorem comap_generate_from {α : Type u_1} {β : Type u_2} {f : α → β} {s : set (set β)} : measurable_space.comap f (generate_from s) = generate_from (set.preimage f '' s) := sorry end measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (f : α → β) := ∀ {t : set β}, is_measurable t → is_measurable (f ⁻¹' t) theorem measurable_iff_le_map {α : Type u_1} {β : Type u_2} {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ measurable_space.map f m₁ := iff.rfl theorem measurable.of_le_map {α : Type u_1} {β : Type u_2} {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : m₂ ≤ measurable_space.map f m₁ → measurable f := iff.mpr measurable_iff_le_map theorem measurable_iff_comap_le {α : Type u_1} {β : Type u_2} {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ measurable_space.comap f m₂ ≤ m₁ := iff.symm measurable_space.comap_le_iff_le_map theorem measurable.comap_le {α : Type u_1} {β : Type u_2} {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f → measurable_space.comap f m₂ ≤ m₁ := iff.mp measurable_iff_comap_le theorem measurable.mono {α : Type u_1} {β : Type u_2} {ma : measurable_space α} {ma' : measurable_space α} {mb : measurable_space β} {mb' : measurable_space β} {f : α → β} (hf : measurable f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : measurable f := fun (t : set β) (ht : is_measurable t) => ha (f ⁻¹' t) (hf (hb t ht)) theorem measurable_from_top {α : Type u_1} {β : Type u_2} [measurable_space β] {f : α → β} : measurable f := fun (s : set β) (hs : is_measurable s) => trivial theorem measurable_generate_from {α : Type u_1} {β : Type u_2} [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀ (t : set β), t ∈ s → is_measurable (f ⁻¹' t)) : measurable f := measurable.of_le_map (measurable_space.generate_from_le h) theorem measurable_id {α : Type u_1} [measurable_space α] : measurable id := fun (t : set α) => id theorem measurable.comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := fun (t : set γ) (ht : is_measurable t) => hf (hg ht) theorem subsingleton.measurable {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] [subsingleton α] {f : α → β} : measurable f := fun (s : set β) (hs : is_measurable s) => subsingleton.is_measurable theorem measurable.piecewise {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {s : set α} {_x : decidable_pred s} {f : α → β} {g : α → β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : measurable (set.piecewise s f g) := sorry /-- this is slightly different from `measurable.piecewise`. It can be used to show `measurable (ite (x=0) 0 1)` by `exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const`, but replacing `measurable.ite` by `measurable.piecewise` in that example proof does not work. -/ theorem measurable.ite {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {p : α → Prop} {_x : decidable_pred p} {f : α → β} {g : α → β} (hp : is_measurable (set_of fun (a : α) => p a)) (hf : measurable f) (hg : measurable g) : measurable fun (x : α) => ite (p x) (f x) (g x) := measurable.piecewise hp hf hg @[simp] theorem measurable_const {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {a : α} : measurable fun (b : β) => a := fun (s : set α) (hs : is_measurable s) => is_measurable.const (a ∈ s) theorem measurable.indicator {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] [HasZero β] {s : set α} {f : α → β} (hf : measurable f) (hs : is_measurable s) : measurable (set.indicator s f) := measurable.piecewise hs hf measurable_const theorem measurable_zero {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] [HasZero α] : measurable 0 := measurable_const theorem measurable_of_not_nonempty {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (h : ¬Nonempty α) (f : α → β) : measurable f := sorry protected instance empty.measurable_space : measurable_space empty := ⊤ protected instance punit.measurable_space : measurable_space PUnit := ⊤ protected instance bool.measurable_space : measurable_space Bool := ⊤ protected instance nat.measurable_space : measurable_space ℕ := ⊤ protected instance int.measurable_space : measurable_space ℤ := ⊤ protected instance rat.measurable_space : measurable_space ℚ := ⊤ theorem measurable_to_encodable {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] [encodable α] {f : β → α} (h : ∀ (y : β), is_measurable (f ⁻¹' singleton (f y))) : measurable f := sorry theorem measurable_unit {α : Type u_1} [measurable_space α] (f : Unit → α) : measurable f := measurable_from_top theorem measurable_from_nat {α : Type u_1} [measurable_space α] {f : ℕ → α} : measurable f := measurable_from_top theorem measurable_to_nat {α : Type u_1} [measurable_space α] {f : α → ℕ} : (∀ (y : α), is_measurable (f ⁻¹' singleton (f y))) → measurable f := measurable_to_encodable theorem measurable_find_greatest' {α : Type u_1} [measurable_space α] {p : α → ℕ → Prop} {N : ℕ} (hN : ∀ (k : ℕ), k ≤ N → is_measurable (set_of fun (x : α) => nat.find_greatest (p x) N = k)) : measurable fun (x : α) => nat.find_greatest (p x) N := measurable_to_nat fun (x : α) => hN (nat.find_greatest (p x) N) nat.find_greatest_le theorem measurable_find_greatest {α : Type u_1} [measurable_space α] {p : α → ℕ → Prop} {N : ℕ} (hN : ∀ (k : ℕ), k ≤ N → is_measurable (set_of fun (x : α) => p x k)) : measurable fun (x : α) => nat.find_greatest (p x) N := sorry theorem measurable_find {α : Type u_1} [measurable_space α] {p : α → ℕ → Prop} (hp : ∀ (x : α), ∃ (N : ℕ), p x N) (hm : ∀ (k : ℕ), is_measurable (set_of fun (x : α) => p x k)) : measurable fun (x : α) => nat.find (hp x) := sorry protected instance subtype.measurable_space {α : Type u_1} {p : α → Prop} [m : measurable_space α] : measurable_space (Subtype p) := measurable_space.comap coe m theorem measurable_subtype_coe {α : Type u_1} [measurable_space α] {p : α → Prop} : measurable coe := measurable_space.le_map_comap theorem measurable.subtype_coe {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → Subtype p} (hf : measurable f) : measurable fun (a : α) => ↑(f a) := measurable.comp measurable_subtype_coe hf theorem measurable.subtype_mk {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ (x : α), p (f x)} : measurable fun (x : α) => { val := f x, property := h x } := sorry theorem is_measurable.subtype_image {α : Type u_1} [measurable_space α] {s : set α} {t : set ↥s} (hs : is_measurable s) : is_measurable t → is_measurable (coe '' t) := sorry theorem measurable_of_measurable_union_cover {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {f : α → β} (s : set α) (t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : set.univ ⊆ s ∪ t) (hc : measurable fun (a : ↥s) => f ↑a) (hd : measurable fun (a : ↥t) => f ↑a) : measurable f := sorry theorem measurable_of_measurable_on_compl_singleton {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable (set.restrict f (set_of fun (x : α) => x ≠ a))) : measurable f := measurable_of_measurable_union_cover (set_of fun (x : α) => x = a) ((set_of fun (x : α) => x = a)ᶜ) is_measurable_eq (is_measurable.compl is_measurable_eq) (fun (x : α) (hx : x ∈ set.univ) => classical.em (x ∈ set_of fun (x : α) => x = a)) subsingleton.measurable hf protected instance prod.measurable_space {α : Type u_1} {β : Type u_2} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := measurable_space.comap prod.fst m₁ ⊔ measurable_space.comap prod.snd m₂ theorem measurable_fst {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : measurable prod.fst := measurable.of_comap_le le_sup_left theorem measurable.fst {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable fun (a : α) => prod.fst (f a) := measurable.comp measurable_fst hf theorem measurable_snd {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : measurable prod.snd := measurable.of_comap_le le_sup_right theorem measurable.snd {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable fun (a : α) => prod.snd (f a) := measurable.comp measurable_snd hf theorem measurable.prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf₁ : measurable fun (a : α) => prod.fst (f a)) (hf₂ : measurable fun (a : α) => prod.snd (f a)) : measurable f := sorry theorem measurable_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} : measurable f ↔ (measurable fun (a : α) => prod.fst (f a)) ∧ measurable fun (a : α) => prod.snd (f a) := sorry theorem measurable.prod_mk {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable fun (a : α) => (f a, g a) := measurable.prod hf hg theorem measurable_prod_mk_left {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {x : α} : measurable (Prod.mk x) := measurable.prod_mk measurable_const measurable_id theorem measurable_prod_mk_right {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {y : β} : measurable fun (x : α) => (x, y) := measurable.prod_mk measurable_id measurable_const theorem measurable.of_uncurry_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β → γ} (hf : measurable (function.uncurry f)) {x : α} : measurable (f x) := measurable.comp hf measurable_prod_mk_left theorem measurable.of_uncurry_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β → γ} (hf : measurable (function.uncurry f)) {y : β} : measurable fun (x : α) => f x y := measurable.comp hf measurable_prod_mk_right theorem measurable_swap {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : measurable prod.swap := measurable.prod measurable_snd measurable_fst theorem measurable_swap_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α × β → γ} : measurable (f ∘ prod.swap) ↔ measurable f := sorry theorem is_measurable.prod {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (set.prod s t) := is_measurable.inter (measurable_fst hs) (measurable_snd ht) theorem is_measurable_prod_of_nonempty {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {s : set α} {t : set β} (h : set.nonempty (set.prod s t)) : is_measurable (set.prod s t) ↔ is_measurable s ∧ is_measurable t := sorry theorem is_measurable_prod {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {s : set α} {t : set β} : is_measurable (set.prod s t) ↔ is_measurable s ∧ is_measurable t ∨ s = ∅ ∨ t = ∅ := sorry theorem is_measurable_swap_iff {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {s : set (α × β)} : is_measurable (prod.swap ⁻¹' s) ↔ is_measurable s := sorry protected instance measurable_space.pi {δ : Type u_4} {π : δ → Type u_7} [m : (a : δ) → measurable_space (π a)] : measurable_space ((a : δ) → π a) := supr fun (a : δ) => measurable_space.comap (fun (b : (a : δ) → π a) => b a) (m a) theorem measurable_pi_iff {α : Type u_1} {δ : Type u_4} [measurable_space α] {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] {g : α → (a : δ) → π a} : measurable g ↔ ∀ (a : δ), measurable fun (x : α) => g x a := sorry theorem measurable_pi_apply {δ : Type u_4} {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] (a : δ) : measurable fun (f : (a : δ) → π a) => f a := measurable.of_comap_le (le_supr (fun (a : δ) => measurable_space.comap (fun (f : (a : δ) → π a) => f a) (_inst_4 a)) a) theorem measurable.eval {α : Type u_1} {δ : Type u_4} [measurable_space α] {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] {a : δ} {g : α → (a : δ) → π a} (hg : measurable g) : measurable fun (x : α) => g x a := measurable.comp (measurable_pi_apply a) hg theorem measurable_pi_lambda {α : Type u_1} {δ : Type u_4} [measurable_space α] {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] (f : α → (a : δ) → π a) (hf : ∀ (a : δ), measurable fun (c : α) => f c a) : measurable f := iff.mpr measurable_pi_iff hf /-- The function `update f a : π a → Π a, π a` is always measurable. This doesn't require `f` to be measurable. This should not be confused with the statement that `update f a x` is measurable. -/ theorem measurable_update {δ : Type u_4} {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] (f : (a : δ) → π a) {a : δ} : measurable (function.update f a) := sorry /- Even though we cannot use projection notation, we still keep a dot to be consistent with similar lemmas, like `is_measurable.prod`. -/ theorem is_measurable.pi {δ : Type u_4} {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] {s : set δ} {t : (i : δ) → set (π i)} (hs : set.countable s) (ht : ∀ (i : δ), i ∈ s → is_measurable (t i)) : is_measurable (set.pi s t) := eq.mpr (id (Eq._oldrec (Eq.refl (is_measurable (set.pi s t))) (set.pi_def s t))) (is_measurable.bInter hs fun (i : δ) (hi : i ∈ s) => measurable_pi_apply i (ht i hi)) theorem is_measurable.pi_univ {δ : Type u_4} {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] [encodable δ] {t : (i : δ) → set (π i)} (ht : ∀ (i : δ), is_measurable (t i)) : is_measurable (set.pi set.univ t) := is_measurable.pi (set.countable_encodable set.univ) fun (i : δ) (_x : i ∈ set.univ) => ht i theorem is_measurable_pi_of_nonempty {δ : Type u_4} {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] {s : set δ} {t : (i : δ) → set (π i)} (hs : set.countable s) (h : set.nonempty (set.pi s t)) : is_measurable (set.pi s t) ↔ ∀ (i : δ), i ∈ s → is_measurable (t i) := sorry theorem is_measurable_pi {δ : Type u_4} {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] {s : set δ} {t : (i : δ) → set (π i)} (hs : set.countable s) : is_measurable (set.pi s t) ↔ (∀ (i : δ), i ∈ s → is_measurable (t i)) ∨ set.pi s t = ∅ := sorry theorem is_measurable.pi_fintype {δ : Type u_4} {π : δ → Type u_7} [(a : δ) → measurable_space (π a)] [fintype δ] {s : set δ} {t : (i : δ) → set (π i)} (ht : ∀ (i : δ), i ∈ s → is_measurable (t i)) : is_measurable (set.pi s t) := is_measurable.pi (set.countable_encodable s) ht protected instance tprod.measurable_space {δ : Type u_4} (π : δ → Type u_1) [(x : δ) → measurable_space (π x)] (l : List δ) : measurable_space (list.tprod π l) := sorry theorem measurable_tprod_mk {δ : Type u_4} {π : δ → Type u_7} [(x : δ) → measurable_space (π x)] (l : List δ) : measurable (list.tprod.mk l) := List.rec measurable_const (fun (i : δ) (l : List δ) (ih : measurable (list.tprod.mk l)) => measurable.prod_mk (measurable_pi_apply i) ih) l theorem measurable_tprod_elim {δ : Type u_4} {π : δ → Type u_7} [(x : δ) → measurable_space (π x)] {l : List δ} {i : δ} (hi : i ∈ l) : measurable fun (v : list.tprod π l) => list.tprod.elim v hi := sorry theorem measurable_tprod_elim' {δ : Type u_4} {π : δ → Type u_7} [(x : δ) → measurable_space (π x)] {l : List δ} (h : ∀ (i : δ), i ∈ l) : measurable (list.tprod.elim' h) := measurable_pi_lambda (list.tprod.elim' h) fun (i : δ) => measurable_tprod_elim (h i) theorem is_measurable.tprod {δ : Type u_4} {π : δ → Type u_7} [(x : δ) → measurable_space (π x)] (l : List δ) {s : (i : δ) → set (π i)} (hs : ∀ (i : δ), is_measurable (s i)) : is_measurable (set.tprod l s) := List.rec is_measurable.univ (fun (i : δ) (l : List δ) (ih : is_measurable (set.tprod l s)) => is_measurable.prod (hs i) ih) l protected instance sum.measurable_space {α : Type u_1} {β : Type u_2} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := measurable_space.map sum.inl m₁ ⊓ measurable_space.map sum.inr m₂ theorem measurable_inl {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : measurable sum.inl := measurable.of_le_map inf_le_left theorem measurable_inr {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : measurable sum.inr := measurable.of_le_map inf_le_right theorem measurable_sum {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le (le_inf (iff.mpr measurable_space.comap_le_iff_le_map hl) (iff.mpr measurable_space.comap_le_iff_le_map hr)) theorem measurable.sum_elim {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : measurable (sum.elim f g) := measurable_sum hf hg theorem is_measurable.inl_image {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s) := sorry theorem is_measurable_range_inl {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : is_measurable (set.range sum.inl) := eq.mpr (id (Eq._oldrec (Eq.refl (is_measurable (set.range sum.inl))) (Eq.symm set.image_univ))) (is_measurable.inl_image is_measurable.univ) theorem is_measurable_inr_image {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s) := sorry theorem is_measurable_range_inr {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : is_measurable (set.range sum.inr) := eq.mpr (id (Eq._oldrec (Eq.refl (is_measurable (set.range sum.inr))) (Eq.symm set.image_univ))) (is_measurable_inr_image is_measurable.univ) protected instance sigma.measurable_space {α : Type u_1} {β : α → Type u_2} [m : (a : α) → measurable_space (β a)] : measurable_space (sigma β) := infi fun (a : α) => measurable_space.map (sigma.mk a) (m a) /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α : Type u_7) (β : Type u_8) [measurable_space α] [measurable_space β] extends α ≃ β where measurable_to_fun : measurable (equiv.to_fun _to_equiv) measurable_inv_fun : measurable (equiv.inv_fun _to_equiv) infixl:25 " ≃ᵐ " => Mathlib.measurable_equiv namespace measurable_equiv protected instance has_coe_to_fun (α : Type u_1) (β : Type u_2) [measurable_space α] [measurable_space β] : has_coe_to_fun (α ≃ᵐ β) := has_coe_to_fun.mk (fun (_x : α ≃ᵐ β) => α → β) fun (e : α ≃ᵐ β) => ⇑(to_equiv e) theorem coe_eq {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (e : α ≃ᵐ β) : ⇑e = ⇑(to_equiv e) := rfl protected theorem measurable {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (e : α ≃ᵐ β) : measurable ⇑e := measurable_to_fun e @[simp] theorem coe_mk {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (e : α ≃ β) (h1 : measurable ⇑e) (h2 : measurable ⇑(equiv.symm e)) : ⇑(mk e h1 h2) = ⇑e := rfl /-- Any measurable space is equivalent to itself. -/ def refl (α : Type u_1) [measurable_space α] : α ≃ᵐ α := mk (equiv.refl α) measurable_id measurable_id protected instance inhabited {α : Type u_1} [measurable_space α] : Inhabited (α ≃ᵐ α) := { default := refl α } /-- The composition of equivalences between measurable spaces. -/ def trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] (ab : α ≃ᵐ β) (bc : β ≃ᵐ γ) : α ≃ᵐ γ := mk (equiv.trans (to_equiv ab) (to_equiv bc)) sorry sorry /-- The inverse of an equivalence between measurable spaces. -/ @[simp] theorem symm_to_equiv {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (ab : α ≃ᵐ β) : to_equiv (symm ab) = equiv.symm (to_equiv ab) := Eq.refl (to_equiv (symm ab)) @[simp] theorem coe_symm_mk {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (e : α ≃ β) (h1 : measurable ⇑e) (h2 : measurable ⇑(equiv.symm e)) : ⇑(symm (mk e h1 h2)) = ⇑(equiv.symm e) := rfl @[simp] theorem symm_comp_self {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (e : α ≃ᵐ β) : ⇑(symm e) ∘ ⇑e = id := funext (equiv.left_inv (to_equiv e)) @[simp] theorem self_comp_symm {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (e : α ≃ᵐ β) : ⇑e ∘ ⇑(symm e) = id := funext (equiv.right_inv (to_equiv e)) /-- Equal measurable spaces are equivalent. -/ protected def cast {α : Type u_1} {β : Type u_1} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : α ≃ᵐ β := mk (equiv.cast h) sorry sorry protected theorem measurable_coe_iff {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] {f : β → γ} (e : α ≃ᵐ β) : measurable (f ∘ ⇑e) ↔ measurable f := sorry /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α × γ ≃ᵐ β × δ := mk (equiv.prod_congr (to_equiv ab) (to_equiv cd)) sorry sorry /-- Products of measurable spaces are symmetric. -/ def prod_comm {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : α × β ≃ᵐ β × α := mk (equiv.prod_comm α β) sorry sorry /-- Products of measurable spaces are associative. -/ def prod_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] [measurable_space β] [measurable_space γ] : (α × β) × γ ≃ᵐ α × β × γ := mk (equiv.prod_assoc α β γ) sorry sorry /-- Sums of measurable spaces are symmetric. -/ def sum_congr {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α ⊕ γ ≃ᵐ β ⊕ δ := mk (equiv.sum_congr (to_equiv ab) (to_equiv cd)) sorry sorry /-- `set.prod s t ≃ (s × t)` as measurable spaces. -/ def set.prod {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (s : set α) (t : set β) : ↥(set.prod s t) ≃ᵐ ↥s × ↥t := mk (equiv.set.prod s t) sorry sorry /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type u_1) [measurable_space α] : ↥set.univ ≃ᵐ α := mk (equiv.set.univ α) sorry sorry /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton {α : Type u_1} [measurable_space α] (a : α) : ↥(singleton a) ≃ᵐ Unit := mk (equiv.set.singleton a) sorry sorry /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ def set.image {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (f : α → β) (s : set α) (hf : function.injective f) (hfm : measurable f) (hfi : ∀ (s : set α), is_measurable s → is_measurable (f '' s)) : ↥s ≃ᵐ ↥(f '' s) := mk (equiv.set.image f s hf) sorry sorry /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ def set.range {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (f : α → β) (hf : function.injective f) (hfm : measurable f) (hfi : ∀ (s : set α), is_measurable s → is_measurable (f '' s)) : α ≃ᵐ ↥(set.range f) := trans (symm (set.univ α)) (trans (set.image f set.univ hf hfm hfi) (measurable_equiv.cast sorry sorry)) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : ↥(set.range sum.inl) ≃ᵐ α := mk (equiv.mk (fun (ab : ↥(set.range sum.inl)) => sorry) (fun (a : α) => { val := sum.inl a, property := sorry }) sorry sorry) sorry sorry /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] : ↥(set.range sum.inr) ≃ᵐ β := mk (equiv.mk (fun (ab : ↥(set.range sum.inr)) => sorry) (fun (b : β) => { val := sum.inr b, property := sorry }) sorry sorry) sorry sorry /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α : Type u_1) (β : Type u_2) (γ : Type u_3) [measurable_space α] [measurable_space β] [measurable_space γ] : (α ⊕ β) × γ ≃ᵐ α × γ ⊕ β × γ := mk (equiv.sum_prod_distrib α β γ) sorry sorry /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α : Type u_1) (β : Type u_2) (γ : Type u_3) [measurable_space α] [measurable_space β] [measurable_space γ] : α × (β ⊕ γ) ≃ᵐ α × β ⊕ α × γ := trans prod_comm (trans (sum_prod_distrib β γ α) (sum_congr prod_comm prod_comm)) /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α : Type u_1) (β : Type u_2) (γ : Type u_3) (δ : Type u_4) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : (α ⊕ β) × (γ ⊕ δ) ≃ᵐ (α × γ ⊕ α × δ) ⊕ β × γ ⊕ β × δ := trans (sum_prod_distrib α β (γ ⊕ δ)) (sum_congr (prod_sum_distrib α γ δ) (prod_sum_distrib β γ δ)) /-- A family of measurable equivalences `Π a, β₁ a ≃ᵐ β₂ a` generates a measurable equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right {δ' : Type u_5} {π : δ' → Type u_7} {π' : δ' → Type u_8} [(x : δ') → measurable_space (π x)] [(x : δ') → measurable_space (π' x)] (e : (a : δ') → π a ≃ᵐ π' a) : ((a : δ') → π a) ≃ᵐ ((a : δ') → π' a) := mk (equiv.Pi_congr_right fun (a : δ') => to_equiv (e a)) sorry sorry /-- Pi-types are measurably equivalent to iterated products. -/ def pi_measurable_equiv_tprod {δ' : Type u_5} {π : δ' → Type u_7} [(x : δ') → measurable_space (π x)] {l : List δ'} (hnd : list.nodup l) (h : ∀ (i : δ'), i ∈ l) : ((i : δ') → π i) ≃ᵐ list.tprod π l := mk (list.tprod.pi_equiv_tprod hnd h) sorry sorry end measurable_equiv /-- A pi-system is a collection of subsets of `α` that is closed under intersections of sets that are not disjoint. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α : Type u_1} (C : set (set α)) := ∀ (s t : set α), s ∈ C → t ∈ C → set.nonempty (s ∩ t) → s ∩ t ∈ C namespace measurable_space theorem is_pi_system_is_measurable {α : Type u_1} [measurable_space α] : is_pi_system (set_of fun (s : set α) => is_measurable s) := fun (s t : set α) (hs : s ∈ set_of fun (s : set α) => is_measurable s) (ht : t ∈ set_of fun (s : set α) => is_measurable s) (_x : set.nonempty (s ∩ t)) => is_measurable.inter hs ht /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type u_7) where has : set α → Prop has_empty : has ∅ has_compl : ∀ {a : set α}, has a → has (aᶜ) has_Union_nat : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ (i : ℕ), has (f i)) → has (set.Union fun (i : ℕ) => f i) namespace dynkin_system theorem ext {α : Type u_1} {d₁ : dynkin_system α} {d₂ : dynkin_system α} : (∀ (s : set α), has d₁ s ↔ has d₂ s) → d₁ = d₂ := sorry theorem has_compl_iff {α : Type u_1} (d : dynkin_system α) {a : set α} : has d (aᶜ) ↔ has d a := sorry theorem has_univ {α : Type u_1} (d : dynkin_system α) : has d set.univ := sorry theorem has_Union {α : Type u_1} (d : dynkin_system α) {β : Type u_2} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀ (i : β), has d (f i)) : has d (set.Union fun (i : β) => f i) := sorry theorem has_union {α : Type u_1} (d : dynkin_system α) {s₁ : set α} {s₂ : set α} (h₁ : has d s₁) (h₂ : has d s₂) (h : s₁ ∩ s₂ ⊆ ∅) : has d (s₁ ∪ s₂) := eq.mpr (id (Eq._oldrec (Eq.refl (has d (s₁ ∪ s₂))) set.union_eq_Union)) (has_Union d (iff.mpr pairwise_disjoint_on_bool h) (iff.mpr bool.forall_bool { left := h₂, right := h₁ })) theorem has_diff {α : Type u_1} (d : dynkin_system α) {s₁ : set α} {s₂ : set α} (h₁ : has d s₁) (h₂ : has d s₂) (h : s₂ ⊆ s₁) : has d (s₁ \ s₂) := sorry protected instance partial_order {α : Type u_1} : partial_order (dynkin_system α) := partial_order.mk (fun (m₁ m₂ : dynkin_system α) => has m₁ ≤ has m₂) (preorder.lt._default fun (m₁ m₂ : dynkin_system α) => has m₁ ≤ has m₂) sorry sorry sorry /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space {α : Type u_1} (m : measurable_space α) : dynkin_system α := mk (is_measurable' m) (is_measurable_empty m) (is_measurable_compl m) sorry theorem of_measurable_space_le_of_measurable_space_iff {α : Type u_1} {m₁ : measurable_space α} {m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has {α : Type u_1} (s : set (set α)) : set α → Prop where | basic : ∀ (t : set α), t ∈ s → generate_has s t | empty : generate_has s ∅ | compl : ∀ {a : set α}, generate_has s a → generate_has s (aᶜ) | Union : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ (i : ℕ), generate_has s (f i)) → generate_has s (set.Union fun (i : ℕ) => f i) theorem generate_has_compl {α : Type u_1} {C : set (set α)} {s : set α} : generate_has C (sᶜ) ↔ generate_has C s := sorry /-- The least Dynkin system containing a collection of basic sets. -/ def generate {α : Type u_1} (s : set (set α)) : dynkin_system α := mk (generate_has s) generate_has.empty sorry sorry theorem generate_has_def {α : Type u_1} {C : set (set α)} : has (generate C) = generate_has C := rfl protected instance inhabited {α : Type u_1} : Inhabited (dynkin_system α) := { default := generate set.univ } /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space {α : Type u_1} (d : dynkin_system α) (h_inter : ∀ (s₁ s₂ : set α), has d s₁ → has d s₂ → has d (s₁ ∩ s₂)) : measurable_space α := mk (has d) (has_empty d) sorry sorry theorem of_measurable_space_to_measurable_space {α : Type u_1} (d : dynkin_system α) (h_inter : ∀ (s₁ s₂ : set α), has d s₁ → has d s₂ → has d (s₁ ∩ s₂)) : of_measurable_space (to_measurable_space d h_inter) = d := ext fun (s : set α) => iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {α : Type u_1} (d : dynkin_system α) {s : set α} (h : has d s) : dynkin_system α := mk (fun (t : set α) => has d (t ∩ s)) sorry sorry sorry theorem generate_le {α : Type u_1} (d : dynkin_system α) {s : set (set α)} (h : ∀ (t : set α), t ∈ s → has d t) : generate s ≤ d := sorry theorem generate_has_subset_generate_measurable {α : Type u_1} {C : set (set α)} {s : set α} (hs : has (generate C) s) : is_measurable' (generate_from C) s := generate_le (of_measurable_space (generate_from C)) (fun (t : set α) => is_measurable_generate_from) s hs theorem generate_inter {α : Type u_1} {s : set (set α)} (hs : is_pi_system s) {t₁ : set α} {t₂ : set α} (ht₁ : has (generate s) t₁) (ht₂ : has (generate s) t₂) : has (generate s) (t₁ ∩ t₂) := sorry /-- If we have a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a "π-system" if it is non-empty. -/ theorem generate_from_eq {α : Type u_1} {s : set (set α)} (hs : is_pi_system s) : generate_from s = to_measurable_space (generate s) fun (t₁ t₂ : set α) => generate_inter hs := sorry end dynkin_system theorem induction_on_inter {α : Type u_1} {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀ (t : set α), t ∈ s → C t) (h_compl : ∀ (t : set α), is_measurable t → C t → C (tᶜ)) (h_union : ∀ (f : ℕ → set α), pairwise (disjoint on f) → (∀ (i : ℕ), is_measurable (f i)) → (∀ (i : ℕ), C (f i)) → C (set.Union fun (i : ℕ) => f i)) {t : set α} : is_measurable t → C t := sorry end measurable_space namespace filter /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class is_measurably_generated {α : Type u_1} [measurable_space α] (f : filter α) where exists_measurable_subset : ∀ {s : set α}, s ∈ f → ∃ (t : set α), ∃ (H : t ∈ f), is_measurable t ∧ t ⊆ s protected instance is_measurably_generated_bot {α : Type u_1} [measurable_space α] : is_measurably_generated ⊥ := is_measurably_generated.mk fun (_x : set α) (_x_1 : _x ∈ ⊥) => Exists.intro ∅ (Exists.intro mem_bot_sets { left := is_measurable.empty, right := set.empty_subset _x }) protected instance is_measurably_generated_top {α : Type u_1} [measurable_space α] : is_measurably_generated ⊤ := is_measurably_generated.mk fun (s : set α) (hs : s ∈ ⊤) => Exists.intro set.univ (Exists.intro univ_mem_sets { left := is_measurable.univ, right := fun (x : α) (_x : x ∈ set.univ) => hs x }) theorem eventually.exists_measurable_mem {α : Type u_1} [measurable_space α] {f : filter α} [is_measurably_generated f] {p : α → Prop} (h : filter.eventually (fun (x : α) => p x) f) : ∃ (s : set α), ∃ (H : s ∈ f), is_measurable s ∧ ∀ (x : α), x ∈ s → p x := is_measurably_generated.exists_measurable_subset h theorem eventually.exists_measurable_mem_of_lift' {α : Type u_1} [measurable_space α] {f : filter α} [is_measurably_generated f] {p : set α → Prop} (h : filter.eventually (fun (s : set α) => p s) (filter.lift' f set.powerset)) : ∃ (s : set α), ∃ (H : s ∈ f), is_measurable s ∧ p s := sorry protected instance inf_is_measurably_generated {α : Type u_1} [measurable_space α] (f : filter α) (g : filter α) [is_measurably_generated f] [is_measurably_generated g] : is_measurably_generated (f ⊓ g) := sorry theorem principal_is_measurably_generated_iff {α : Type u_1} [measurable_space α] {s : set α} : is_measurably_generated (principal s) ↔ is_measurable s := sorry theorem Mathlib.is_measurable.principal_is_measurably_generated {α : Type u_1} [measurable_space α] {s : set α} : is_measurable s → is_measurably_generated (principal s) := iff.mpr principal_is_measurably_generated_iff protected instance infi_is_measurably_generated {α : Type u_1} {ι : Sort u_6} [measurable_space α] {f : ι → filter α} [∀ (i : ι), is_measurably_generated (f i)] : is_measurably_generated (infi fun (i : ι) => f i) := sorry end filter /-- We say that a collection of sets is countably spanning if a countable subset spans the whole type. This is a useful condition in various parts of measure theory. For example, it is a needed condition to show that the product of two collections generate the product sigma algebra, see `generate_from_prod_eq`. -/ def is_countably_spanning {α : Type u_1} (C : set (set α)) := ∃ (s : ℕ → set α), (∀ (n : ℕ), s n ∈ C) ∧ (set.Union fun (n : ℕ) => s n) = set.univ theorem is_countably_spanning_is_measurable {α : Type u_1} [measurable_space α] : is_countably_spanning (set_of fun (s : set α) => is_measurable s) := Exists.intro (fun (_x : ℕ) => set.univ) { left := fun (_x : ℕ) => is_measurable.univ, right := set.Union_const set.univ }
42671ec1cf8cab137bf340368df5dd1134625313
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finset/mul_antidiagonal.lean
154fbc72e8a2490937a28d73b4cffff664b6c09c
[ "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
3,824
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yaël Dillies -/ import data.set.pointwise.basic import data.set.mul_antidiagonal /-! # Multiplication antidiagonal as a `finset`. We construct the `finset` of all pairs of an element in `s` and an element in `t` that multiply to `a`, given that `s` and `t` are well-ordered.-/ namespace set open_locale pointwise variables {α : Type*} {s t : set α} @[to_additive] lemma is_pwo.mul [ordered_cancel_comm_monoid α] (hs : s.is_pwo) (ht : t.is_pwo) : is_pwo (s * t) := by { rw ←image_mul_prod, exact (hs.prod ht).image_of_monotone (monotone_fst.mul' monotone_snd) } variables [linear_ordered_cancel_comm_monoid α] @[to_additive] lemma is_wf.mul (hs : s.is_wf) (ht : t.is_wf) : is_wf (s * t) := (hs.is_pwo.mul ht.is_pwo).is_wf @[to_additive] lemma is_wf.min_mul (hs : s.is_wf) (ht : t.is_wf) (hsn : s.nonempty) (htn : t.nonempty) : (hs.mul ht).min (hsn.mul htn) = hs.min hsn * ht.min htn := begin refine le_antisymm (is_wf.min_le _ _ (mem_mul.2 ⟨_, _, hs.min_mem _, ht.min_mem _, rfl⟩)) _, rw is_wf.le_min_iff, rintro _ ⟨x, y, hx, hy, rfl⟩, exact mul_le_mul' (hs.min_le _ hx) (ht.min_le _ hy), end end set namespace finset open_locale pointwise variables {α : Type*} variables [ordered_cancel_comm_monoid α] {s t : set α} (hs : s.is_pwo) (ht : t.is_pwo) (a : α) /-- `finset.mul_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`, but its construction requires proofs that `s` and `t` are well-ordered. -/ @[to_additive "`finset.add_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`, but its construction requires proofs that `s` and `t` are well-ordered."] noncomputable def mul_antidiagonal : finset (α × α) := (set.mul_antidiagonal.finite_of_is_pwo hs ht a).to_finset variables {hs ht a} {u : set α} {hu : u.is_pwo} {x : α × α} @[simp, to_additive] lemma mem_mul_antidiagonal : x ∈ mul_antidiagonal hs ht a ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 * x.2 = a := by simp [mul_antidiagonal, and_rotate] @[to_additive] lemma mul_antidiagonal_mono_left (h : u ⊆ s) : mul_antidiagonal hu ht a ⊆ mul_antidiagonal hs ht a := set.finite.to_finset_subset.2 $ set.mul_antidiagonal_mono_left h @[to_additive] lemma mul_antidiagonal_mono_right (h : u ⊆ t) : mul_antidiagonal hs hu a ⊆ mul_antidiagonal hs ht a := set.finite.to_finset_subset.2 $ set.mul_antidiagonal_mono_right h @[simp, to_additive] lemma swap_mem_mul_antidiagonal : x.swap ∈ finset.mul_antidiagonal hs ht a ↔ x ∈ finset.mul_antidiagonal ht hs a := by simp [mul_comm, and.left_comm] @[to_additive] lemma support_mul_antidiagonal_subset_mul : {a | (mul_antidiagonal hs ht a).nonempty} ⊆ s * t := λ a ⟨b, hb⟩, by { rw mem_mul_antidiagonal at hb, exact ⟨b.1, b.2, hb⟩ } @[to_additive] lemma is_pwo_support_mul_antidiagonal : {a | (mul_antidiagonal hs ht a).nonempty}.is_pwo := (hs.mul ht).mono support_mul_antidiagonal_subset_mul @[to_additive] lemma mul_antidiagonal_min_mul_min {α} [linear_ordered_cancel_comm_monoid α] {s t : set α} (hs : s.is_wf) (ht : t.is_wf) (hns : s.nonempty) (hnt : t.nonempty) : mul_antidiagonal hs.is_pwo ht.is_pwo ((hs.min hns) * (ht.min hnt)) = {(hs.min hns, ht.min hnt)} := begin ext ⟨a, b⟩, simp only [mem_mul_antidiagonal, mem_singleton, prod.ext_iff], split, { rintro ⟨has, hat, hst⟩, obtain rfl := (hs.min_le hns has).eq_of_not_lt (λ hlt, (mul_lt_mul_of_lt_of_le hlt $ ht.min_le hnt hat).ne' hst), exact ⟨rfl, mul_left_cancel hst⟩ }, { rintro ⟨rfl, rfl⟩, exact ⟨hs.min_mem _, ht.min_mem _, rfl⟩ } end end finset
2bf681f00167956b0147926efb5c72b8bbffb69b
bb31430994044506fa42fd667e2d556327e18dfe
/src/linear_algebra/prod.lean
98b279f10df23d1a4cdbb2f474c893ed5aff5ae3
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
31,296
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov, Eric Wieser -/ import linear_algebra.span import order.partial_sups import algebra.algebra.prod /-! ### Products of modules This file defines constructors for linear maps whose domains or codomains are products. It contains theorems relating these to each other, as well as to `submodule.prod`, `submodule.map`, `submodule.comap`, `linear_map.range`, and `linear_map.ker`. ## Main definitions - products in the domain: - `linear_map.fst` - `linear_map.snd` - `linear_map.coprod` - `linear_map.prod_ext` - products in the codomain: - `linear_map.inl` - `linear_map.inr` - `linear_map.prod` - products in both domain and codomain: - `linear_map.prod_map` - `linear_equiv.prod_map` - `linear_equiv.skew_prod` -/ universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} variables {M₅ M₆ : Type*} section prod namespace linear_map variables (S : Type*) [semiring R] [semiring S] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [add_comm_monoid M₅] [add_comm_monoid M₆] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables [module R M₅] [module R M₆] variables (f : M →ₗ[R] M₂) section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := { to_fun := prod.fst, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := { to_fun := prod.snd, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl theorem fst_surjective : function.surjective (fst R M M₂) := λ x, ⟨(x, 0), rfl⟩ theorem snd_surjective : function.surjective (snd R M M₂) := λ x, ⟨(0, x), rfl⟩ /-- The prod of two linear maps is a linear map. -/ @[simps] def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (M →ₗ[R] M₂ × M₃) := { to_fun := pi.prod f g, map_add' := λ x y, by simp only [pi.prod, prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [pi.prod, prod.smul_mk, map_smul, ring_hom.id_apply] } lemma coe_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ⇑(f.prod g) = pi.prod f g := rfl @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := fun_like.coe_injective pi.prod_fst_snd /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def prod_equiv [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] : ((M →ₗ[R] M₂) × (M →ₗ[R] M₃)) ≃ₗ[S] (M →ₗ[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, map_add' := λ a b, rfl, map_smul' := λ r a, rfl } section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := prod linear_map.id 0 /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := prod 0 linear_map.id theorem range_inl : range (inl R M M₂) = ker (snd R M M₂) := begin ext x, simp only [mem_ker, mem_range], split, { rintros ⟨y, rfl⟩, refl }, { intro h, exact ⟨x.fst, prod.ext rfl h.symm⟩ } end theorem ker_snd : ker (snd R M M₂) = range (inl R M M₂) := eq.symm $ range_inl R M M₂ theorem range_inr : range (inr R M M₂) = ker (fst R M M₂) := begin ext x, simp only [mem_ker, mem_range], split, { rintros ⟨y, rfl⟩, refl }, { intro h, exact ⟨x.snd, prod.ext h.symm rfl⟩ } end theorem ker_fst : ker (fst R M M₂) = range (inr R M M₂) := eq.symm $ range_inr R M M₂ end @[simp] theorem coe_inl : (inl R M M₂ : M → M × M₂) = λ x, (x, 0) := rfl theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem coe_inr : (inr R M M₂ : M₂ → M × M₂) = prod.mk 0 := rfl theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := f.comp (fst _ _ _) + g.comp (snd _ _ _) @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M × M₂) : coprod f g x = f x.1 + g x.2 := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem comp_coprod (f : M₃ →ₗ[R] M₄) (g₁ : M →ₗ[R] M₃) (g₂ : M₂ →ₗ[R] M₃) : f.comp (g₁.coprod g₂) = (f.comp g₁).coprod (f.comp g₂) := ext $ λ x, f.map_add (g₁ x.1) (g₂ x.2) theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext; simp @[simp] theorem coprod_comp_prod (f : M₂ →ₗ[R] M₄) (g : M₃ →ₗ[R] M₄) (f' : M →ₗ[R] M₂) (g' : M →ₗ[R] M₃) : (f.coprod g).comp (f'.prod g') = f.comp f' + g.comp g' := rfl @[simp] lemma coprod_map_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (S : submodule R M) (S' : submodule R M₂) : (submodule.prod S S').map (linear_map.coprod f g) = S.map f ⊔ S'.map g := set_like.coe_injective $ begin simp only [linear_map.coprod_apply, submodule.coe_sup, submodule.map_coe], rw [←set.image2_add, set.image2_image_left, set.image2_image_right], exact set.image_prod (λ m m₂, f m + g m₂), end /-- Taking the product of two maps with the same codomain is equivalent to taking the product of their domains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def coprod_equiv [module S M₃] [smul_comm_class R S M₃] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₃)) ≃ₗ[S] (M × M₂ →ₗ[R] M₃) := { to_fun := λ f, f.1.coprod f.2, inv_fun := λ f, (f.comp (inl _ _ _), f.comp (inr _ _ _)), left_inv := λ f, by simp only [prod.mk.eta, coprod_inl, coprod_inr], right_inv := λ f, by simp only [←comp_coprod, comp_id, coprod_inl_inr], map_add' := λ a b, by { ext, simp only [prod.snd_add, add_apply, coprod_apply, prod.fst_add, add_add_add_comm] }, map_smul' := λ r a, by { dsimp, ext, simp only [smul_add, smul_apply, prod.smul_snd, prod.smul_fst, coprod_apply] } } theorem prod_ext_iff {f g : M × M₂ →ₗ[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := (coprod_equiv ℕ).symm.injective.eq_iff.symm.trans prod.ext_iff /-- Split equality of linear maps from a product into linear maps over each component, to allow `ext` to apply lemmas specific to `M →ₗ M₃` and `M₂ →ₗ M₃`. See note [partially-applied ext lemmas]. -/ @[ext] theorem prod_ext {f g : M × M₂ →ₗ[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl lemma prod_map_comap_prod (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) (S : submodule R M₂) (S' : submodule R M₄) : (submodule.prod S S').comap (linear_map.prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ lemma ker_prod_map (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) : (linear_map.prod_map f g).ker = submodule.prod f.ker g.ker := begin dsimp only [ker], rw [←prod_map_comap_prod, submodule.prod_bot], end @[simp] lemma prod_map_id : (id : M →ₗ[R] M).prod_map (id : M₂ →ₗ[R] M₂) = id := linear_map.ext $ λ _, prod.mk.eta @[simp] lemma prod_map_one : (1 : M →ₗ[R] M).prod_map (1 : M₂ →ₗ[R] M₂) = 1 := linear_map.ext $ λ _, prod.mk.eta lemma prod_map_comp (f₁₂ : M →ₗ[R] M₂) (f₂₃ : M₂ →ₗ[R] M₃) (g₁₂ : M₄ →ₗ[R] M₅) (g₂₃ : M₅ →ₗ[R] M₆) : f₂₃.prod_map g₂₃ ∘ₗ f₁₂.prod_map g₁₂ = (f₂₃ ∘ₗ f₁₂).prod_map (g₂₃ ∘ₗ g₁₂) := rfl lemma prod_map_mul (f₁₂ : M →ₗ[R] M) (f₂₃ : M →ₗ[R] M) (g₁₂ : M₂ →ₗ[R] M₂) (g₂₃ : M₂ →ₗ[R] M₂) : f₂₃.prod_map g₂₃ * f₁₂.prod_map g₁₂ = (f₂₃ * f₁₂).prod_map (g₂₃ * g₁₂) := rfl lemma prod_map_add (f₁ : M →ₗ[R] M₃) (f₂ : M →ₗ[R] M₃) (g₁ : M₂ →ₗ[R] M₄) (g₂ : M₂ →ₗ[R] M₄) : (f₁ + f₂).prod_map (g₁ + g₂) = f₁.prod_map g₁ + f₂.prod_map g₂ := rfl @[simp] lemma prod_map_zero : (0 : M →ₗ[R] M₂).prod_map (0 : M₃ →ₗ[R] M₄) = 0 := rfl @[simp] lemma prod_map_smul [module S M₃] [module S M₄] [smul_comm_class R S M₃] [smul_comm_class R S M₄] (s : S) (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : prod_map (s • f) (s • g) = s • prod_map f g := rfl variables (R M M₂ M₃ M₄) /-- `linear_map.prod_map` as a `linear_map` -/ @[simps] def prod_map_linear [module S M₃] [module S M₄] [smul_comm_class R S M₃] [smul_comm_class R S M₄] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₄)) →ₗ[S] ((M × M₂) →ₗ[R] (M₃ × M₄)) := { to_fun := λ f, prod_map f.1 f.2, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl} /-- `linear_map.prod_map` as a `ring_hom` -/ @[simps] def prod_map_ring_hom : (M →ₗ[R] M) × (M₂ →ₗ[R] M₂) →+* ((M × M₂) →ₗ[R] (M × M₂)) := { to_fun := λ f, prod_map f.1 f.2, map_one' := prod_map_one, map_zero' := rfl, map_add' := λ _ _, rfl, map_mul' := λ _ _, rfl } variables {R M M₂ M₃ M₄} section map_mul variables {A : Type*} [non_unital_non_assoc_semiring A] [module R A] variables {B : Type*} [non_unital_non_assoc_semiring B] [module R B] lemma inl_map_mul (a₁ a₂ : A) : linear_map.inl R A B (a₁ * a₂) = linear_map.inl R A B a₁ * linear_map.inl R A B a₂ := prod.ext rfl (by simp) lemma inr_map_mul (b₁ b₂ : B) : linear_map.inr R A B (b₁ * b₂) = linear_map.inr R A B b₁ * linear_map.inr R A B b₂ := prod.ext (by simp) rfl end map_mul end linear_map end prod namespace linear_map variables (R M M₂) variables [comm_semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] /-- `linear_map.prod_map` as an `algebra_hom` -/ @[simps] def prod_map_alg_hom : (module.End R M) × (module.End R M₂) →ₐ[R] module.End R (M × M₂) := { commutes' := λ _, rfl, ..prod_map_ring_hom R M M₂ } end linear_map namespace linear_map open submodule variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma is_compl_range_inl_inr : is_compl (inl R M M₂).range (inr R M M₂).range := begin split, { rw disjoint_def, rintros ⟨_, _⟩ ⟨x, hx⟩ ⟨y, hy⟩, simp only [prod.ext_iff, inl_apply, inr_apply, mem_bot] at hx hy ⊢, exact ⟨hy.1.symm, hx.2.symm⟩ }, { rw codisjoint_iff_le_sup, rintros ⟨x, y⟩ -, simp only [mem_sup, mem_range, exists_prop], refine ⟨(x, 0), ⟨x, rfl⟩, (0, y), ⟨y, rfl⟩, _⟩, simp } end lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := is_compl.sup_eq_top is_compl_range_inl_inr lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw set_like.le_def, rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image] @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end lemma ker_prod_ker_le_ker_coprod {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := by { rintros ⟨y, z⟩, simp {contextual := tt} } lemma ker_coprod_of_disjoint_range {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := begin apply le_antisymm _ (ker_prod_ker_le_ker_coprod f g), rintros ⟨y, z⟩ h, simp only [mem_ker, mem_prod, coprod_apply] at h ⊢, have : f y ∈ f.range ⊓ g.range, { simp only [true_and, mem_range, mem_inf, exists_apply_eq_apply], use -z, rwa [eq_comm, map_neg, ← sub_eq_zero, sub_neg_eq_add] }, rw [hd.eq_bot, mem_bot] at this, rw [this] at h, simpa [this] using h, end end linear_map namespace submodule open linear_map variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] lemma sup_eq_range (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, set_like.exists] variables (p : submodule R M) (q : submodule R M₂) @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_snd] variables (R M M₂) /-- `M` as a submodule of `M × N`. -/ def fst : submodule R (M × M₂) := (⊥ : submodule R M₂).comap (linear_map.snd R M M₂) /-- `M` as a submodule of `M × N` is isomorphic to `M`. -/ @[simps] def fst_equiv : submodule.fst R M M₂ ≃ₗ[R] M := { to_fun := λ x, x.1.1, inv_fun := λ m, ⟨⟨m, 0⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma fst_map_fst : (submodule.fst R M M₂).map (linear_map.fst R M M₂) = ⊤ := by tidy lemma fst_map_snd : (submodule.fst R M M₂).map (linear_map.snd R M M₂) = ⊥ := by { tidy, exact 0, } /-- `N` as a submodule of `M × N`. -/ def snd : submodule R (M × M₂) := (⊥ : submodule R M).comap (linear_map.fst R M M₂) /-- `N` as a submodule of `M × N` is isomorphic to `N`. -/ @[simps] def snd_equiv : submodule.snd R M M₂ ≃ₗ[R] M₂ := { to_fun := λ x, x.1.2, inv_fun := λ n, ⟨⟨0, n⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma snd_map_fst : (submodule.snd R M M₂).map (linear_map.fst R M M₂) = ⊥ := by { tidy, exact 0, } lemma snd_map_snd : (submodule.snd R M M₂).map (linear_map.snd R M M₂) = ⊤ := by tidy lemma fst_sup_snd : submodule.fst R M M₂ ⊔ submodule.snd R M M₂ = ⊤ := begin rw eq_top_iff, rintro ⟨m, n⟩ -, rw [show (m, n) = (m, 0) + (0, n), by simp], apply submodule.add_mem (submodule.fst R M M₂ ⊔ submodule.snd R M M₂), { exact submodule.mem_sup_left (submodule.mem_comap.mpr (by simp)), }, { exact submodule.mem_sup_right (submodule.mem_comap.mpr (by simp)), }, end lemma fst_inf_snd : submodule.fst R M M₂ ⊓ submodule.snd R M M₂ = ⊥ := by tidy lemma le_prod_iff {p₁ : submodule R M} {p₂ : submodule R M₂} {q : submodule R (M × M₂)} : q ≤ p₁.prod p₂ ↔ map (linear_map.fst R M M₂) q ≤ p₁ ∧ map (linear_map.snd R M M₂) q ≤ p₂ := begin split, { intros h, split, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 }, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, } end lemma prod_le_iff {p₁ : submodule R M} {p₂ : submodule R M₂} {q : submodule R (M × M₂)} : p₁.prod p₂ ≤ q ↔ map (linear_map.inl R M M₂) p₁ ≤ q ∧ map (linear_map.inr R M M₂) p₂ ≤ q := begin split, { intros h, split, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨hx, zero_mem p₂⟩, }, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨zero_mem p₁, hx⟩, }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ ⟨h1, h2⟩, have h1' : (linear_map.inl R _ _) x1 ∈ q, { apply hH, simpa using h1, }, have h2' : (linear_map.inr R _ _) x2 ∈ q, { apply hK, simpa using h2, }, simpa using add_mem h1' h2', } end lemma prod_eq_bot_iff {p₁ : submodule R M} {p₂ : submodule R M₂} : p₁.prod p₂ = ⊥ ↔ p₁ = ⊥ ∧ p₂ = ⊥ := by simp only [eq_bot_iff, prod_le_iff, (gc_map_comap _).le_iff_le, comap_bot, ker_inl, ker_inr] lemma prod_eq_top_iff {p₁ : submodule R M} {p₂ : submodule R M₂} : p₁.prod p₂ = ⊤ ↔ p₁ = ⊤ ∧ p₂ = ⊤ := by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, map_top, range_fst, range_snd] end submodule namespace linear_equiv /-- Product of modules is commutative up to linear isomorphism. -/ @[simps apply] def prod_comm (R M N : Type*) [semiring R] [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] : (M × N) ≃ₗ[R] (N × M) := { to_fun := prod.swap, map_smul' := λ r ⟨m, n⟩, rfl, ..add_equiv.prod_comm } section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_smul' := λ c x, prod.ext (e₁.map_smulₛₗ c _) (e₂.map_smulₛₗ c _), .. e₁.to_add_equiv.prod_congr e₂.to_add_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end end linear_equiv namespace linear_map open submodule variables [ring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall, pi.prod], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { simp only [mem_ker.mp hx', map_add, zero_add]}, { simp [←eq_sub_iff_add_eq.1 H, map_add, add_left_inj, self_eq_add_right, mem_ker.mp hy'] } end end linear_map namespace linear_map /-! ## Tunnels and tailings Some preliminary work for establishing the strong rank condition for noetherian rings. Given a morphism `f : M × N →ₗ[R] M` which is `i : injective f`, we can find an infinite decreasing `tunnel f i n` of copies of `M` inside `M`, and sitting beside these, an infinite sequence of copies of `N`. We picturesquely name these as `tailing f i n` for each individual copy of `N`, and `tailings f i n` for the supremum of the first `n+1` copies: they are the pieces left behind, sitting inside the tunnel. By construction, each `tailing f i (n+1)` is disjoint from `tailings f i n`; later, when we assume `M` is noetherian, this implies that `N` must be trivial, and establishes the strong rank condition for any left-noetherian ring. -/ section tunnel -- (This doesn't work over a semiring: we need to use that `submodule R M` is a modular lattice, -- which requires cancellation.) variables [ring R] variables {N : Type*} [add_comm_group M] [module R M] [add_comm_group N] [module R N] open function /-- An auxiliary construction for `tunnel`. The composition of `f`, followed by the isomorphism back to `K`, followed by the inclusion of this submodule back into `M`. -/ def tunnel_aux (f : M × N →ₗ[R] M) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : M × N →ₗ[R] M := (Kφ.1.subtype.comp Kφ.2.symm.to_linear_map).comp f lemma tunnel_aux_injective (f : M × N →ₗ[R] M) (i : injective f) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : injective (tunnel_aux f Kφ) := (subtype.val_injective.comp Kφ.2.symm.injective).comp i noncomputable theory /-- Auxiliary definition for `tunnel`. -/ -- Even though we have `noncomputable theory`, -- we get an error without another `noncomputable` here. noncomputable def tunnel' (f : M × N →ₗ[R] M) (i : injective f) : ℕ → Σ (K : submodule R M), K ≃ₗ[R] M | 0 := ⟨⊤, linear_equiv.of_top ⊤ rfl⟩ | (n+1) := ⟨(submodule.fst R M N).map (tunnel_aux f (tunnel' n)), ((submodule.fst R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' n))).symm.trans (submodule.fst_equiv R M N)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a nested sequence of submodules all isomorphic to `M`. -/ def tunnel (f : M × N →ₗ[R] M) (i : injective f) : ℕ →o (submodule R M)ᵒᵈ := ⟨λ n, order_dual.to_dual (tunnel' f i n).1, monotone_nat_of_le_succ (λ n, begin dsimp [tunnel', tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a sequence of submodules all isomorphic to `N`. -/ def tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : submodule R M := (submodule.snd R M N).map (tunnel_aux f (tunnel' f i n)) /-- Each `tailing f i n` is a copy of `N`. -/ def tailing_linear_equiv (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≃ₗ[R] N := ((submodule.snd R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' f i n))).symm.trans (submodule.snd_equiv R M N) lemma tailing_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≤ (tunnel f i n).of_dual := begin dsimp [tailing, tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end lemma tailing_disjoint_tunnel_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailing f i n) (tunnel f i (n+1)).of_dual := begin rw disjoint_iff, dsimp [tailing, tunnel, tunnel'], rw [submodule.map_inf_eq_map_inf_comap, submodule.comap_map_eq_of_injective (tunnel_aux_injective _ i _), inf_comm, submodule.fst_inf_snd, submodule.map_bot], end lemma tailing_sup_tunnel_succ_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ⊔ (tunnel f i (n+1)).of_dual ≤ (tunnel f i n).of_dual := begin dsimp [tailing, tunnel, tunnel', tunnel_aux], rw [←submodule.map_sup, sup_comm, submodule.fst_sup_snd, submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end /-- The supremum of all the copies of `N` found inside the tunnel. -/ def tailings (f : M × N →ₗ[R] M) (i : injective f) : ℕ → submodule R M := partial_sups (tailing f i) @[simp] lemma tailings_zero (f : M × N →ₗ[R] M) (i : injective f) : tailings f i 0 = tailing f i 0 := by simp [tailings] @[simp] lemma tailings_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailings f i (n+1) = tailings f i n ⊔ tailing f i (n+1) := by simp [tailings] lemma tailings_disjoint_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tunnel f i (n+1)).of_dual := begin induction n with n ih, { simp only [tailings_zero], apply tailing_disjoint_tunnel_succ, }, { simp only [tailings_succ], refine disjoint.disjoint_sup_left_of_disjoint_sup_right _ _, apply tailing_disjoint_tunnel_succ, apply disjoint.mono_right _ ih, apply tailing_sup_tunnel_succ_le_tunnel, }, end lemma tailings_disjoint_tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tailing f i (n+1)) := disjoint.mono_right (tailing_le_tunnel f i _) (tailings_disjoint_tunnel f i _) end tunnel section graph variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_group M₃] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) /-- Graph of a linear map. -/ def graph : submodule R (M × M₂) := { carrier := {p | p.2 = f p.1}, add_mem' := λ a b (ha : _ = _) (hb : _ = _), begin change _ + _ = f (_ + _), rw [map_add, ha, hb] end, zero_mem' := eq.symm (map_zero f), smul_mem' := λ c x (hx : _ = _), begin change _ • _ = f (_ • _), rw [map_smul, hx] end } @[simp] lemma mem_graph_iff (x : M × M₂) : x ∈ f.graph ↔ x.2 = f x.1 := iff.rfl lemma graph_eq_ker_coprod : g.graph = ((-g).coprod linear_map.id).ker := begin ext x, change _ = _ ↔ -(g x.1) + x.2 = _, rw [add_comm, add_neg_eq_zero] end lemma graph_eq_range_prod : f.graph = (linear_map.id.prod f).range := begin ext x, exact ⟨λ hx, ⟨x.1, prod.ext rfl hx.symm⟩, λ ⟨u, hu⟩, hu ▸ rfl⟩ end end graph end linear_map
5641c121a8da59ced2868aad807a40450e45d15e
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/compiler/phashmap2.lean
feda9d19d04962042328b497802bca71d7a26ed6
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,571
lean
import Std.Data.PersistentHashMap import Lean.Data.Format open Lean Std Std.PersistentHashMap abbrev Map := PersistentHashMap Nat Nat partial def formatMap : Node Nat Nat → Format | Node.collision keys vals _ => Format.sbracket $ keys.size.fold (fun i fmt => let k := keys.get! i; let v := vals.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ "c@" ++ Format.paren (format k ++ " => " ++ format v)) Format.nil | Node.entries entries => Format.sbracket $ entries.size.fold (fun i fmt => let entry := entries.get! i; let p := if i > 0 then fmt ++ format "," ++ Format.line else fmt; p ++ match entry with | Entry.null => "<null>" | Entry.ref node => formatMap node | Entry.entry k v => Format.paren (format k ++ " => " ++ format v)) Format.nil def main : IO Unit := do let a : Array Nat := [1, 2, 3].toArray; IO.println (a.indexOf 2); let m : Map := PersistentHashMap.empty; let m := m.insert 1 1; let m := m.insert 33 2; let m := m.insert 65 3; -- IO.println (formatMap m.root); IO.println m.stats; let m := m.erase 33; IO.println (m.find? 1); IO.println (m.find? 33); IO.println (m.find? 65); IO.println m.stats; let m := m.erase 1; IO.println (m.find? 1); IO.println (m.find? 33); IO.println (m.find? 65); IO.println m.stats; let m := m.erase 1; IO.println (m.find? 1); IO.println (m.find? 33); IO.println (m.find? 65); let m := m.erase 65; IO.println (m.find? 1); IO.println (m.find? 33); IO.println (m.find? 65); IO.println m.stats
86e93b01576c7af824d79ff1110042166669945a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/projective_space/basic.lean
20cab642407c3e39056c50e3b72db771fdb9f06b
[ "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
8,053
lean
/- Copyright (c) 2022 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import linear_algebra.finite_dimensional /-! # Projective Spaces This file contains the definition of the projectivization of a vector space over a field, as well as the bijection between said projectivization and the collection of all one dimensional subspaces of the vector space. ## Notation `ℙ K V` is notation for `projectivization K V`, the projectivization of a `K`-vector space `V`. ## Constructing terms of `ℙ K V`. We have three ways to construct terms of `ℙ K V`: - `projectivization.mk K v hv` where `v : V` and `hv : v ≠ 0`. - `projectivization.mk' K v` where `v : { w : V // w ≠ 0 }`. - `projectivization.mk'' H h` where `H : submodule K V` and `h : finrank H = 1`. ## Other definitions - For `v : ℙ K V`, `v.submodule` gives the corresponding submodule of `V`. - `projectivization.equiv_submodule` is the equivalence between `ℙ K V` and `{ H : submodule K V // finrank H = 1 }`. - For `v : ℙ K V`, `v.rep : V` is a representative of `v`. -/ variables (K V : Type*) [division_ring K] [add_comm_group V] [module K V] /-- The setoid whose quotient is the projectivization of `V`. -/ def projectivization_setoid : setoid { v : V // v ≠ 0 } := (mul_action.orbit_rel Kˣ V).comap coe /-- The projectivization of the `K`-vector space `V`. The notation `ℙ K V` is preferred. -/ @[nolint has_nonempty_instance] def projectivization := quotient (projectivization_setoid K V) notation `ℙ` := projectivization namespace projectivization variables {V} /-- Construct an element of the projectivization from a nonzero vector. -/ def mk (v : V) (hv : v ≠ 0) : ℙ K V := quotient.mk' ⟨v,hv⟩ /-- A variant of `projectivization.mk` in terms of a subtype. `mk` is preferred. -/ def mk' (v : { v : V // v ≠ 0 }) : ℙ K V := quotient.mk' v @[simp] lemma mk'_eq_mk (v : { v : V // v ≠ 0}) : mk' K v = mk K v v.2 := by { dsimp [mk, mk'], congr' 1, simp } instance [nontrivial V] : nonempty (ℙ K V) := let ⟨v, hv⟩ := exists_ne (0 : V) in ⟨mk K v hv⟩ variable {K} /-- Choose a representative of `v : projectivization K V` in `V`. -/ protected noncomputable def rep (v : ℙ K V) : V := v.out' lemma rep_nonzero (v : ℙ K V) : v.rep ≠ 0 := v.out'.2 @[simp] lemma mk_rep (v : ℙ K V) : mk K v.rep v.rep_nonzero = v := by { dsimp [mk, projectivization.rep], simp } open finite_dimensional /-- Consider an element of the projectivization as a submodule of `V`. -/ protected def submodule (v : ℙ K V) : submodule K V := quotient.lift_on' v (λ v, K ∙ (v : V)) $ begin rintro ⟨a, ha⟩ ⟨b, hb⟩ ⟨x, (rfl : x • b = a)⟩, exact (submodule.span_singleton_group_smul_eq _ x _), end variable (K) lemma mk_eq_mk_iff (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) : mk K v hv = mk K w hw ↔ ∃ (a : Kˣ), a • w = v := quotient.eq' /-- Two nonzero vectors go to the same point in projective space if and only if one is a scalar multiple of the other. -/ lemma mk_eq_mk_iff' (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) : mk K v hv = mk K w hw ↔ ∃ (a : K), a • w = v := begin rw mk_eq_mk_iff K v w hv hw, split, { rintro ⟨a, ha⟩, exact ⟨a, ha⟩ }, { rintro ⟨a, ha⟩, refine ⟨units.mk0 a (λ c, hv.symm _), ha⟩, rwa [c, zero_smul] at ha } end lemma exists_smul_eq_mk_rep (v : V) (hv : v ≠ 0) : ∃ (a : Kˣ), a • v = (mk K v hv).rep := show (projectivization_setoid K V).rel _ _, from quotient.mk_out' ⟨v, hv⟩ variable {K} /-- An induction principle for `projectivization`. Use as `induction v using projectivization.ind`. -/ @[elab_as_eliminator] lemma ind {P : ℙ K V → Prop} (h : ∀ (v : V) (h : v ≠ 0), P (mk K v h)) : ∀ p, P p := quotient.ind' $ subtype.rec $ by exact h @[simp] lemma submodule_mk (v : V) (hv : v ≠ 0) : (mk K v hv).submodule = K ∙ v := rfl lemma submodule_eq (v : ℙ K V) : v.submodule = K ∙ v.rep := by { conv_lhs { rw ← v.mk_rep }, refl } lemma finrank_submodule (v : ℙ K V) : finrank K v.submodule = 1 := begin rw submodule_eq, exact finrank_span_singleton v.rep_nonzero, end instance (v : ℙ K V) : finite_dimensional K v.submodule := by { rw ← v.mk_rep, change finite_dimensional K (K ∙ v.rep), apply_instance } lemma submodule_injective : function.injective (projectivization.submodule : ℙ K V → submodule K V) := begin intros u v h, replace h := le_of_eq h, simp only [submodule_eq] at h, rw submodule.le_span_singleton_iff at h, rw [← mk_rep v, ← mk_rep u], apply quotient.sound', obtain ⟨a,ha⟩ := h u.rep (submodule.mem_span_singleton_self _), have : a ≠ 0 := λ c, u.rep_nonzero (by simpa [c] using ha.symm), use [units.mk0 a this, ha], end variables (K V) /-- The equivalence between the projectivization and the collection of subspaces of dimension 1. -/ noncomputable def equiv_submodule : ℙ K V ≃ { H : submodule K V // finrank K H = 1 } := equiv.of_bijective (λ v, ⟨v.submodule, v.finrank_submodule⟩) begin split, { intros u v h, apply_fun (λ e, e.val) at h, apply submodule_injective h }, { rintros ⟨H, h⟩, rw finrank_eq_one_iff' at h, obtain ⟨v, hv, h⟩ := h, have : (v : V) ≠ 0 := λ c, hv (subtype.coe_injective c), use mk K v this, symmetry, ext x, revert x, erw ← set.ext_iff, ext x, dsimp [-set_like.mem_coe], rw [submodule.span_singleton_eq_range], refine ⟨λ hh, _, _⟩, { obtain ⟨c,hc⟩ := h ⟨x,hh⟩, exact ⟨c, congr_arg coe hc⟩ }, { rintros ⟨c,rfl⟩, refine submodule.smul_mem _ _ v.2 } } end variables {K V} /-- Construct an element of the projectivization from a subspace of dimension 1. -/ noncomputable def mk'' (H : _root_.submodule K V) (h : finrank K H = 1) : ℙ K V := (equiv_submodule K V).symm ⟨H,h⟩ @[simp] lemma submodule_mk'' (H : _root_.submodule K V) (h : finrank K H = 1) : (mk'' H h).submodule = H := begin suffices : (equiv_submodule K V) (mk'' H h) = ⟨H,h⟩, by exact congr_arg coe this, dsimp [mk''], simp end @[simp] lemma mk''_submodule (v : ℙ K V) : mk'' v.submodule v.finrank_submodule = v := show (equiv_submodule K V).symm (equiv_submodule K V _) = _, by simp section map variables {L W : Type*} [division_ring L] [add_comm_group W] [module L W] /-- An injective semilinear map of vector spaces induces a map on projective spaces. -/ def map {σ : K →+* L} (f : V →ₛₗ[σ] W) (hf : function.injective f) : ℙ K V → ℙ L W := quotient.map' (λ v, ⟨f v, λ c, v.2 (hf (by simp [c]))⟩) begin rintros ⟨u,hu⟩ ⟨v,hv⟩ ⟨a,ha⟩, use units.map σ.to_monoid_hom a, dsimp at ⊢ ha, erw [← f.map_smulₛₗ, ha], end /-- Mapping with respect to a semilinear map over an isomorphism of fields yields an injective map on projective spaces. -/ lemma map_injective {σ : K →+* L} {τ : L →+* K} [ring_hom_inv_pair σ τ] (f : V →ₛₗ[σ] W) (hf : function.injective f) : function.injective (map f hf) := begin intros u v h, rw [← u.mk_rep, ← v.mk_rep] at *, apply quotient.sound', dsimp [map, mk] at h, simp only [quotient.eq'] at h, obtain ⟨a,ha⟩ := h, use units.map τ.to_monoid_hom a, dsimp at ⊢ ha, have : (a : L) = σ (τ a), by rw ring_hom_inv_pair.comp_apply_eq₂, change (a : L) • f v.rep = f u.rep at ha, rw [this, ← f.map_smulₛₗ] at ha, exact hf ha, end @[simp] lemma map_id : map (linear_map.id : V →ₗ[K] V) (linear_equiv.refl K V).injective = id := by { ext v, induction v using projectivization.ind, refl } @[simp] lemma map_comp {F U : Type*} [field F] [add_comm_group U] [module F U] {σ : K →+* L} {τ : L →+* F} {γ : K →+* F} [ring_hom_comp_triple σ τ γ] (f : V →ₛₗ[σ] W) (hf : function.injective f) (g : W →ₛₗ[τ] U) (hg : function.injective g) : map (g.comp f) (hg.comp hf) = map g hg ∘ map f hf := by { ext v, induction v using projectivization.ind, refl } end map end projectivization
51b87395176311a5e5b84a728f4979e844d950e4
de8d0cdc3dc15aa390280472764229d0e14e734c
/src/quotient.lean
d6bf9d64469dd5c1f7d6eb1685f2502a33eeb562
[]
no_license
amesnard0/lean-topology
94720ccf0af34961b24b52b96bcfb19df5c8f544
e8f6a720c435cb59d098579a26f6eb70ea05f91a
refs/heads/main
1,682,525,569,376
1,622,116,766,000
1,622,116,766,000
358,047,823
0
0
null
null
null
null
UTF-8
Lean
false
false
3,542
lean
import tactic import data.set.finite import data.real.basic import topological_spaces import neighbourhoods import topological_spaces2 import metric_spaces open set open topological_space open metric_space lemma Q_dense : dense {(q : ℝ) | (q : ℚ)} := begin apply subset.antisymm, simp, intros x hx, have clef : ∀ (n : ℕ), ∃ (q : ℚ), x < q ∧ (q : ℝ) < x + 1/(n+1), intro n, apply exists_rat_btwn, { have : (0 : ℝ) < 1/(n+1), exact nat.one_div_pos_of_nat, linarith }, choose u hu using clef, apply seq_lim_closure (λ n, (u n : ℝ)), simp, sorry, end -- Topologie quotient : instance quot.topological_space {X : Type} [topological_space X] (s : setoid X) : topological_space (quotient s) := { is_open := λ U, is_open ((quotient.mk') ⁻¹' U), univ_mem := univ_mem, inter := begin intros A B hA hB, apply inter, exact hA, exact hB, end, union := begin intros B hB, rw preimage_sUnion, apply union, simp, intro b, apply union, simp, exact hB b, end } -- Relation d'equivalence definissant ℝ/ℚ : def real.rel_Q : setoid ℝ := { r := λ x y, ∃ (q : ℚ), x - y = q, iseqv := begin repeat {split}, intro x, use 0, simp, rintros x y ⟨q, hq⟩, use -q, simp, rw ← hq, simp, rintros x y z ⟨q, hq⟩ ⟨q', hq'⟩, use (q + q'), calc x - z = (x - y) + (y - z) : by linarith ... = ↑(q + q') : by simp [hq, hq'], end} -- La topologie quotient sur ℝ/ℚ est la topologie grossiere : example (U : set (quotient real.rel_Q)) : is_open U ↔ U = ∅ ∨ U = univ := begin split, { intro hyp, cases em (U.nonempty) with h1 h2, { right, cases h1 with X hX, cases quotient.surjective_quotient_mk' X with x hx, rw ← hx at hX, rcases is_open_metric_iff.1 hyp x hX with ⟨r, hr, H⟩, apply subset.antisymm, simp, intros Y hY, cases quotient.surjective_quotient_mk' Y with y hy, let V := {z : ℝ | dist (x - y) z < r }, have hV : V ∈ neighbourhoods (x - y), { apply generated_filter.generator, split, apply generated_open.generator, use [x - y, r], calc dist (x - y) (x - y) = 0 : (dist_eq_zero_iff _ _).2 rfl ... < r : hr }, have clef : closure {(q : ℝ) | (q : ℚ)} = univ, exact Q_dense, cases (point_of_closure {(q : ℝ) | (q : ℚ)} (x - y)).1 (by simp [clef]) V hV with z hz, rcases hz with ⟨hz, q, hq⟩, have hyz : quotient.mk' (y + z) = Y, rw ← hy, rw quotient.eq', use q, simp [hq], rw ← hyz, apply H, have : x - (y + z) = (x - y) - z, by linarith, calc dist x (y + z) = abs (x - (y + z)) : rfl ... = abs ((x - y) - z) : by simp [this] ... = dist (x - y) z : rfl ... < r : hz, }, { left, apply le_antisymm, intros x hx, apply h2, use [x, hx], simp, }, }, { intro hyp, cases hyp with h1 h2, rw h1, exact empty_mem, rw h2, exact univ_mem, }, end -- Relation d'equivalence definissant ℝ/ℤ : def real.rel_Z : setoid ℝ := { r := λ x y, ∃ (n : ℤ), x - y = n, iseqv := begin repeat {split}, intro x, use 0, simp, rintros x y ⟨n, hn⟩, use -n, simp, rw ← hn, simp, rintros x y z ⟨n, hn⟩ ⟨n', hn'⟩, use (n + n'), calc x - z = (x - y) + (y - z) : by linarith ... = ↑(n + n') : by simp [hn, hn'], end }
d99b4a10505ab302b839b9275f1862de3890c85c
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/number_theory/lucas_lehmer.lean
84e00fda916c8a53bd1daf6e19986a8b6d5e31da
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
17,083
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Scott Morrison, Ainsley Pahljina -/ import tactic.ring_exp import tactic.interval_cases import data.nat.parity import data.zmod.basic import group_theory.order_of_element import ring_theory.fintype /-! # The Lucas-Lehmer test for Mersenne primes. We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`. We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic required to calculate the residue, and enables us to prove ``` example : prime (mersenne 127) := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test) ``` ## TODO - Show reverse implication. - Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`. - Find some bigger primes! ## History This development began as a student project by Ainsley Pahljina, and was then cleaned up for mathlib by Scott Morrison. The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro. -/ /-- The Mersenne numbers, 2^p - 1. -/ def mersenne (p : ℕ) : ℕ := 2^p - 1 lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p := begin dsimp [mersenne], calc 0 < 2^1 - 1 : by norm_num ... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h) end namespace lucas_lehmer open nat /-! We now define three(!) different versions of the recurrence `s (i+1) = (s i)^2 - 2`. These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or in `ℤ` but applying `% (2^p - 1)` at each step. They are each useful at different points in the proof, so we take a moment setting up the lemmas relating them. -/ /-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/ def s : ℕ → ℤ | 0 := 4 | (i+1) := (s i)^2 - 2 /-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/ def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1) | 0 := 4 | (i+1) := (s_zmod i)^2 - 2 /-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/ def s_mod (p : ℕ) : ℕ → ℤ | 0 := 4 % (2^p - 1) | (i+1) := ((s_mod i)^2 - 2) % (2^p - 1) lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 := begin apply ne_of_gt, simp only [gt_iff_lt, sub_pos], exact_mod_cast nat.one_lt_two_pow p w, end lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i := begin cases i; dsimp [s_mod], { trivial, }, { apply int.mod_nonneg, exact mersenne_int_ne_zero p w }, end lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i := by cases i; simp [s_mod] lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 := begin rw ←s_mod_mod, convert int.mod_lt _ _, { refine (abs_of_nonneg _).symm, simp only [sub_nonneg, ge_iff_le], exact_mod_cast nat.one_le_two_pow p, }, { exact mersenne_int_ne_zero p w, }, end lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):= begin induction i with i ih, { dsimp [s, s_zmod], norm_num, }, { push_cast [s, s_zmod, ih] }, end -- These next two don't make good `norm_cast` lemmas. lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) := begin have : 1 ≤ b^p := nat.one_le_pow p b w, push_cast [this], end lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) := int.coe_nat_pow_pred 2 p dec_trivial lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) := by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *] /-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/ def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2) lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) : lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 := begin dsimp [lucas_lehmer_residue], rw s_zmod_eq_s_mod p, split, { -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1` -- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`. intro h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h, apply s_mod_nonneg _ (nat.lt_of_succ_lt w), convert s_mod_lt _ (nat.lt_of_succ_lt w) (p-2), push_cast [nat.one_le_two_pow p], refl, }, { intro h, rw h, simp, }, end /-- A Mersenne number `2^p-1` is prime if and only if the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero. -/ @[derive decidable_pred] def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0 /-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/ def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩ instance fact_pnat_pos (q : ℕ+) : fact (0 < (q : ℕ)) := q.2 /-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/ -- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3), -- obtaining the ring structure for free, -- but that seems to be more trouble than it's worth; -- if it were easy to make the definition, -- cardinality calculations would be somewhat more involved, too. @[derive [add_comm_group, decidable_eq, fintype, inhabited]] def X (q : ℕ+) : Type := (zmod q) × (zmod q) namespace X variable {q : ℕ+} @[ext] lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y := begin cases x, cases y, congr; assumption end @[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl @[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl @[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl @[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl instance : has_mul (X q) := { mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) } @[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl @[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl instance : has_one (X q) := { one := ⟨1,0⟩ } @[simp] lemma one_fst : (1 : X q).1 = 1 := rfl @[simp] lemma one_snd : (1 : X q).2 = 0 := rfl @[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl @[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl @[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl @[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, } instance : monoid (X q) := { mul_assoc := λ x y z, by { ext; { dsimp, ring }, }, one := ⟨1,0⟩, one_mul := λ x, by { ext; simp, }, mul_one := λ x, by { ext; simp, }, ..(infer_instance : has_mul (X q)) } lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z := by { ext; { dsimp, ring }, } lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z := by { ext; { dsimp, ring }, } instance : ring (X q) := { left_distrib := left_distrib, right_distrib := right_distrib, ..(infer_instance : add_comm_group (X q)), ..(infer_instance : monoid (X q)) } instance : comm_ring (X q) := { mul_comm := λ x y, by { ext; { dsimp, ring }, }, ..(infer_instance : ring (X q))} instance [fact (1 < (q : ℕ))] : nontrivial (X q) := ⟨⟨0, 1, λ h, by { injection h with h1 _, exact zero_ne_one h1 } ⟩⟩ @[simp] lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_left_inj], exact n_ih, } end @[simp] lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_zero], exact n_ih, } end @[simp] lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) := by { induction n; simp, } @[simp] lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) := by { induction n; simp, } @[norm_cast] lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) := by { ext; simp; ring } @[norm_cast] lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) := by { ext; simp, } /-- The cardinality of `X` is `q^2`. -/ lemma X_card : fintype.card (X q) = q^2 := begin dsimp [X], rw [fintype.card_prod, zmod.card q], ring, end /-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/ lemma units_card (w : 1 < q) : fintype.card (units (X q)) < q^2 := begin haveI : fact (1 < (q : ℕ)) := w, convert card_units_lt (X q), rw X_card, end /-- We define `ω = 2 + √3`. -/ def ω : X q := (2, 1) /-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/ def ωb : X q := (2, -1) lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 := begin dsimp [ω, ωb], ext; simp; ring, end lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 := begin dsimp [ω, ωb], ext; simp; ring, end /-- A closed form for the recurrence relation. -/ lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) := begin induction i with i ih, { dsimp [s, ω, ωb], ext; { simp; refl, }, }, { calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl ... = ((s i : X q)^2 - 2) : by push_cast ... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih ... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring ... = (ω^(2^i))^2 + (ωb^(2^i))^2 : by rw [←mul_pow ωb ω, ωb_mul_ω, one_pow, mul_one, add_sub_cancel] ... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, pow_succ'] } end end X open X /-! Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`. -/ /-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/ lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin by_contradiction, simp at a, interval_cases q (p'+2); clear a, { -- If q = 1, we get a contradiction from 2^p = 2 dsimp [q] at h, injection h with h', clear h, simp [mersenne] at h', exact lt_irrefl 2 (calc 2 ≤ p'+2 : nat.le_add_left _ _ ... < 2^(p'+2) : nat.lt_two_pow _ ... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), }, { -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1 dsimp [q] at h, injection h with h', clear h, rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, pow_succ] at h', exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', } end theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : ∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) = k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 := begin dsimp [lucas_lehmer_residue] at h, rw s_zmod_eq_s p' at h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, cases h with k h, use k, replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q dsimp at h, rw closed_form at h, replace h := congr_arg (λ x, ω^2^p' * x) h, dsimp at h, have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp, rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, one_pow] at h, rw [mul_comm, coe_mul] at h, rw [mul_comm _ (k : X (q (p'+2)))] at h, replace h := eq_sub_of_add_eq h, exact_mod_cast h, end /-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/ theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 := begin ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd], apply nat.min_fac_dvd, end theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+1)) = -1 := begin cases ω_pow_formula p' h with k w, rw [mersenne_coe_X] at w, simpa using w, end theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+2)) = 1 := calc (ω : X (q (p'+2)))^2^(p'+2) = (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←pow_succ'] ... = (-1)^2 : by rw ω_pow_eq_neg_one p' h ... = 1 : by simp /-- `ω` as an element of the group of units. -/ def ω_unit (p : ℕ) : units (X (q p)) := { val := ω, inv := ωb, val_inv := by simp [ω_mul_ωb], inv_val := by simp [ωb_mul_ω], } @[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl /-- The order of `ω` in the unit group is exactly `2^p`. -/ theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : order_of (ω_unit (p'+2)) = 2^(p'+2) := begin apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p { norm_num, }, { intro o, have ω_pow := order_of_dvd_iff_pow_eq_one.1 o, replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) : units (X (q (p'+2))) → X (q (p'+2))) ω_pow, simp at ω_pow, have h : (1 : zmod (q (p'+2))) = -1 := congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)), haveI : fact (2 < (q (p'+2) : ℕ)) := two_lt_q _, apply zmod.neg_one_ne_one h.symm, }, { apply order_of_dvd_iff_pow_eq_one.2, apply units.ext, push_cast, exact ω_pow_eq_one p' h, } end lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 := calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm ... ≤ fintype.card (units (X _)) : order_of_le_card_univ ... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _)) end lucas_lehmer export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue) open lucas_lehmer theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime := begin let p' := p - 2, have z : p = p' + 2 := (nat.sub_eq_iff_eq_add w).mp rfl, have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl), contrapose, intros a t, rw z at a, rw z at t, have h₁ := order_ineq p' t, have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a, have h := lt_of_lt_of_le h₁ h₂, exact not_lt_of_ge (nat.sub_le _ _) h, end -- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better. example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial -- Next we use `norm_num` to calculate each `s p i`. namespace lucas_lehmer open tactic meta instance nat_pexpr : has_to_pexpr ℕ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ meta instance int_pexpr : has_to_pexpr ℤ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ lemma s_mod_succ {p a i b c} (h1 : (2^p - 1 : ℤ) = a) (h2 : s_mod p i = b) (h3 : (b * b - 2) % a = c) : s_mod p (i+1) = c := by { dsimp [s_mod, mersenne], rw [h1, h2, pow_two, h3] } /-- Given a goal of the form `lucas_lehmer_test p`, attempt to do the calculation using `norm_num` to certify each step. -/ meta def run_test : tactic unit := do `(lucas_lehmer_test %%p) ← target, `[dsimp [lucas_lehmer_test]], `[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num], p ← eval_expr ℕ p, -- Calculate the candidate Mersenne prime let M : ℤ := 2^p - 1, t ← to_expr ``(2^%%p - 1 = %%M), v ← to_expr ``(by norm_num : 2^%%p - 1 = %%M), w ← assertv `w t v, -- Unfortunately this creates something like `w : 2^5 - 1 = int.of_nat 31`. -- We could make a better `has_to_pexpr ℤ` instance, or just: `[simp only [int.coe_nat_zero, int.coe_nat_succ, int.of_nat_eq_coe, zero_add, int.coe_nat_bit1] at w], -- base case t ← to_expr ``(s_mod %%p 0 = 4), v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%p 0 = 4), h ← assertv `h t v, -- step case, repeated p-2 times iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })], -- now close the goal h ← get_local `h, exact h end lucas_lehmer /-- We verify that the tactic works to prove `127.prime`. -/ example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test). /-! This implementation works successfully to prove `(2^127 - 1).prime`, and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean]. `(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!), and unfortunately the next Mersenne prime `(2^521 - 1)`, which was the first "computer era" prime, is out of reach with the current implementation. There's still low hanging fruit available to do faster computations based on the formula n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1] and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation. Someone should do this, too! -/ lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] := -- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446 begin conv in k {rw [← nat.mod_add_div k (2^n), add_comm]}, refine nat.modeq.modeq_add _ (by refl), conv {congr, skip, skip, rw ← one_mul (k/2^n)}, refine nat.modeq.modeq_mul _ (by refl), symmetry, rw [nat.modeq.modeq_iff_dvd, int.coe_nat_sub], exact pow_pos (show 0 < 2, from dec_trivial) _ end -- It's hard to know what the limiting factor for large Mersenne primes would be. -- In the purely computational world, I think it's the squaring operation in `s`.
b9b41eb9f9a327f08e617b8879da55be8414d01f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/localization/module.lean
68953652dc66a00949d82e14278047b165435fc3
[ "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
3,013
lean
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu, Anne Baanen -/ import linear_algebra.basis import ring_theory.localization.fraction_ring import ring_theory.localization.integer /-! # Modules / vector spaces over localizations / fraction fields This file contains some results about vector spaces over the field of fractions of a ring. ## Main results * `linear_independent.localization`: `b` is linear independent over a localization of `R` if it is linear independent over `R` itself * `basis.localization`: promote an `R`-basis `b` to an `Rₛ`-basis, where `Rₛ` is a localization of `R` * `linear_independent.iff_fraction_ring`: `b` is linear independent over `R` iff it is linear independent over `Frac(R)` -/ open_locale big_operators open_locale non_zero_divisors section localization variables {R : Type*} (Rₛ : Type*) [comm_ring R] [comm_ring Rₛ] [algebra R Rₛ] variables (S : submonoid R) [hT : is_localization S Rₛ] include hT section add_comm_monoid variables {M : Type*} [add_comm_monoid M] [module R M] [module Rₛ M] [is_scalar_tower R Rₛ M] lemma linear_independent.localization {ι : Type*} {b : ι → M} (hli : linear_independent R b) : linear_independent Rₛ b := begin rw linear_independent_iff' at ⊢ hli, intros s g hg i hi, choose a g' hg' using is_localization.exist_integer_multiples S s g, letI := λ i, classical.prop_decidable (i ∈ s), specialize hli s (λ i, if hi : i ∈ s then g' i hi else 0) _ i hi, { rw [← @smul_zero _ M _ _ (a : R), ← hg, finset.smul_sum], refine finset.sum_congr rfl (λ i hi, _), dsimp only, rw [dif_pos hi, ← is_scalar_tower.algebra_map_smul Rₛ, hg' i hi, smul_assoc], apply_instance }, refine ((is_localization.map_units Rₛ a).mul_right_eq_zero).mp _, rw [← algebra.smul_def, ← map_zero (algebra_map R Rₛ), ← hli], simp [hi, hg'] end end add_comm_monoid section add_comm_group variables {M : Type*} [add_comm_group M] [module R M] [module Rₛ M] [is_scalar_tower R Rₛ M] /-- Promote a basis for `M` over `R` to a basis for `M` over the localization `Rₛ` -/ noncomputable def basis.localization {ι : Type*} (b : basis ι R M) : basis ι Rₛ M := basis.mk (b.linear_independent.localization Rₛ S) $ by { rw [← eq_top_iff, ← @submodule.restrict_scalars_eq_top_iff Rₛ R, eq_top_iff, ← b.span_eq], apply submodule.span_le_restrict_scalars } end add_comm_group end localization section fraction_ring variables (R K : Type*) [comm_ring R] [field K] [algebra R K] [is_fraction_ring R K] variables {V : Type*} [add_comm_group V] [module R V] [module K V] [is_scalar_tower R K V] lemma linear_independent.iff_fraction_ring {ι : Type*} {b : ι → V} : linear_independent R b ↔ linear_independent K b := ⟨linear_independent.localization K (R⁰), linear_independent.restrict_scalars (smul_left_injective R one_ne_zero)⟩ end fraction_ring