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
af24ec62393576ca1271edad25ca6e2d931a03a6
618003631150032a5676f229d13a079ac875ff77
/src/computability/primrec.lean
465c962e5bf151afe3bd42e2e0600c60e8fdbecc
[ "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
51,994
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.equiv.list /-! # 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 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 (function.swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (function.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 section prio set_option default_priority 100 -- see Note [default priority] /-- 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))) end prio 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 := (primcodable.prim α).of_eq $ λ n, show _ = encode (option.map e (option.map _ _)), by cases decode α n; simp 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₂ (function.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 [function.swap], cases e : p.1 - p.2 with n, { simp [nat.sub_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 snd fst 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 decode2 : primrec (decode2 α) := 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, {refl}, 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_le_right 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_concat]; 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_concat] 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.fin_equiv_subtype _) 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.decode2 α 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 $ by simp [set.range, option.eq_none_iff_forall_not_mem, encodable.mem_decode2] 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.decode2.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 (@fin.val 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 (nat.le_of_sub_eq_zero 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, {refl}, 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
91a5faa8052ce9b7eca3e8077de9b27ca33c83ea
675b8263050a5d74b89ceab381ac81ce70535688
/src/algebra/big_operators/order.lean
c743c181fbcdf312ba8529c3bc49435163cdf360
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,182
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 algebra.big_operators.basic /-! # Results about big operators with values in an ordered algebraic structure. Mostly monotonicity results for the `∑` operation. -/ universes u v w open_locale big_operators variables {α : Type u} {β : Type v} {γ : Type w} namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (∑ x in s, g x) ≤ ∑ x in s, f (g x) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [linear_ordered_field α] {f : β → α} {s : finset β} : abs (∑ x in s, f x) ≤ ∑ x in s, abs (f x) := le_sum_of_subadditive _ abs_zero abs_add s f lemma abs_prod [linear_ordered_comm_ring α] {f : β → α} {s : finset β} : abs (∏ x in s, f x) = ∏ x in s, abs (f x) := (abs_hom.to_monoid_hom : α →* α).map_prod _ _ section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → (∑ x in s, f x) ≤ (∑ x in s, g x) := begin classical, apply finset.induction_on s, exact (λ _, le_refl _), assume a s ha ih h, have : f a + (∑ x in s, f x) ≤ g a + (∑ x in s, g x), from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] end theorem card_le_mul_card_image_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * t.card := calc s.card = (∑ a in t, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_fiberwise Hf ... ≤ (∑ _ in t, n) : sum_le_sum hn ... = _ : by simp [mul_comm] theorem card_le_mul_card_image [decidable_eq γ] {f : α → γ} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := card_le_mul_card_image_of_maps_to (λ x, mem_image_of_mem _) n hn theorem mul_card_image_le_card_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, n ≤ (s.filter (λ x, f x = a)).card) : n * t.card ≤ s.card := calc n * t.card = (∑ _ in t, n) : by simp [mul_comm] ... ≤ (∑ a in t, (s.filter (λ x, f x = a)).card) : sum_le_sum hn ... = s.card : by rw ← card_eq_sum_card_fiberwise Hf theorem mul_card_image_le_card [decidable_eq γ] {f : α → γ} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, n ≤ (s.filter (λ x, f x = a)).card) : n * (s.image f).card ≤ s.card := mul_card_image_le_card_of_maps_to (λ x, mem_image_of_mem _) n hn lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ (∑ x in s, f x) := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : (∑ x in s, f x) ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := by classical; calc (∑ x in s₁, f x) ≤ (∑ x in s₂ \ s₁, f x) + (∑ x in s₁, f x) : le_add_of_nonneg_left $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = ∑ x in s₂ \ s₁ ∪ s₁, f x : (sum_union sdiff_disjoint).symm ... = (∑ x in s₂, f x) : by rw [sdiff_union_of_subset h] lemma sum_mono_set_of_nonneg (hf : ∀ x, 0 ≤ f x) : monotone (λ s, ∑ x in s, f x) := λ s₁ s₂ hs, sum_le_sum_of_subset_of_nonneg hs $ λ x _ _, hf x lemma sum_fiberwise_le_sum_of_sum_fiber_nonneg [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} {f : α → β} (h : ∀ y ∉ t, (0 : β) ≤ ∑ x in s.filter (λ x, g x = y), f x) : (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ ∑ x in s, f x := calc (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ (∑ y in t ∪ s.image g, ∑ x in s.filter (λ x, g x = y), f x) : sum_le_sum_of_subset_of_nonneg (subset_union_left _ _) $ λ y hyts, h y ... = ∑ x in s, f x : sum_fiberwise_of_maps_to (λ x hx, mem_union.2 $ or.inr $ mem_image_of_mem _ hx) _ lemma sum_le_sum_fiberwise_of_sum_fiber_nonpos [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} {f : α → β} (h : ∀ y ∉ t, (∑ x in s.filter (λ x, g x = y), f x) ≤ 0) : (∑ x in s, f x) ≤ ∑ y in t, ∑ x in s.filter (λ x, g x = y), f x := @sum_fiberwise_le_sum_of_sum_fiber_nonneg α (order_dual β) _ _ _ _ _ _ _ h lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) := begin classical, apply finset.induction_on s, exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩, assume a s ha ih H, have : ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] end lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ (∑ x in s, f x) := have ∑ x in {a}, f x ≤ (∑ x in s, f x), from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_add_comm_monoid section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid β] @[simp] lemma sum_eq_zero_iff : ∑ x in s, f x = 0 ↔ ∀ x ∈ s, f x = 0 := sum_eq_zero_iff_of_nonneg $ λ x hx, zero_le (f x) lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_mono_set (f : α → β) : monotone (λ s, ∑ x in s, f x) := λ s₁ s₂ hs, sum_le_sum_of_subset hs lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := by classical; calc (∑ x in s₁, f x) = ∑ x in s₁.filter (λx, f x = 0), f x + ∑ x in s₁.filter (λx, f x ≠ 0), f x : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ (∑ x in s₂, f x) : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_add_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_add_comm_monoid β] theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : (∑ x in s, f x) < (∑ x in s, g x) := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)], exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj) end lemma sum_lt_sum_of_nonempty (hs : s.nonempty) (Hlt : ∀ x ∈ s, f x < g x) : (∑ x in s, f x) < (∑ x in s, g x) := begin apply sum_lt_sum, { intros i hi, apply le_of_lt (Hlt i hi) }, cases hs with i hi, exact ⟨i, hi, Hlt i hi⟩, end lemma sum_lt_sum_of_subset [decidable_eq α] (h : s₁ ⊆ s₂) {i : α} (hi : i ∈ s₂ \ s₁) (hpos : 0 < f i) (hnonneg : ∀ j ∈ s₂ \ s₁, 0 ≤ f j) : (∑ x in s₁, f x) < (∑ x in s₂, f x) := calc (∑ x in s₁, f x) < (∑ x in insert i s₁, f x) : begin simp only [mem_sdiff] at hi, rw sum_insert hi.2, exact lt_add_of_pos_left (∑ x in s₁, f x) hpos, end ... ≤ (∑ x in s₂, f x) : begin simp only [mem_sdiff] at hi, apply sum_le_sum_of_subset_of_nonneg, { simp [finset.insert_subset, h, hi.1] }, { assume x hx h'x, apply hnonneg x, simp [mem_insert, not_or_distrib] at h'x, rw mem_sdiff, simp [hx, h'x] } end end ordered_cancel_comm_monoid section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_add_comm_monoid β] theorem exists_lt_of_sum_lt (Hlt : (∑ x in s, f x) < ∑ x in s, g x) : ∃ i ∈ s, f i < g i := begin contrapose! Hlt with Hle, exact sum_le_sum Hle end theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : (∑ x in s, f x) ≤ ∑ x in s, g x) : ∃ i ∈ s, f i ≤ g i := begin contrapose! Hle with Hlt, rcases hs with ⟨i, hi⟩, exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩ end lemma exists_pos_of_sum_zero_of_exists_nonzero (f : α → β) (h₁ : ∑ e in s, f e = 0) (h₂ : ∃ x ∈ s, f x ≠ 0) : ∃ x ∈ s, 0 < f x := begin contrapose! h₁, obtain ⟨x, m, x_nz⟩ : ∃ x ∈ s, f x ≠ 0 := h₂, apply ne_of_lt, calc ∑ e in s, f e < ∑ e in s, 0 : sum_lt_sum h₁ ⟨x, m, lt_of_le_of_ne (h₁ x m) x_nz⟩ ... = 0 : by rw [finset.sum_const, nsmul_zero], end end linear_ordered_cancel_comm_monoid section linear_ordered_comm_ring variables [linear_ordered_comm_ring β] open_locale classical /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ (∏ x in s, f x) := prod_induction f (λ x, 0 ≤ x) (λ _ _ ha hb, mul_nonneg ha hb) zero_le_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < (∏ x in s, f x) := prod_induction f (λ x, 0 < x) (λ _ _ ha hb, mul_pos ha hb) zero_lt_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : (∏ x in s, f x) ≤ (∏ x in s, g x) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end lemma prod_le_one {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ 1) : (∏ x in s, f x) ≤ 1 := begin convert ← prod_le_prod h0 h1, exact finset.prod_const_one end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `linear_ordered_comm_ring`. -/ lemma prod_add_prod_le {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) (hg : ∀ i ∈ s, 0 ≤ g i) (hh : ∀ i ∈ s, 0 ≤ h i) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin simp_rw [← mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_of_nonneg_right h2i _), { rw [right_distrib], apply add_le_add; apply mul_le_mul_of_nonneg_left; try { apply prod_le_prod }; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption }, { apply prod_nonneg, simp only [and_imp, mem_sdiff, mem_singleton], intros j h1j h2j, refine le_trans (hg j h1j) (hgf j h1j h2j) } end end linear_ordered_comm_ring section canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring β] lemma prod_le_prod' {s : finset α} {f g : α → β} (h : ∀ i ∈ s, f i ≤ g i) : (∏ x in s, f x) ≤ (∏ x in s, g x) := begin classical, induction s using finset.induction with a s has ih h, { simp }, { rw [finset.prod_insert has, finset.prod_insert has], apply canonically_ordered_semiring.mul_le_mul, { exact h _ (finset.mem_insert_self a s) }, { exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } } end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `canonically_ordered_comm_semiring`. -/ lemma prod_add_prod_le' {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin classical, simp_rw [← mul_prod_diff_singleton hi], refine le_trans _ (canonically_ordered_semiring.mul_le_mul_right' h2i _), rw [right_distrib], apply add_le_add; apply canonically_ordered_semiring.mul_le_mul_left'; apply prod_le_prod'; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption end end canonically_ordered_comm_semiring end finset namespace with_top open finset open_locale classical /-- A sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_add_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → (∑ x in s, f x) < ⊤ := λ h, sum_induction f (λ a, a < ⊤) (by { simp_rw add_lt_top, tauto }) zero_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : (∑ x in s, f x) < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : (∑ x in s, f x) = ⊤ ↔ (∃a∈s, f a = ⊤) := begin rw ← not_iff_not, push_neg, simp only [← lt_top_iff_ne_top], exact sum_lt_top_iff end end with_top
64f45b2b84bba8dde7e97673e1cd5d37aa3a35e7
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/computability/NFA.lean
41e194ea2dded0a777c50110a7179622edd5ea44
[ "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
4,103
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import computability.DFA /-! # Nondeterministic Finite Automata This file contains the definition of a Nondeterministic Finite Automaton (NFA), a state machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set by evaluating the string over every possible path. We show that DFA's are equivalent to NFA's however the construction from NFA to DFA uses an exponential number of states. Note that this definition allows for Automaton with infinite states, a `fintype` instance must be supplied for true NFA's. -/ universes u v /-- An NFA is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). Note the transition function sends a state to a `set` of states. These are the states that it may be sent to. -/ structure NFA (α : Type u) (σ : Type v) := (step : σ → α → set σ) (start : set σ) (accept : set σ) variables {α : Type u} {σ σ' : Type v} (M : NFA α σ) namespace NFA instance : inhabited (NFA α σ) := ⟨ NFA.mk (λ _ _, ∅) ∅ ∅ ⟩ /-- `M.step_set S a` is the union of `M.step s a` for all `s ∈ S`. -/ def step_set : set σ → α → set σ := λ Ss a, Ss >>= (λ S, (M.step S a)) lemma mem_step_set (s : σ) (S : set σ) (a : α) : s ∈ M.step_set S a ↔ ∃ t ∈ S, s ∈ M.step t a := by simp only [step_set, set.mem_Union, set.bind_def] /-- `M.eval_from S x` computes all possible paths though `M` with input `x` starting at an element of `S`. -/ def eval_from (start : set σ) : list α → set σ := list.foldl M.step_set start /-- `M.eval x` computes all possible paths though `M` with input `x` starting at an element of `M.start`. -/ def eval := M.eval_from M.start /-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/ def accepts : language α := λ x, ∃ S ∈ M.accept, S ∈ M.eval x /-- `M.to_DFA` is an `DFA` constructed from a `NFA` `M` using the subset construction. The states is the type of `set`s of `M.state` and the step function is `M.step_set`. -/ def to_DFA : DFA α (set σ) := { step := M.step_set, start := M.start, accept := {S | ∃ s ∈ S, s ∈ M.accept} } @[simp] lemma to_DFA_correct : M.to_DFA.accepts = M.accepts := begin ext x, rw [accepts, DFA.accepts, eval, DFA.eval], change list.foldl _ _ _ ∈ {S | _} ↔ _, finish end lemma pumping_lemma [fintype σ] {x : list α} (hx : x ∈ M.accepts) (hlen : fintype.card (set σ) ≤ list.length x) : ∃ a b c, x = a ++ b ++ c ∧ a.length + b.length ≤ fintype.card (set σ) ∧ b ≠ [] ∧ {a} * language.star {b} * {c} ≤ M.accepts := begin rw ←to_DFA_correct at hx ⊢, exact M.to_DFA.pumping_lemma hx hlen end end NFA namespace DFA /-- `M.to_NFA` is an `NFA` constructed from a `DFA` `M` by using the same start and accept states and a transition function which sends `s` with input `a` to the singleton `M.step s a`. -/ def to_NFA (M : DFA α σ') : NFA α σ' := { step := λ s a, {M.step s a}, start := {M.start}, accept := M.accept } @[simp] lemma to_NFA_eval_from_match (M : DFA α σ) (start : σ) (s : list α) : M.to_NFA.eval_from {start} s = {M.eval_from start s} := begin change list.foldl M.to_NFA.step_set {start} s = {list.foldl M.step start s}, induction s with a s ih generalizing start, { tauto }, { rw [list.foldl, list.foldl], have h : M.to_NFA.step_set {start} a = {M.step start a}, { rw NFA.step_set, finish }, rw h, tauto } end @[simp] lemma to_NFA_correct (M : DFA α σ) : M.to_NFA.accepts = M.accepts := begin ext x, change (∃ S H, S ∈ M.to_NFA.eval_from {M.start} x) ↔ _, rw to_NFA_eval_from_match, split, { rintro ⟨ S, hS₁, hS₂ ⟩, rw set.mem_singleton_iff at hS₂, rw hS₂ at hS₁, assumption }, { intro h, use M.eval x, finish } end end DFA
c685a605dab9aa26e120e002cd91802ccd02247e
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/module/ordered.lean
2b839528e34c1c80342bfc0eb629f6d7f6780f0d
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,122
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 algebra.module.pi import algebra.ordered_smul import algebra.module.prod import algebra.ordered_field /-! # Ordered module In this file we provide lemmas about `ordered_smul` that hold once a module structure is present. ## References * https://en.wikipedia.org/wiki/Ordered_module ## Tags ordered module, ordered scalar, ordered smul, ordered action, ordered vector space -/ variables {k M N : Type*} section field variables [linear_ordered_field k] [ordered_add_comm_group M] [module k M] [ordered_smul k M] [ordered_add_comm_group N] [module k N] [ordered_smul k N] lemma smul_le_smul_iff_of_neg {a b : M} {c : k} (hc : c < 0) : c • a ≤ c • b ↔ b ≤ a := begin rw [← neg_neg c, neg_smul, neg_smul (-c), neg_le_neg_iff, smul_le_smul_iff_of_pos (neg_pos.2 hc)], apply_instance, end -- TODO: solve `prod.has_lt` and `prod.has_le` misalignment issue instance prod.ordered_smul : ordered_smul k (M × N) := ordered_smul.mk' $ λ (v u : M × N) (c : k) h hc, ⟨smul_le_smul_of_nonneg h.1.1 hc.le, smul_le_smul_of_nonneg h.1.2 hc.le⟩ instance pi.ordered_smul {ι : Type*} {M : ι → Type*} [Π i, ordered_add_comm_group (M i)] [Π i, mul_action_with_zero k (M i)] [∀ i, ordered_smul k (M i)] : ordered_smul k (Π i : ι, M i) := begin refine (ordered_smul.mk' $ λ v u c h hc i, _), change c • v i ≤ c • u i, exact smul_le_smul_of_nonneg (h.le i) hc.le, end -- Sometimes Lean fails to apply the dependent version to non-dependent functions, -- so we define another instance instance pi.ordered_smul' {ι : Type*} {M : Type*} [ordered_add_comm_group M] [mul_action_with_zero k M] [ordered_smul k M] : ordered_smul k (ι → M) := pi.ordered_smul end field namespace order_dual instance [semiring k] [ordered_add_comm_monoid M] [module k M] : module k (order_dual M) := { add_smul := λ r s x, order_dual.rec (add_smul _ _) x, zero_smul := λ m, order_dual.rec (zero_smul _) m } end order_dual
6716d27c92d3c7134f0e1fcf7a564dc81f5ecde0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/algebra/operations.lean
ce6aee3a6aacfb1e805c86d0d6bab0c3cc9896ca
[ "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
16,561
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.algebra.bilinear import algebra.module.submodule_pointwise /-! # Multiplication and division of submodules of an algebra. An interface for multiplication and division of sub-R-modules of an R-algebra A is developed. ## Main definitions Let `R` be a commutative ring (or semiring) and aet `A` be an `R`-algebra. * `1 : submodule R A` : the R-submodule R of the R-algebra A * `has_mul (submodule R A)` : multiplication of two sub-R-modules M and N of A is defined to be the smallest submodule containing all the products `m * n`. * `has_div (submodule R A)` : `I / J` is defined to be the submodule consisting of all `a : A` such that `a • J ⊆ I` It is proved that `submodule R A` is a semiring, and also an algebra over `set A`. ## Tags multiplication of submodules, division of subodules, submodule semiring -/ universes uι u v open algebra set open_locale big_operators open_locale pointwise namespace submodule variables {ι : Sort uι} variables {R : Type u} [comm_semiring R] section ring variables {A : Type v} [semiring A] [algebra R A] variables (S T : set A) {M N P Q : submodule R A} {m n : A} /-- `1 : submodule R A` is the submodule R of A. -/ instance : has_one (submodule R A) := ⟨(algebra.linear_map R A).range⟩ theorem one_eq_range : (1 : submodule R A) = (algebra.linear_map R A).range := rfl lemma algebra_map_mem (r : R) : algebra_map R A r ∈ (1 : submodule R A) := linear_map.mem_range_self _ _ @[simp] lemma mem_one {x : A} : x ∈ (1 : submodule R A) ↔ ∃ y, algebra_map R A y = x := by simp only [one_eq_range, linear_map.mem_range, algebra.linear_map_apply] theorem one_eq_span : (1 : submodule R A) = R ∙ 1 := begin apply submodule.ext, intro a, simp only [mem_one, mem_span_singleton, algebra.smul_def, mul_one] end theorem one_le : (1 : submodule R A) ≤ P ↔ (1 : A) ∈ P := by simpa only [one_eq_span, span_le, set.singleton_subset_iff] /-- Multiplication of sub-R-modules of an R-algebra A. The submodule `M * N` is the smallest R-submodule of `A` containing the elements `m * n` for `m ∈ M` and `n ∈ N`. -/ instance : has_mul (submodule R A) := ⟨λ M N, ⨆ s : M, N.map $ algebra.lmul R A s.1⟩ theorem mul_mem_mul (hm : m ∈ M) (hn : n ∈ N) : m * n ∈ M * N := (le_supr _ ⟨m, hm⟩ : _ ≤ M * N) ⟨n, hn, rfl⟩ theorem mul_le : M * N ≤ P ↔ ∀ (m ∈ M) (n ∈ N), m * n ∈ P := ⟨λ H m hm n hn, H $ mul_mem_mul hm hn, λ H, supr_le $ λ ⟨m, hm⟩, map_le_iff_le_comap.2 $ λ n hn, H m hm n hn⟩ lemma mul_to_add_submonoid : (M * N).to_add_submonoid = M.to_add_submonoid * N.to_add_submonoid := begin dsimp [has_mul.mul], simp_rw [←algebra.lmul_left_to_add_monoid_hom R, algebra.lmul_left, ←map_to_add_submonoid], rw supr_to_add_submonoid, refl, end @[elab_as_eliminator] protected theorem mul_induction_on {C : A → Prop} {r : A} (hr : r ∈ M * N) (hm : ∀ (m ∈ M) (n ∈ N), C (m * n)) (ha : ∀ x y, C x → C y → C (x + y)) : C r := begin rw [←mem_to_add_submonoid, mul_to_add_submonoid] at hr, exact add_submonoid.mul_induction_on hr hm ha, end /-- A dependent version of `mul_induction_on`. -/ @[elab_as_eliminator] protected theorem mul_induction_on' {C : Π r, r ∈ M * N → Prop} (hm : ∀ (m ∈ M) (n ∈ N), C (m * n) (mul_mem_mul ‹_› ‹_›)) (ha : ∀ x hx y hy, C x hx → C y hy → C (x + y) (add_mem _ ‹_› ‹_›)) {r : A} (hr : r ∈ M * N) : C r hr := begin refine exists.elim _ (λ (hr : r ∈ M * N) (hc : C r hr), hc), exact submodule.mul_induction_on hr (λ x hx y hy, ⟨_, hm _ hx _ hy⟩) (λ x y ⟨_, hx⟩ ⟨_, hy⟩, ⟨_, ha _ _ _ _ hx hy⟩), end variables R theorem span_mul_span : span R S * span R T = span R (S * T) := begin apply le_antisymm, { rw mul_le, intros a ha b hb, apply span_induction ha, work_on_goal 0 { intros, apply span_induction hb, work_on_goal 0 { intros, exact subset_span ⟨_, _, ‹_›, ‹_›, rfl⟩ } }, all_goals { intros, simp only [mul_zero, zero_mul, zero_mem, left_distrib, right_distrib, mul_smul_comm, smul_mul_assoc], try {apply add_mem _ _ _}, try {apply smul_mem _ _ _} }, assumption' }, { rw span_le, rintros _ ⟨a, b, ha, hb, rfl⟩, exact mul_mem_mul (subset_span ha) (subset_span hb) } end variables {R} variables (M N P Q) protected theorem mul_assoc : (M * N) * P = M * (N * P) := le_antisymm (mul_le.2 $ λ mn hmn p hp, suffices M * N ≤ (M * (N * P)).comap (algebra.lmul_right R p), from this hmn, mul_le.2 $ λ m hm n hn, show m * n * p ∈ M * (N * P), from (mul_assoc m n p).symm ▸ mul_mem_mul hm (mul_mem_mul hn hp)) (mul_le.2 $ λ m hm np hnp, suffices N * P ≤ (M * N * P).comap (algebra.lmul_left R m), from this hnp, mul_le.2 $ λ n hn p hp, show m * (n * p) ∈ M * N * P, from mul_assoc m n p ▸ mul_mem_mul (mul_mem_mul hm hn) hp) @[simp] theorem mul_bot : M * ⊥ = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hn ⊢; rw [hn, mul_zero] @[simp] theorem bot_mul : ⊥ * M = ⊥ := eq_bot_iff.2 $ mul_le.2 $ λ m hm n hn, by rw [submodule.mem_bot] at hm ⊢; rw [hm, zero_mul] @[simp] protected theorem one_mul : (1 : submodule R A) * M = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, one_mul, span_eq] } @[simp] protected theorem mul_one : M * 1 = M := by { conv_lhs { rw [one_eq_span, ← span_eq M] }, erw [span_mul_span, mul_one, span_eq] } variables {M N P Q} @[mono] theorem mul_le_mul (hmp : M ≤ P) (hnq : N ≤ Q) : M * N ≤ P * Q := mul_le.2 $ λ m hm n hn, mul_mem_mul (hmp hm) (hnq hn) theorem mul_le_mul_left (h : M ≤ N) : M * P ≤ N * P := mul_le_mul h (le_refl P) theorem mul_le_mul_right (h : N ≤ P) : M * N ≤ M * P := mul_le_mul (le_refl M) h variables (M N P) theorem mul_sup : M * (N ⊔ P) = M * N ⊔ M * P := le_antisymm (mul_le.2 $ λ m hm np hnp, let ⟨n, hn, p, hp, hnp⟩ := mem_sup.1 hnp in mem_sup.2 ⟨_, mul_mem_mul hm hn, _, mul_mem_mul hm hp, hnp ▸ (mul_add m n p).symm⟩) (sup_le (mul_le_mul_right le_sup_left) (mul_le_mul_right le_sup_right)) theorem sup_mul : (M ⊔ N) * P = M * P ⊔ N * P := le_antisymm (mul_le.2 $ λ mn hmn p hp, let ⟨m, hm, n, hn, hmn⟩ := mem_sup.1 hmn in mem_sup.2 ⟨_, mul_mem_mul hm hp, _, mul_mem_mul hn hp, hmn ▸ (add_mul m n p).symm⟩) (sup_le (mul_le_mul_left le_sup_left) (mul_le_mul_left le_sup_right)) lemma mul_subset_mul : (↑M : set A) * (↑N : set A) ⊆ (↑(M * N) : set A) := by { rintros _ ⟨i, j, hi, hj, rfl⟩, exact mul_mem_mul hi hj } lemma map_mul {A'} [semiring A'] [algebra R A'] (f : A →ₐ[R] A') : map f.to_linear_map (M * N) = map f.to_linear_map M * map f.to_linear_map N := calc map f.to_linear_map (M * N) = ⨆ (i : M), (N.map (lmul R A i)).map f.to_linear_map : map_supr _ _ ... = map f.to_linear_map M * map f.to_linear_map N : begin apply congr_arg Sup, ext S, split; rintros ⟨y, hy⟩, { use [f y, mem_map.mpr ⟨y.1, y.2, rfl⟩], refine trans _ hy, ext, simp }, { obtain ⟨y', hy', fy_eq⟩ := mem_map.mp y.2, use [y', hy'], refine trans _ hy, rw f.to_linear_map_apply at fy_eq, ext, simp [fy_eq] } end section decidable_eq open_locale classical lemma mem_span_mul_finite_of_mem_span_mul {S : set A} {S' : set A} {x : A} (hx : x ∈ span R (S * S')) : ∃ (T T' : finset A), ↑T ⊆ S ∧ ↑T' ⊆ S' ∧ x ∈ span R (T * T' : set A) := begin obtain ⟨U, h, hU⟩ := mem_span_finite_of_mem_span hx, obtain ⟨T, T', hS, hS', h⟩ := finset.subset_mul h, use [T, T', hS, hS'], have h' : (U : set A) ⊆ T * T', { assumption_mod_cast, }, have h'' := span_mono h' hU, assumption, end end decidable_eq lemma mul_eq_span_mul_set (s t : submodule R A) : s * t = span R ((s : set A) * (t : set A)) := by rw [← span_mul_span, span_eq, span_eq] lemma supr_mul (s : ι → submodule R A) (t : submodule R A) : (⨆ i, s i) * t = ⨆ i, s i * t := begin suffices : (⨆ i, span R (s i : set A)) * span R t = (⨆ i, span R (s i) * span R t), { simpa only [span_eq] using this }, simp_rw [span_mul_span, ← span_Union, span_mul_span, set.Union_mul], end lemma mul_supr (t : submodule R A) (s : ι → submodule R A) : t * (⨆ i, s i) = ⨆ i, t * s i := begin suffices : span R (t : set A) * (⨆ i, span R (s i)) = (⨆ i, span R t * span R (s i)), { simpa only [span_eq] using this }, simp_rw [span_mul_span, ← span_Union, span_mul_span, set.mul_Union], end lemma mem_span_mul_finite_of_mem_mul {P Q : submodule R A} {x : A} (hx : x ∈ P * Q) : ∃ (T T' : finset A), (T : set A) ⊆ P ∧ (T' : set A) ⊆ Q ∧ x ∈ span R (T * T' : set A) := submodule.mem_span_mul_finite_of_mem_span_mul (by rwa [← submodule.span_eq P, ← submodule.span_eq Q, submodule.span_mul_span] at hx) variables {M N P} /-- Sub-R-modules of an R-algebra form a semiring. -/ instance : semiring (submodule R A) := { one_mul := submodule.one_mul, mul_one := submodule.mul_one, mul_assoc := submodule.mul_assoc, zero_mul := bot_mul, mul_zero := mul_bot, left_distrib := mul_sup, right_distrib := sup_mul, ..submodule.pointwise_add_comm_monoid, ..submodule.has_one, ..submodule.has_mul } variables (M) lemma pow_subset_pow {n : ℕ} : (↑M : set A)^n ⊆ ↑(M^n : submodule R A) := begin induction n with n ih, { erw [pow_zero, pow_zero, set.singleton_subset_iff], rw [set_like.mem_coe, ← one_le], exact le_rfl }, { rw [pow_succ, pow_succ], refine set.subset.trans (set.mul_subset_mul (subset.refl _) ih) _, apply mul_subset_mul } end /-- Dependent version of `submodule.pow_induction_on`. -/ protected theorem pow_induction_on' {C : Π (n : ℕ) x, x ∈ M ^ n → Prop} (hr : ∀ r : R, C 0 (algebra_map _ _ r) (algebra_map_mem r)) (hadd : ∀ x y i hx hy, C i x hx → C i y hy → C i (x + y) (add_mem _ ‹_› ‹_›)) (hmul : ∀ (m ∈ M) i x hx, C i x hx → C (i.succ) (m * x) (mul_mem_mul H hx)) {x : A} {n : ℕ} (hx : x ∈ M ^ n) : C n x hx := begin induction n with n n_ih generalizing x, { rw pow_zero at hx, obtain ⟨r, rfl⟩ := hx, exact hr r, }, exact submodule.mul_induction_on' (λ m hm x ih, hmul _ hm _ _ _ (n_ih ih)) (λ x hx y hy Cx Cy, hadd _ _ _ _ _ Cx Cy) hx, end /-- To show a property on elements of `M ^ n` holds, it suffices to show that it holds for scalars, is closed under addition, and holds for `m * x` where `m ∈ M` and it holds for `x` -/ protected theorem pow_induction_on {C : A → Prop} (hr : ∀ r : R, C (algebra_map _ _ r)) (hadd : ∀ x y, C x → C y → C (x + y)) (hmul : ∀ (m ∈ M) x, C x → C (m * x)) {x : A} {n : ℕ} (hx : x ∈ M ^ n) : C x := submodule.pow_induction_on' M (by exact hr) (λ x y i hx hy, hadd x y) (λ m hm i x hx, hmul _ hm _) hx /-- `span` is a semiring homomorphism (recall multiplication is pointwise multiplication of subsets on either side). -/ def span.ring_hom : set_semiring A →+* submodule R A := { to_fun := submodule.span R, map_zero' := span_empty, map_one' := one_eq_span.symm, map_add' := span_union, map_mul' := λ s t, by erw [span_mul_span, ← image_mul_prod] } end ring section comm_ring variables {A : Type v} [comm_semiring A] [algebra R A] variables {M N : submodule R A} {m n : A} theorem mul_mem_mul_rev (hm : m ∈ M) (hn : n ∈ N) : n * m ∈ M * N := mul_comm m n ▸ mul_mem_mul hm hn variables (M N) protected theorem mul_comm : M * N = N * M := le_antisymm (mul_le.2 $ λ r hrm s hsn, mul_mem_mul_rev hsn hrm) (mul_le.2 $ λ r hrn s hsm, mul_mem_mul_rev hsm hrn) /-- Sub-R-modules of an R-algebra A form a semiring. -/ instance : comm_semiring (submodule R A) := { mul_comm := submodule.mul_comm, .. submodule.semiring } lemma prod_span {ι : Type*} (s : finset ι) (M : ι → set A) : (∏ i in s, submodule.span R (M i)) = submodule.span R (∏ i in s, M i) := begin letI := classical.dec_eq ι, refine finset.induction_on s _ _, { simp [one_eq_span, set.singleton_one] }, { intros _ _ H ih, rw [finset.prod_insert H, finset.prod_insert H, ih, span_mul_span] } end lemma prod_span_singleton {ι : Type*} (s : finset ι) (x : ι → A) : (∏ i in s, span R ({x i} : set A)) = span R {∏ i in s, x i} := by rw [prod_span, set.finset_prod_singleton] variables (R A) /-- R-submodules of the R-algebra A are a module over `set A`. -/ instance module_set : module (set_semiring A) (submodule R A) := { smul := λ s P, span R s * P, smul_add := λ _ _ _, mul_add _ _ _, add_smul := λ s t P, show span R (s ⊔ t) * P = _, by { erw [span_union, right_distrib] }, mul_smul := λ s t P, show _ = _ * (_ * _), by { rw [← mul_assoc, span_mul_span, ← image_mul_prod] }, one_smul := λ P, show span R {(1 : A)} * P = _, by { conv_lhs {erw ← span_eq P}, erw [span_mul_span, one_mul, span_eq] }, zero_smul := λ P, show span R ∅ * P = ⊥, by erw [span_empty, bot_mul], smul_zero := λ _, mul_bot _ } variables {R A} lemma smul_def {s : set_semiring A} {P : submodule R A} : s • P = span R s * P := rfl lemma smul_le_smul {s t : set_semiring A} {M N : submodule R A} (h₁ : s.down ≤ t.down) (h₂ : M ≤ N) : s • M ≤ t • N := mul_le_mul (span_mono h₁) h₂ lemma smul_singleton (a : A) (M : submodule R A) : ({a} : set A).up • M = M.map (lmul_left _ a) := begin conv_lhs {rw ← span_eq M}, change span _ _ * span _ _ = _, rw [span_mul_span], apply le_antisymm, { rw span_le, rintros _ ⟨b, m, hb, hm, rfl⟩, rw [set_like.mem_coe, mem_map, set.mem_singleton_iff.mp hb], exact ⟨m, hm, rfl⟩ }, { rintros _ ⟨m, hm, rfl⟩, exact subset_span ⟨a, m, set.mem_singleton a, hm, rfl⟩ } end section quotient /-- The elements of `I / J` are the `x` such that `x • J ⊆ I`. In fact, we define `x ∈ I / J` to be `∀ y ∈ J, x * y ∈ I` (see `mem_div_iff_forall_mul_mem`), which is equivalent to `x • J ⊆ I` (see `mem_div_iff_smul_subset`), but nicer to use in proofs. This is the general form of the ideal quotient, traditionally written $I : J$. -/ instance : has_div (submodule R A) := ⟨ λ I J, { carrier := { x | ∀ y ∈ J, x * y ∈ I }, zero_mem' := λ y hy, by { rw zero_mul, apply submodule.zero_mem }, add_mem' := λ a b ha hb y hy, by { rw add_mul, exact submodule.add_mem _ (ha _ hy) (hb _ hy) }, smul_mem' := λ r x hx y hy, by { rw algebra.smul_mul_assoc, exact submodule.smul_mem _ _ (hx _ hy) } } ⟩ lemma mem_div_iff_forall_mul_mem {x : A} {I J : submodule R A} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := iff.refl _ lemma mem_div_iff_smul_subset {x : A} {I J : submodule R A} : x ∈ I / J ↔ x • (J : set A) ⊆ I := ⟨ λ h y ⟨y', hy', xy'_eq_y⟩, by { rw ← xy'_eq_y, apply h, assumption }, λ h y hy, h (set.smul_mem_smul_set hy) ⟩ lemma le_div_iff {I J K : submodule R A} : I ≤ J / K ↔ ∀ (x ∈ I) (z ∈ K), x * z ∈ J := iff.refl _ lemma le_div_iff_mul_le {I J K : submodule R A} : I ≤ J / K ↔ I * K ≤ J := by rw [le_div_iff, mul_le] @[simp] lemma one_le_one_div {I : submodule R A} : 1 ≤ 1 / I ↔ I ≤ 1 := begin split, all_goals {intro hI}, {rwa [le_div_iff_mul_le, one_mul] at hI}, {rwa [le_div_iff_mul_le, one_mul]}, end lemma le_self_mul_one_div {I : submodule R A} (hI : I ≤ 1) : I ≤ I * (1 / I) := begin rw [← mul_one I] {occs := occurrences.pos [1]}, apply mul_le_mul_right (one_le_one_div.mpr hI), end lemma mul_one_div_le_one {I : submodule R A} : I * (1 / I) ≤ 1 := begin rw submodule.mul_le, intros m hm n hn, rw [submodule.mem_div_iff_forall_mul_mem] at hn, rw mul_comm, exact hn m hm, end @[simp] lemma map_div {B : Type*} [comm_ring B] [algebra R B] (I J : submodule R A) (h : A ≃ₐ[R] B) : (I / J).map h.to_linear_map = I.map h.to_linear_map / J.map h.to_linear_map := begin ext x, simp only [mem_map, mem_div_iff_forall_mul_mem], split, { rintro ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩, exact ⟨x * y, hx _ hy, h.map_mul x y⟩ }, { rintro hx, refine ⟨h.symm x, λ z hz, _, h.apply_symm_apply x⟩, obtain ⟨xz, xz_mem, hxz⟩ := hx (h z) ⟨z, hz, rfl⟩, convert xz_mem, apply h.injective, erw [h.map_mul, h.apply_symm_apply, hxz] } end end quotient end comm_ring end submodule
2d297cd44076c57622e4ddabf17c356718ba5699
4e3bf8e2b29061457a887ac8889e88fa5aa0e34c
/lean/love06_monads_homework_sheet.lean
63f047997f2a8d11c06c1d0ffddea78c303e8ee3
[]
no_license
mukeshtiwari/logical_verification_2019
9f964c067a71f65eb8884743273fbeef99e6503d
16f62717f55ed5b7b87e03ae0134791a9bef9b9a
refs/heads/master
1,619,158,844,208
1,585,139,500,000
1,585,139,500,000
249,906,380
0
0
null
1,585,118,728,000
1,585,118,727,000
null
UTF-8
Lean
false
false
3,124
lean
/- LoVe Homework 6: Monads -/ import .lovelib namespace LoVe /- Question 1: `map` for Monads Define `map` for monads. This is the generalization of `map` on lists. Use the monad operations to define `map`. The functorial properties (`map_id` and `map_map`) are derived from the monad laws. This time, we use Lean's monad definition. In combination, `monad` and `is_lawful_monad` include the same constants, laws, and syntactic sugar as the `lawful_monad` type class from the lecture. -/ section map /- We fix a lawful monad `m`: -/ variables {m : Type → Type} [monad m] [is_lawful_monad m] /- 1.1. Define `map` on `m`. **Hint:** The challenge is to find a way to create `m β`. Follow the types. One way to proceed is to list all the arguments and operations available (e.g., `pure`, `>>=`) with their types and see if you can plug them together like Lego blocks. -/ def map {α β} (f : α → β) (ma : m α) : m β := := sorry /- 1.2. Prove the identity law for `map`. **Hint**: You will need the `bind_pure` property of monads. -/ lemma map_id {α} (ma : m α) : map id ma = ma := sorry /- 1.3. Prove the composition law for `map`. -/ lemma map_map {α β γ} (f : α → β) (g : β → γ) (ma : m α) : map g (map f ma) = map (g ∘ f) ma := sorry end map /- Question 2 **optional**: Monadic Structure on Lists -/ /- `list` can be seen as a monad, similar to `option` but with several possible outcomes. It is also similar to `set`, but the results are ordered and finite. The code below sets `list` up as a monad. -/ namespace list protected def bind {α β : Type} : list α → (α → list β) → list β | [] f := [] | (a :: as) f := f a ++ bind as f protected def pure {α : Type} (a : α) : list α := [a] lemma pure_eq_singleton {α : Type} (a : α) : pure a = [a] := by refl instance : monad list := { pure := @list.pure, bind := @list.bind } /- 2.1 **optional**. Prove the following properties of `bind` under the empty list (`[]`), the list constructor (`::`), and `++`. -/ @[simp] lemma bind_nil {α β : Type} (f : α → list β) : [] >>= f = [] := sorry @[simp] lemma bind_cons {α β : Type} (f : α → list β) (a : α) (as : list α) : list.cons a as >>= f = f a ++ (as >>= f) := sorry @[simp] lemma bind_append {α β : Type} (f : α → list β) : ∀as as' : list α, (as ++ as') >>= f = (as >>= f) ++ (as' >>= f) := sorry /- 2.2. Prove the monadic laws for `list`. **Hint:** The simplifier cannot see through the type class definition of `pure`. You can use `pure_eq_singleton` to unfold the definition or `show` to state the lemma statement using `bind` and `[…]`. -/ lemma pure_bind {α β : Type} (a : α) (f : α → list β) : (pure a >>= f) = f a := sorry lemma bind_pure {α : Type} : ∀as : list α, as >>= pure = as := sorry lemma bind_assoc {α β γ : Type} (f : α → list β) (g : β → list γ) : ∀as : list α, (as >>= f) >>= g = as >>= (λa, f a >>= g) := sorry lemma bind_pure_comp_eq_map {α β : Type} {f : α → β} : ∀as : list α, as >>= (pure ∘ f) = list.map f as := sorry end list end LoVe
fbe263b13f3d711548d1ef0454fae5ce0422d155
3c9dc4ea6cc92e02634ef557110bde9eae393338
/src/Lean/LocalContext.lean
5f8b43f8dffa48ff9605fe37ad535e8efdfa95e1
[ "Apache-2.0" ]
permissive
shingtaklam1324/lean4
3d7efe0c8743a4e33d3c6f4adbe1300df2e71492
351285a2e8ad0cef37af05851cfabf31edfb5970
refs/heads/master
1,676,827,679,740
1,610,462,623,000
1,610,552,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,854
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 Std.Data.PersistentArray import Lean.Expr import Lean.Hygiene namespace Lean inductive LocalDecl where | cdecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) | ldecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep : Bool) deriving Inhabited @[export lean_mk_local_decl] def mkLocalDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) : LocalDecl := LocalDecl.cdecl index fvarId userName type bi @[export lean_mk_let_decl] def mkLetDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : LocalDecl := LocalDecl.ldecl index fvarId userName type val false @[export lean_local_decl_binder_info] def LocalDecl.binderInfoEx : LocalDecl → BinderInfo | LocalDecl.cdecl _ _ _ _ bi => bi | _ => BinderInfo.default namespace LocalDecl def isLet : LocalDecl → Bool | cdecl .. => false | ldecl .. => true def index : LocalDecl → Nat | cdecl (index := i) .. => i | ldecl (index := i) .. => i def setIndex : LocalDecl → Nat → LocalDecl | cdecl _ id n t bi, idx => cdecl idx id n t bi | ldecl _ id n t v nd, idx => ldecl idx id n t v nd def fvarId : LocalDecl → FVarId | cdecl (fvarId := id) .. => id | ldecl (fvarId := id) .. => id def userName : LocalDecl → Name | cdecl (userName := n) .. => n | ldecl (userName := n) .. => n def type : LocalDecl → Expr | cdecl (type := t) .. => t | ldecl (type := t) .. => t def setType : LocalDecl → Expr → LocalDecl | cdecl idx id n _ bi, t => cdecl idx id n t bi | ldecl idx id n _ v nd, t => ldecl idx id n t v nd def binderInfo : LocalDecl → BinderInfo | cdecl (bi := bi) .. => bi | ldecl .. => BinderInfo.default def isAuxDecl (d : LocalDecl) : Bool := d.binderInfo.isAuxDecl def value? : LocalDecl → Option Expr | cdecl .. => none | ldecl (value := v) .. => some v def value : LocalDecl → Expr | cdecl .. => panic! "let declaration expected" | ldecl (value := v) .. => v def setValue : LocalDecl → Expr → LocalDecl | ldecl idx id n t _ nd, v => ldecl idx id n t v nd | d, _ => d def updateUserName : LocalDecl → Name → LocalDecl | cdecl index id _ type bi, userName => cdecl index id userName type bi | ldecl index id _ type val nd, userName => ldecl index id userName type val nd def updateBinderInfo : LocalDecl → BinderInfo → LocalDecl | cdecl index id n type _, bi => cdecl index id n type bi | ldecl .., _ => panic! "unexpected let declaration" def toExpr (decl : LocalDecl) : Expr := mkFVar decl.fvarId def hasExprMVar : LocalDecl → Bool | cdecl (type := t) .. => t.hasExprMVar | ldecl (type := t) (value := v) .. => t.hasExprMVar || v.hasExprMVar end LocalDecl open Std (PersistentHashMap PersistentArray PArray) structure LocalContext where fvarIdToDecl : PersistentHashMap FVarId LocalDecl := {} decls : PersistentArray (Option LocalDecl) := {} deriving Inhabited namespace LocalContext @[export lean_mk_empty_local_ctx] def mkEmpty : Unit → LocalContext := fun _ => {} def empty : LocalContext := {} @[export lean_local_ctx_is_empty] def isEmpty (lctx : LocalContext) : Bool := lctx.fvarIdToDecl.isEmpty /- Low level API for creating local declarations. It is used to implement actions in the monads `Elab` and `Tactic`. It should not be used directly since the argument `(name : Name)` is assumed to be "unique". -/ @[export lean_local_ctx_mk_local_decl] def mkLocalDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo := BinderInfo.default) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let decl := LocalDecl.cdecl idx fvarId userName type bi { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } @[export lean_local_ctx_mk_let_decl] def mkLetDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep := false) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let decl := LocalDecl.ldecl idx fvarId userName type value nonDep { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } /- Low level API -/ def addDecl (lctx : LocalContext) (newDecl : LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let newDecl := newDecl.setIndex idx { fvarIdToDecl := map.insert newDecl.fvarId newDecl, decls := decls.push newDecl } @[export lean_local_ctx_find] def find? (lctx : LocalContext) (fvarId : FVarId) : Option LocalDecl := lctx.fvarIdToDecl.find? fvarId def findFVar? (lctx : LocalContext) (e : Expr) : Option LocalDecl := lctx.find? e.fvarId! def get! (lctx : LocalContext) (fvarId : FVarId) : LocalDecl := match lctx.find? fvarId with | some d => d | none => panic! "unknown free variable" def getFVar! (lctx : LocalContext) (e : Expr) : LocalDecl := lctx.get! e.fvarId! def contains (lctx : LocalContext) (fvarId : FVarId) : Bool := lctx.fvarIdToDecl.contains fvarId def containsFVar (lctx : LocalContext) (e : Expr) : Bool := lctx.contains e.fvarId! def getFVarIds (lctx : LocalContext) : Array FVarId := lctx.decls.foldl (init := #[]) fun r decl? => match decl? with | some decl => r.push decl.fvarId | none => r def getFVars (lctx : LocalContext) : Array Expr := lctx.getFVarIds.map mkFVar private partial def popTailNoneAux (a : PArray (Option LocalDecl)) : PArray (Option LocalDecl) := if a.size == 0 then a else match a.get! (a.size - 1) with | none => popTailNoneAux a.pop | some _ => a @[export lean_local_ctx_erase] def erase (lctx : LocalContext) (fvarId : FVarId) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match map.find? fvarId with | none => lctx | some decl => { fvarIdToDecl := map.erase fvarId, decls := popTailNoneAux (decls.set decl.index none) } @[export lean_local_ctx_pop] def pop (lctx : LocalContext): LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => if decls.size == 0 then lctx else match decls.get! (decls.size - 1) with | none => lctx -- unreachable | some decl => { fvarIdToDecl := map.erase decl.fvarId, decls := popTailNoneAux decls.pop } @[export lean_local_ctx_find_from_user_name] def findFromUserName? (lctx : LocalContext) (userName : Name) : Option LocalDecl := lctx.decls.findSomeRev? fun decl => match decl with | none => none | some decl => if decl.userName == userName then some decl else none @[export lean_local_ctx_uses_user_name] def usesUserName (lctx : LocalContext) (userName : Name) : Bool := (lctx.findFromUserName? userName).isSome private partial def getUnusedNameAux (lctx : LocalContext) (suggestion : Name) (i : Nat) : Name × Nat := let curr := suggestion.appendIndexAfter i if lctx.usesUserName curr then getUnusedNameAux lctx suggestion (i + 1) else (curr, i + 1) @[export lean_local_ctx_get_unused_name] def getUnusedName (lctx : LocalContext) (suggestion : Name) : Name := let suggestion := suggestion.eraseMacroScopes if lctx.usesUserName suggestion then (getUnusedNameAux lctx suggestion 1).1 else suggestion @[export lean_local_ctx_last_decl] def lastDecl (lctx : LocalContext) : Option LocalDecl := lctx.decls.get! (lctx.decls.size - 1) def setUserName (lctx : LocalContext) (fvarId : FVarId) (userName : Name) : LocalContext := let decl := lctx.get! fvarId let decl := decl.updateUserName userName { fvarIdToDecl := lctx.fvarIdToDecl.insert decl.fvarId decl, decls := lctx.decls.set decl.index decl } @[export lean_local_ctx_rename_user_name] def renameUserName (lctx : LocalContext) (fromName : Name) (toName : Name) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.findFromUserName? fromName with | none => lctx | some decl => let decl := decl.updateUserName toName; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } /-- Low-level function for updating the local context. Assumptions about `f`, the resulting nested expressions must be definitionally equal to their original values, the `index` nor `fvarId` are modified. -/ @[inline] def modifyLocalDecl (lctx : LocalContext) (fvarId : FVarId) (f : LocalDecl → LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.find? fvarId with | none => lctx | some decl => let decl := f decl; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } def updateBinderInfo (lctx : LocalContext) (fvarId : FVarId) (bi : BinderInfo) : LocalContext := modifyLocalDecl lctx fvarId fun decl => decl.updateBinderInfo bi @[export lean_local_ctx_num_indices] def numIndices (lctx : LocalContext) : Nat := lctx.decls.size @[export lean_local_ctx_get] def getAt! (lctx : LocalContext) (i : Nat) : Option LocalDecl := lctx.decls.get! i section universes u v variables {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] def foldlM (lctx : LocalContext) (f : β → LocalDecl → m β) (init : β) (start : Nat := 0) : m β := lctx.decls.foldlM (init := init) (start := start) fun b decl => match decl with | none => pure b | some decl => f b decl @[specialize] def forM (lctx : LocalContext) (f : LocalDecl → m PUnit) : m PUnit := lctx.decls.forM fun decl => match decl with | none => pure PUnit.unit | some decl => f decl @[specialize] def findDeclM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeM? fun decl => match decl with | none => pure none | some decl => f decl @[specialize] def findDeclRevM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeRevM? fun decl => match decl with | none => pure none | some decl => f decl end @[inline] def foldl {β} (lctx : LocalContext) (f : β → LocalDecl → β) (init : β) (start : Nat := 0) : β := Id.run <| lctx.foldlM f init start @[inline] def findDecl? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run <| lctx.findDeclM? f @[inline] def findDeclRev? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run <| lctx.findDeclRevM? f partial def isSubPrefixOfAux (a₁ a₂ : PArray (Option LocalDecl)) (exceptFVars : Array Expr) (i j : Nat) : Bool := if i < a₁.size then match a₁[i] with | none => isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j | some decl₁ => if exceptFVars.any fun fvar => fvar.fvarId! == decl₁.fvarId then isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j else if j < a₂.size then match a₂[j] with | none => isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1) | some decl₂ => if decl₁.fvarId == decl₂.fvarId then isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) (j+1) else isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1) else false else true /- Given `lctx₁ - exceptFVars` of the form `(x_1 : A_1) ... (x_n : A_n)`, then return true iff there is a local context `B_1* (x_1 : A_1) ... B_n* (x_n : A_n)` which is a prefix of `lctx₂` where `B_i`'s are (possibly empty) sequences of local declarations. -/ def isSubPrefixOf (lctx₁ lctx₂ : LocalContext) (exceptFVars : Array Expr := #[]) : Bool := isSubPrefixOfAux lctx₁.decls lctx₂.decls exceptFVars 0 0 @[inline] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := let b := b.abstract xs xs.size.foldRev (init := b) fun i b => let x := xs[i] match lctx.findFVar? x with | some (LocalDecl.cdecl _ _ n ty bi) => let ty := ty.abstractRange i xs; if isLambda then Lean.mkLambda n bi ty b else Lean.mkForall n bi ty b | some (LocalDecl.ldecl _ _ n ty val nonDep) => if b.hasLooseBVar 0 then let ty := ty.abstractRange i xs let val := val.abstractRange i xs mkLet n ty val b nonDep else b.lowerLooseBVars 1 1 | none => panic! "unknown free variable" def mkLambda (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding true lctx xs b def mkForall (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding false lctx xs b section universes u variables {m : Type → Type u} [Monad m] @[inline] def anyM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.anyM fun d => match d with | some decl => p decl | none => pure false @[inline] def allM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.allM fun d => match d with | some decl => p decl | none => pure true end @[inline] def any (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run <| lctx.anyM p @[inline] def all (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run <| lctx.allM p def sanitizeNames (lctx : LocalContext) : StateM NameSanitizerState LocalContext := do let st ← get if !getSanitizeNames st.options then pure lctx else flip StateT.run' ({} : NameSet) $ lctx.decls.size.foldRevM (fun i lctx => match lctx.decls.get! i with | none => pure lctx | some decl => do let usedNames ← get set <| usedNames.insert decl.userName if decl.userName.hasMacroScopes || usedNames.contains decl.userName then do let userNameNew ← sanitizeName decl.userName pure <| lctx.setUserName decl.fvarId userNameNew else pure lctx) lctx end LocalContext class MonadLCtx (m : Type → Type) where getLCtx : m LocalContext export MonadLCtx (getLCtx) instance (m n) [MonadLCtx m] [MonadLift m n] : MonadLCtx n where getLCtx := liftM (getLCtx : m _) def replaceFVarIdAtLocalDecl (fvarId : FVarId) (e : Expr) (d : LocalDecl) : LocalDecl := if d.fvarId == fvarId then d else match d with | LocalDecl.cdecl idx id n type bi => LocalDecl.cdecl idx id n (type.replaceFVarId fvarId e) bi | LocalDecl.ldecl idx id n type val nonDep => LocalDecl.ldecl idx id n (type.replaceFVarId fvarId e) (val.replaceFVarId fvarId e) nonDep end Lean
43ead54e6a7036a0e25b1a522e28e0d4aae057e9
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/analysis/convex/basic.lean
6d320eb69ff141250528ee65513d58d6b090510c
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
35,237
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov, Yaël Dillies -/ import algebra.module.ordered import linear_algebra.affine_space.affine_map /-! # Convex sets and functions in vector spaces In a 𝕜-vector space, we define the following objects and properties. * `segment 𝕜 x y`: Closed segment joining `x` and `y`. * `open_segment 𝕜 x y`: Open segment joining `x` and `y`. * `convex 𝕜 s`: A set `s` is convex if for any two points `x y ∈ s` it includes `segment 𝕜 x y`. * `std_simplex 𝕜 ι`: The standard simplex in `ι → 𝕜` (currently requires `fintype ι`). It is the intersection of the positive quadrant with the hyperplane `s.sum = 1`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex. ## Notations We provide the following notation: * `[x -[𝕜] y] = segment 𝕜 x y` in locale `convex` ## TODO Generalize all this file to affine spaces. Should we rename `segment` and `open_segment` to `convex.Icc` and `convex.Ioo`? Should we also define `clopen_segment`/`convex.Ico`/`convex.Ioc`? -/ variables {𝕜 E F β : Type*} open linear_map set open_locale big_operators classical pointwise /-! ### Segment -/ section ordered_semiring variables [ordered_semiring 𝕜] [add_comm_monoid E] section has_scalar variables (𝕜) [has_scalar 𝕜 E] /-- Segments in a vector space. -/ def segment (x y : E) : set E := {z : E | ∃ (a b : 𝕜) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} /-- Open segment in a vector space. Note that `open_segment 𝕜 x x = {x}` instead of being `∅` when the base semiring has some element between `0` and `1`. -/ def open_segment (x y : E) : set E := {z : E | ∃ (a b : 𝕜) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1), a • x + b • y = z} localized "notation `[` x ` -[` 𝕜 `] ` y `]` := segment 𝕜 x y" in convex lemma segment_symm (x y : E) : [x -[𝕜] y] = [y -[𝕜] x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma open_segment_symm (x y : E) : open_segment 𝕜 x y = open_segment 𝕜 y x := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma open_segment_subset_segment (x y : E) : open_segment 𝕜 x y ⊆ [x -[𝕜] y] := λ z ⟨a, b, ha, hb, hab, hz⟩, ⟨a, b, ha.le, hb.le, hab, hz⟩ end has_scalar open_locale convex section mul_action_with_zero variables (𝕜) [mul_action_with_zero 𝕜 E] lemma left_mem_segment (x y : E) : x ∈ [x -[𝕜] y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x -[𝕜] y] := segment_symm 𝕜 y x ▸ left_mem_segment 𝕜 y x end mul_action_with_zero section module variables (𝕜) [module 𝕜 E] lemma segment_same (x : E) : [x -[𝕜] x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment 𝕜 z z⟩ lemma mem_open_segment_of_ne_left_right {x y z : E} (hx : x ≠ z) (hy : y ≠ z) (hz : z ∈ [x -[𝕜] y]) : z ∈ open_segment 𝕜 x y := begin obtain ⟨a, b, ha, hb, hab, hz⟩ := hz, by_cases ha' : a = 0, { rw [ha', zero_add] at hab, rw [ha', hab, zero_smul, one_smul, zero_add] at hz, exact (hy hz).elim }, by_cases hb' : b = 0, { rw [hb', add_zero] at hab, rw [hb', hab, zero_smul, one_smul, add_zero] at hz, exact (hx hz).elim }, exact ⟨a, b, ha.lt_of_ne (ne.symm ha'), hb.lt_of_ne (ne.symm hb'), hab, hz⟩, end variables {𝕜} lemma open_segment_subset_iff_segment_subset {x y : E} {s : set E} (hx : x ∈ s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ s ↔ [x -[𝕜] y] ⊆ s := begin refine ⟨λ h z hz, _, (open_segment_subset_segment 𝕜 x y).trans⟩, obtain rfl | hxz := eq_or_ne x z, { exact hx }, obtain rfl | hyz := eq_or_ne y z, { exact hy }, exact h (mem_open_segment_of_ne_left_right 𝕜 hxz hyz hz), end lemma convex.combo_self {a b : 𝕜} (h : a + b = 1) (x : E) : a • x + b • x = x := by rw [←add_smul, h, one_smul] end module end ordered_semiring open_locale convex section ordered_ring variables [ordered_ring 𝕜] section add_comm_group variables (𝕜) [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] section densely_ordered variables [nontrivial 𝕜] [densely_ordered 𝕜] @[simp] lemma open_segment_same (x : E) : open_segment 𝕜 x x = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [← add_smul, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ (h : z = x), begin obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one, refine ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, _⟩, rw [←add_smul, add_sub_cancel'_right, one_smul, h], end⟩ end densely_ordered lemma segment_eq_image (x y : E) : [x -[𝕜] y] = (λ θ : 𝕜, (1 - θ) • x + θ • y) '' Icc (0 : 𝕜) 1 := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma open_segment_eq_image (x y : E) : open_segment 𝕜 x y = (λ (θ : 𝕜), (1 - θ) • x + θ • y) '' Ioo (0 : 𝕜) 1 := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ lt_add_of_pos_left _ ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1 - θ, θ, sub_pos.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image₂ (x y : E) : [x -[𝕜] y] = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma open_segment_eq_image₂ (x y : E) : open_segment 𝕜 x y = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 = 1} := by simp only [open_segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_image' (x y : E) : [x -[𝕜] y] = (λ (θ : 𝕜), x + θ • (y - x)) '' Icc (0 : 𝕜) 1 := by { convert segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma open_segment_eq_image' (x y : E) : open_segment 𝕜 x y = (λ (θ : 𝕜), x + θ • (y - x)) '' Ioo (0 : 𝕜) 1 := by { convert open_segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' [a -[𝕜] b] = [f a -[𝕜] f b] := set.ext (λ x, by simp_rw [segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul]) @[simp] lemma open_segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' open_segment 𝕜 a b = open_segment 𝕜 (f a) (f b) := set.ext (λ x, by simp_rw [open_segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul]) lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b -[𝕜] a + c] ↔ x ∈ [b -[𝕜] c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end @[simp] lemma mem_open_segment_translate (a : E) {x b c : E} : a + x ∈ open_segment 𝕜 (a + b) (a + c) ↔ x ∈ open_segment 𝕜 b c := begin rw [open_segment_eq_image', open_segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b -[𝕜] a + c] = [b -[𝕜] c] := set.ext $ λ x, mem_segment_translate 𝕜 a lemma open_segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' open_segment 𝕜 (a + b) (a + c) = open_segment 𝕜 b c := set.ext $ λ x, mem_open_segment_translate 𝕜 a lemma segment_translate_image (a b c : E) : (λ x, a + x) '' [b -[𝕜] c] = [a + b -[𝕜] a + c] := segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a lemma open_segment_translate_image (a b c : E) : (λ x, a + x) '' open_segment 𝕜 b c = open_segment 𝕜 (a + b) (a + c) := open_segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] @[simp] lemma left_mem_open_segment_iff [no_zero_smul_divisors 𝕜 E] {x y : E} : x ∈ open_segment 𝕜 x y ↔ x = y := begin split, { rintro ⟨a, b, ha, hb, hab, hx⟩, refine smul_right_injective _ hb.ne' ((add_right_inj (a • x)).1 _), rw [hx, ←add_smul, hab, one_smul] }, { rintro rfl, rw open_segment_same, exact mem_singleton _ } end @[simp] lemma right_mem_open_segment_iff {x y : E} : y ∈ open_segment 𝕜 x y ↔ x = y := by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm] end add_comm_group end linear_ordered_field /-! #### Segments in an ordered space Relates `segment`, `open_segment` and `set.Icc`, `set.Ico`, `set.Ioc`, `set.Ioo` -/ section ordered_semiring variables [ordered_semiring 𝕜] section ordered_add_comm_monoid variables [ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] lemma segment_subset_Icc {x y : E} (h : x ≤ y) : [x -[𝕜] y] ⊆ Icc x y := begin rintro z ⟨a, b, ha, hb, hab, rfl⟩, split, calc x = a • x + b • x :(convex.combo_self hab _).symm ... ≤ a • x + b • y : add_le_add_left (smul_le_smul_of_nonneg h hb) _, calc a • x + b • y ≤ a • y + b • y : add_le_add_right (smul_le_smul_of_nonneg h ha) _ ... = y : convex.combo_self hab _, end end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] lemma open_segment_subset_Ioo {x y : E} (h : x < y) : open_segment 𝕜 x y ⊆ Ioo x y := begin rintro z ⟨a, b, ha, hb, hab, rfl⟩, split, calc x = a • x + b • x : (convex.combo_self hab _).symm ... < a • x + b • y : add_lt_add_left (smul_lt_smul_of_pos h hb) _, calc a • x + b • y < a • y + b • y : add_lt_add_right (smul_lt_smul_of_pos h ha) _ ... = y : convex.combo_self hab _, end end ordered_cancel_add_comm_monoid end ordered_semiring section linear_ordered_field variables [linear_ordered_field 𝕜] lemma Icc_subset_segment {x y : 𝕜} : Icc x y ⊆ [x -[𝕜] y] := begin rintro z ⟨hxz, hyz⟩, obtain rfl | h := (hxz.trans hyz).eq_or_lt, { rw segment_same, exact hyz.antisymm hxz }, rw ←sub_nonneg at hxz hyz, rw ←sub_pos at h, refine ⟨(y - z) / (y - x), (z - x) / (y - x), div_nonneg hyz h.le, div_nonneg hxz h.le, _, _⟩, { rw [←add_div, sub_add_sub_cancel, div_self h.ne'] }, { rw [smul_eq_mul, smul_eq_mul, ←mul_div_right_comm, ←mul_div_right_comm, ←add_div, div_eq_iff h.ne', add_comm, sub_mul, sub_mul, mul_comm x, sub_add_sub_cancel, mul_sub] } end @[simp] lemma segment_eq_Icc {x y : 𝕜} (h : x ≤ y) : [x -[𝕜] y] = Icc x y := (segment_subset_Icc h).antisymm Icc_subset_segment lemma Ioo_subset_open_segment {x y : 𝕜} : Ioo x y ⊆ open_segment 𝕜 x y := λ z hz, mem_open_segment_of_ne_left_right _ hz.1.ne hz.2.ne' (Icc_subset_segment $ Ioo_subset_Icc_self hz) @[simp] lemma open_segment_eq_Ioo {x y : 𝕜} (h : x < y) : open_segment 𝕜 x y = Ioo x y := (open_segment_subset_Ioo h).antisymm Ioo_subset_open_segment lemma segment_eq_Icc' (x y : 𝕜) : [x -[𝕜] y] = Icc (min x y) (max x y) := begin cases le_total x y, { rw [segment_eq_Icc h, max_eq_right h, min_eq_left h] }, { rw [segment_symm, segment_eq_Icc h, max_eq_left h, min_eq_right h] } end lemma open_segment_eq_Ioo' {x y : 𝕜} (hxy : x ≠ y) : open_segment 𝕜 x y = Ioo (min x y) (max x y) := begin cases hxy.lt_or_lt, { rw [open_segment_eq_Ioo h, max_eq_right h.le, min_eq_left h.le] }, { rw [open_segment_symm, open_segment_eq_Ioo h, max_eq_left h.le, min_eq_right h.le] } end lemma segment_eq_interval (x y : 𝕜) : [x -[𝕜] y] = interval x y := segment_eq_Icc' _ _ /-- A point is in an `Icc` iff it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {x y : 𝕜} (h : x ≤ y) {z : 𝕜} : z ∈ Icc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z := begin rw ←segment_eq_Icc h, simp_rw [←exists_prop], refl, end /-- A point is in an `Ioo` iff it can be expressed as a strict convex combination of the endpoints. -/ lemma convex.mem_Ioo {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ioo x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z := begin rw ←open_segment_eq_Ioo h, simp_rw [←exists_prop], refl, end /-- A point is in an `Ioc` iff it can be expressed as a semistrict convex combination of the endpoints. -/ lemma convex.mem_Ioc {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ioc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z := begin split, { rintro hz, obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ioc_subset_Icc_self hz), obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rw [hab, one_mul, zero_mul, add_zero] at hz, exact (hz.1.ne rfl).elim }, { exact ⟨a, b, ha, hb', hab, rfl⟩ } }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rwa [hab, one_mul, zero_mul, zero_add, right_mem_Ioc] }, { exact Ioo_subset_Ioc_self ((convex.mem_Ioo h).2 ⟨a, b, ha', hb, hab, rfl⟩) } } end /-- A point is in an `Ico` iff it can be expressed as a semistrict convex combination of the endpoints. -/ lemma convex.mem_Ico {x y : 𝕜} (h : x < y) {z : 𝕜} : z ∈ Ico x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z := begin split, { rintro hz, obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ico_subset_Icc_self hz), obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rw [hab, one_mul, zero_mul, zero_add] at hz, exact (hz.2.ne rfl).elim }, { exact ⟨a, b, ha', hb, hab, rfl⟩ } }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rwa [hab, one_mul, zero_mul, add_zero, left_mem_Ico] }, { exact Ioo_subset_Ico_self ((convex.mem_Ioo h).2 ⟨a, b, ha, hb', hab, rfl⟩) } } end end linear_ordered_field /-! ### Convexity of sets -/ section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section has_scalar variables (𝕜) [has_scalar 𝕜 E] [has_scalar 𝕜 F] (s : set E) /-- Convexity of sets. -/ def convex : Prop := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s variables {𝕜 s} lemma convex_iff_segment_subset : convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x -[𝕜] y] ⊆ s := begin split, { rintro h x y hx hy z ⟨a, b, ha, hb, hab, rfl⟩, exact h hx hy ha hb hab }, { rintro h x y hx hy a b ha hb hab, exact h hx hy ⟨a, b, ha, hb, hab, rfl⟩ } end lemma convex.segment_subset (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : [x -[𝕜] y] ⊆ s := convex_iff_segment_subset.1 h hx hy lemma convex.open_segment_subset (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ s := (open_segment_subset_segment 𝕜 x y).trans (h.segment_subset hx hy) /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset : convex 𝕜 s ↔ ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintro hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) lemma convex_empty : convex 𝕜 (∅ : set E) := by finish lemma convex_univ : convex 𝕜 (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex 𝕜 s) : convex 𝕜 (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s : ι → set E} (h : ∀ i : ι, convex 𝕜 (s i)) : convex 𝕜 (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma directed.convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed (⊆) s) (hc : ∀ ⦃i : ι⦄, convex 𝕜 (s i)) : convex 𝕜 (⋃ i, s i) := begin rintro x y hx hy a b ha hb hab, rw mem_Union at ⊢ hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact ⟨k, hc (hik hx) (hjk hy) ha hb hab⟩, end lemma directed_on.convex_sUnion {c : set (set E)} (hdir : directed_on (⊆) c) (hc : ∀ ⦃A : set E⦄, A ∈ c → convex 𝕜 A) : convex 𝕜 (⋃₀c) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).convex_Union (λ A, hc A.2), end end has_scalar section module variables [module 𝕜 E] [module 𝕜 F] {s : set E} lemma convex_iff_forall_pos : convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy ha.le hb.le hab, _⟩, intros h x y hx hy a b ha hb hab, cases ha.eq_or_lt with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases hb.eq_or_lt with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_pairwise_on_pos : convex 𝕜 s ↔ s.pairwise_on (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s) := begin refine ⟨λ h x hx y hy _ a b ha hb hab, h hx hy ha.le hb.le hab, _⟩, intros h x y hx hy a b ha hb hab, obtain rfl | ha' := ha.eq_or_lt, { rw [zero_add] at hab, rwa [hab, zero_smul, one_smul, zero_add] }, obtain rfl | hb' := hb.eq_or_lt, { rw [add_zero] at hab, rwa [hab, zero_smul, one_smul, add_zero] }, obtain rfl | hxy := eq_or_ne x y, { rwa convex.combo_self hab }, exact h _ hx _ hy hxy ha' hb' hab, end lemma convex_iff_open_segment_subset : convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → open_segment 𝕜 x y ⊆ s := begin rw convex_iff_segment_subset, exact forall₂_congr (λ x y, forall₂_congr $ λ hx hy, (open_segment_subset_iff_segment_subset hx hy).symm), end lemma convex_singleton (c : E) : convex 𝕜 ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex.linear_image (hs : convex 𝕜 s) (f : E →ₗ[𝕜] F) : convex 𝕜 (s.image f) := begin intros x y hx hy a b ha hb hab, obtain ⟨x', hx', rfl⟩ := mem_image_iff_bex.1 hx, obtain ⟨y', hy', rfl⟩ := mem_image_iff_bex.1 hy, exact ⟨a • x' + b • y', hs hx' hy' ha hb hab, by rw [f.map_add, f.map_smul, f.map_smul]⟩, end lemma convex.is_linear_image (hs : convex 𝕜 s) {f : E → F} (hf : is_linear_map 𝕜 f) : convex 𝕜 (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex 𝕜 s) (f : E →ₗ[𝕜] F) : convex 𝕜 (s.preimage f) := begin intros x y hx hy a b ha hb hab, rw [mem_preimage, f.map_add, f.map_smul, f.map_smul], exact hs hx hy ha hb hab, end lemma convex.is_linear_preimage {s : set F} (hs : convex 𝕜 s) {f : E → F} (hf : is_linear_map 𝕜 f) : convex 𝕜 (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.add {t : set E} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.translate (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, z + x) '' s) := begin intros x y hx hy a b ha hb hab, obtain ⟨x', hx', rfl⟩ := mem_image_iff_bex.1 hx, obtain ⟨y', hy', rfl⟩ := mem_image_iff_bex.1 hy, refine ⟨a • x' + b • y', hs hx' hy' ha hb hab, _⟩, rw [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul], end /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_right (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, z + x) ⁻¹' s) := begin intros x y hx hy a b ha hb hab, have h := hs hx hy ha hb hab, rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h, end /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_left (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, x + z) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right z section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β] lemma convex_Iic (r : β) : convex 𝕜 (Iic r) := λ x y hx hy a b ha hb hab, calc a • x + b • y ≤ a • r + b • r : add_le_add (smul_le_smul_of_nonneg hx ha) (smul_le_smul_of_nonneg hy hb) ... = r : convex.combo_self hab _ lemma convex_Ici (r : β) : convex 𝕜 (Ici r) := @convex_Iic 𝕜 (order_dual β) _ _ _ _ r lemma convex_Icc (r s : β) : convex 𝕜 (Icc r s) := Ici_inter_Iic.subst ((convex_Ici r).inter $ convex_Iic s) lemma convex_halfspace_le {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_ge {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | f w = r} := begin simp_rw le_antisymm_iff, exact (convex_halfspace_le h r).inter (convex_halfspace_ge h r), end end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β] lemma convex_Iio (r : β) : convex 𝕜 (Iio r) := begin intros x y hx hy a b ha hb hab, obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rwa [zero_smul, zero_add, hab, one_smul] }, rw mem_Iio at hx hy, calc a • x + b • y < a • r + b • r : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx ha') (smul_le_smul_of_nonneg hy.le hb) ... = r : convex.combo_self hab _ end lemma convex_Ioi (r : β) : convex 𝕜 (Ioi r) := @convex_Iio 𝕜 (order_dual β) _ _ _ _ r lemma convex_Ioo (r s : β) : convex 𝕜 (Ioo r s) := Ioi_inter_Iio.subst ((convex_Ioi r).inter $ convex_Iio s) lemma convex_Ico (r s : β) : convex 𝕜 (Ico r s) := Ici_inter_Iio.subst ((convex_Ici r).inter $ convex_Iio s) lemma convex_Ioc (r s : β) : convex 𝕜 (Ioc r s) := Ioi_inter_Iic.subst ((convex_Ioi r).inter $ convex_Iic s) lemma convex_halfspace_lt {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_gt {f : E → β} (h : is_linear_map 𝕜 f) (r : β) : convex 𝕜 {w | r < f w} := (convex_Ioi r).is_linear_preimage h end ordered_cancel_add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β] lemma convex_interval (r s : β) : convex 𝕜 (interval r s) := convex_Icc _ _ end linear_ordered_add_comm_monoid end module end add_comm_monoid section add_comm_group variables [add_comm_group E] [module 𝕜 E] {s t : set E} lemma convex.combo_eq_vadd {a b : 𝕜} {x y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := calc a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel ... = b • (y - x) + x : by rw [smul_sub, convex.combo_self h] lemma convex.sub (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 ((λ x : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex_segment (x y : E) : convex 𝕜 [x -[𝕜] y] := begin rintro p q ⟨ap, bp, hap, hbp, habp, rfl⟩ ⟨aq, bq, haq, hbq, habq, rfl⟩ a b ha hb hab, refine ⟨a * ap + b * aq, a * bp + b * bq, add_nonneg (mul_nonneg ha hap) (mul_nonneg hb haq), add_nonneg (mul_nonneg ha hbp) (mul_nonneg hb hbq), _, _⟩, { rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] }, { simp_rw [add_smul, mul_smul, smul_add], exact add_add_add_comm _ _ _ _ } end lemma convex_open_segment (a b : E) : convex 𝕜 (open_segment 𝕜 a b) := begin rw convex_iff_open_segment_subset, rintro p q ⟨ap, bp, hap, hbp, habp, rfl⟩ ⟨aq, bq, haq, hbq, habq, rfl⟩ z ⟨a, b, ha, hb, hab, rfl⟩, refine ⟨a * ap + b * aq, a * bp + b * bq, add_pos (mul_pos ha hap) (mul_pos hb haq), add_pos (mul_pos ha hbp) (mul_pos hb hbq), _, _⟩, { rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] }, { simp_rw [add_smul, mul_smul, smul_add], exact add_add_add_comm _ _ _ _ } end end add_comm_group end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] [module 𝕜 E] [module 𝕜 F] {s : set E} lemma convex.smul (hs : convex 𝕜 s) (c : 𝕜) : convex 𝕜 (c • s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (hs : convex 𝕜 s) (c : 𝕜) : convex 𝕜 ((λ z, c • z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.affinity (hs : convex 𝕜 s) (z : E) (c : 𝕜) : convex 𝕜 ((λ x, z + c • x) '' s) := begin have h := (hs.smul c).translate z, rwa [←image_smul, image_image] at h, end end add_comm_monoid end ordered_comm_semiring section ordered_ring variables [ordered_ring 𝕜] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E} lemma convex.add_smul_mem (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ s) {t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : x + t • y ∈ s := begin have h : x + t • y = (1 - t) • x + t • (x + y), { rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] }, rw h, exact hs hx hy (sub_nonneg_of_le ht.2) ht.1 (sub_add_cancel _ _), end lemma convex.smul_mem_of_zero_mem (hs : convex 𝕜 s) {x : E} (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) {t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : t • x ∈ s := by simpa using hs.add_smul_mem zero_mem (by simpa using hx) ht lemma convex.add_smul_sub_mem (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : x + t • (y - x) ∈ s := begin apply h.segment_subset hx hy, rw segment_eq_image', exact mem_image_of_mem _ ht, end /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : 𝕜} {x y : E} {f : E →ᵃ[𝕜] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := begin simp only [convex.combo_eq_vadd h, ← vsub_eq_sub], exact f.apply_line_map _ _ _, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᵃ[𝕜] F) {s : set F} (hs : convex 𝕜 s) : convex 𝕜 (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᵃ[𝕜] F) {s : set E} (hs : convex 𝕜 s) : convex 𝕜 (f '' s) := begin rintro x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.neg (hs : convex 𝕜 s) : convex 𝕜 ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex 𝕜 s) : convex 𝕜 ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg end add_comm_group end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] section add_comm_group variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E} /-- Alternative definition of set convexity, using division. -/ lemma convex_iff_div : convex 𝕜 s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨λ h x y hx hy a b ha hb hab, begin apply h hx hy, { have ha', from mul_le_mul_of_nonneg_left ha (inv_pos.2 hab).le, rwa [mul_zero, ←div_eq_inv_mul] at ha' }, { have hb', from mul_le_mul_of_nonneg_left hb (inv_pos.2 hab).le, rwa [mul_zero, ←div_eq_inv_mul] at hb' }, { rw ←add_div, exact div_self hab.ne' } end, λ h x y hx hy a b ha hb hab, begin have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ lemma convex.mem_smul_of_zero_mem (h : convex 𝕜 s) {x : E} (zero_mem : (0 : E) ∈ s) (hx : x ∈ s) {t : 𝕜} (ht : 1 ≤ t) : x ∈ t • s := begin rw mem_smul_set_iff_inv_smul_mem₀ (zero_lt_one.trans_le ht).ne', exact h.smul_mem_of_zero_mem zero_mem hx ⟨inv_nonneg.2 (zero_le_one.trans ht), inv_le_one ht⟩, end lemma convex.add_smul (h_conv : convex 𝕜 s) {p q : 𝕜} (hp : 0 ≤ p) (hq : 0 ≤ q) : (p + q) • s = p • s + q • s := begin obtain rfl | hs := s.eq_empty_or_nonempty, { simp_rw [smul_set_empty, add_empty] }, obtain rfl | hp' := hp.eq_or_lt, { rw [zero_add, zero_smul_set hs, zero_add] }, obtain rfl | hq' := hq.eq_or_lt, { rw [add_zero, zero_smul_set hs, add_zero] }, ext, split, { rintro ⟨v, hv, rfl⟩, exact ⟨p • v, q • v, smul_mem_smul_set hv, smul_mem_smul_set hv, (add_smul _ _ _).symm⟩ }, { rintro ⟨v₁, v₂, ⟨v₁₁, h₁₂, rfl⟩, ⟨v₂₁, h₂₂, rfl⟩, rfl⟩, have hpq := add_pos hp' hq', exact mem_smul_set.2 ⟨_, h_conv h₁₂ h₂₂ (div_pos hp' hpq).le (div_pos hq' hpq).le (by rw [←div_self hpq.ne', add_div] : p / (p + q) + q / (p + q) = 1), by simp only [← mul_smul, smul_add, mul_div_cancel' _ hpq.ne']⟩ } end end add_comm_group end linear_ordered_field /-! #### Convex sets in an ordered space Relates `convex` and `ord_connected`. -/ section lemma set.ord_connected.convex_of_chain [ordered_semiring 𝕜] [ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {s : set E} (hs : s.ord_connected) (h : zorn.chain (≤) s) : convex 𝕜 s := begin intros x y hx hy a b ha hb hab, obtain hxy | hyx := h.total_of_refl hx hy, { refine hs.out hx hy (mem_Icc.2 ⟨_, _⟩), calc x = a • x + b • x : (convex.combo_self hab _).symm ... ≤ a • x + b • y : add_le_add_left (smul_le_smul_of_nonneg hxy hb) _, calc a • x + b • y ≤ a • y + b • y : add_le_add_right (smul_le_smul_of_nonneg hxy ha) _ ... = y : convex.combo_self hab _ }, { refine hs.out hy hx (mem_Icc.2 ⟨_, _⟩), calc y = a • y + b • y : (convex.combo_self hab _).symm ... ≤ a • x + b • y : add_le_add_right (smul_le_smul_of_nonneg hyx ha) _, calc a • x + b • y ≤ a • x + b • x : add_le_add_left (smul_le_smul_of_nonneg hyx hb) _ ... = x : convex.combo_self hab _ } end lemma set.ord_connected.convex [ordered_semiring 𝕜] [linear_ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {s : set E} (hs : s.ord_connected) : convex 𝕜 s := hs.convex_of_chain (zorn.chain_of_trichotomous s) lemma convex_iff_ord_connected [linear_ordered_field 𝕜] {s : set 𝕜} : convex 𝕜 s ↔ s.ord_connected := begin simp_rw [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (λ x, forall_swap) end alias convex_iff_ord_connected ↔ convex.ord_connected _ end /-! #### Convexity of submodules/subspaces -/ section submodule open submodule lemma submodule.convex [ordered_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] (K : submodule 𝕜 E) : convex 𝕜 (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] (K : subspace 𝕜 E) : convex 𝕜 (↑K : set E) := K.convex end submodule /-! ### Simplex -/ section simplex variables (𝕜) (ι : Type*) [ordered_semiring 𝕜] [fintype ι] /-- The standard simplex in the space of functions `ι → 𝕜` is the set of vectors with non-negative coordinates with total sum `1`. This is the free object in the category of convex spaces. -/ def std_simplex : set (ι → 𝕜) := {f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1} lemma std_simplex_eq_inter : std_simplex 𝕜 ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex 𝕜 (std_simplex 𝕜 ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:𝕜) 0) ∈ std_simplex 𝕜 ι := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩ end simplex
f8d741c9fa21be3116c1a09039d9cd6fc2026342
fe84e287c662151bb313504482b218a503b972f3
/src/group_theory/dihedral.lean
41e0f36deb0fde3d4c748c5fef9a8756eada90c3
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
19,900
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland We define finite dihedral groups, with elements denoted by `r i` and `s i` for `i : zmod n`. We show that a pair of elements `r0, s0 ∈ G` satisfying appropriate relations gives rise to a homomorphism `Dₙ → G`, sending `r i` to `r0 ^ i` and `s i` to `(r0 ^ i) * s0`. (We have chosen to formulate this in a way that works when `G` is merely a monoid, as that makes it easier to deal with `Dₙ`-actions as homomorphisms from `Dₙ` to endomorphism monoids. Thus, our relations are `r0 ^ n = s0 * s0 = 1` and `r0 * s0 * r0 = s0`.) We also do the case n = ∞ separately. -/ import data.fintype.basic import algebra.power_mod import group_theory.subgroup.basic import group_theory.group_action import group_theory.action_instances import group_theory.cyclic namespace group_theory variables (n : ℕ) [fact (n > 0)] @[derive decidable_eq] inductive dihedral | r : (zmod n) → dihedral | s : (zmod n) → dihedral namespace dihedral variable {n} def log : dihedral n → (zmod n) | (r i) := i | (s i) := i def is_s : dihedral n → bool | (r _) := ff | (s _) := tt def to_bz : dihedral n → bool × (zmod n) | (r i) := ⟨ff, i⟩ | (s i) := ⟨tt, i⟩ def of_bz : bool × (zmod n) → dihedral n | ⟨ff, i⟩ := r i | ⟨tt, i⟩ := s i variable (n) def bz_equiv : dihedral n ≃ (bool × (zmod n)) := { to_fun := to_bz, inv_fun := of_bz, left_inv := λ g, by cases g; refl, right_inv := λ bi, by rcases bi with ⟨_|_, i⟩ ; refl } variable {n} instance : fintype (dihedral n) := fintype.of_equiv (bool × (zmod n)) (bz_equiv n).symm lemma card : fintype.card (dihedral n) = 2 * n := by simp [fintype.card_congr (bz_equiv n), zmod.card] def one : dihedral n := r 0 def inv : ∀ (g : dihedral n), dihedral n | (r i) := r (-i) | (s i) := s i def mul : ∀ (g h : dihedral n), dihedral n | (r i) (r j) := r (i + j) | (r i) (s j) := s (i + j) | (s i) (r j) := s (i - j) | (s i) (s j) := r (i - j) instance : has_one (dihedral n) := ⟨r 0⟩ lemma one_eq : (1 : dihedral n) = r 0 := rfl instance : has_inv (dihedral n) := ⟨dihedral.inv⟩ lemma r_inv (i : zmod n) : (r i)⁻¹ = r (- i) := rfl lemma s_inv (i : zmod n) : (s i)⁻¹ = s i := rfl instance : has_mul (dihedral n) := ⟨dihedral.mul⟩ lemma rr_mul (i j : zmod n) : (r i) * (r j) = r (i + j) := rfl lemma rs_mul (i j : zmod n) : (r i) * (s j) = s (i + j) := rfl lemma sr_mul (i j : zmod n) : (s i) * (r j) = s (i - j) := rfl lemma ss_mul (i j : zmod n) : (s i) * (s j) = r (i - j) := rfl instance : group (dihedral n) := { one := has_one.one, mul := has_mul.mul, inv := has_inv.inv, one_mul := λ a, by { rcases a with (i|i); simp only [one_eq,rr_mul,rs_mul,zero_add] }, mul_one := λ a, by { rcases a with (i|i); simp only [one_eq,rr_mul,sr_mul,add_zero,sub_zero] }, mul_left_inv := λ a, by { rcases a with (i|i); simp only [one_eq,r_inv,s_inv,rr_mul,ss_mul]; ring }, mul_assoc := λ a b c, begin rcases a with (i|i); rcases b with (j|j); rcases c with (k|k); simp only [rr_mul,rs_mul,sr_mul,ss_mul]; ring, end } def inc : cyclic n →* dihedral n := { to_fun := λ ⟨i⟩, r i, map_one' := rfl, map_mul' := λ ⟨i⟩ ⟨j⟩, rfl } lemma s_mul_self (i : zmod n) : (s i) * (s i) = 1 := by { rw [ss_mul, sub_self, one_eq] } lemma r_pow_nat (i : zmod n) (j : ℕ) : (r i) ^ j = r (i * j) := begin induction j with j ih, { have : ((0 : ℕ) : zmod n) = 0 := rfl, rw [pow_zero, nat.cast_zero, mul_zero], refl }, { rw [pow_succ, ih, rr_mul, add_comm, nat.succ_eq_add_one, nat.cast_add, nat.cast_one, mul_add, mul_one] } end lemma r_pow_int (i : zmod n) (j : ℤ) : (r i) ^ j = r (i * j) := begin cases j with j, { have : int.of_nat j = j := rfl, rw this, have : ((j : ℤ) : zmod n) = j := rfl, rw this, rw [zpow_coe_nat, r_pow_nat] }, { rw [zpow_neg_succ_of_nat,r_pow_nat, r_inv, int.cast_neg_succ_of_nat,mul_neg], congr' 1, } end lemma r_pow_zmod (i j : zmod n) : (r i) ^ j = r (i * j) := begin change (r i) ^ j.val = _, rw [r_pow_nat i j.val, zmod.nat_cast_zmod_val] end lemma r_pow_n (i : zmod n) : (r i) ^ n = 1 := by rw[r_pow_nat,one_eq,zmod.nat_cast_self,mul_zero] lemma s_pow_nat (i : zmod n) (j : ℕ) : (s i) ^ j = cond j.bodd (s i) 1 := begin induction j with j ih, refl, { rw [pow_succ, j.bodd_succ, ih], cases j.bodd; simp [bnot, cond, ss_mul], refl, } end lemma s_pow_int (i : zmod n) (j : ℤ) : (s i) ^ j = cond j.bodd (s i) 1 := begin cases j; simp [int.bodd, s_pow_nat], { cases j.bodd; simp [bnot, cond, s_inv] } end variable (n) structure prehom (M : Type*) [monoid M] := (r s : M) (hr : r ^ (n : ℕ) = 1) (hs : s * s = 1) (hrs : r * s * r = s) variable {n} namespace prehom @[ext] lemma ext {M : Type*} [monoid M] {p q : prehom n M} : p.r = q.r → p.s = q.s → p = q := begin cases p, cases q, rintro ⟨er⟩ ⟨es⟩, refl end variables {M : Type*} [monoid M] (p : prehom n M) lemma sr_rs : ∀ (i : ℕ), p.r ^ i * p.s * (p.r ^ i) = p.s | 0 := by rw [pow_zero, one_mul, mul_one] | (i + 1) := calc p.r ^ (i + 1) * p.s * p.r ^ (i + 1) = p.r ^ (i + 1) * p.s * p.r ^ (1 + i) : by rw [add_comm i 1] ... = (p.r ^ i * p.r) * p.s * (p.r * p.r ^ i) : by rw [pow_add, pow_add, pow_one] ... = (p.r ^ i) * ((p.r * p.s) * (p.r * (p.r ^ i))) : by rw [mul_assoc (p.r ^ i) p.r p.s, mul_assoc (p.r ^ i)] ... = (p.r ^ i) * (((p.r * p.s) * p.r) * p.r ^ i) : by rw [mul_assoc (p.r * p.s) p.r (p.r ^ i)] ... = p.s : by rw [hrs, ← mul_assoc, sr_rs i] lemma sr_rs' : ∀ (i : zmod n), p.s * p.r ^ i = p.r ^ (- i) * p.s := λ i, begin exact calc p.s * p.r ^ i = 1 * (p.s * p.r ^ i) : (one_mul _).symm ... = p.r ^ ((- i) + i) * (p.s * p.r ^ i) : by { rw [← pow_mod_zero n], rw[neg_add_self] } ... = (p.r ^ (- i)) * (p.r ^ i * p.s * (p.r ^ i)) : by rw [pow_mod_add p.hr, mul_assoc (p.r ^ (- i)), mul_assoc] ... = (p.r ^ (- i)) * (p.r ^ i.val * p.s * p.r ^ i.val) : rfl ... = (p.r ^ (- i)) * p.s : by rw [p.sr_rs i.val] end include M p def to_hom₀ : (dihedral n) → M | (dihedral.r i) := p.r ^ i | (dihedral.s i) := p.r ^ i * p.s def to_hom : (dihedral n) →* M := { to_fun := p.to_hom₀, map_one' := by { rw[one_eq,to_hom₀, pow_mod_zero] }, map_mul' := λ a b, begin cases a with i i; cases b with j j; simp only [rr_mul, rs_mul, sr_mul, ss_mul, to_hom₀], { rw [pow_mod_add p.hr], }, { rw [← mul_assoc, pow_mod_add p.hr] }, { rw [mul_assoc, p.sr_rs' j, ← mul_assoc, sub_eq_add_neg, pow_mod_add p.hr] }, { rw [mul_assoc, ← mul_assoc p.s _ p.s, p.sr_rs' j, mul_assoc, hs, mul_one, sub_eq_add_neg, pow_mod_add p.hr] } end } @[simp] lemma to_hom.map_r (i : zmod n) : p.to_hom (dihedral.r i) = p.r ^ i := rfl @[simp] lemma to_hom.map_s (i : zmod n) : p.to_hom (dihedral.s i) = p.r ^ i * p.s := rfl omit p variable {n} def of_hom (f : dihedral n →* M) : prehom n M := { r := f (dihedral.r 1), s := f (dihedral.s 0), hr := begin let h := f.map_pow (dihedral.r 1) n, rw [r_pow_nat, one_mul, zmod.nat_cast_self, ← dihedral.one_eq, f.map_one] at h, exact h.symm end, hs := by rw [← f.map_mul, s_mul_self, f.map_one], hrs := by rw [← f.map_mul, ← f.map_mul, rs_mul, sr_mul, add_zero, sub_self] } @[simp] lemma of_hom.r_def (f : dihedral n →* M) : (of_hom f).r = f (dihedral.r 1) := rfl @[simp] lemma of_hom.s_def (f : dihedral n →* M) : (of_hom f).s = f (dihedral.s 0) := rfl lemma of_to_hom : of_hom (to_hom p) = p := by { ext; dsimp[to_hom,of_hom,to_hom₀], {exact pow_mod_one p.hr}, {rw[pow_mod_zero,one_mul],} } /- ext (pow_mod_one p.hr) (one_mul p.s) -/ lemma to_of_hom (f : dihedral n →* M) : to_hom (of_hom f) = f := begin ext g, cases g with i i, { rw [to_hom.map_r, of_hom.r_def, ← f.map_pow_mod, r_pow_zmod, one_mul] }, { rw [to_hom.map_s, of_hom.r_def, of_hom.s_def, ← f.map_pow_mod, ← f.map_mul, r_pow_zmod, rs_mul, add_zero, one_mul ] } end variables (n M) def hom_equiv : prehom n M ≃ ((dihedral n) →* M) := { to_fun := to_hom, inv_fun := of_hom, left_inv := of_to_hom, right_inv := to_of_hom } end prehom lemma generation {H : submonoid (dihedral n)} (hr : r 1 ∈ H) (hs : s 0 ∈ H) : H = ⊤ := begin ext g, simp only [submonoid.mem_top,iff_true], have hr' : ∀ (k : ℕ), r (k : zmod n) ∈ H := λ k, begin induction k with k ih, { exact H.one_mem }, { have : (r (k : zmod n)) * (r 1) = r (k.succ : zmod n) := by { rw [rr_mul, nat.cast_succ] }, rw [← this], exact H.mul_mem ih hr } end, cases g with i i; rw[← i.nat_cast_zmod_val] , { exact hr' i.val }, { have : ∀ (j : zmod n), s j = (r j) * (s 0) := λ j, by { rw[rs_mul, add_zero] }, rw [this], exact H.mul_mem (hr' _) hs } end @[ext] lemma hom_ext {M : Type*} [monoid M] {f g : dihedral n →* M} : f = g ↔ (f (dihedral.r 1) = g (dihedral.r 1)) ∧ (f (dihedral.s 0) = g (dihedral.s 0)) := begin split, { rintro ⟨_⟩, split; refl }, { rintro ⟨hr,hs⟩, exact (prehom.hom_equiv n M).symm.injective (prehom.ext hr hs) } end lemma map_smul_iff {X Y : Type*} [mul_action (dihedral n) X] [mul_action (dihedral n) X] [mul_action (dihedral n) Y] (f : X → Y) : (∀ (g : dihedral n) (x : X), f (g • x) = g • (f x)) ↔ (∀ x : X, f ((s 0 : dihedral n) • x) = (s 0 : dihedral n) • (f x)) ∧ (∀ x : X, f ((r 1 : dihedral n) • x) = (r 1 : dihedral n) • (f x)) := begin split, { intro h, exact ⟨h _, h _⟩ }, rintro ⟨hs,hr⟩ g, let H : submonoid (dihedral n) := mul_action.equivariantizer (dihedral n) f, change (s 0) ∈ H at hs, change (r 1) ∈ H at hr, change g ∈ H, rw[generation hr hs], apply submonoid.mem_top end end dihedral @[derive decidable_eq] inductive infinite_dihedral | r : ℤ → infinite_dihedral | s : ℤ → infinite_dihedral namespace infinite_dihedral variable {n} def log : infinite_dihedral → ℤ | (r i) := i | (s i) := i def is_s : infinite_dihedral → bool | (r _) := ff | (s _) := tt def to_bz : infinite_dihedral → bool × ℤ | (r i) := ⟨ff, i⟩ | (s i) := ⟨tt, i⟩ def of_bz : bool × ℤ → infinite_dihedral | ⟨ff, i⟩ := r i | ⟨tt, i⟩ := s i variable (n) def bz_equiv : infinite_dihedral ≃ (bool × ℤ) := { to_fun := to_bz, inv_fun := of_bz, left_inv := λ g, by { cases g; refl }, right_inv := λ bi, by { rcases bi with ⟨_|_, i⟩ ; refl } } variable {n} def one : infinite_dihedral := r 0 def inv : ∀ (g : infinite_dihedral), infinite_dihedral | (r i) := r (-i) | (s i) := s i def mul : ∀ (g h : infinite_dihedral), infinite_dihedral | (r i) (r j) := r (i + j) | (r i) (s j) := s (i + j) | (s i) (r j) := s (i - j) | (s i) (s j) := r (i - j) instance : has_one (infinite_dihedral) := ⟨r 0⟩ lemma one_eq : (1 : infinite_dihedral) = r 0 := rfl instance : has_inv (infinite_dihedral) := ⟨infinite_dihedral.inv⟩ lemma r_inv (i : ℤ) : (r i)⁻¹ = r (- i) := rfl lemma s_inv (i : ℤ) : (s i)⁻¹ = s i := rfl instance : has_mul (infinite_dihedral) := ⟨infinite_dihedral.mul⟩ lemma rr_mul (i j : ℤ) : (r i) * (r j) = r (i + j) := rfl lemma rs_mul (i j : ℤ) : (r i) * (s j) = s (i + j) := rfl lemma sr_mul (i j : ℤ) : (s i) * (r j) = s (i - j) := rfl lemma ss_mul (i j : ℤ) : (s i) * (s j) = r (i - j) := rfl lemma srs (i : ℤ) : (s 0) * (r i) * (s 0) = r (- i) := by { simp [sr_mul,ss_mul] } instance : group (infinite_dihedral) := { one := has_one.one, mul := has_mul.mul, inv := has_inv.inv, one_mul := λ a, by { rcases a with (i|i); simp only [one_eq,rr_mul,rs_mul,zero_add] }, mul_one := λ a, by { rcases a with (i|i); simp only [one_eq,rr_mul,sr_mul,add_zero,sub_zero] }, mul_left_inv := λ a, by { rcases a with (i|i); simp only [one_eq,r_inv,s_inv,rr_mul,ss_mul]; ring }, mul_assoc := λ a b c, begin rcases a with (i|i); rcases b with (j|j); rcases c with (k|k); simp only [rr_mul,rs_mul,sr_mul,ss_mul]; ring, end } def inc : infinite_cyclic →* infinite_dihedral := { to_fun := λ ⟨i⟩, r i, map_one' := rfl, map_mul' := λ ⟨i⟩ ⟨j⟩, rfl } lemma s_mul_self (i : ℤ) : (s i) * (s i) = 1 := by { rw [ss_mul, sub_self, one_eq] } lemma r_pow_nat (i : ℤ) (j : ℕ) : (r i) ^ j = r (i * j) := begin induction j with j ih, { rw [pow_zero, int.coe_nat_zero, mul_zero, one_eq] }, { rw [pow_succ, ih, rr_mul, add_comm, nat.succ_eq_add_one, int.coe_nat_add, int.coe_nat_one, mul_add, mul_one] } end lemma r_pow_int (i j : ℤ) : (r i) ^ j = r (i * j) := begin cases j with j, { have : int.of_nat j = j := rfl, rw[this,zpow_coe_nat,r_pow_nat] }, { have : int.neg_succ_of_nat j = - (j + 1) := rfl, rw [zpow_neg_succ_of_nat,r_pow_nat,r_inv,this,mul_neg], congr' 1, } end lemma generation {H : submonoid infinite_dihedral} (hr : r 1 ∈ H) (hs : s 0 ∈ H) : H = ⊤ := begin ext g, simp only [submonoid.mem_top,iff_true], have h₀ : ∀ (k : ℕ), r k ∈ H := λ k, begin induction k with k ih, { exact H.one_mem }, { have : (r k) * (r 1) = r k.succ := by { rw [rr_mul], refl }, rw [← this], exact H.mul_mem ih hr } end, have h₁ : ∀ (k : ℕ), r (- k) ∈ H := λ k, begin have := H.mul_mem (H.mul_mem hs (h₀ k)) hs, rw[srs] at this, exact this end, have h₂ : ∀ (k : ℤ), r k ∈ H := begin rintro (k|k), exact h₀ k, exact h₁ k.succ, end, cases g with i i, { exact h₂ i }, { have : (s i) = (r i) * (s 0) := by { rw[rs_mul,add_zero]}, rw[this], exact H.mul_mem (h₂ i) hs, } end @[ext] lemma hom_ext {M : Type*} [monoid M] {f g : infinite_dihedral →* M} : f = g ↔ (f (infinite_dihedral.r 1) = g (infinite_dihedral.r 1)) ∧ (f (infinite_dihedral.s 0) = g (infinite_dihedral.s 0)) := begin split, { intro h, cases h, split; refl }, rintro ⟨hr,hs⟩, let H : submonoid infinite_dihedral := monoid_hom.eq_mlocus f g, change _ ∈ H at hr, change _ ∈ H at hs, have h := generation hr hs, ext x, change x ∈ H, rw[h], exact submonoid.mem_top x, end structure prehom (M : Type*) [monoid M] := (r s : M) (hs : s * s = 1) (hrs : r * s * r = s) namespace prehom @[ext] lemma ext {M : Type*} [monoid M] {p q : prehom M} : p.r = q.r → p.s = q.s → p = q := begin cases p, cases q, rintro ⟨er⟩ ⟨es⟩, refl end variables {M : Type*} [monoid M] (p : prehom M) def r_unit : units M := { val := p.r, inv := p.s * p.r * p.s, val_inv := by rw [← mul_assoc, ← mul_assoc, p.hrs, p.hs], inv_val := by rw [mul_assoc, mul_assoc, ← mul_assoc p.r, p.hrs, p.hs] } def s_unit : units M := { val := p.s, inv := p.s, val_inv := p.hs, inv_val := p.hs } @[simp] lemma r_unit_coe : (p.r_unit : M) = p.r := rfl @[simp] lemma r_unit_val : p.r_unit.val = p.r := rfl @[simp] lemma r_unit_inv : p.r_unit.inv = p.s * p.r * p.s := rfl @[simp] lemma s_unit_coe : (p.s_unit : M) = p.s := rfl @[simp] lemma s_unit_val : p.s_unit.val = p.s := rfl @[simp] lemma s_unit_inv : p.s_unit.inv = p.s := rfl theorem hs_unit : p.s_unit * p.s_unit = 1 := units.ext p.hs theorem hrs_unit : p.r_unit * p.s_unit * p.r_unit = p.s_unit := units.ext p.hrs lemma sr_rs : ∀ (i : ℕ), p.r ^ i * p.s * (p.r ^ i) = p.s | 0 := by rw [pow_zero, one_mul, mul_one] | (i + 1) := calc p.r ^ (i + 1) * p.s * p.r ^ (i + 1) = p.r ^ (i + 1) * p.s * p.r ^ (1 + i) : by rw [add_comm i 1] ... = (p.r ^ i * p.r) * p.s * (p.r * p.r ^ i) : by rw [pow_add, pow_add, pow_one] ... = (p.r ^ i) * ((p.r * p.s) * (p.r * (p.r ^ i))) : by rw [mul_assoc (p.r ^ i) p.r p.s, mul_assoc (p.r ^ i)] ... = (p.r ^ i) * (((p.r * p.s) * p.r) * p.r ^ i) : by rw [mul_assoc (p.r * p.s) p.r (p.r ^ i)] ... = p.s : by rw [hrs, ← mul_assoc, sr_rs i] lemma sr_rs_unit : ∀ (i : ℤ), p.r_unit ^ i * p.s_unit * (p.r_unit ^ i) = p.s_unit := begin suffices h : ∀ (i : ℕ), p.r_unit ^ i * p.s_unit * (p.r_unit ^ i) = p.s_unit, { intro i, cases i with i i, { have : int.of_nat i = i := rfl, rw [this, zpow_coe_nat, h i] }, { rw[← h i.succ], let u := p.r_unit ^ i.succ, let v := p.s_unit, change (u⁻¹ * (u * v * u)) * u⁻¹ = u * v * u, rw [mul_assoc, mul_assoc, mul_inv_self, mul_one], rw [← mul_assoc, inv_mul_self, one_mul], symmetry, exact h i.succ } }, { intro i, apply units.ext, rw [units.coe_mul, units.coe_mul, units.coe_pow, p.r_unit_coe, p.s_unit_coe, p.sr_rs] } end lemma sr_rs' (i : ℤ) : p.s_unit * (p.r_unit ^ i) = (p.r_unit) ^ (- i) * p.s_unit := calc p.s_unit * p.r_unit ^ i = 1 * (p.s_unit * p.r_unit ^ i) : (one_mul _).symm ... = (p.r_unit ^ ((- i) + i)) * (p.s_unit * p.r_unit ^ i) : by { rw [← pow_zero p.r_unit, neg_add_self], refl } ... = (p.r_unit ^ (- i)) * ((p.r_unit ^ i) * p.s_unit * (p.r_unit ^ i)) : by { rw [zpow_add, mul_assoc (p.r_unit ^ (- i)), mul_assoc] } ... = p.r_unit ^ (- i) * p.s_unit : by { rw [p.sr_rs_unit] } include M p def to_hom₀ : infinite_dihedral → M | (infinite_dihedral.r i) := ((p.r_unit ^ i : units M) : M) | (infinite_dihedral.s i) := ((p.r_unit ^ i * p.s_unit : units M) : M) def to_hom : infinite_dihedral →* M := { to_fun := p.to_hom₀, map_one' := rfl, map_mul' := λ a b, begin cases a with i i; cases b with j j; simp only [rr_mul, rs_mul, sr_mul, ss_mul, to_hom₀]; rw [← units.coe_mul], { rw [zpow_add], }, { rw [← mul_assoc, zpow_add] }, { rw [mul_assoc, p.sr_rs' j, ← mul_assoc, sub_eq_add_neg, zpow_add] }, { rw [mul_assoc, ← mul_assoc p.s_unit _ p.s_unit], rw [p.sr_rs' j, mul_assoc, p.hs_unit, mul_one, sub_eq_add_neg, zpow_add] } end } lemma to_hom.map_r (i : ℤ) : p.to_hom (infinite_dihedral.r i) = (p.r_unit ^ i : units M) := rfl lemma to_hom.map_r_nat (i : ℕ) : p.to_hom (infinite_dihedral.r i) = p.r ^ i := by { rw [to_hom.map_r, zpow_coe_nat, units.coe_pow], refl } lemma to_hom.map_s (i : ℤ) : p.to_hom (infinite_dihedral.s i) = (p.r_unit ^ i * p.s_unit : units M) := rfl lemma to_hom.map_s_nat (i : ℕ) : p.to_hom (infinite_dihedral.s i) = p.r ^ i * p.s := by { rw [to_hom.map_s, zpow_coe_nat, units.coe_mul, units.coe_pow], refl } omit p variable {n} def of_hom (f : infinite_dihedral →* M) : prehom M := { r := f (infinite_dihedral.r 1), s := f (infinite_dihedral.s 0), hs := by rw [← f.map_mul, s_mul_self, f.map_one], hrs := by rw [← f.map_mul, ← f.map_mul, rs_mul, sr_mul, add_zero, sub_self] } @[simp] lemma of_hom.r_def (f : infinite_dihedral →* M) : (of_hom f).r = f (infinite_dihedral.r 1) := rfl @[simp] lemma of_hom.s_def (f : infinite_dihedral →* M) : (of_hom f).s = f (infinite_dihedral.s 0) := rfl lemma of_to_hom : of_hom (to_hom p) = p := begin ext, { rw [of_hom.r_def, to_hom.map_r, zpow_one], refl }, { rw [of_hom.s_def, to_hom.map_s, zpow_zero, one_mul], refl } end lemma units.pow_inv (M : Type*) [monoid M] (g : units M) (n : ℕ) : (g ^ n).inv = g.inv ^ n := begin induction n with n ih, { rw [pow_zero,pow_zero], refl }, { rw [pow_succ], change _ * _ = _, rw [ih, n.succ_eq_add_one, pow_add, pow_one] } end lemma to_of_hom (f : infinite_dihedral →* M) : to_hom (of_hom f) = f := begin apply hom_ext.mpr, split, { have : (1 : ℤ) = (1 : ℕ) := rfl, rw [this,to_hom.map_r_nat,pow_one,of_hom.r_def], refl }, { rw [to_hom.map_s,zpow_zero,one_mul,s_unit_coe,of_hom.s_def] } end def hom_equiv : prehom M ≃ (infinite_dihedral →* M) := { to_fun := to_hom, inv_fun := of_hom, left_inv := of_to_hom, right_inv := to_of_hom } end prehom end infinite_dihedral end group_theory
549eb5bd533bcb11b966ce53736e5201433d19db
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/sites/spaces.lean
98acc234ad27c65fe9217dc3529889bafa54dfb6
[ "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
3,049
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 topology.opens import category_theory.sites.grothendieck import category_theory.sites.pretopology import category_theory.limits.lattice /-! # Grothendieck topology on a topological space Define the Grothendieck topology and the pretopology associated to a topological space, and show that the pretopology induces the topology. The covering (pre)sieves on `X` are those for which the union of domains contains `X`. ## Tags site, Grothendieck topology, space ## References * [https://ncatlab.org/nlab/show/Grothendieck+topology][nlab] * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] ## Implementation notes We define the two separately, rather than defining the Grothendieck topology as that generated by the pretopology for the purpose of having nice definitional properties for the sieves. -/ universe u namespace opens variables (T : Type u) [topological_space T] open category_theory topological_space category_theory.limits /-- The Grothendieck topology associated to a topological space. -/ def grothendieck_topology : grothendieck_topology (opens T) := { sieves := λ X S, ∀ x ∈ X, ∃ U (f : U ⟶ X), S f ∧ x ∈ U, top_mem' := λ X x hx, ⟨_, 𝟙 _, trivial, hx⟩, pullback_stable' := λ X Y S f hf y hy, begin rcases hf y (f.le hy) with ⟨U, g, hg, hU⟩, refine ⟨U ⊓ Y, hom_of_le inf_le_right, _, hU, hy⟩, apply S.downward_closed hg (hom_of_le inf_le_left), end, transitive' := λ X S hS R hR x hx, begin rcases hS x hx with ⟨U, f, hf, hU⟩, rcases hR hf _ hU with ⟨V, g, hg, hV⟩, exact ⟨_, g ≫ f, hg, hV⟩, end } /-- The Grothendieck pretopology associated to a topological space. -/ def pretopology : pretopology (opens T) := { coverings := λ X R, ∀ x ∈ X, ∃ U (f : U ⟶ X), R f ∧ x ∈ U, has_isos := λ X Y f i x hx, by exactI ⟨_, _, presieve.singleton_self _, (inv f).le hx⟩, pullbacks := λ X Y f S hS x hx, begin rcases hS _ (f.le hx) with ⟨U, g, hg, hU⟩, refine ⟨_, _, presieve.pullback_arrows.mk _ _ hg, _⟩, have : U ⊓ Y ≤ pullback g f, refine le_of_hom (pullback.lift (hom_of_le inf_le_left) (hom_of_le inf_le_right) rfl), apply this ⟨hU, hx⟩, end, transitive := λ X S Ti hS hTi x hx, begin rcases hS x hx with ⟨U, f, hf, hU⟩, rcases hTi f hf x hU with ⟨V, g, hg, hV⟩, exact ⟨_, _, ⟨_, g, f, hf, hg, rfl⟩, hV⟩, end } /-- The pretopology associated to a space induces the Grothendieck topology associated to the space. -/ @[simp] lemma pretopology_to_grothendieck : pretopology.to_grothendieck _ (opens.pretopology T) = opens.grothendieck_topology T := begin apply le_antisymm, { rintro X S ⟨R, hR, RS⟩ x hx, rcases hR x hx with ⟨U, f, hf, hU⟩, exact ⟨_, f, RS _ hf, hU⟩ }, { intros X S hS, exact ⟨S, hS, le_refl _⟩ } end end opens
39e4190c5ca60027f441fe5f9579e10ff5711397
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/problem_sheets/Part_II/sheet1_q2_solutions.lean
ccad325cd9ba4dff2fcdd5cab38ae5724998b15c
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
1,905
lean
import tactic variables (x y : ℕ) open nat theorem Q2a : 1 * x = x ∧ x = x * 1 := begin split, { induction x with d hd, refl, rw [mul_succ,hd], }, rw [mul_succ, mul_zero, zero_add], end -- Dr Lawn does not define z in her problem sheet. -- Fortunately I can infer the type of z from the context. variable z : ℕ theorem Q2b : (x + y) * z = x * z + y * z := begin induction z with d hd, refl, rw [mul_succ, hd, mul_succ, mul_succ], ac_refl, end theorem Q2c : (x * y) * z = x * (y * z) := begin induction z with d hd, { refl }, { rw [mul_succ, mul_succ, hd, mul_add] } end -- Q3 def def is_pred (x y : ℕ) := x.succ = y theorem Q3a : ¬ ∃ x : ℕ, is_pred x 0 := begin intro h, cases h with x hx, unfold is_pred at hx, apply succ_ne_zero x, assumption, end theorem Q3b : y ≠ 0 → ∃! x, is_pred x y := begin intro hy, cases y, exfalso, apply hy, refl, clear hy, use y, split, { dsimp only, unfold is_pred, }, intro z, dsimp only [is_pred], exact succ_inj'.1, end def aux : 0 < y → ∃ x, is_pred x y := begin intro hy, cases Q3b _ (ne_of_lt hy).symm with x hx, use x, exact hx.1, end -- definition of pred' is "choose a random d such that succ(d) = n" noncomputable def pred' : ℕ+ → ℕ := λ nhn, classical.some (aux nhn nhn.2) theorem pred'_def : ∀ np : ℕ+, is_pred (pred' np) np := λ nhn, classical.some_spec (aux nhn nhn.2) def succ' : ℕ → ℕ+ := λ n, ⟨n.succ, zero_lt_succ n⟩ noncomputable definition Q3c : ℕ+ ≃ ℕ := { to_fun := pred', inv_fun := succ', left_inv := begin rintro np, have h := pred'_def, unfold succ', ext, dsimp, unfold is_pred at h, rw h, end, right_inv := begin intro n, unfold succ', have h := pred'_def, unfold is_pred at h, rw ← succ_inj', rw h, clear h, refl, end }
0fb9d10dea073ee0d516be2a5d3be7dda61ec908
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/12_Axioms.org.10.lean
57bdfcdc5ec6852bef9d6145356326574d8ca16e
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
92
lean
import standard open eq or local notation `⟨` H₁ `,` H₂ `⟩` := and.intro H₁ H₂
c928f1ec085d80f17c9b5b79c7e48d1109cde209
9c2e8d73b5c5932ceb1333265f17febc6a2f0a39
/src/K/tableau.lean
2970679300412a41b9878bec4377c7e11d20f2cc
[ "MIT" ]
permissive
minchaowu/ModalTab
2150392108dfdcaffc620ff280a8b55fe13c187f
9bb0bf17faf0554d907ef7bdd639648742889178
refs/heads/master
1,626,266,863,244
1,592,056,874,000
1,592,056,874,000
153,314,364
12
1
null
null
null
null
UTF-8
Lean
false
false
1,106
lean
import .full_language .jump def fml_is_sat (Γ : list fml) : bool := match tableau (list.map fml.to_nnf Γ) with | node.closed _ _ _ := ff | node.open_ _ := tt end theorem classical_correctness (Γ : list fml) : fml_is_sat Γ = tt ↔ ∃ (st : Type) (k : kripke st) s, fml_sat k s Γ := begin cases h : fml_is_sat Γ, constructor, { intro, contradiction }, { intro hsat, cases eq : tableau (list.map fml.to_nnf Γ), rcases hsat with ⟨w, k, s, hsat⟩, apply false.elim, apply a, rw trans_sat_iff at hsat, exact hsat, { dsimp [fml_is_sat] at h, rw eq at h, contradiction } }, { split, intro, dsimp [fml_is_sat] at h, cases eq : tableau (list.map fml.to_nnf Γ), { rw eq at h, contradiction }, { split, split, split, have := a_1.2, rw ←trans_sat_iff at this, exact this }, { simp } } end open fml def fml.exm : fml := or (var 1) (neg (var 1)) def K : fml := impl (box (impl (var 1) (var 2))) (impl (box $ var 1) (box $ var 2)) def tst : list fml := [dia $ and (var 0) (neg $ var 1), dia $ var 1, box $ var 2, and (var 1) (var 2)] #eval fml_is_sat tst
273f558b53ca0d0574f2a07eef2af978a33436d5
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/formal/cylinder/definitions.lean
a296e3a7bdede14cc4420a60242393534352785d
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
4,846
lean
import category_theory.base import category_theory.natural_transformation import category_theory.functor_category import category_theory.colimit_lemmas open category_theory open category_theory.category local notation f ` ∘ `:80 g:80 := g ≫ f local notation F ` ∘ᶠ `:80 G:80 := G.comp F universes v u -- TODO: Move these elsewhere notation t ` @> `:90 X:90 := t.app X namespace homotopy_theory.cylinder -- An "abstract endpoint" of a "cylinder"; there are two. inductive endpoint | zero | one instance : has_zero endpoint := ⟨endpoint.zero⟩ instance : has_one endpoint := ⟨endpoint.one⟩ -- A cylinder functor (with contraction). We treat the contraction as -- part of the basic structure as it is needed to define "homotopy -- rel". -- -- The standard example is C = Top, IX = X × [0,1], i ε x = (x, ε), -- p (x, t) = x. class has_cylinder (C : Type u) [category.{v} C] := (I : C ↝ C) (i : endpoint → (functor.id C ⟶ I)) (p : I ⟶ functor.id C) (pi : ∀ ε, p ∘ i ε = nat_trans.id _) section parameters {C : Type u} [category.{v} C] [has_cylinder.{v} C] def I : C ↝ C := has_cylinder.I @[reducible] def i : Π ε, functor.id C ⟶ I := has_cylinder.i @[reducible] def p : I ⟶ functor.id C := has_cylinder.p @[simp] lemma pi_components (ε) {A : C} : p.app A ∘ (i ε).app A = 𝟙 A := show (p ∘ (i ε)).app A = 𝟙 A, by erw has_cylinder.pi; refl lemma i_nat_assoc (ε) {y z w : C} (g : I.obj z ⟶ w) (h : y ⟶ z) : g ∘ i ε @> z ∘ h = g ∘ I &> h ∘ i ε @> y := by erw [←assoc, (i ε).naturality]; simp lemma p_nat_assoc {y z w : C} (g : z ⟶ w) (h : y ⟶ z) : g ∘ p @> z ∘ I &> h = g ∘ h ∘ p @> y := by erw [←assoc, p.naturality]; simp end section boundary variables {C : Type u} [category.{v} C] [has_coproducts.{v} C] -- If C admits coproducts, then we can combine the inclusions `i 0` -- and `i 1` into a single natural transformation `∂I ⟶ I`, where `∂I` -- is defined by `∂I A = A ⊔ A`. (`∂I` does not depend on `I`.) def boundary_I : C ↝ C := { obj := λ A, A ⊔ A, map := λ A B f, coprod_of_maps f f, map_id' := λ A, by apply coprod.uniqueness; simp, map_comp' := λ A B C f g, by apply coprod.uniqueness; rw ←assoc; simp } notation `∂I` := boundary_I variables [has_cylinder C] def ii : ∂I ⟶ I := show ∂I ⟶ (I : C ↝ C), from { app := λ (A : C), coprod.induced (i 0 @> A) (i 1 @> A), naturality' := λ A B f, begin dsimp [boundary_I], apply coprod.uniqueness; { rw [←assoc, ←assoc], simpa using (i _).naturality f } end } @[simp] lemma iii₀_assoc {A B : C} (f : I.obj A ⟶ B) : f ∘ ii.app A ∘ i₀ = f ∘ (i 0).app A := by rw ←assoc; dsimp [ii]; simp @[simp] lemma iii₁_assoc {A B : C} (f : I.obj A ⟶ B) : f ∘ ii.app A ∘ i₁ = f ∘ (i 1).app A := by rw ←assoc; dsimp [ii]; simp end boundary def endpoint.v : endpoint → endpoint | endpoint.zero := endpoint.one | endpoint.one := endpoint.zero @[simp] lemma endpoint.vv (ε : endpoint) : ε.v.v = ε := by cases ε; refl -- "Time-reversal" on a cylinder functor. The standard example is (on -- Top as above) v (x, t) = (x, 1 - t). -- -- The condition v² = 1 is not in Williamson; we add it here because -- it holds in the standard examples and lets us reverse the homotopy -- extension property. (Actually it would be enough for v to be an -- isomorphism.) class has_cylinder_with_involution (C : Type u) [category C] extends has_cylinder C := (v : I ⟶ I) (vi : ∀ ε, v ∘ i ε = i ε.v) (vv : v ∘ v = 𝟙 _) (pv : p ∘ v = p) section parameters {C : Type u} [category.{v} C] [has_cylinder_with_involution C] local notation `I` := (I : C ↝ C) @[reducible] def v : I ⟶ I := has_cylinder_with_involution.v @[simp] lemma vi_components {A : C} (ε) : v @> A ∘ i ε @> A = i ε.v @> A := show (v ∘ i ε) @> A = (i ε.v) @> A, by rw has_cylinder_with_involution.vi; refl @[simp] lemma vv_components {A : C} : v @> A ∘ v @> A = 𝟙 (I.obj A) := show (v ∘ v) @> A = _, by rw has_cylinder_with_involution.vv; refl end section interchange variables (C : Type u) [cat : category.{v} C] [has_cylinder C] include cat -- This one is still necessary because of some weird interaction -- between the "local notation `I`" and "variables {C}" below. local notation `I` := (I : C ↝ C) -- Interchange of two applications of the cylinder functor. The -- standard example is (on Top as above) T (x, t, t') = (x, t', t). class cylinder_has_interchange := (T : I ∘ᶠ I ⟶ I ∘ᶠ I) (Ti : ∀ ε A, T @> _ ∘ i ε @> I.obj A = I &> (i ε @> A)) (TIi : ∀ ε A, T @> _ ∘ I &> (i ε @> A) = i ε @> I.obj A) variables [cylinder_has_interchange.{v} C] variables {C} @[reducible] def T : I ∘ᶠ I ⟶ I ∘ᶠ I := cylinder_has_interchange.T end interchange end homotopy_theory.cylinder
41bf9ec04316ef76224923f095aa1e86a747a452
4727251e0cd73359b15b664c3170e5d754078599
/src/control/uliftable.lean
3cdadee22171d8c1bf7a916b4f532dbb93f8c2cf
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,581
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.monad.basic import control.monad.cont import control.monad.writer import logic.equiv.basic import tactic.interactive /-! # Universe lifting for type families Some functors such as `option` and `list` are universe polymorphic. Unlike type polymorphism where `option α` is a function application and reasoning and generalizations that apply to functions can be used, `option.{u}` and `option.{v}` are not one function applied to two universe names but one polymorphic definition instantiated twice. This means that whatever works on `option.{u}` is hard to transport over to `option.{v}`. `uliftable` is an attempt at improving the situation. `uliftable option.{u} option.{v}` gives us a generic and composable way to use `option.{u}` in a context that requires `option.{v}`. It is often used in tandem with `ulift` but the two are purposefully decoupled. ## Main definitions * `uliftable` class ## Tags universe polymorphism functor -/ universes u₀ u₁ v₀ v₁ v₂ w w₀ w₁ variables {s : Type u₀} {s' : Type u₁} {r r' w w' : Type*} /-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type u₂`, this class convert between instantiations, from `M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/ class uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) := (congr [] {α β} : α ≃ β → f α ≃ g β) namespace uliftable /-- The most common practical use `uliftable` (together with `up`), this function takes `x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/ @[reducible] def up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} : f α → g (ulift α) := (uliftable.congr f g equiv.ulift.symm).to_fun /-- The most common practical use of `uliftable` (together with `up`), this function takes `x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/ @[reducible] def down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} : g (ulift α) → f α := (uliftable.congr f g equiv.ulift.symm).inv_fun /-- convenient shortcut to avoid manipulating `ulift` -/ def adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁) [uliftable F G] [monad G] {α β} (x : F α) (f : α → G β) : G β := up x >>= f ∘ ulift.down /-- convenient shortcut to avoid manipulating `ulift` -/ def adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁} [L : uliftable G F] [monad F] {α β} (x : F α) (f : α → G β) : G β := @down.{v₀ v₁ (max u₀ v₀)} G F L β $ x >>= @up.{v₀ v₁ (max u₀ v₀)} G F L β ∘ f /-- map function that moves up universes -/ def up_map {F : Type u₀ → Type u₁} {G : Type.{max u₀ v₀} → Type v₁} [inst : uliftable F G] [functor G] {α β} (f : α → β) (x : F α) : G β := functor.map (f ∘ ulift.down) (up x) /-- map function that moves down universes -/ def down_map {F : Type.{max u₀ v₀} → Type u₁} {G : Type u₀ → Type v₁} [inst : uliftable G F] [functor F] {α β} (f : α → β) (x : F α) : G β := down (functor.map (ulift.up ∘ f) x : F (ulift β)) @[simp] lemma up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} (x : g (ulift α)) : up (down x : f α) = x := (uliftable.congr f g equiv.ulift.symm).right_inv _ @[simp] lemma down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} (x : f α) : down (up x : g _) = x := (uliftable.congr f g equiv.ulift.symm).left_inv _ end uliftable open ulift instance : uliftable id id := { congr := λ α β F, F } /-- for specific state types, this function helps to create a uliftable instance -/ def state_t.uliftable' {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁} [uliftable m m'] (F : s ≃ s') : uliftable (state_t s m) (state_t s' m') := { congr := λ α β G, state_t.equiv $ equiv.Pi_congr F $ λ _, uliftable.congr _ _ $ equiv.prod_congr G F } instance {m m'} [uliftable m m'] : uliftable (state_t s m) (state_t (ulift s) m') := state_t.uliftable' equiv.ulift.symm /-- for specific reader monads, this function helps to create a uliftable instance -/ def reader_t.uliftable' {m m'} [uliftable m m'] (F : s ≃ s') : uliftable (reader_t s m) (reader_t s' m') := { congr := λ α β G, reader_t.equiv $ equiv.Pi_congr F $ λ _, uliftable.congr _ _ G } instance {m m'} [uliftable m m'] : uliftable (reader_t s m) (reader_t (ulift s) m') := reader_t.uliftable' equiv.ulift.symm /-- for specific continuation passing monads, this function helps to create a uliftable instance -/ def cont_t.uliftable' {m m'} [uliftable m m'] (F : r ≃ r') : uliftable (cont_t r m) (cont_t r' m') := { congr := λ α β, cont_t.equiv (uliftable.congr _ _ F) } instance {s m m'} [uliftable m m'] : uliftable (cont_t s m) (cont_t (ulift s) m') := cont_t.uliftable' equiv.ulift.symm /-- for specific writer monads, this function helps to create a uliftable instance -/ def writer_t.uliftable' {m m'} [uliftable m m'] (F : w ≃ w') : uliftable (writer_t w m) (writer_t w' m') := { congr := λ α β G, writer_t.equiv $ uliftable.congr _ _ $ equiv.prod_congr G F } instance {m m'} [uliftable m m'] : uliftable (writer_t s m) (writer_t (ulift s) m') := writer_t.uliftable' equiv.ulift.symm
edfd49e20df6cc54658c268a4e82369ab21a4518
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/stage0/src/Lean/Elab.lean
03f42f5f00084857a27c1d327dfb7416536aa6bf
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
1,211
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.Elab.Import import Lean.Elab.Exception import Lean.Elab.Config import Lean.Elab.Command import Lean.Elab.Term import Lean.Elab.App import Lean.Elab.Binders import Lean.Elab.LetRec import Lean.Elab.Frontend import Lean.Elab.BuiltinNotation import Lean.Elab.Declaration import Lean.Elab.Tactic import Lean.Elab.Match -- HACK: must come after `Match` because builtin elaborators (for `match` in this case) do not take priorities import Lean.Elab.Quotation import Lean.Elab.Syntax import Lean.Elab.Do import Lean.Elab.StructInst import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.Print import Lean.Elab.MutualDef import Lean.Elab.AuxDef import Lean.Elab.PreDefinition import Lean.Elab.Deriving import Lean.Elab.DeclarationRange import Lean.Elab.Extra import Lean.Elab.GenInjective import Lean.Elab.BuiltinTerm import Lean.Elab.Arg import Lean.Elab.PatternVar import Lean.Elab.ElabRules import Lean.Elab.Macro import Lean.Elab.Notation import Lean.Elab.Mixfix import Lean.Elab.MacroRules import Lean.Elab.BuiltinCommand
975d3013229860bcedfed8fcb475da8e87dba826
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/sheaves/sheaf_of_functions.lean
ae650e24d907ddaa10a11e0d87e3d4187e9d40d6
[ "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
4,024
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import topology.sheaves.presheaf_of_functions import topology.sheaves.sheaf_condition.unique_gluing import category_theory.limits.shapes.types import topology.local_homeomorph /-! # Sheaf conditions for presheaves of (continuous) functions. We show that * `Top.sheaf_condition.to_Type`: not-necessarily-continuous functions into a type form a sheaf * `Top.sheaf_condition.to_Types`: in fact, these may be dependent functions into a type family For * `Top.sheaf_condition.to_Top`: continuous functions into a topological space form a sheaf please see `topology/sheaves/local_predicate.lean`, where we set up a general framework for constructing sub(pre)sheaves of the sheaf of dependent functions. ## Future work Obviously there's more to do: * sections of a fiber bundle * various classes of smooth and structure preserving functions * functions into spaces with algebraic structure, which the sections inherit -/ open category_theory open category_theory.limits open topological_space open topological_space.opens universe u noncomputable theory variables (X : Top.{u}) open Top namespace Top.presheaf /-- We show that the presheaf of functions to a type `T` (no continuity assumptions, just plain functions) form a sheaf. In fact, the proof is identical when we do this for dependent functions to a type family `T`, so we do the more general case. -/ lemma to_Types_is_sheaf (T : X → Type u) : (presheaf_to_Types X T).is_sheaf := is_sheaf_of_is_sheaf_unique_gluing_types _ $ λ ι U sf hsf, -- We use the sheaf condition in terms of unique gluing -- U is a family of open sets, indexed by `ι` and `sf` is a compatible family of sections. -- In the informal comments below, I'll just write `U` to represent the union. begin -- Our first goal is to define a function "lifted" to all of `U`. -- We do this one point at a time. Using the axiom of choice, we can pick for each -- `x : supr U` an index `i : ι` such that `x` lies in `U i` choose index index_spec using λ x : supr U, opens.mem_supr.mp x.2, -- Using this data, we can glue our functions together to a single section let s : Π x : supr U, T x := λ x, sf (index x) ⟨x.1, index_spec x⟩, refine ⟨s,_,_⟩, { intro i, ext x, -- Now we need to verify that this lifted function restricts correctly to each set `U i`. -- Of course, the difficulty is that at any given point `x ∈ U i`, -- we may have used the axiom of choice to pick a different `j` with `x ∈ U j` -- when defining the function. -- Thus we'll need to use the fact that the restrictions are compatible. convert congr_fun (hsf (index ⟨x,_⟩) i) ⟨x,⟨index_spec ⟨x.1,_⟩,x.2⟩⟩, ext, refl }, { -- Now we just need to check that the lift we picked was the only possible one. -- So we suppose we had some other gluing `t` of our sections intros t ht, -- and observe that we need to check that it agrees with our choice -- for each `f : s .X` and each `x ∈ supr U`. ext x, convert congr_fun (ht (index x)) ⟨x.1,index_spec x⟩, ext, refl } end -- We verify that the non-dependent version is an immediate consequence: /-- The presheaf of not-necessarily-continuous functions to a target type `T` satsifies the sheaf condition. -/ lemma to_Type_is_sheaf (T : Type u) : (presheaf_to_Type X T).is_sheaf := to_Types_is_sheaf X (λ _, T) end Top.presheaf namespace Top /-- The sheaf of not-necessarily-continuous functions on `X` with values in type family `T : X → Type u`. -/ def sheaf_to_Types (T : X → Type u) : sheaf (Type u) X := ⟨presheaf_to_Types X T, presheaf.to_Types_is_sheaf _ _⟩ /-- The sheaf of not-necessarily-continuous functions on `X` with values in a type `T`. -/ def sheaf_to_Type (T : Type u) : sheaf (Type u) X := ⟨presheaf_to_Type X T, presheaf.to_Type_is_sheaf _ _⟩ end Top
0745d443ee8fc22b99ce5fc0c8258b0127b6fd10
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/induction_tac3.lean
f0305aaf75870364696b3cb723683690a14dac36
[ "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
506
lean
open tactic example (p q : Prop) : p ∨ q → q ∨ p := by do H ← intro `H, induction H, constructor_idx 2, assumption, constructor_idx 1, assumption open nat example (n : ℕ) : n = 0 ∨ n = succ (pred n) := by do n ← get_local `n, induction n, constructor_idx 1, reflexivity, constructor_idx 2, reflexivity, return () example (n : ℕ) (H : n ≠ 0) : n > 0 → n = succ (pred n) := by do n ← get_local `n, induction n, intro `H1, contradiction, intros, reflexivity
af82b8f24c5c10a4e8c5c2071ee2ea77559aedf4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/category/Profinite/as_limit.lean
da4c971533e1a9ab63d09410507bf3aeb1a32caf
[ "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,307
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne, Adam Topaz -/ import topology.category.Profinite.basic import topology.discrete_quotient /-! # Profinite sets as limits of finite sets. We show that any profinite set is isomorphic to the limit of its discrete (hence finite) quotients. ## Definitions There are a handful of definitions in this file, given `X : Profinite`: 1. `X.fintype_diagram` is the functor `discrete_quotient X ⥤ Fintype` whose limit is isomorphic to `X` (the limit taking place in `Profinite` via `Fintype_to_Profinite`, see 2). 2. `X.diagram` is an abbreviation for `X.fintype_diagram ⋙ Fintype_to_Profinite`. 3. `X.as_limit_cone` is the cone over `X.diagram` whose cone point is `X`. 4. `X.iso_as_limit_cone_lift` is the isomorphism `X ≅ (Profinite.limit_cone X.diagram).X` induced by lifting `X.as_limit_cone`. 5. `X.as_limit_cone_iso` is the isomorphism `X.as_limit_cone ≅ (Profinite.limit_cone X.diagram)` induced by `X.iso_as_limit_cone_lift`. 6. `X.as_limit` is a term of type `is_limit X.as_limit_cone`. 7. `X.lim : category_theory.limits.limit_cone X.as_limit_cone` is a bundled combination of 3 and 6. -/ noncomputable theory open category_theory namespace Profinite universe u variables (X : Profinite.{u}) /-- The functor `discrete_quotient X ⥤ Fintype` whose limit is isomorphic to `X`. -/ def fintype_diagram : discrete_quotient X ⥤ Fintype := { obj := λ S, Fintype.of S, map := λ S T f, discrete_quotient.of_le f.le } /-- An abbreviation for `X.fintype_diagram ⋙ Fintype_to_Profinite`. -/ abbreviation diagram : discrete_quotient X ⥤ Profinite := X.fintype_diagram ⋙ Fintype.to_Profinite /-- A cone over `X.diagram` whose cone point is `X`. -/ def as_limit_cone : category_theory.limits.cone X.diagram := { X := X, π := { app := λ S, ⟨S.proj, S.proj_is_locally_constant.continuous⟩ } } instance is_iso_as_limit_cone_lift : is_iso ((limit_cone_is_limit X.diagram).lift X.as_limit_cone) := is_iso_of_bijective _ begin refine ⟨λ a b, _, λ a, _⟩, { intro h, refine discrete_quotient.eq_of_proj_eq (λ S, _), apply_fun (λ f : (limit_cone X.diagram).X, f.val S) at h, exact h }, { obtain ⟨b, hb⟩ := discrete_quotient.exists_of_compat (λ S, a.val S) (λ _ _ h, a.prop (hom_of_le h)), refine ⟨b, _⟩, ext S : 3, apply hb }, end /-- The isomorphism between `X` and the explicit limit of `X.diagram`, induced by lifting `X.as_limit_cone`. -/ def iso_as_limit_cone_lift : X ≅ (limit_cone X.diagram).X := as_iso $ (limit_cone_is_limit _).lift X.as_limit_cone /-- The isomorphism of cones `X.as_limit_cone` and `Profinite.limit_cone X.diagram`. The underlying isomorphism is defeq to `X.iso_as_limit_cone_lift`. -/ def as_limit_cone_iso : X.as_limit_cone ≅ limit_cone _ := limits.cones.ext (iso_as_limit_cone_lift _) (λ _, rfl) /-- `X.as_limit_cone` is indeed a limit cone. -/ def as_limit : category_theory.limits.is_limit X.as_limit_cone := limits.is_limit.of_iso_limit (limit_cone_is_limit _) X.as_limit_cone_iso.symm /-- A bundled version of `X.as_limit_cone` and `X.as_limit`. -/ def lim : limits.limit_cone X.diagram := ⟨X.as_limit_cone, X.as_limit⟩ end Profinite
bcc5e29a1b2fb2e9ad9ac7c0a840735dac34acad
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/interp.lean
aeecc41c5a5324be45e2c5abb8cd449d012bc5d6
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
747
lean
open bool nat open function inductive univ := | ubool : univ | unat : univ | uarrow : univ → univ → univ open univ definition interp : univ → Type₁ | ubool := bool | unat := nat | (uarrow fr to) := interp fr → interp to definition foo : Π (u : univ) (el : interp u), interp u | ubool tt := ff | ubool ff := tt | unat n := succ n | (uarrow fr to) f := λ x : interp fr, f (foo fr x) definition is_even : nat → bool | zero := tt | (succ n) := bnot (is_even n) example : foo unat 10 = 11 := rfl example : foo ubool tt = ff := rfl example : foo (uarrow unat ubool) (λ x : nat, is_even x) 3 = tt := rfl example : foo (uarrow unat ubool) (λ x : nat, is_even x) 4 = ff := rfl
1b7d2751d109dbbc62f2f70018bae2e2d5e5b61f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/def10.lean
ea254c6f0bc53dc8edc703b6479ba2f8137ea5bf
[ "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
450
lean
open nat inductive bv : nat → Type | nil : bv 0 | cons : ∀ (n) (hd : bool) (tl : bv n), bv (succ n) open bv bool definition h : ∀ {n}, bv (succ (succ n)) → bool | .(succ m) (cons (succ (succ m)) b v) := b | .(0) (cons (succ nat.zero) b v) := bnot b example (m : nat) (b : bool) (v : bv (succ (succ m))) : @h (succ m) (cons (succ (succ m)) b v) = b := rfl example (m : nat) (b : bool) (v : bv 1) : @h 0 (cons 1 b v) = bnot b := rfl
79f46201e780abf2469716379a181ae22e6afcaa
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/abelian/homology.lean
4aea6cb3442c6393dfbaec50c6925b7356d13a56
[ "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
11,952
lean
/- Copyright (c) 2022 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Amelia Livingston -/ import algebra.homology.additive import category_theory.abelian.pseudoelements import category_theory.limits.preserves.shapes.kernels import category_theory.limits.preserves.shapes.images /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The object `homology f g w`, where `w : f ≫ g = 0`, can be identified with either a cokernel or a kernel. The isomorphism with a cokernel is `homology_iso_cokernel_lift`, which was obtained elsewhere. In the case of an abelian category, this file shows the isomorphism with a kernel as well. We use these isomorphisms to obtain the analogous api for `homology`: - `homology.ι` is the map from `homology f g w` into the cokernel of `f`. - `homology.π'` is the map from `kernel g` to `homology f g w`. - `homology.desc'` constructs a morphism from `homology f g w`, when it is viewed as a cokernel. - `homology.lift` constructs a morphism to `homology f g w`, when it is viewed as a kernel. - Various small lemmas are proved as well, mimicking the API for (co)kernels. With these definitions and lemmas, the isomorphisms between homology and a (co)kernel need not be used directly. -/ open category_theory.limits open category_theory noncomputable theory universes v u variables {A : Type u} [category.{v} A] [abelian A] variables {X Y Z : A} (f : X ⟶ Y) (g : Y ⟶ Z) (w : f ≫ g = 0) namespace category_theory.abelian /-- The cokernel of `kernel.lift g f w`. This is isomorphic to `homology f g w`. See `homology_iso_cokernel_lift`. -/ abbreviation homology_c : A := cokernel (kernel.lift g f w) /-- The kernel of `cokernel.desc f g w`. This is isomorphic to `homology f g w`. See `homology_iso_kernel_desc`. -/ abbreviation homology_k : A := kernel (cokernel.desc f g w) /-- The canonical map from `homology_c` to `homology_k`. This is an isomorphism, and it is used in obtaining the API for `homology f g w` in the bottom of this file. -/ abbreviation homology_c_to_k : homology_c f g w ⟶ homology_k f g w := cokernel.desc _ (kernel.lift _ (kernel.ι _ ≫ cokernel.π _) (by simp)) begin apply limits.equalizer.hom_ext, simp, end local attribute [instance] pseudoelement.hom_to_fun pseudoelement.has_zero instance : mono (homology_c_to_k f g w) := begin apply pseudoelement.mono_of_zero_of_map_zero, intros a ha, obtain ⟨a,rfl⟩ := pseudoelement.pseudo_surjective_of_epi (cokernel.π (kernel.lift g f w)) a, apply_fun (kernel.ι (cokernel.desc f g w)) at ha, simp only [←pseudoelement.comp_apply, cokernel.π_desc, kernel.lift_ι, pseudoelement.apply_zero] at ha, simp only [pseudoelement.comp_apply] at ha, obtain ⟨b,hb⟩ : ∃ b, f b = _ := (pseudoelement.pseudo_exact_of_exact (exact_cokernel f)).2 _ ha, rsuffices ⟨c, rfl⟩ : ∃ c, kernel.lift g f w c = a, { simp [← pseudoelement.comp_apply] }, use b, apply_fun kernel.ι g, swap, { apply pseudoelement.pseudo_injective_of_mono }, simpa [← pseudoelement.comp_apply] end instance : epi (homology_c_to_k f g w) := begin apply pseudoelement.epi_of_pseudo_surjective, intros a, let b := kernel.ι (cokernel.desc f g w) a, obtain ⟨c,hc⟩ : ∃ c, cokernel.π f c = b, apply pseudoelement.pseudo_surjective_of_epi (cokernel.π f), have : g c = 0, { dsimp [b] at hc, rw [(show g = cokernel.π f ≫ cokernel.desc f g w, by simp), pseudoelement.comp_apply, hc], simp [← pseudoelement.comp_apply] }, obtain ⟨d,hd⟩ : ∃ d, kernel.ι g d = c, { apply (pseudoelement.pseudo_exact_of_exact exact_kernel_ι).2 _ this }, use cokernel.π (kernel.lift g f w) d, apply_fun kernel.ι (cokernel.desc f g w), swap, { apply pseudoelement.pseudo_injective_of_mono }, simp only [←pseudoelement.comp_apply, cokernel.π_desc, kernel.lift_ι], simp only [pseudoelement.comp_apply, hd, hc], end instance (w : f ≫ g = 0) : is_iso (homology_c_to_k f g w) := is_iso_of_mono_of_epi _ end category_theory.abelian /-- The homology associated to `f` and `g` is isomorphic to a kernel. -/ def homology_iso_kernel_desc : homology f g w ≅ kernel (cokernel.desc f g w) := homology_iso_cokernel_lift _ _ _ ≪≫ as_iso (category_theory.abelian.homology_c_to_k _ _ _) namespace homology -- `homology.π` is taken /-- The canonical map from the kernel of `g` to the homology of `f` and `g`. -/ def π' : kernel g ⟶ homology f g w := cokernel.π _ ≫ (homology_iso_cokernel_lift _ _ _).inv /-- The canonical map from the homology of `f` and `g` to the cokernel of `f`. -/ def ι : homology f g w ⟶ cokernel f := (homology_iso_kernel_desc _ _ _).hom ≫ kernel.ι _ /-- Obtain a morphism from the homology, given a morphism from the kernel. -/ def desc' {W : A} (e : kernel g ⟶ W) (he : kernel.lift g f w ≫ e = 0) : homology f g w ⟶ W := (homology_iso_cokernel_lift _ _ _).hom ≫ cokernel.desc _ e he /-- Obtain a moprhism to the homology, given a morphism to the kernel. -/ def lift {W : A} (e : W ⟶ cokernel f) (he : e ≫ cokernel.desc f g w = 0) : W ⟶ homology f g w := kernel.lift _ e he ≫ (homology_iso_kernel_desc _ _ _).inv @[simp, reassoc] lemma π'_desc' {W : A} (e : kernel g ⟶ W) (he : kernel.lift g f w ≫ e = 0) : π' f g w ≫ desc' f g w e he = e := by { dsimp [π', desc'], simp } @[simp, reassoc] lemma lift_ι {W : A} (e : W ⟶ cokernel f) (he : e ≫ cokernel.desc f g w = 0) : lift f g w e he ≫ ι _ _ _ = e := by { dsimp [ι, lift], simp } @[simp, reassoc] lemma condition_π' : kernel.lift g f w ≫ π' f g w = 0 := by { dsimp [π'], simp } @[simp, reassoc] lemma condition_ι : ι f g w ≫ cokernel.desc f g w = 0 := by { dsimp [ι], simp } @[ext] lemma hom_from_ext {W : A} (a b : homology f g w ⟶ W) (h : π' f g w ≫ a = π' f g w ≫ b) : a = b := begin dsimp [π'] at h, apply_fun (λ e, (homology_iso_cokernel_lift f g w).inv ≫ e), swap, { intros i j hh, apply_fun (λ e, (homology_iso_cokernel_lift f g w).hom ≫ e) at hh, simpa using hh }, simp only [category.assoc] at h, exact coequalizer.hom_ext h, end @[ext] lemma hom_to_ext {W : A} (a b : W ⟶ homology f g w) (h : a ≫ ι f g w = b ≫ ι f g w) : a = b := begin dsimp [ι] at h, apply_fun (λ e, e ≫ (homology_iso_kernel_desc f g w).hom), swap, { intros i j hh, apply_fun (λ e, e ≫ (homology_iso_kernel_desc f g w).inv) at hh, simpa using hh }, simp only [← category.assoc] at h, exact equalizer.hom_ext h, end @[simp, reassoc] lemma π'_ι : π' f g w ≫ ι f g w = kernel.ι _ ≫ cokernel.π _ := by { dsimp [π', ι, homology_iso_kernel_desc], simp } @[simp, reassoc] lemma π'_eq_π : (kernel_subobject_iso _).hom ≫ π' f g w = π _ _ _ := begin dsimp [π', homology_iso_cokernel_lift], simp only [← category.assoc], rw iso.comp_inv_eq, dsimp [π, homology_iso_cokernel_image_to_kernel'], simp, end section variables {X' Y' Z' : A} (f' : X' ⟶ Y') (g' : Y' ⟶ Z') (w' : f' ≫ g' = 0) @[simp, reassoc] lemma π'_map (α β h) : π' _ _ _ ≫ map w w' α β h = kernel.map _ _ α.right β.right (by simp [h,β.w.symm]) ≫ π' _ _ _ := begin apply_fun (λ e, (kernel_subobject_iso _).hom ≫ e), swap, { intros i j hh, apply_fun (λ e, (kernel_subobject_iso _).inv ≫ e) at hh, simpa using hh }, dsimp [map], simp only [π'_eq_π_assoc], dsimp [π], simp only [cokernel.π_desc], rw [← iso.inv_comp_eq, ← category.assoc], have : (limits.kernel_subobject_iso g).inv ≫ limits.kernel_subobject_map β = kernel.map _ _ β.left β.right β.w.symm ≫ (kernel_subobject_iso _).inv, { rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv], ext, dsimp, simp }, rw this, simp only [category.assoc], dsimp [π', homology_iso_cokernel_lift], simp only [cokernel_iso_of_eq_inv_comp_desc, cokernel.π_desc_assoc], congr' 1, { congr, exact h.symm }, { rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv], dsimp [homology_iso_cokernel_image_to_kernel'], simp } end lemma map_eq_desc'_lift_left (α β h) : map w w' α β h = homology.desc' _ _ _ (homology.lift _ _ _ (kernel.ι _ ≫ β.left ≫ cokernel.π _) (by simp)) (by { ext, simp only [←h, category.assoc, zero_comp, lift_ι, kernel.lift_ι_assoc], erw ← reassoc_of α.w, simp } ) := begin apply homology.hom_from_ext, simp only [π'_map, π'_desc'], dsimp [π', lift], rw iso.eq_comp_inv, dsimp [homology_iso_kernel_desc], ext, simp [h], end lemma map_eq_lift_desc'_left (α β h) : map w w' α β h = homology.lift _ _ _ (homology.desc' _ _ _ (kernel.ι _ ≫ β.left ≫ cokernel.π _) (by { simp only [kernel.lift_ι_assoc, ← h], erw ← reassoc_of α.w, simp })) (by { ext, simp }) := by { rw map_eq_desc'_lift_left, ext, simp } lemma map_eq_desc'_lift_right (α β h) : map w w' α β h = homology.desc' _ _ _ (homology.lift _ _ _ (kernel.ι _ ≫ α.right ≫ cokernel.π _) (by simp [h])) (by { ext, simp only [category.assoc, zero_comp, lift_ι, kernel.lift_ι_assoc], erw ← reassoc_of α.w, simp } ) := by { rw map_eq_desc'_lift_left, ext, simp [h] } lemma map_eq_lift_desc'_right (α β h) : map w w' α β h = homology.lift _ _ _ (homology.desc' _ _ _ (kernel.ι _ ≫ α.right ≫ cokernel.π _) (by { simp only [kernel.lift_ι_assoc], erw ← reassoc_of α.w, simp })) (by { ext, simp [h] }) := by { rw map_eq_desc'_lift_right, ext, simp } @[simp, reassoc] lemma map_ι (α β h) : map w w' α β h ≫ ι f' g' w' = ι f g w ≫ cokernel.map f f' α.left β.left (by simp [h, β.w.symm]) := begin rw [map_eq_lift_desc'_left, lift_ι], ext, simp only [← category.assoc], rw [π'_ι, π'_desc', category.assoc, category.assoc, cokernel.π_desc], end end end homology namespace category_theory.functor variables {ι : Type*} {c : complex_shape ι} {B : Type*} [category B] [abelian B] (F : A ⥤ B) [functor.additive F] [preserves_finite_limits F] [preserves_finite_colimits F] /-- When `F` is an exact additive functor, `F(Hᵢ(X)) ≅ Hᵢ(F(X))` for `X` a complex. -/ noncomputable def homology_iso (C : homological_complex A c) (j : ι) : F.obj (C.homology j) ≅ ((F.map_homological_complex _).obj C).homology j := (preserves_cokernel.iso _ _).trans (cokernel.map_iso _ _ ((F.map_iso (image_subobject_iso _)).trans ((preserves_image.iso _ _).symm.trans (image_subobject_iso _).symm)) ((F.map_iso (kernel_subobject_iso _)).trans ((preserves_kernel.iso _ _).trans (kernel_subobject_iso _).symm)) begin dsimp, ext, simp only [category.assoc, image_to_kernel_arrow], erw [kernel_subobject_arrow', kernel_comparison_comp_ι, image_subobject_arrow'], simp [←F.map_comp], end) /-- If `F` is an exact additive functor, then `F` commutes with `Hᵢ` (up to natural isomorphism). -/ noncomputable def homology_functor_iso (i : ι) : homology_functor A c i ⋙ F ≅ F.map_homological_complex c ⋙ homology_functor B c i := nat_iso.of_components (λ X, homology_iso F X i) begin intros X Y f, dsimp, rw [←iso.inv_comp_eq, ←category.assoc, ←iso.eq_comp_inv], refine coequalizer.hom_ext _, dsimp [homology_iso], simp only [homology.map, ←category.assoc, cokernel.π_desc], simp only [category.assoc, cokernel_comparison_map_desc, cokernel.π_desc, π_comp_cokernel_comparison, ←F.map_comp], erw ←kernel_subobject_iso_comp_kernel_map_assoc, simp only [homological_complex.hom.sq_from_right, homological_complex.hom.sq_from_left, F.map_homological_complex_map_f, F.map_comp], dunfold homological_complex.d_from homological_complex.hom.next, dsimp, rw [kernel_map_comp_preserves_kernel_iso_inv_assoc, ←F.map_comp_assoc, ←kernel_map_comp_kernel_subobject_iso_inv], any_goals { simp }, end end category_theory.functor
ee3c7f44922092e71671b026fc17e52ce6dcb8f5
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/set/finite.lean
0cd1144cbf2ce9900d43c08df1c8661e41d915c9
[ "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
53,764
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, Kyle Miller -/ import data.finset.sort import data.set.functor import data.finite.basic /-! # Finite sets This file defines predicates for finite and infinite sets and provides `fintype` instances for many set constructions. It also proves basic facts about finite sets and gives ways to manipulate `set.finite` expressions. ## Main definitions * `set.finite : set α → Prop` * `set.infinite : set α → Prop` * `set.to_finite` to prove `set.finite` for a `set` from a `finite` instance. * `set.finite.to_finset` to noncomputably produce a `finset` from a `set.finite` proof. (See `set.to_finset` for a computable version.) ## Implementation A finite set is defined to be a set whose coercion to a type has a `fintype` instance. Since `set.finite` is `Prop`-valued, this is the mere fact that the `fintype` instance exists. There are two components to finiteness constructions. The first is `fintype` instances for each construction. This gives a way to actually compute a `finset` that represents the set, and these may be accessed using `set.to_finset`. This gets the `finset` in the correct form, since otherwise `finset.univ : finset s` is a `finset` for the subtype for `s`. The second component is "constructors" for `set.finite` that give proofs that `fintype` instances exist classically given other `set.finite` proofs. Unlike the `fintype` instances, these *do not* use any decidability instances since they do not compute anything. ## Tags finite sets -/ open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if there is a `finset` with the same elements. This is represented as there being a `fintype` instance for the set coerced to a type. Note: this is a custom inductive type rather than `nonempty (fintype s)` so that it won't be frozen as a local instance. -/ @[protected] inductive finite (s : set α) : Prop | intro : fintype s → finite -- The `protected` attribute does not take effect within the same namespace block. end set namespace set lemma finite_def {s : set α} : s.finite ↔ nonempty (fintype s) := ⟨λ ⟨h⟩, ⟨h⟩, λ ⟨h⟩, ⟨h⟩⟩ alias finite_def ↔ finite.nonempty_fintype _ lemma finite_coe_iff {s : set α} : finite s ↔ s.finite := by rw [finite_iff_nonempty_fintype, finite_def] /-- Constructor for `set.finite` using a `finite` instance. -/ theorem to_finite (s : set α) [finite s] : s.finite := finite_coe_iff.mp ‹_› /-- Construct a `finite` instance for a `set` from a `finset` with the same elements. -/ protected lemma finite.of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : p.finite := ⟨fintype.of_finset s H⟩ /-- Projection of `set.finite` to its `finite` instance. This is intended to be used with dot notation. See also `set.finite.fintype` and `set.finite.nonempty_fintype`. -/ protected lemma finite.to_subtype {s : set α} (h : s.finite) : finite s := finite_coe_iff.mpr h /-- A finite set coerced to a type is a `fintype`. This is the `fintype` projection for a `set.finite`. Note that because `finite` isn't a typeclass, this definition will not fire if it is made into an instance -/ protected noncomputable def finite.fintype {s : set α} (h : s.finite) : fintype s := h.nonempty_fintype.some /-- Using choice, get the `finset` that represents this `set.` -/ protected noncomputable def finite.to_finset {s : set α} (h : s.finite) : finset α := @set.to_finset _ _ h.fintype theorem finite.exists_finset {s : set α} (h : s.finite) : ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s := by { casesI h, exact ⟨s.to_finset, λ _, mem_to_finset⟩ } theorem finite.exists_finset_coe {s : set α} (h : s.finite) : ∃ s' : finset α, ↑s' = s := by { casesI h, exact ⟨s.to_finset, s.coe_to_finset⟩ } /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) coe set.finite := { prf := λ s hs, hs.exists_finset_coe } /-- A set is infinite if it is not finite. This is protected so that it does not conflict with global `infinite`. -/ protected def infinite (s : set α) : Prop := ¬ s.finite @[simp] lemma not_infinite {s : set α} : ¬ s.infinite ↔ s.finite := not_not /-- See also `finite_or_infinite`, `fintype_or_infinite`. -/ protected lemma finite_or_infinite (s : set α) : s.finite ∨ s.infinite := em _ /-! ### Basic properties of `set.finite.to_finset` -/ namespace finite variables {s t : set α} {a : α} {hs : s.finite} {ht : t.finite} @[simp] protected lemma mem_to_finset (h : s.finite) : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] protected lemma coe_to_finset (h : s.finite) : (h.to_finset : set α) = s := @coe_to_finset _ _ h.fintype @[simp] protected lemma to_finset_nonempty (h : s.finite) : h.to_finset.nonempty ↔ s.nonempty := by rw [← finset.coe_nonempty, finite.coe_to_finset] /-- Note that this is an equality of types not holding definitionally. Use wisely. -/ lemma coe_sort_to_finset (h : s.finite) : ↥h.to_finset = ↥s := by rw [← finset.coe_sort_coe _, h.coe_to_finset] @[simp] protected lemma to_finset_inj : hs.to_finset = ht.to_finset ↔ s = t := @to_finset_inj _ _ _ hs.fintype ht.fintype @[simp] lemma to_finset_subset {t : finset α} : hs.to_finset ⊆ t ↔ s ⊆ t := by rw [←finset.coe_subset, finite.coe_to_finset] @[simp] lemma to_finset_ssubset {t : finset α} : hs.to_finset ⊂ t ↔ s ⊂ t := by rw [←finset.coe_ssubset, finite.coe_to_finset] @[simp] lemma subset_to_finset {s : finset α} : s ⊆ ht.to_finset ↔ ↑s ⊆ t := by rw [←finset.coe_subset, finite.coe_to_finset] @[simp] lemma ssubset_to_finset {s : finset α} : s ⊂ ht.to_finset ↔ ↑s ⊂ t := by rw [←finset.coe_ssubset, finite.coe_to_finset] @[mono] protected lemma to_finset_subset_to_finset : hs.to_finset ⊆ ht.to_finset ↔ s ⊆ t := by simp only [← finset.coe_subset, finite.coe_to_finset] @[mono] protected lemma to_finset_ssubset_to_finset : hs.to_finset ⊂ ht.to_finset ↔ s ⊂ t := by simp only [← finset.coe_ssubset, finite.coe_to_finset] alias finite.to_finset_subset_to_finset ↔ _ to_finset_mono alias finite.to_finset_ssubset_to_finset ↔ _ to_finset_strict_mono attribute [protected] to_finset_mono to_finset_strict_mono @[simp] protected lemma to_finset_set_of [fintype α] (p : α → Prop) [decidable_pred p] (h : {x | p x}.finite) : h.to_finset = finset.univ.filter p := by { ext, simp } @[simp] lemma disjoint_to_finset {hs : s.finite} {ht : t.finite} : disjoint hs.to_finset ht.to_finset ↔ disjoint s t := @disjoint_to_finset _ _ _ hs.fintype ht.fintype protected lemma to_finset_inter [decidable_eq α] (hs : s.finite) (ht : t.finite) (h : (s ∩ t).finite) : h.to_finset = hs.to_finset ∩ ht.to_finset := by { ext, simp } protected lemma to_finset_union [decidable_eq α] (hs : s.finite) (ht : t.finite) (h : (s ∪ t).finite) : h.to_finset = hs.to_finset ∪ ht.to_finset := by { ext, simp } protected lemma to_finset_diff [decidable_eq α] (hs : s.finite) (ht : t.finite) (h : (s \ t).finite) : h.to_finset = hs.to_finset \ ht.to_finset := by { ext, simp } protected lemma to_finset_symm_diff [decidable_eq α] (hs : s.finite) (ht : t.finite) (h : (s ∆ t).finite) : h.to_finset = hs.to_finset ∆ ht.to_finset := by { ext, simp [mem_symm_diff, finset.mem_symm_diff] } protected lemma to_finset_compl [decidable_eq α] [fintype α] (hs : s.finite) (h : sᶜ.finite) : h.to_finset = hs.to_finsetᶜ := by { ext, simp } @[simp] protected lemma to_finset_empty (h : (∅ : set α).finite) : h.to_finset = ∅ := by { ext, simp } -- Note: Not `simp` because `set.finite.to_finset_set_of` already proves it @[simp] protected lemma to_finset_univ [fintype α] (h : (set.univ : set α).finite) : h.to_finset = finset.univ := by { ext, simp } @[simp] protected lemma to_finset_eq_empty {h : s.finite} : h.to_finset = ∅ ↔ s = ∅ := @to_finset_eq_empty _ _ h.fintype @[simp] protected lemma to_finset_eq_univ [fintype α] {h : s.finite} : h.to_finset = finset.univ ↔ s = univ := @to_finset_eq_univ _ _ _ h.fintype protected lemma to_finset_image [decidable_eq β] (f : α → β) (hs : s.finite) (h : (f '' s).finite) : h.to_finset = hs.to_finset.image f := by { ext, simp } @[simp] protected lemma to_finset_range [decidable_eq α] [fintype β] (f : β → α) (h : (range f).finite) : h.to_finset = finset.univ.image f := by { ext, simp } end finite /-! ### Fintype instances Every instance here should have a corresponding `set.finite` constructor in the next section. -/ section fintype_instances instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α (equiv.set.univ α).symm /-- If `(set.univ : set α)` is finite then `α` is a finite type. -/ noncomputable def fintype_of_finite_univ (H : (univ : set α).finite) : fintype α := @fintype.of_equiv _ (univ : set α) H.fintype (equiv.set.univ _) instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [decidable_eq α] [fintype s] [fintype t] : fintype (s ∩ t : set α) := fintype.of_finset (s.to_finset ∩ t.to_finset) $ by simp /-- A `fintype` instance for set intersection where the left set has a `fintype` instance. -/ instance fintype_inter_of_left (s t : set α) [fintype s] [decidable_pred (∈ t)] : fintype (s ∩ t : set α) := fintype.of_finset (s.to_finset.filter (∈ t)) $ by simp /-- A `fintype` instance for set intersection where the right set has a `fintype` instance. -/ instance fintype_inter_of_right (s t : set α) [fintype t] [decidable_pred (∈ s)] : fintype (s ∩ t : set α) := fintype.of_finset (t.to_finset.filter (∈ s)) $ by simp [and_comm] /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred (∈ t)] (h : t ⊆ s) : fintype t := by { rw ← inter_eq_self_of_subset_right h, apply set.fintype_inter_of_left } instance fintype_diff [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s \ t : set α) := fintype.of_finset (s.to_finset \ t.to_finset) $ by simp instance fintype_diff_left (s t : set α) [fintype s] [decidable_pred (∈ t)] : fintype (s \ t : set α) := set.fintype_sep s (∈ tᶜ) instance fintype_Union [decidable_eq α] [fintype (plift ι)] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bUnion (λ i : plift ι, (f i.down).to_finset)) $ by simp instance fintype_sUnion [decidable_eq α] {s : set (set α)} [fintype s] [H : ∀ (t : s), fintype (t : set α)] : fintype (⋃₀ s) := by { rw sUnion_eq_Union, exact @set.fintype_Union _ _ _ _ _ H } /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ def fintype_bUnion [decidable_eq α] {ι : Type*} (s : set ι) [fintype s] (t : ι → set α) (H : ∀ i ∈ s, fintype (t i)) : fintype (⋃(x ∈ s), t x) := fintype.of_finset (s.to_finset.attach.bUnion (λ x, by { haveI := H x (by simpa using x.property), exact (t x).to_finset })) $ by simp instance fintype_bUnion' [decidable_eq α] {ι : Type*} (s : set ι) [fintype s] (t : ι → set α) [∀ i, fintype (t i)] : fintype (⋃(x ∈ s), t x) := fintype.of_finset (s.to_finset.bUnion (λ x, (t x).to_finset)) $ by simp /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion s f H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := set.fintype_bUnion' s f instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp instance fintype_singleton (a : α) : fintype ({a} : set α) := fintype.of_finset {a} $ by simp instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton /-- A `fintype` instance for inserting an element into a `set` using the corresponding `insert` function on `finset`. This requires `decidable_eq α`. There is also `set.fintype_insert'` when `a ∈ s` is decidable. -/ instance fintype_insert (a : α) (s : set α) [decidable_eq α] [fintype s] : fintype (insert a s : set α) := fintype.of_finset (insert a s.to_finset) $ by simp /-- A `fintype` structure on `insert a s` when inserting a new element. -/ def fintype_insert_of_not_mem {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a ::ₘ s.to_finset.1, s.to_finset.nodup.cons (by simp [h]) ⟩ $ by simp /-- A `fintype` structure on `insert a s` when inserting a pre-existing element. -/ def fintype_insert_of_mem {a : α} (s : set α) [fintype s] (h : a ∈ s) : fintype (insert a s : set α) := fintype.of_finset s.to_finset $ by simp [h] /-- The `set.fintype_insert` instance requires decidable equality, but when `a ∈ s` is decidable for this particular `a` we can still get a `fintype` instance by using `set.fintype_insert_of_not_mem` or `set.fintype_insert_of_mem`. This instance pre-dates `set.fintype_insert`, and it is less efficient. When `decidable_mem_of_fintype` is made a local instance, then this instance would override `set.fintype_insert` if not for the fact that its priority has been adjusted. See Note [lower instance priority]. -/ @[priority 100] instance fintype_insert' (a : α) (s : set α) [decidable $ a ∈ s] [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then fintype_insert_of_mem s h else fintype_insert_of_not_mem s h instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, (f '' s).to_finset.2.filter_map g $ injective_of_partial_inv_right I⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end instance fintype_range [decidable_eq α] (f : ι → α) [fintype (plift ι)] : fintype (range f) := fintype.of_finset (finset.univ.image $ f ∘ plift.down) $ by simp [equiv.plift.exists_congr_left] instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) /-- This is not an instance so that it does not conflict with the one in src/order/locally_finite. -/ def nat.fintype_Iio (n : ℕ) : fintype (Iio n) := set.fintype_lt_nat n instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (s ×ˢ t : set (α × β)) := fintype.of_finset (s.to_finset ×ˢ t.to_finset) $ by simp instance fintype_off_diag [decidable_eq α] (s : set α) [fintype s] : fintype s.off_diag := fintype.of_finset s.to_finset.off_diag $ by simp /-- `image2 f s t` is `fintype` if `s` and `t` are. -/ instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) := by { rw ← image_prod, apply set.fintype_image } instance fintype_seq [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f.seq s) := by { rw seq_def, apply set.fintype_bUnion' } instance fintype_seq' {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := set.fintype_seq f s instance fintype_mem_finset (s : finset α) : fintype {a | a ∈ s} := finset.fintype_coe_sort s end fintype_instances end set /-! ### Finset -/ namespace finset /-- Gives a `set.finite` for the `finset` coerced to a `set`. This is a wrapper around `set.to_finite`. -/ @[simp] lemma finite_to_set (s : finset α) : (s : set α).finite := set.to_finite _ @[simp] lemma finite_to_set_to_finset (s : finset α) : s.finite_to_set.to_finset = s := by { ext, rw [set.finite.mem_to_finset, mem_coe] } end finset namespace multiset @[simp] lemma finite_to_set (s : multiset α) : {x | x ∈ s}.finite := by { classical, simpa only [← multiset.mem_to_finset] using s.to_finset.finite_to_set } @[simp] lemma finite_to_set_to_finset [decidable_eq α] (s : multiset α) : s.finite_to_set.to_finset = s.to_finset := by { ext x, simp } end multiset @[simp] lemma list.finite_to_set (l : list α) : {x | x ∈ l}.finite := (show multiset α, from ⟦l⟧).finite_to_set /-! ### Finite instances There is seemingly some overlap between the following instances and the `fintype` instances in `data.set.finite`. While every `fintype` instance gives a `finite` instance, those instances that depend on `fintype` or `decidable` instances need an additional `finite` instance to be able to generally apply. Some set instances do not appear here since they are consequences of others, for example `subtype.finite` for subsets of a finite type. -/ namespace finite.set open_locale classical example {s : set α} [finite α] : finite s := infer_instance example : finite (∅ : set α) := infer_instance example (a : α) : finite ({a} : set α) := infer_instance instance finite_union (s t : set α) [finite s] [finite t] : finite (s ∪ t : set α) := by { casesI nonempty_fintype s, casesI nonempty_fintype t, apply_instance } instance finite_sep (s : set α) (p : α → Prop) [finite s] : finite ({a ∈ s | p a} : set α) := by { casesI nonempty_fintype s, apply_instance } protected lemma subset (s : set α) {t : set α} [finite s] (h : t ⊆ s) : finite t := by { rw ←sep_eq_of_subset h, apply_instance } instance finite_inter_of_right (s t : set α) [finite t] : finite (s ∩ t : set α) := finite.set.subset t (inter_subset_right s t) instance finite_inter_of_left (s t : set α) [finite s] : finite (s ∩ t : set α) := finite.set.subset s (inter_subset_left s t) instance finite_diff (s t : set α) [finite s] : finite (s \ t : set α) := finite.set.subset s (diff_subset s t) instance finite_range (f : ι → α) [finite ι] : finite (range f) := by { haveI := fintype.of_finite (plift ι), apply_instance } instance finite_Union [finite ι] (f : ι → set α) [∀ i, finite (f i)] : finite (⋃ i, f i) := begin rw [Union_eq_range_psigma], apply set.finite_range end instance finite_sUnion {s : set (set α)} [finite s] [H : ∀ (t : s), finite (t : set α)] : finite (⋃₀ s) := by { rw sUnion_eq_Union, exact @finite.set.finite_Union _ _ _ _ H } lemma finite_bUnion {ι : Type*} (s : set ι) [finite s] (t : ι → set α) (H : ∀ i ∈ s, finite (t i)) : finite (⋃(x ∈ s), t x) := begin rw [bUnion_eq_Union], haveI : ∀ (i : s), finite (t i) := λ i, H i i.property, apply_instance, end instance finite_bUnion' {ι : Type*} (s : set ι) [finite s] (t : ι → set α) [∀ i, finite (t i)] : finite (⋃(x ∈ s), t x) := finite_bUnion s t (λ i h, infer_instance) /-- Example: `finite (⋃ (i < n), f i)` where `f : ℕ → set α` and `[∀ i, finite (f i)]` (when given instances from `data.nat.interval`). -/ instance finite_bUnion'' {ι : Type*} (p : ι → Prop) [h : finite {x | p x}] (t : ι → set α) [∀ i, finite (t i)] : finite (⋃ x (h : p x), t x) := @finite.set.finite_bUnion' _ _ (set_of p) h t _ instance finite_Inter {ι : Sort*} [nonempty ι] (t : ι → set α) [∀ i, finite (t i)] : finite (⋂ i, t i) := finite.set.subset (t $ classical.arbitrary ι) (Inter_subset _ _) instance finite_insert (a : α) (s : set α) [finite s] : finite (insert a s : set α) := finite.set.finite_union {a} s instance finite_image (s : set α) (f : α → β) [finite s] : finite (f '' s) := by { casesI nonempty_fintype s, apply_instance } instance finite_replacement [finite α] (f : α → β) : finite {(f x) | (x : α)} := finite.set.finite_range f instance finite_prod (s : set α) (t : set β) [finite s] [finite t] : finite (s ×ˢ t : set (α × β)) := finite.of_equiv _ (equiv.set.prod s t).symm instance finite_image2 (f : α → β → γ) (s : set α) (t : set β) [finite s] [finite t] : finite (image2 f s t : set γ) := by { rw ← image_prod, apply_instance } instance finite_seq (f : set (α → β)) (s : set α) [finite f] [finite s] : finite (f.seq s) := by { rw seq_def, apply_instance } end finite.set namespace set /-! ### Constructors for `set.finite` Every constructor here should have a corresponding `fintype` instance in the previous section (or in the `fintype` module). The implementation of these constructors ideally should be no more than `set.to_finite`, after possibly setting up some `fintype` and classical `decidable` instances. -/ section set_finite_constructors @[nontriviality] lemma finite.of_subsingleton [subsingleton α] (s : set α) : s.finite := s.to_finite theorem finite_univ [finite α] : (@univ α).finite := set.to_finite _ theorem finite_univ_iff : (@univ α).finite ↔ finite α := finite_coe_iff.symm.trans (equiv.set.univ α).finite_iff alias finite_univ_iff ↔ _root_.finite.of_finite_univ _ theorem finite.union {s t : set α} (hs : s.finite) (ht : t.finite) : (s ∪ t).finite := by { casesI hs, casesI ht, apply to_finite } theorem finite.finite_of_compl {s : set α} (hs : s.finite) (hsc : sᶜ.finite) : finite α := by { rw [← finite_univ_iff, ← union_compl_self s], exact hs.union hsc } lemma finite.sup {s t : set α} : s.finite → t.finite → (s ⊔ t).finite := finite.union theorem finite.sep {s : set α} (hs : s.finite) (p : α → Prop) : {a ∈ s | p a}.finite := by { casesI hs, apply to_finite } theorem finite.inter_of_left {s : set α} (hs : s.finite) (t : set α) : (s ∩ t).finite := by { casesI hs, apply to_finite } theorem finite.inter_of_right {s : set α} (hs : s.finite) (t : set α) : (t ∩ s).finite := by { casesI hs, apply to_finite } theorem finite.inf_of_left {s : set α} (h : s.finite) (t : set α) : (s ⊓ t).finite := h.inter_of_left t theorem finite.inf_of_right {s : set α} (h : s.finite) (t : set α) : (t ⊓ s).finite := h.inter_of_right t theorem finite.subset {s : set α} (hs : s.finite) {t : set α} (ht : t ⊆ s) : t.finite := by { casesI hs, haveI := finite.set.subset _ ht, apply to_finite } theorem finite.diff {s : set α} (hs : s.finite) (t : set α) : (s \ t).finite := by { casesI hs, apply to_finite } theorem finite.of_diff {s t : set α} (hd : (s \ t).finite) (ht : t.finite) : s.finite := (hd.union ht).subset $ subset_diff_union _ _ theorem finite_Union [finite ι] {f : ι → set α} (H : ∀ i, (f i).finite) : (⋃ i, f i).finite := by { haveI := λ i, (H i).fintype, apply to_finite } theorem finite.sUnion {s : set (set α)} (hs : s.finite) (H : ∀ t ∈ s, set.finite t) : (⋃₀ s).finite := by { casesI hs, haveI := λ (i : s), (H i i.2).to_subtype, apply to_finite } theorem finite.bUnion {ι} {s : set ι} (hs : s.finite) {t : ι → set α} (ht : ∀ i ∈ s, (t i).finite) : (⋃(i ∈ s), t i).finite := by { classical, casesI hs, haveI := fintype_bUnion s t (λ i hi, (ht i hi).fintype), apply to_finite } /-- Dependent version of `finite.bUnion`. -/ theorem finite.bUnion' {ι} {s : set ι} (hs : s.finite) {t : Π (i ∈ s), set α} (ht : ∀ i ∈ s, (t i ‹_›).finite) : (⋃(i ∈ s), t i ‹_›).finite := by { casesI hs, rw [bUnion_eq_Union], apply finite_Union (λ (i : s), ht i.1 i.2), } theorem finite.sInter {α : Type*} {s : set (set α)} {t : set α} (ht : t ∈ s) (hf : t.finite) : (⋂₀ s).finite := hf.subset (sInter_subset_of_mem ht) theorem finite.bind {α β} {s : set α} {f : α → set β} (h : s.finite) (hf : ∀ a ∈ s, (f a).finite) : (s >>= f).finite := h.bUnion hf @[simp] theorem finite_empty : (∅ : set α).finite := to_finite _ @[simp] theorem finite_singleton (a : α) : ({a} : set α).finite := to_finite _ theorem finite_pure (a : α) : (pure a : set α).finite := to_finite _ @[simp] theorem finite.insert (a : α) {s : set α} (hs : s.finite) : (insert a s).finite := by { casesI hs, apply to_finite } theorem finite.image {s : set α} (f : α → β) (hs : s.finite) : (f '' s).finite := by { casesI hs, apply to_finite } theorem finite_range (f : ι → α) [finite ι] : (range f).finite := to_finite _ lemma finite.dependent_image {s : set α} (hs : s.finite) (F : Π i ∈ s, β) : {y : β | ∃ x (hx : x ∈ s), y = F x hx}.finite := by { casesI hs, simpa [range, eq_comm] using finite_range (λ x : s, F x x.2) } theorem finite.map {α β} {s : set α} : ∀ (f : α → β), s.finite → (f <$> s).finite := finite.image theorem finite.of_finite_image {s : set α} {f : α → β} (h : (f '' s).finite) (hi : set.inj_on f s) : s.finite := by { casesI h, exact ⟨fintype.of_injective (λ a, (⟨f a.1, mem_image_of_mem f a.2⟩ : f '' s)) (λ a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq)⟩ } lemma finite_of_finite_preimage {f : α → β} {s : set β} (h : (f ⁻¹' s).finite) (hs : s ⊆ range f) : s.finite := by { rw [← image_preimage_eq_of_subset hs], exact finite.image f h } theorem finite.of_preimage {f : α → β} {s : set β} (h : (f ⁻¹' s).finite) (hf : surjective f) : s.finite := hf.image_preimage s ▸ h.image _ theorem finite.preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : s.finite) : (f ⁻¹' s).finite := (h.subset (image_preimage_subset f s)).of_finite_image I theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite := h.preimage (λ _ _ _ _ h', f.injective h') lemma finite_lt_nat (n : ℕ) : set.finite {i | i < n} := to_finite _ lemma finite_le_nat (n : ℕ) : set.finite {i | i ≤ n} := to_finite _ lemma finite.prod {s : set α} {t : set β} (hs : s.finite) (ht : t.finite) : (s ×ˢ t : set (α × β)).finite := by { casesI hs, casesI ht, apply to_finite } lemma finite.off_diag {s : set α} (hs : s.finite) : s.off_diag.finite := by { classical, casesI hs, apply set.to_finite } lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : s.finite) (ht : t.finite) : (image2 f s t).finite := by { casesI hs, casesI ht, apply to_finite } theorem finite.seq {f : set (α → β)} {s : set α} (hf : f.finite) (hs : s.finite) : (f.seq s).finite := by { classical, casesI hf, casesI hs, apply to_finite } theorem finite.seq' {α β : Type u} {f : set (α → β)} {s : set α} (hf : f.finite) (hs : s.finite) : (f <*> s).finite := hf.seq hs theorem finite_mem_finset (s : finset α) : {a | a ∈ s}.finite := to_finite _ lemma subsingleton.finite {s : set α} (h : s.subsingleton) : s.finite := h.induction_on finite_empty finite_singleton lemma finite_preimage_inl_and_inr {s : set (α ⊕ β)} : (sum.inl ⁻¹' s).finite ∧ (sum.inr ⁻¹' s).finite ↔ s.finite := ⟨λ h, image_preimage_inl_union_image_preimage_inr s ▸ (h.1.image _).union (h.2.image _), λ h, ⟨h.preimage (sum.inl_injective.inj_on _), h.preimage (sum.inr_injective.inj_on _)⟩⟩ theorem exists_finite_iff_finset {p : set α → Prop} : (∃ s : set α, s.finite ∧ p s) ↔ ∃ s : finset α, p ↑s := ⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩, λ ⟨s, hs⟩, ⟨s, s.finite_to_set, hs⟩⟩ /-- There are finitely many subsets of a given finite set -/ lemma finite.finite_subsets {α : Type u} {a : set α} (h : a.finite) : {b | b ⊆ a}.finite := ⟨fintype.of_finset ((finset.powerset h.to_finset).map finset.coe_emb.1) $ λ s, by simpa [← @exists_finite_iff_finset α (λ t, t ⊆ a ∧ t = s), finite.subset_to_finset, ← and.assoc] using h.subset⟩ /-- Finite product of finite sets is finite -/ lemma finite.pi {δ : Type*} [finite δ] {κ : δ → Type*} {t : Π d, set (κ d)} (ht : ∀ d, (t d).finite) : (pi univ t).finite := begin casesI nonempty_fintype δ, lift t to Π d, finset (κ d) using ht, classical, rw ← fintype.coe_pi_finset, apply finset.finite_to_set end /-- A finite union of finsets is finite. -/ lemma union_finset_finite_of_range_finite (f : α → finset β) (h : (range f).finite) : (⋃ a, (f a : set β)).finite := by { rw ← bUnion_range, exact h.bUnion (λ y hy, y.finite_to_set) } lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : (range f).finite) (hg : (range g).finite) : (range (λ x, if p x then f x else g x)).finite := (hf.union hg).subset range_ite_subset lemma finite_range_const {c : β} : (range (λ x : α, c)).finite := (finite_singleton c).subset range_const_subset end set_finite_constructors /-! ### Properties -/ instance finite.inhabited : inhabited {s : set α // s.finite} := ⟨⟨∅, finite_empty⟩⟩ @[simp] lemma finite_union {s t : set α} : (s ∪ t).finite ↔ s.finite ∧ t.finite := ⟨λ h, ⟨h.subset (subset_union_left _ _), h.subset (subset_union_right _ _)⟩, λ ⟨hs, ht⟩, hs.union ht⟩ theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : (f '' s).finite ↔ s.finite := ⟨λ h, h.of_finite_image hi, finite.image _⟩ lemma univ_finite_iff_nonempty_fintype : (univ : set α).finite ↔ nonempty (fintype α) := ⟨λ h, ⟨fintype_of_finite_univ h⟩, λ ⟨_i⟩, by exactI finite_univ⟩ @[simp] lemma finite.to_finset_singleton {a : α} (ha : ({a} : set α).finite := finite_singleton _) : ha.to_finset = {a} := finset.ext $ by simp @[simp] lemma finite.to_finset_insert [decidable_eq α] {s : set α} {a : α} (hs : (insert a s).finite) : hs.to_finset = insert a (hs.subset $ subset_insert _ _).to_finset := finset.ext $ by simp lemma finite.to_finset_insert' [decidable_eq α] {a : α} {s : set α} (hs : s.finite) : (hs.insert a).to_finset = insert a hs.to_finset := finite.to_finset_insert _ lemma finite.to_finset_prod {s : set α} {t : set β} (hs : s.finite) (ht : t.finite) : hs.to_finset ×ˢ ht.to_finset = (hs.prod ht).to_finset := finset.ext $ by simp lemma finite.to_finset_off_diag {s : set α} [decidable_eq α] (hs : s.finite) : hs.off_diag.to_finset = hs.to_finset.off_diag := finset.ext $ by simp lemma finite.fin_embedding {s : set α} (h : s.finite) : ∃ (n : ℕ) (f : fin n ↪ α), range f = s := ⟨_, (fintype.equiv_fin (h.to_finset : set α)).symm.as_embedding, by simp⟩ lemma finite.fin_param {s : set α} (h : s.finite) : ∃ (n : ℕ) (f : fin n → α), injective f ∧ range f = s := let ⟨n, f, hf⟩ := h.fin_embedding in ⟨n, f, f.injective, hf⟩ lemma finite_option {s : set (option α)} : s.finite ↔ {x : α | some x ∈ s}.finite := ⟨λ h, h.preimage_embedding embedding.some, λ h, ((h.image some).insert none).subset $ λ x, option.cases_on x (λ _, or.inl rfl) (λ x hx, or.inr $ mem_image_of_mem _ hx)⟩ lemma finite_image_fst_and_snd_iff {s : set (α × β)} : (prod.fst '' s).finite ∧ (prod.snd '' s).finite ↔ s.finite := ⟨λ h, (h.1.prod h.2).subset $ λ x h, ⟨mem_image_of_mem _ h, mem_image_of_mem _ h⟩, λ h, ⟨h.image _, h.image _⟩⟩ lemma forall_finite_image_eval_iff {δ : Type*} [finite δ] {κ : δ → Type*} {s : set (Π d, κ d)} : (∀ d, (eval d '' s).finite) ↔ s.finite := ⟨λ h, (finite.pi h).subset $ subset_pi_eval_image _ _, λ h d, h.image _⟩ lemma finite_subset_Union {s : set α} (hs : s.finite) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, I.finite ∧ s ⊆ ⋃ i ∈ I, t i := begin casesI hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, λ x hx, _⟩, rw [bUnion_range, mem_Union], exact ⟨⟨x, hx⟩, hf _⟩ end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : t.finite) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, I.finite ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, (σ i).finite) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, tfin.subset (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : s.finite) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → set.finite s → C s → C (insert a s)) : C s := begin lift s to finset α using h, induction s using finset.cons_induction_on with a s ha hs, { rwa [finset.coe_empty] }, { rw [finset.coe_cons], exact @H1 a s ha (set.to_finite _) hs } end /-- Analogous to `finset.induction_on'`. -/ @[elab_as_eliminator] theorem finite.induction_on' {C : set α → Prop} {S : set α} (h : S.finite) (H0 : C ∅) (H1 : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → C s → C (insert a s)) : C S := begin refine @set.finite.induction_on α (λ s, s ⊆ S → C s) S h (λ _, H0) _ subset.rfl, intros a s has hsf hCs haS, rw insert_subset at haS, exact H1 haS.1 haS.2 has (hCs haS.2) end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀ (s : set α), s.finite → Prop} {s : set α} (h : s.finite) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀ h : set.finite s, C s h → C (insert a s) (h.insert a)) : C s h := have ∀ h : s.finite, C s h, from finite.induction_on h (λ h, H0) (λ a s has hs ih h, H1 has hs (ih _)), this h section local attribute [instance] nat.fintype_Iio /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ lemma seq_of_forall_finite_exists {γ : Type*} {P : γ → set γ → Prop} (h : ∀ t : set γ, t.finite → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := ⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h (range $ λ m : Iio n, ih m.1 m.2) (finite_range _), λ n, begin classical, refine nat.strong_rec_on' n (λ n ih, _), rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _), ext x, split, { rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ }, { rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ } end⟩ end /-! ### Cardinality -/ theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card theorem card_fintype_insert_of_not_mem {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert_of_not_mem s h) = fintype.card s + 1 := by rw [fintype_insert_of_not_mem, fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert_of_not_mem s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := fintype.card_lt_of_injective_not_surjective (set.inclusion h.1) (set.inclusion_injective h.1) $ λ hst, (ssubset_iff_subset_ne.1 h).2 (eq_of_inclusion_surjective hst) lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := fintype.card_le_of_injective (set.inclusion hsub) (set.inclusion_injective hsub) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.of_injective f hf lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset.card = fintype.card s := begin rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], refine fintype.card_congr (equiv.set_congr _), ext x, show x ∈ h.to_finset ↔ x ∈ s, simp, end lemma card_ne_eq [fintype α] (a : α) [fintype {x : α | x ≠ a}] : fintype.card {x : α | x ≠ a} = fintype.card α - 1 := begin haveI := classical.dec_eq α, rw [←to_finset_card, to_finset_set_of, finset.filter_ne', finset.card_erase_of_mem (finset.mem_univ _), finset.card_univ], end /-! ### Infinite sets -/ theorem infinite_univ_iff : (@univ α).infinite ↔ infinite α := by rw [set.infinite, finite_univ_iff, not_finite_iff_infinite] theorem infinite_univ [h : infinite α] : (@univ α).infinite := infinite_univ_iff.2 h theorem infinite_coe_iff {s : set α} : infinite s ↔ s.infinite := not_finite_iff_infinite.symm.trans finite_coe_iff.not alias infinite_coe_iff ↔ _ infinite.to_subtype /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def infinite.nat_embedding (s : set α) (h : s.infinite) : ℕ ↪ s := by { haveI := h.to_subtype, exact infinite.nat_embedding s } lemma infinite.exists_subset_card_eq {s : set α} (hs : s.infinite) (n : ℕ) : ∃ t : finset α, ↑t ⊆ s ∧ t.card = n := ⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩ lemma infinite.nonempty {s : set α} (h : s.infinite) : s.nonempty := let a := infinite.nat_embedding s h 37 in ⟨a.1, a.2⟩ lemma infinite_of_finite_compl [infinite α] {s : set α} (hs : sᶜ.finite) : s.infinite := λ h, set.infinite_univ (by simpa using hs.union h) lemma finite.infinite_compl [infinite α] {s : set α} (hs : s.finite) : sᶜ.infinite := λ h, set.infinite_univ (by simpa using hs.union h) protected theorem infinite.mono {s t : set α} (h : s ⊆ t) : s.infinite → t.infinite := mt (λ ht, ht.subset h) lemma infinite.diff {s t : set α} (hs : s.infinite) (ht : t.finite) : (s \ t).infinite := λ h, hs $ h.of_diff ht @[simp] lemma infinite_union {s t : set α} : (s ∪ t).infinite ↔ s.infinite ∨ t.infinite := by simp only [set.infinite, finite_union, not_and_distrib] theorem infinite_of_infinite_image (f : α → β) {s : set α} (hs : (f '' s).infinite) : s.infinite := mt (finite.image f) hs theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : (f '' s).infinite ↔ s.infinite := not_congr $ finite_image_iff hi theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β} (hi : inj_on f s) (hm : maps_to f s t) (hs : s.infinite) : t.infinite := ((infinite_image_iff hi).2 hs).mono (maps_to'.mp hm) theorem infinite.exists_ne_map_eq_of_maps_to {s : set α} {t : set β} {f : α → β} (hs : s.infinite) (hf : maps_to f s t) (ht : t.finite) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin contrapose! ht, exact infinite_of_inj_on_maps_to (λ x hx y hy, not_imp_not.1 (ht x hx y hy)) hf hs end theorem infinite_range_of_injective [infinite α] {f : α → β} (hi : injective f) : (range f).infinite := by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ } theorem infinite_of_injective_forall_mem [infinite α] {s : set β} {f : α → β} (hi : injective f) (hf : ∀ x : α, f x ∈ s) : s.infinite := by { rw ←range_subset_iff at hf, exact (infinite_range_of_injective hi).mono hf } lemma infinite.exists_nat_lt {s : set ℕ} (hs : s.infinite) (n : ℕ) : ∃ m ∈ s, n < m := let ⟨m, hm⟩ := (hs.diff $ set.finite_le_nat n).nonempty in ⟨m, by simpa using hm⟩ lemma infinite.exists_not_mem_finset {s : set α} (hs : s.infinite) (f : finset α) : ∃ a ∈ s, a ∉ f := let ⟨a, has, haf⟩ := (hs.diff (to_finite f)).nonempty in ⟨a, has, λ h, haf $ finset.mem_coe.1 h⟩ lemma not_inj_on_infinite_finite_image {f : α → β} {s : set α} (h_inf : s.infinite) (h_fin : (f '' s).finite) : ¬ inj_on f s := begin haveI : finite (f '' s) := finite_coe_iff.mpr h_fin, haveI : infinite s := infinite_coe_iff.mpr h_inf, have := not_injective_infinite_finite ((f '' s).cod_restrict (s.restrict f) $ λ x, ⟨x, x.property, rfl⟩), contrapose! this, rwa [injective_cod_restrict, ← inj_on_iff_injective], end /-! ### Order properties -/ lemma finite_is_top (α : Type*) [partial_order α] : {x : α | is_top x}.finite := (subsingleton_is_top α).finite lemma finite_is_bot (α : Type*) [partial_order α] : {x : α | is_bot x}.finite := (subsingleton_is_bot α).finite theorem infinite.exists_lt_map_eq_of_maps_to [linear_order α] {s : set α} {t : set β} {f : α → β} (hs : s.infinite) (hf : maps_to f s t) (ht : t.finite) : ∃ (x ∈ s) (y ∈ s), x < y ∧ f x = f y := let ⟨x, hx, y, hy, hxy, hf⟩ := hs.exists_ne_map_eq_of_maps_to hf ht in hxy.lt_or_lt.elim (λ hxy, ⟨x, hx, y, hy, hxy, hf⟩) (λ hyx, ⟨y, hy, x, hx, hyx, hf.symm⟩) lemma finite.exists_lt_map_eq_of_forall_mem [linear_order α] [infinite α] {t : set β} {f : α → β} (hf : ∀ a, f a ∈ t) (ht : t.finite) : ∃ a b, a < b ∧ f a = f b := begin rw ←maps_univ_to at hf, obtain ⟨a, -, b, -, h⟩ := (@infinite_univ α _).exists_lt_map_eq_of_maps_to hf ht, exact ⟨a, b, h⟩, end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : s.finite) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_min_image f ⟨x, h1.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : s.finite) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_max_image f ⟨x, h1.mem_to_finset.2 hx⟩ theorem exists_lower_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f a ≤ f b := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_min_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end theorem exists_upper_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f b ≤ f a := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_max_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end lemma finite.supr_binfi_of_monotone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.frame α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, monotone (f i)) : (⨆ j, ⨅ i ∈ s, f i j) = ⨅ i ∈ s, ⨆ j, f i j := begin revert hf, refine hs.induction_on _ _, { intro hf, simp [supr_const] }, { intros a s has hs ihs hf, rw [ball_insert_iff] at hf, simp only [infi_insert, ← ihs hf.2], exact supr_inf_of_monotone hf.1 (λ j₁ j₂ hj, infi₂_mono $ λ i hi, hf.2 i hi hj) } end lemma finite.supr_binfi_of_antitone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.frame α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, antitone (f i)) : (⨆ j, ⨅ i ∈ s, f i j) = ⨅ i ∈ s, ⨆ j, f i j := @finite.supr_binfi_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ hs _ (λ i hi, (hf i hi).dual_left) lemma finite.infi_bsupr_of_monotone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.coframe α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, monotone (f i)) : (⨅ j, ⨆ i ∈ s, f i j) = ⨆ i ∈ s, ⨅ j, f i j := hs.supr_binfi_of_antitone (λ i hi, (hf i hi).dual_right) lemma finite.infi_bsupr_of_antitone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.coframe α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, antitone (f i)) : (⨅ j, ⨆ i ∈ s, f i j) = ⨆ i ∈ s, ⨅ j, f i j := hs.supr_binfi_of_monotone (λ i hi, (hf i hi).dual_right) lemma _root_.supr_infi_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.frame α] {f : ι → ι' → α} (hf : ∀ i, monotone (f i)) : (⨆ j, ⨅ i, f i j) = ⨅ i, ⨆ j, f i j := by simpa only [infi_univ] using finite_univ.supr_binfi_of_monotone (λ i hi, hf i) lemma _root_.supr_infi_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.frame α] {f : ι → ι' → α} (hf : ∀ i, antitone (f i)) : (⨆ j, ⨅ i, f i j) = ⨅ i, ⨆ j, f i j := @supr_infi_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ _ (λ i, (hf i).dual_left) lemma _root_.infi_supr_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.coframe α] {f : ι → ι' → α} (hf : ∀ i, monotone (f i)) : (⨅ j, ⨆ i, f i j) = ⨆ i, ⨅ j, f i j := supr_infi_of_antitone (λ i, (hf i).dual_right) lemma _root_.infi_supr_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.coframe α] {f : ι → ι' → α} (hf : ∀ i, antitone (f i)) : (⨅ j, ⨆ i, f i j) = ⨆ i, ⨅ j, f i j := supr_infi_of_monotone (λ i, (hf i).dual_right) /-- An increasing union distributes over finite intersection. -/ lemma Union_Inter_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (≤)] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := supr_infi_of_monotone hs /-- A decreasing union distributes over finite intersection. -/ lemma Union_Inter_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (swap (≤))] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, antitone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := supr_infi_of_antitone hs /-- An increasing intersection distributes over finite union. -/ lemma Inter_Union_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (swap (≤))] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋂ j : ι', ⋃ i : ι, s i j) = ⋃ i : ι, ⋂ j : ι', s i j := infi_supr_of_monotone hs /-- A decreasing intersection distributes over finite union. -/ lemma Inter_Union_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (≤)] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, antitone (s i)) : (⋂ j : ι', ⋃ i : ι, s i j) = ⋃ i : ι, ⋂ j : ι', s i j := infi_supr_of_antitone hs lemma Union_pi_of_monotone {ι ι' : Type*} [linear_order ι'] [nonempty ι'] {α : ι → Type*} {I : set ι} {s : Π i, ι' → set (α i)} (hI : I.finite) (hs : ∀ i ∈ I, monotone (s i)) : (⋃ j : ι', I.pi (λ i, s i j)) = I.pi (λ i, ⋃ j, s i j) := begin simp only [pi_def, bInter_eq_Inter, preimage_Union], haveI := hI.fintype, exact Union_Inter_of_monotone (λ i j₁ j₂ h, preimage_mono $ hs i i.2 h) end lemma Union_univ_pi_of_monotone {ι ι' : Type*} [linear_order ι'] [nonempty ι'] [finite ι] {α : ι → Type*} {s : Π i, ι' → set (α i)} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', pi univ (λ i, s i j)) = pi univ (λ i, ⋃ j, s i j) := Union_pi_of_monotone finite_univ (λ i _, hs i) lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : (range (λ x, nat.find_greatest (P x) b)).finite := (finite_le_nat b).subset $ range_subset_iff.2 $ λ x, nat.find_greatest_le _ lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃ a ∈ s, ∀ a' ∈ s, f a ≤ f a' → f a = f a' := begin refine h.induction_on _ _, { exact λ h, absurd h not_nonempty_empty }, intros a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, λ c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, λ c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ protected lemma finite.bdd_above (hs : s.finite) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : I.finite) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) lemma infinite_of_not_bdd_above : ¬ bdd_above s → s.infinite := mt finite.bdd_above end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ protected lemma finite.bdd_below (hs : s.finite) : bdd_below s := @finite.bdd_above αᵒᵈ _ _ _ hs /--A finite union of sets which are all bounded below is still bounded below.-/ lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : I.finite) : bdd_below (⋃ i ∈ I, S i) ↔ ∀ i ∈ I, bdd_below (S i) := @finite.bdd_above_bUnion αᵒᵈ _ _ _ _ _ H lemma infinite_of_not_bdd_below : ¬ bdd_below s → s.infinite := begin contrapose!, rw not_infinite, apply finite.bdd_below, end end end set namespace finset /-- A finset is bounded above. -/ protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := s.finite_to_set.bdd_above /-- A finset is bounded below. -/ protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := s.finite_to_set.bdd_below end finset /-- If a set `s` does not contain any elements between any pair of elements `x, z ∈ s` with `x ≤ z` (i.e if given `x, y, z ∈ s` such that `x ≤ y ≤ z`, then `y` is either `x` or `z`), then `s` is finite. -/ lemma set.finite_of_forall_between_eq_endpoints {α : Type*} [linear_order α] (s : set α) (h : ∀ (x ∈ s) (y ∈ s) (z ∈ s), x ≤ y → y ≤ z → x = y ∨ y = z) : set.finite s := begin by_contra hinf, change s.infinite at hinf, rcases hinf.exists_subset_card_eq 3 with ⟨t, hts, ht⟩, let f := t.order_iso_of_fin ht, let x := f 0, let y := f 1, let z := f 2, have := h x (hts x.2) y (hts y.2) z (hts z.2) (f.monotone $ by dec_trivial) (f.monotone $ by dec_trivial), have key₁ : (0 : fin 3) ≠ 1 := by dec_trivial, have key₂ : (1 : fin 3) ≠ 2 := by dec_trivial, cases this, { dsimp only [x, y] at this, exact key₁ (f.injective $ subtype.coe_injective this) }, { dsimp only [y, z] at this, exact key₂ (f.injective $ subtype.coe_injective this) } end
665a6aee76496805b1f96c4215c15b60a1ee6972
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/limits/shapes/pullbacks.lean
553e5e1e2e9159aab24a43a705bd7e39ba59403f
[ "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
26,517
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel, Bhavik Mehta -/ import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. ## References * [Stacks: Fibre products](https://stacks.math.columbia.edu/tag/001U) * [Stacks: Pushouts](https://stacks.math.columbia.edu/tag/0025) -/ noncomputable theory open category_theory namespace category_theory.limits universes v u local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback, defined as a special case of `wide_pullback_shape`. -/ abbreviation walking_cospan : Type v := wide_pullback_shape walking_pair /-- The left point of the walking cospan. -/ abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ abbreviation walking_cospan.one : walking_cospan := none /-- The type of objects for the diagram indexing a pushout, defined as a special case of `wide_pushout_shape`. -/ abbreviation walking_span : Type v := wide_pushout_shape walking_pair /-- The left point of the walking span. -/ abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ abbreviation walking_span.zero : walking_span := none namespace walking_cospan /-- The type of arrows for the diagram indexing a pullback. -/ abbreviation hom : walking_cospan → walking_cospan → Type v := wide_pullback_shape.hom /-- The left arrow of the walking cospan. -/ abbreviation hom.inl : left ⟶ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ abbreviation hom.inr : right ⟶ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ abbreviation hom.id (X : walking_cospan) : X ⟶ X := wide_pullback_shape.hom.id X instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy end walking_cospan namespace walking_span /-- The type of arrows for the diagram indexing a pushout. -/ abbreviation hom : walking_span → walking_span → Type v := wide_pushout_shape.hom /-- The left arrow of the walking span. -/ abbreviation hom.fst : zero ⟶ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ abbreviation hom.snd : zero ⟶ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ abbreviation hom.id (X : walking_span) : X ⟶ X := wide_pushout_shape.hom.id X instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy end walking_span open walking_span.hom walking_cospan.hom wide_pullback_shape.hom wide_pushout_shape.hom variables {C : Type u} [category.{v} C] /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan ⥤ C := wide_pullback_shape.wide_cospan Z (λ j, walking_pair.cases_on j X Y) (λ j, walking_pair.cases_on j f g) /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span ⥤ C := wide_pushout_shape.wide_span X (λ j, walking_pair.cases_on j Y Z) (λ j, walking_pair.cases_on j f g) @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an pullback is naturally isomorphic (actually, equal) to a `cospan` -/ def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) /-- Every diagram indexing a pushout is naturally isomorphic (actually, equal) to a `span` -/ def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) variables {X Y Z : C} /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app walking_cospan.left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app walking_cospan.right /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : pullback_cone f g) (lift : Π (s : cone (cospan f g)), s.X ⟶ t.X) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ t.fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ t.snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, option.cases_on j (by { rw [← s.w inl, ← t.w inl, ←category.assoc], congr, exact fac_left s, } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_limit_aux' (t : pullback_cone f g) (create : Π (s : pullback_cone f g), {l // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ ∀ {m}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) : limits.is_limit t := pullback_cone.is_limit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ @[simps] def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, option.cases_on j (fst ≫ f) (λ j', walking_pair.cases_on j' fst snd) } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.one = fst ≫ f := rfl @[simp] lemma mk_fst {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).fst = fst := rfl @[simp] lemma mk_snd {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).snd = snd := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := (t.w inl).trans (t.w inr).symm /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w inl, reassoc_of h₀] lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pullback_cone` constructed using `pullback_cone.mk` is a limit cone. -/ def is_limit.mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) (lift : Π (s : pullback_cone f g), s.X ⟶ W) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ W) (w_fst : m ≫ fst = s.fst) (w_snd : m ≫ snd = s.snd), m = lift s) : is_limit (mk fst snd eq) := is_limit_aux _ lift fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pullback square is a pullback square. -/ def flip_is_limit {W : C} {h : W ⟶ X} {k : W ⟶ Y} {comm : h ≫ f = k ≫ g} (t : is_limit (mk _ _ comm.symm)) : is_limit (mk _ _ comm) := is_limit_aux' _ $ λ s, begin refine ⟨(is_limit.lift' t _ _ s.condition.symm).1, (is_limit.lift' t _ _ _).2.2, (is_limit.lift' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).equalizer_ext, { rwa (is_limit.lift' t _ _ _).2.1 }, { rwa (is_limit.lift' t _ _ _).2.2 }, end end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app walking_span.left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app walking_span.right /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : pushout_cocone f g) (desc : Π (s : pushout_cocone f g), t.X ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), t.inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), t.inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, option.cases_on j (by { simp [← s.w fst, ← t.w fst, fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_colimit_aux' (t : pushout_cocone f g) (create : Π (s : pushout_cocone f g), {l // t.inl ≫ l = s.inl ∧ t.inr ≫ l = s.inr ∧ ∀ {m}, t.inl ≫ m = s.inl → t.inr ≫ m = s.inr → m = l}) : is_colimit t := is_colimit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ @[simps] def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, option.cases_on j (f ≫ inl) (λ j', walking_pair.cases_on j' inl inr) } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.zero = f ≫ inl := rfl @[simp] lemma mk_inl {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inl = inl := rfl @[simp] lemma mk_inr {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inr = inr := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := (t.w fst).trans (t.w snd).symm /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w fst, category.assoc, category.assoc, h₀] lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pushout_cocone` constructed using `pushout_cocone.mk` is a colimit cocone. -/ def is_colimit.mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) (desc : Π (s : pushout_cocone f g), W ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : W ⟶ s.X) (w_inl : inl ≫ m = s.inl) (w_inr : inr ≫ m = s.inr), m = desc s) : is_colimit (mk inl inr eq) := is_colimit_aux _ desc fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pushout square is a pushout square. -/ def flip_is_colimit {W : C} {h : Y ⟶ W} {k : Z ⟶ W} {comm : f ≫ h = g ≫ k} (t : is_colimit (mk _ _ comm.symm)) : is_colimit (mk _ _ comm) := is_colimit_aux' _ $ λ s, begin refine ⟨(is_colimit.desc' t _ _ s.condition.symm).1, (is_colimit.desc' t _ _ _).2.2, (is_colimit.desc' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).coequalizer_ext, { rwa (is_colimit.desc' t _ _ _).2.1 }, { rwa (is_colimit.desc' t _ _ _).2.2 }, end end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ @[simps] def cone.of_pullback_cone {F : walking_cospan ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).inv } /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ @[simps] def cocone.of_pushout_cocone {F : walking_span ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := (diagram_iso_span F).hom ≫ t.ι } /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ @[simps] def pullback_cone.of_cone {F : walking_cospan ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).hom } /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ @[simps] def pushout_cocone.of_cocone {F : walking_span ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := (diagram_iso_span F).inv ≫ t.ι } /-- `has_pullback f g` represents a particular choice of limiting cone for the pair of morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`. -/ abbreviation has_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) := has_limit (cospan f g) /-- `has_pushout f g` represents a particular choice of colimiting cocone for the pair of morphisms `f : X ⟶ Y` and `g : X ⟶ Z`. -/ abbreviation has_pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) := has_colimit (span f g) /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ @[reassoc] lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ @[reassoc] lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ by simp [← pullback.condition, reassoc_of h]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ by simp [pullback.condition, reassoc_of h]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ by simp [← pushout.condition_assoc, h] ⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ by simp [pushout.condition_assoc, h]) h⟩ variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms See https://stacks.math.columbia.edu/tag/001W. -/ abbreviation has_pullbacks := has_limits_of_shape walking_cospan C /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ abbreviation has_pushouts := has_colimits_of_shape walking_span C /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ lemma has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks C := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ lemma has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } end category_theory.limits
a362a7ea2340895735e2752a7e94dc93ccff6bd4
82e44445c70db0f03e30d7be725775f122d72f3e
/src/ring_theory/polynomial/bernstein.lean
08188d2d4cfb079f0bc5829147efa90d39564730
[ "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
15,801
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 data.polynomial.derivative import data.polynomial.algebra_map import data.mv_polynomial.pderiv import data.nat.choose.sum import linear_algebra.basis import ring_theory.polynomial.pochhammer /-! # Bernstein polynomials The definition of the Bernstein polynomials ``` bernstein_polynomial (R : Type*) [comm_ring R] (n ν : ℕ) : polynomial R := (choose n ν) * X^ν * (1 - X)^(n - ν) ``` and the fact that for `ν : fin (n+1)` these are linearly independent over `ℚ`. We prove the basic identities * `(finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1` * `(finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X` * `(finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2` ## Notes See also `analysis.special_functions.bernstein`, which defines the Bernstein approximations of a continuous function `f : C([0,1], ℝ)`, and shows that these converge uniformly to `f`. -/ noncomputable theory open nat (choose) open polynomial (X) variables (R : Type*) [comm_ring R] /-- `bernstein_polynomial R n ν` is `(choose n ν) * X^ν * (1 - X)^(n - ν)`. Although the coefficients are integers, it is convenient to work over an arbitrary commutative ring. -/ def bernstein_polynomial (n ν : ℕ) : polynomial R := choose n ν * X^ν * (1 - X)^(n - ν) example : bernstein_polynomial ℤ 3 2 = 3 * X^2 - 3 * X^3 := begin norm_num [bernstein_polynomial, choose], ring, end namespace bernstein_polynomial lemma eq_zero_of_lt {n ν : ℕ} (h : n < ν) : bernstein_polynomial R n ν = 0 := by simp [bernstein_polynomial, nat.choose_eq_zero_of_lt h] section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map (f : R →+* S) (n ν : ℕ) : (bernstein_polynomial R n ν).map f = bernstein_polynomial S n ν := by simp [bernstein_polynomial] end lemma flip (n ν : ℕ) (h : ν ≤ n) : (bernstein_polynomial R n ν).comp (1-X) = bernstein_polynomial R n (n-ν) := begin dsimp [bernstein_polynomial], simp [h, nat.sub_sub_assoc, mul_right_comm], end lemma flip' (n ν : ℕ) (h : ν ≤ n) : bernstein_polynomial R n ν = (bernstein_polynomial R n (n-ν)).comp (1-X) := begin rw [←flip _ _ _ h, polynomial.comp_assoc], simp, end lemma eval_at_0 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 0 = if ν = 0 then 1 else 0 := begin dsimp [bernstein_polynomial], split_ifs, { subst h, simp, }, { simp [zero_pow (nat.pos_of_ne_zero h)], }, end lemma eval_at_1 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 1 = if ν = n then 1 else 0 := begin dsimp [bernstein_polynomial], split_ifs, { subst h, simp, }, { obtain w | w := (n - ν).eq_zero_or_pos, { simp [nat.choose_eq_zero_of_lt ((nat.le_of_sub_eq_zero w).lt_of_ne (ne.symm h))] }, { simp [zero_pow w] } }, end. lemma derivative_succ_aux (n ν : ℕ) : (bernstein_polynomial R (n+1) (ν+1)).derivative = (n+1) * (bernstein_polynomial R n ν - bernstein_polynomial R n (ν + 1)) := begin dsimp [bernstein_polynomial], suffices : ↑((n + 1).choose (ν + 1)) * ((↑ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) -(↑((n + 1).choose (ν + 1)) * X ^ (ν + 1) * (↑(n - ν) * (1 - X) ^ (n - ν - 1))) = (↑n + 1) * (↑(n.choose ν) * X ^ ν * (1 - X) ^ (n - ν) - ↑(n.choose (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1))), { simpa [polynomial.derivative_pow, ←sub_eq_add_neg], }, conv_rhs { rw mul_sub, }, -- We'll prove the two terms match up separately. refine congr (congr_arg has_sub.sub _) _, { simp only [←mul_assoc], refine congr (congr_arg (*) (congr (congr_arg (*) _) rfl)) rfl, -- Now it's just about binomial coefficients exact_mod_cast congr_arg (λ m : ℕ, (m : polynomial R)) (nat.succ_mul_choose_eq n ν).symm, }, { rw nat.sub_sub, rw [←mul_assoc,←mul_assoc], congr' 1, rw mul_comm , rw [←mul_assoc,←mul_assoc], congr' 1, norm_cast, congr' 1, convert (nat.choose_mul_succ_eq n (ν + 1)).symm using 1, { convert mul_comm _ _ using 2, simp, }, { apply mul_comm, }, }, end lemma derivative_succ (n ν : ℕ) : (bernstein_polynomial R n (ν+1)).derivative = n * (bernstein_polynomial R (n-1) ν - bernstein_polynomial R (n-1) (ν+1)) := begin cases n, { simp [bernstein_polynomial], }, { apply derivative_succ_aux, } end lemma derivative_zero (n : ℕ) : (bernstein_polynomial R n 0).derivative = -n * bernstein_polynomial R (n-1) 0 := begin dsimp [bernstein_polynomial], simp [polynomial.derivative_pow], end lemma iterate_derivative_at_0_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 0 = 0 := begin cases ν, { rintro ⟨⟩, }, { rw nat.lt_succ_iff, induction k with k ih generalizing n ν, { simp [eval_at_0], }, { simp only [derivative_succ, int.coe_nat_eq_zero, int.nat_cast_eq_coe_nat, mul_eq_zero, function.comp_app, function.iterate_succ, polynomial.iterate_derivative_sub, polynomial.iterate_derivative_cast_nat_mul, polynomial.eval_mul, polynomial.eval_nat_cast, polynomial.eval_sub], intro h, apply mul_eq_zero_of_right, rw [ih _ _ (nat.le_of_succ_le h), sub_zero], convert ih _ _ (nat.pred_le_pred h), exact (nat.succ_pred_eq_of_pos (k.succ_pos.trans_le h)).symm } }, end @[simp] lemma iterate_derivative_succ_at_0_eq_zero (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n (ν+1))).eval 0 = 0 := iterate_derivative_at_0_eq_zero_of_lt R n (lt_add_one ν) open polynomial @[simp] lemma iterate_derivative_at_0 (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 = (pochhammer R ν).eval (n - (ν - 1) : ℕ) := begin by_cases h : ν ≤ n, { induction ν with ν ih generalizing n h, { simp [eval_at_0], }, { have h' : ν ≤ n-1 := nat.le_sub_right_of_add_le h, simp only [derivative_succ, ih (n-1) h', iterate_derivative_succ_at_0_eq_zero, nat.succ_sub_succ_eq_sub, nat.sub_zero, sub_zero, iterate_derivative_sub, iterate_derivative_cast_nat_mul, eval_one, eval_mul, eval_add, eval_sub, eval_X, eval_comp, eval_nat_cast, function.comp_app, function.iterate_succ, pochhammer_succ_left], obtain rfl | h'' := ν.eq_zero_or_pos, { simp }, { have : n - 1 - (ν - 1) = n - ν, { rw ←nat.succ_le_iff at h'', rw [nat.sub_sub, add_comm, nat.sub_add_cancel h''] }, rw [this, pochhammer_eval_succ], rw_mod_cast nat.sub_add_cancel (h'.trans n.pred_le) } } }, { simp only [not_le] at h, rw [nat.sub_eq_zero_of_le (nat.le_pred_of_lt h), eq_zero_of_lt R h], simp [pos_iff_ne_zero.mp (pos_of_gt h)] }, end lemma iterate_derivative_at_0_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 ≠ 0 := begin simp only [int.coe_nat_eq_zero, bernstein_polynomial.iterate_derivative_at_0, ne.def, nat.cast_eq_zero], simp only [←pochhammer_eval_cast], norm_cast, apply ne_of_gt, obtain rfl|h' := nat.eq_zero_or_pos ν, { simp, }, { rw ← nat.succ_pred_eq_of_pos h' at h, exact pochhammer_pos _ _ (nat.sub_pos_of_lt (nat.lt_of_succ_le h)) } end /-! Rather than redoing the work of evaluating the derivatives at 1, we use the symmetry of the Bernstein polynomials. -/ lemma iterate_derivative_at_1_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < n - ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 1 = 0 := begin intro w, rw flip' _ _ _ (nat.lt_of_sub_pos (pos_of_gt w)).le, simp [polynomial.eval_comp, iterate_derivative_at_0_eq_zero_of_lt R n w], end @[simp] lemma iterate_derivative_at_1 (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 = (-1)^(n-ν) * (pochhammer R (n - ν)).eval (ν + 1) := begin rw flip' _ _ _ h, simp [polynomial.eval_comp, h], obtain rfl | h' := h.eq_or_lt, { simp, }, { congr, norm_cast, rw [nat.sub_sub, nat.sub_sub_self (nat.succ_le_iff.mpr h')] }, end lemma iterate_derivative_at_1_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 ≠ 0 := begin rw [bernstein_polynomial.iterate_derivative_at_1 _ _ _ h, ne.def, neg_one_pow_mul_eq_zero_iff, ←nat.cast_succ, ←pochhammer_eval_cast, ←nat.cast_zero, nat.cast_inj], exact (pochhammer_pos _ _ (nat.succ_pos ν)).ne', end open submodule lemma linear_independent_aux (n k : ℕ) (h : k ≤ n + 1): linear_independent ℚ (λ ν : fin k, bernstein_polynomial ℚ n ν) := begin induction k with k ih, { apply linear_independent_empty_type, }, { apply linear_independent_fin_succ'.mpr, fsplit, { exact ih (le_of_lt h), }, { -- The actual work! -- We show that the (n-k)-th derivative at 1 doesn't vanish, -- but vanishes for everything in the span. clear ih, simp only [nat.succ_eq_add_one, add_le_add_iff_right] at h, simp only [fin.coe_last, fin.init_def], dsimp, apply not_mem_span_of_apply_not_mem_span_image ((polynomial.derivative_lhom ℚ)^(n-k)), simp only [not_exists, not_and, submodule.mem_map, submodule.span_image], intros p m, apply_fun (polynomial.eval (1 : ℚ)), simp only [polynomial.derivative_lhom_coe, linear_map.pow_apply], -- The right hand side is nonzero, -- so it will suffice to show the left hand side is always zero. suffices : (polynomial.derivative^[n-k] p).eval 1 = 0, { rw [this], exact (iterate_derivative_at_1_ne_zero ℚ n k h).symm, }, apply span_induction m, { simp, rintro ⟨a, w⟩, simp only [fin.coe_mk], rw [iterate_derivative_at_1_eq_zero_of_lt ℚ n ((nat.sub_lt_sub_left_iff h).mpr w)] }, { simp, }, { intros x y hx hy, simp [hx, hy], }, { intros a x h, simp [h], }, }, }, end /-- The Bernstein polynomials are linearly independent. We prove by induction that the collection of `bernstein_polynomial n ν` for `ν = 0, ..., k` are linearly independent. The inductive step relies on the observation that the `(n-k)`-th derivative, evaluated at 1, annihilates `bernstein_polynomial n ν` for `ν < k`, but has a nonzero value at `ν = k`. -/ lemma linear_independent (n : ℕ) : linear_independent ℚ (λ ν : fin (n+1), bernstein_polynomial ℚ n ν) := linear_independent_aux n (n+1) (le_refl _) lemma sum (n : ℕ) : (finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1 := begin -- We calculate `(x + (1-x))^n` in two different ways. conv { congr, congr, skip, funext, dsimp [bernstein_polynomial], rw [mul_assoc, mul_comm], }, rw ←add_pow, simp, end open polynomial open mv_polynomial lemma sum_smul (n : ℕ) : (finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X := begin -- We calculate the `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { simp [x], }, have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], }, let e : bool → polynomial R := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: have h : (x+y)^n = (x+y)^n := rfl, apply_fun (pderiv tt) at h, apply_fun (aeval e) at h, apply_fun (λ p, p * X) at h, -- On the left hand side we'll use the binomial theorem, then simplify. -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, ↑k * polynomial.X ^ (k - 1) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X = k • bernstein_polynomial R n k, { rintro (_|k), { simp, }, { dsimp [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, conv at h { to_lhs, rw [add_pow, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: apply_congr, skip, simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w], }, -- On the right hand side, we'll just simplify. conv at h { to_rhs, rw [pderiv_pow, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp [e] }, simpa using h, end lemma sum_mul_smul (n : ℕ) : (finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2 := begin -- We calculate the second `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { simp [x], }, have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], }, let e : bool → polynomial R := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the second `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: have h : (x+y)^n = (x+y)^n := rfl, apply_fun (pderiv tt) at h, apply_fun (pderiv tt) at h, apply_fun (aeval e) at h, apply_fun (λ p, p * X^2) at h, -- On the left hand side we'll use the binomial theorem, then simplify. -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, ↑k * (↑(k-1) * polynomial.X ^ (k - 1 - 1)) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X^2 = (k * (k-1)) • bernstein_polynomial R n k, { rintro (_|k), { simp, }, { rcases k with (_|k), { simp, }, { dsimp [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, }, conv at h { to_lhs, rw [add_pow, (pderiv tt).map_sum, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: apply_congr, skip, simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w] }, -- On the right hand side, we'll just simplify. conv at h { to_rhs, simp only [pderiv_one, pderiv_mul, pderiv_pow, pderiv_nat_cast, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp [e, smul_smul] }, simpa using h, end /-- A certain linear combination of the previous three identities, which we'll want later. -/ lemma variance (n : ℕ) : (finset.range (n+1)).sum (λ ν, (n • polynomial.X - ν)^2 * bernstein_polynomial R n ν) = n • polynomial.X * (1 - polynomial.X) := begin have p : (finset.range (n+1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) + (1 - (2 * n) • polynomial.X) * (finset.range (n+1)).sum (λ ν, ν • bernstein_polynomial R n ν) + (n^2 • X^2) * (finset.range (n+1)).sum (λ ν, bernstein_polynomial R n ν) = _ := rfl, conv at p { to_lhs, rw [finset.mul_sum, finset.mul_sum, ←finset.sum_add_distrib, ←finset.sum_add_distrib], simp only [←nat_cast_mul], simp only [←mul_assoc], simp only [←add_mul], }, conv at p { to_rhs, rw [sum, sum_smul, sum_mul_smul, ←nat_cast_mul], }, calc _ = _ : finset.sum_congr rfl (λ k m, _) ... = _ : p ... = _ : _, { congr' 1, simp only [←nat_cast_mul] with push_cast, cases k; { simp, ring, }, }, { simp only [←nat_cast_mul] with push_cast, cases n; { simp, ring, }, }, end end bernstein_polynomial
fdf8acb6b8442ea8f11dbd33f3f91324093bd339
137c667471a40116a7afd7261f030b30180468c2
/src/data/real/basic.lean
75ed8363a8579a6dd61a73e0a3108e6f4648c2f0
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,726
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import order.conditionally_complete_lattice import data.real.cau_seq_completion import algebra.archimedean import algebra.star.basic /-! # Real numbers from Cauchy sequences This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers. This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply lifting everything to `ℚ`. -/ /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul instance : comm_ring ℝ := begin refine_struct { zero := 0, one := 1, mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := λ a b, a + (-b), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩ }; repeat { rintro ⟨_⟩, }; try { refl }; simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy]; apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip end /-! Extra instances to short-circuit type class resolution. These short-circuits have an additional property of ensuring that a computable path is found; if `field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable` version of them. -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : has_sub ℝ := by apply_instance instance : module ℝ ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : star_ring ℝ := star_ring_of_comm /-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this is `cau_seq.completion.of_rat`, not `rat.cast`. -/ def of_rat : ℚ →+* ℝ := by refine_struct { to_fun := of_cauchy ∘ of_rat }; simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add, one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy] lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ := quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert of_rat_lt.2 zero_lt_one; simp protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : ordered_ring ℝ := { add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : ordered_semiring ℝ := 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 instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩ open_locale classical noncomputable instance : linear_order ℝ := { le_total := begin intros a b, induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa using le_total a b, end, decidable_le := by apply_instance, .. real.partial_order } noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.to_domain } /-- The real numbers are an ordered `*`-ring, with the trivial `*`-structure. -/ instance : star_ordered_ring ℝ := { star_mul_self_nonneg := λ r, mul_self_nonneg r, } @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv' noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← zero_cauchy, inv_cauchy], ..real.linear_ordered_comm_ring, ..real.domain } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : distrib_lattice ℝ := by apply_instance noncomputable instance : lattice ℝ := by apply_instance noncomputable instance : semilattice_inf ℝ := by apply_instance noncomputable instance : semilattice_sup ℝ := by apply_instance noncomputable instance : has_inf ℝ := by apply_instance noncomputable instance : has_sup ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := of_rat.eq_rat_cast theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin choose f hf using begin refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } end, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 := rfl theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup_def, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup {x | -x ∈ S}⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup {x | -x ∈ S} := rfl theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end section -- this proof times out without this local attribute [instance, priority 1000] classical.prop_decidable theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) end theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s ‹s.nonempty› H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s ‹s.nonempty› H, ..real.linear_order, ..real.lattice} lemma lt_Inf_add_pos {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {ε : ℝ} (hε : 0 < ε) : ∃ a ∈ s, a < Inf s + ε := (Inf_lt _ h' h).1 $ lt_add_of_pos_right _ hε lemma add_pos_lt_Sup {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {ε : ℝ} (hε : ε < 0) : ∃ a ∈ s, Sup s + ε < a := (real.lt_Sup _ h' h).1 $ add_lt_iff_neg_left.mpr hε lemma Inf_le_iff {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {a : ℝ} : Inf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε := begin rw le_iff_forall_pos_lt_add, split; intros H ε ε_pos, { exact exists_lt_of_cInf_lt h' (H ε ε_pos) }, { rcases H ε ε_pos with ⟨x, x_in, hx⟩, exact cInf_lt_of_lt h x_in hx } end lemma le_Sup_iff {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {a : ℝ} : a ≤ Sup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x := begin rw le_iff_forall_pos_lt_add, refine ⟨λ H ε ε_neg, _, λ H ε ε_pos, _⟩, { exact exists_lt_of_lt_cSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) }, { rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩, exact sub_lt_iff_lt_add.mp (lt_cSup_of_lt h x_in hx) } end theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { simp [Sup_empty] }, { apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) } end /-- As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is bounded above by `0` to show that `Sup S ≤ 0`. -/ lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, { simp [Sup_empty] }, { apply Sup_le_ub _ hS₂ hS, } end /-- As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, { simp [Inf_empty] }, { apply lb_le_Inf S hS₂ hS } end /-- As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`. -/ lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { simp [Inf_empty] }, { apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) } end theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) (sub_lt_self _ (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real
d70896bcb8c2f8707fa21f6b45a7d236e0018b9b
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/src/tidy/tidy.lean
ede436e171cc66fe0b54423408c4b438a475ee20
[]
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
2,975
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 .force import .backwards_reasoning import .forwards_reasoning import .fsplit import .automatic_induction import .tidy_attributes import .intro_at_least_one import .chain import .rewrite_search import .rewrite_search.tracer import .injections import .unfold_aux universe variables u v attribute [reducible] cast -- attribute [reducible] lift_t coe_t coe_b has_coe_to_fun.coe attribute [reducible] eq.mpr attribute [ematch] subtype.property meta def dsimp' := `[dsimp {unfold_reducible := tt, md := semireducible}] meta def dsimp_all' := `[dsimp at * {unfold_reducible := tt, md := semireducible}] open tactic -- TODO split_ifs? -- TODO refine_struct? meta def exact_decidable := `[exact dec_trivial] >> pure "exact dec_trivial" meta def default_tidy_tactics : list (tactic string) := [ force (reflexivity) >> pure "refl", exact_decidable, propositional_goal >> assumption >> pure "assumption", forwards_reasoning, forwards_library_reasoning, backwards_reasoning, `[ext1] >> pure "ext1", intro_at_least_one >>= λ ns, pure ("intros " ++ (" ".intercalate ns)), automatic_induction, `[apply_auto_param] >> pure "apply_auto_param", `[dsimp at *] >> pure "dsimp at *", `[simp at *] >> pure "simp at *", fsplit >> pure "fsplit", injections_and_clear >> pure "injections_and_clear", terminal_goal >> (`[solve_by_elim]) >> pure "solve_by_elim", unfold_aux >> pure "unfold_aux", -- recover' >> pure "recover'", run_tidy_tactics ] meta structure tidy_cfg extends chain_cfg := ( trace_result : bool := ff ) ( tactics : list (tactic string) := default_tidy_tactics ) meta def tidy ( cfg : tidy_cfg := {} ) : tactic unit := do results ← chain cfg.to_chain_cfg cfg.tactics, if cfg.trace_result then trace ("/- obviously says: -/ " ++ (", ".intercalate results)) else tactic.skip meta def obviously_tactics : list (tactic string) := [ tactic.interactive.rewrite_search_using [`ematch] ] -- TODO should switch this back to search eventually meta def obviously' : tactic unit := tidy { tactics := default_tidy_tactics ++ obviously_tactics, trace_result := ff, trace_steps := ff } meta def obviously_vis : tactic unit := tidy { tactics := default_tidy_tactics ++ [ tactic.interactive.rewrite_search_using [`ematch] { trace_summary := tt, view := visualiser } ], trace_result := tt, trace_steps := ff } instance subsingleton_pempty : subsingleton pempty := by tidy instance subsingleton_punit : subsingleton punit := by tidy
ff85e6092d98f8ed9785c984a39242f8ee5274a0
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_topology/fundamental_groupoid/induced_maps.lean
a1c1a2b4c194c6e48305e70c7cf94e3cb50b10b7
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,705
lean
/- Copyright (c) 2022 Praneeth Kolichala. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Praneeth Kolichala -/ import topology.homotopy.equiv import category_theory.equivalence import algebraic_topology.fundamental_groupoid.product /-! # Homotopic maps induce naturally isomorphic functors ## Main definitions - `fundamental_groupoid_functor.homotopic_maps_nat_iso H` The natural isomorphism between the induced functors `f : π(X) ⥤ π(Y)` and `g : π(X) ⥤ π(Y)`, given a homotopy `H : f ∼ g` - `fundamental_groupoid_functor.equiv_of_homotopy_equiv hequiv` The equivalence of the categories `π(X)` and `π(Y)` given a homotopy equivalence `hequiv : X ≃ₕ Y` between them. ## Implementation notes - In order to be more universe polymorphic, we define `continuous_map.homotopy.ulift_map` which lifts a homotopy from `I × X → Y` to `(Top.of ((ulift I) × X)) → Y`. This is because this construction uses `fundamental_groupoid_functor.prod_to_prod_Top` to convert between pairs of paths in I and X and the corresponding path after passing through a homotopy `H`. But `fundamental_groupoid_functor.prod_to_prod_Top` requires two spaces in the same universe. -/ noncomputable theory universe u open fundamental_groupoid open category_theory open fundamental_groupoid_functor open_locale fundamental_groupoid open_locale unit_interval namespace unit_interval /-- The path 0 ⟶ 1 in I -/ def path01 : path (0 : I) 1 := { to_fun := id, source' := rfl, target' := rfl } /-- The path 0 ⟶ 1 in ulift I -/ def upath01 : path (ulift.up 0 : ulift.{u} I) (ulift.up 1) := { to_fun := ulift.up, source' := rfl, target' := rfl } local attribute [instance] path.homotopic.setoid /-- The homotopy path class of 0 → 1 in `ulift I` -/ def uhpath01 : @from_top (Top.of $ ulift.{u} I) (ulift.up (0 : I)) ⟶ from_top (ulift.up 1) := ⟦upath01⟧ end unit_interval namespace continuous_map.homotopy open unit_interval (uhpath01) local attribute [instance] path.homotopic.setoid section casts /-- Abbreviation for `eq_to_hom` that accepts points in a topological space -/ abbreviation hcast {X : Top} {x₀ x₁ : X} (hx : x₀ = x₁) : from_top x₀ ⟶ from_top x₁ := eq_to_hom hx @[simp] lemma hcast_def {X : Top} {x₀ x₁ : X} (hx₀ : x₀ = x₁) : hcast hx₀ = eq_to_hom hx₀ := rfl variables {X₁ X₂ Y : Top.{u}} {f : C(X₁, Y)} {g : C(X₂, Y)} {x₀ x₁ : X₁} {x₂ x₃ : X₂} {p : path x₀ x₁} {q : path x₂ x₃} (hfg : ∀ t, f (p t) = g (q t)) include hfg /-- If `f(p(t) = g(q(t))` for two paths `p` and `q`, then the induced path homotopy classes `f(p)` and `g(p)` are the same as well, despite having a priori different types -/ lemma heq_path_of_eq_image : (πₘ f).map ⟦p⟧ == (πₘ g).map ⟦q⟧ := by { simp only [map_eq, ← path.homotopic.map_lift], apply path.homotopic.hpath_hext, exact hfg, } private lemma start_path : f x₀ = g x₂ := by { convert hfg 0; simp only [path.source], } private lemma end_path : f x₁ = g x₃ := by { convert hfg 1; simp only [path.target], } lemma eq_path_of_eq_image : (πₘ f).map ⟦p⟧ = hcast (start_path hfg) ≫ (πₘ g).map ⟦q⟧ ≫ hcast (end_path hfg).symm := by { rw functor.conj_eq_to_hom_iff_heq, exact heq_path_of_eq_image hfg } end casts /- We let `X` and `Y` be spaces, and `f` and `g` be homotopic maps between them -/ variables {X Y : Top.{u}} {f g : C(X, Y)} (H : continuous_map.homotopy f g) {x₀ x₁ : X} (p : from_top x₀ ⟶ from_top x₁) /-! These definitions set up the following diagram, for each path `p`: f(p) *--------* | \ | H₀ | \ d | H₁ | \ | *--------* g(p) Here, `H₀ = H.eval_at x₀` is the path from `f(x₀)` to `g(x₀)`, and similarly for `H₁`. Similarly, `f(p)` denotes the path in Y that the induced map `f` takes `p`, and similarly for `g(p)`. Finally, `d`, the diagonal path, is H(0 ⟶ 1, p), the result of the induced `H` on `path.homotopic.prod (0 ⟶ 1) p`, where `(0 ⟶ 1)` denotes the path from `0` to `1` in `I`. It is clear that the diagram commutes (`H₀ ≫ g(p) = d = f(p) ≫ H₁`), but unfortunately, many of the paths do not have defeq starting/ending points, so we end up needing some casting. -/ /-- Interpret a homotopy `H : C(I × X, Y) as a map C(ulift I × X, Y) -/ def ulift_map : C(Top.of (ulift.{u} I × X), Y) := ⟨λ x, H (x.1.down, x.2), H.continuous.comp ((continuous_induced_dom.comp continuous_fst).prod_mk continuous_snd)⟩ @[simp] lemma ulift_apply (i : ulift.{u} I) (x : X) : H.ulift_map (i, x) = H (i.down, x) := rfl /-- An abbreviation for `prod_to_prod_Top`, with some types already in place to help the typechecker. In particular, the first path should be on the ulifted unit interval. -/ abbreviation prod_to_prod_Top_I {a₁ a₂ : Top.of (ulift I)} {b₁ b₂ : X} (p₁ : from_top a₁ ⟶ from_top a₂) (p₂ : from_top b₁ ⟶ from_top b₂) := @category_theory.functor.map _ _ _ _ (prod_to_prod_Top (Top.of $ ulift I) X) (a₁, b₁) (a₂, b₂) (p₁, p₂) /-- The diagonal path `d` of a homotopy `H` on a path `p` -/ def diagonal_path : from_top (H (0, x₀)) ⟶ from_top (H (1, x₁)) := (πₘ H.ulift_map).map (prod_to_prod_Top_I uhpath01 p) /-- The diagonal path, but starting from `f x₀` and going to `g x₁` -/ def diagonal_path' : from_top (f x₀) ⟶ from_top (g x₁) := hcast (H.apply_zero x₀).symm ≫ (H.diagonal_path p) ≫ hcast (H.apply_one x₁) /-- Proof that `f(p) = H(0 ⟶ 0, p)`, with the appropriate casts -/ lemma apply_zero_path : (πₘ f).map p = hcast (H.apply_zero x₀).symm ≫ (πₘ H.ulift_map).map (prod_to_prod_Top_I (𝟙 (ulift.up 0)) p) ≫ hcast (H.apply_zero x₁) := begin apply quotient.induction_on p, intro p', apply @eq_path_of_eq_image _ _ _ _ H.ulift_map _ _ _ _ _ ((path.refl (ulift.up _)).prod p'), simp, end /-- Proof that `g(p) = H(1 ⟶ 1, p)`, with the appropriate casts -/ lemma apply_one_path : (πₘ g).map p = hcast (H.apply_one x₀).symm ≫ ((πₘ H.ulift_map).map (prod_to_prod_Top_I (𝟙 (ulift.up 1)) p)) ≫ hcast (H.apply_one x₁) := begin apply quotient.induction_on p, intro p', apply @eq_path_of_eq_image _ _ _ _ H.ulift_map _ _ _ _ _ ((path.refl (ulift.up _)).prod p'), simp, end /-- Proof that `H.eval_at x = H(0 ⟶ 1, x ⟶ x)`, with the appropriate casts -/ lemma eval_at_eq (x : X) : ⟦H.eval_at x⟧ = hcast (H.apply_zero x).symm ≫ (πₘ H.ulift_map).map (prod_to_prod_Top_I uhpath01 (𝟙 x)) ≫ hcast (H.apply_one x).symm.symm := begin dunfold prod_to_prod_Top_I uhpath01 hcast, refine (@functor.conj_eq_to_hom_iff_heq (πₓ Y) _ _ _ _ _ _ _ _ _).mpr _, simp only [id_eq_path_refl, prod_to_prod_Top_map, path.homotopic.prod_lift, map_eq, ← path.homotopic.map_lift], apply path.homotopic.hpath_hext, intro, refl, end /- Finally, we show `d = f(p) ≫ H₁ = H₀ ≫ g(p)` -/ lemma eq_diag_path : (πₘ f).map p ≫ ⟦H.eval_at x₁⟧ = H.diagonal_path' p ∧ (⟦H.eval_at x₀⟧ ≫ (πₘ g).map p : from_top (f x₀) ⟶ from_top (g x₁)) = H.diagonal_path' p := begin rw [H.apply_zero_path, H.apply_one_path, H.eval_at_eq, H.eval_at_eq], dunfold prod_to_prod_Top_I, split; { slice_lhs 2 5 { simp [← category_theory.functor.map_comp], }, refl, }, end end continuous_map.homotopy namespace fundamental_groupoid_functor open category_theory open_locale fundamental_groupoid local attribute [instance] path.homotopic.setoid variables {X Y : Top.{u}} {f g : C(X, Y)} (H : continuous_map.homotopy f g) /-- Given a homotopy H : f ∼ g, we have an associated natural isomorphism between the induced functors `f` and `g` -/ def homotopic_maps_nat_iso : πₘ f ⟶ πₘ g := { app := λ x, ⟦H.eval_at x⟧, naturality' := λ x y p, by rw [(H.eq_diag_path p).1, (H.eq_diag_path p).2] } instance : is_iso (homotopic_maps_nat_iso H) := by apply nat_iso.is_iso_of_is_iso_app open_locale continuous_map /-- Homotopy equivalent topological spaces have equivalent fundamental groupoids. -/ def equiv_of_homotopy_equiv (hequiv : X ≃ₕ Y) : πₓ X ≌ πₓ Y := begin apply equivalence.mk (πₘ hequiv.to_fun : πₓ X ⥤ πₓ Y) (πₘ hequiv.inv_fun : πₓ Y ⥤ πₓ X); simp only [Groupoid.hom_to_functor, Groupoid.id_to_functor], { convert (as_iso (homotopic_maps_nat_iso hequiv.left_inv.some)).symm, exacts [((π).map_id X).symm, ((π).map_comp _ _).symm] }, { convert as_iso (homotopic_maps_nat_iso hequiv.right_inv.some), exacts [((π).map_comp _ _).symm, ((π).map_id Y).symm] }, end end fundamental_groupoid_functor
70c9a2b2c266ce9740a5cb84d023e9a3d22b4a7b
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_1680.lean
1f086b15ffcf7cc0d02f987618b24cadaee5bdd8
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
159
lean
import logic.basic variables p q : Prop -- BEGIN example (h : ¬(p ∨ q)) : ¬q ∧ ¬p := begin rw ←not_or_distrib, rw or_comm, exact h, end -- END
aa0390088bba6728ba39ab051095178427b97f7c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finsupp/pointwise.lean
e2de0c10f122ed81bfd3bc6541c35fbb3fc33d8f
[ "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
3,887
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 data.finsupp.defs import algebra.ring.pi /-! # The pointwise product on `finsupp`. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. For the convolution product on `finsupp` when the domain has a binary operation, see the type synonyms `add_monoid_algebra` (which is in turn used to define `polynomial` and `mv_polynomial`) and `monoid_algebra`. -/ noncomputable theory open finset universes u₁ u₂ u₃ u₄ u₅ variables {α : Type u₁} {β : Type u₂} {γ : Type u₃} {δ : Type u₄} {ι : Type u₅} namespace finsupp /-! ### Declarations about the pointwise product on `finsupp`s -/ section variables [mul_zero_class β] /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is `f a * g a`. -/ instance : has_mul (α →₀ β) := ⟨zip_with (*) (mul_zero 0)⟩ lemma coe_mul (g₁ g₂ : α →₀ β) : ⇑(g₁ * g₂) = g₁ * g₂ := rfl @[simp] lemma mul_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ * g₂) a = g₁ a * g₂ a := rfl lemma support_mul [decidable_eq α] {g₁ g₂ : α →₀ β} : (g₁ * g₂).support ⊆ g₁.support ∩ g₂.support := begin intros a h, simp only [mul_apply, mem_support_iff] at h, simp only [mem_support_iff, mem_inter, ne.def], rw ←not_or_distrib, intro w, apply h, cases w; { rw w, simp }, end instance : mul_zero_class (α →₀ β) := finsupp.coe_fn_injective.mul_zero_class _ coe_zero coe_mul end instance [semigroup_with_zero β] : semigroup_with_zero (α →₀ β) := finsupp.coe_fn_injective.semigroup_with_zero _ coe_zero coe_mul instance [non_unital_non_assoc_semiring β] : non_unital_non_assoc_semiring (α →₀ β) := finsupp.coe_fn_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_semiring β] : non_unital_semiring (α →₀ β) := finsupp.coe_fn_injective.non_unital_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_comm_semiring β] : non_unital_comm_semiring (α →₀ β) := finsupp.coe_fn_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl) instance [non_unital_non_assoc_ring β] : non_unital_non_assoc_ring (α →₀ β) := finsupp.coe_fn_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_ring β] : non_unital_ring (α →₀ β) := finsupp.coe_fn_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) instance [non_unital_comm_ring β] : non_unital_comm_ring (α →₀ β) := finsupp.coe_fn_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl) -- TODO can this be generalized in the direction of `pi.has_smul'` -- (i.e. dependent functions and finsupps) -- TODO in theory this could be generalised, we only really need `smul_zero` for the definition instance pointwise_scalar [semiring β] : has_smul (α → β) (α →₀ β) := { smul := λ f g, finsupp.of_support_finite (λ a, f a • g a) begin apply set.finite.subset g.finite_support, simp only [function.support_subset_iff, finsupp.mem_support_iff, ne.def, finsupp.fun_support_eq, finset.mem_coe], intros x hx h, apply hx, rw [h, smul_zero], end } @[simp] lemma coe_pointwise_smul [semiring β] (f : α → β) (g : α →₀ β) : ⇑(f • g) = f • g := rfl /-- The pointwise multiplicative action of functions on finitely supported functions -/ instance pointwise_module [semiring β] : module (α → β) (α →₀ β) := function.injective.module _ coe_fn_add_hom coe_fn_injective coe_pointwise_smul end finsupp
19cd64107d1ac04cf31b3ed89940d396b54d7718
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/int/units.lean
741d16d48802fe7fc2ef5ac17898700675c111f3
[ "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
3,773
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.nat.units import data.int.basic import algebra.ring.units /-! # Lemmas about units in `ℤ`. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace int /-! ### units -/ @[simp] theorem units_nat_abs (u : ℤˣ) : 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 : ℤˣ) : u = 1 ∨ u = -1 := by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma is_unit_eq_one_or {a : ℤ} : is_unit a → a = 1 ∨ a = -1 | ⟨x, hx⟩ := hx ▸ (units_eq_one_or _).imp (congr_arg coe) (congr_arg coe) lemma is_unit_iff {a : ℤ} : is_unit a ↔ a = 1 ∨ a = -1 := begin refine ⟨λ h, is_unit_eq_one_or h, λ h, _⟩, rcases h with rfl | rfl, { exact is_unit_one }, { exact is_unit_one.neg } end lemma is_unit_eq_or_eq_neg {a b : ℤ} (ha : is_unit a) (hb : is_unit b) : a = b ∨ a = -b := begin rcases is_unit_eq_one_or hb with rfl | rfl, { exact is_unit_eq_one_or ha }, { rwa [or_comm, neg_neg, ←is_unit_iff] }, end lemma eq_one_or_neg_one_of_mul_eq_one {z w : ℤ} (h : z * w = 1) : z = 1 ∨ z = -1 := is_unit_iff.mp (is_unit_of_mul_eq_one z w h) lemma eq_one_or_neg_one_of_mul_eq_one' {z w : ℤ} (h : z * w = 1) : (z = 1 ∧ w = 1) ∨ (z = -1 ∧ w = -1) := begin have h' : w * z = 1 := (mul_comm z w) ▸ h, rcases eq_one_or_neg_one_of_mul_eq_one h with rfl | rfl; rcases eq_one_or_neg_one_of_mul_eq_one h' with rfl | rfl; tauto, end theorem eq_of_mul_eq_one {z w : ℤ} (h : z * w = 1) : z = w := (eq_one_or_neg_one_of_mul_eq_one' h).elim (λ h, h.1.trans h.2.symm) (λ h, h.1.trans h.2.symm) lemma mul_eq_one_iff_eq_one_or_neg_one {z w : ℤ} : z * w = 1 ↔ z = 1 ∧ w = 1 ∨ z = -1 ∧ w = -1 := begin refine ⟨eq_one_or_neg_one_of_mul_eq_one', λ h, or.elim h (λ H, _) (λ H, _)⟩; rcases H with ⟨rfl, rfl⟩; refl, end lemma eq_one_or_neg_one_of_mul_eq_neg_one' {z w : ℤ} (h : z * w = -1) : z = 1 ∧ w = -1 ∨ z = -1 ∧ w = 1 := begin rcases is_unit_eq_one_or (is_unit.mul_iff.mp (int.is_unit_iff.mpr (or.inr h))).1 with rfl | rfl, { exact or.inl ⟨rfl, one_mul w ▸ h⟩, }, { exact or.inr ⟨rfl, neg_inj.mp (neg_one_mul w ▸ h)⟩, } end lemma mul_eq_neg_one_iff_eq_one_or_neg_one {z w : ℤ} : z * w = -1 ↔ z = 1 ∧ w = -1 ∨ z = -1 ∧ w = 1 := begin refine ⟨eq_one_or_neg_one_of_mul_eq_neg_one', λ h, or.elim h (λ H, _) (λ H, _)⟩; rcases H with ⟨rfl, rfl⟩; refl, end theorem is_unit_iff_nat_abs_eq {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := by simp [nat_abs_eq_iff, is_unit_iff, nat.cast_zero] alias is_unit_iff_nat_abs_eq ↔ is_unit.nat_abs_eq _ @[norm_cast] lemma of_nat_is_unit {n : ℕ} : is_unit (n : ℤ) ↔ is_unit n := by rw [nat.is_unit_iff, is_unit_iff_nat_abs_eq, nat_abs_of_nat] lemma is_unit_mul_self {a : ℤ} (ha : is_unit a) : a * a = 1 := (is_unit_eq_one_or ha).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma is_unit_add_is_unit_eq_is_unit_add_is_unit {a b c d : ℤ} (ha : is_unit a) (hb : is_unit b) (hc : is_unit c) (hd : is_unit d) : a + b = c + d ↔ a = c ∧ b = d ∨ a = d ∧ b = c := begin rw is_unit_iff at ha hb hc hd, cases ha; cases hb; cases hc; cases hd; subst ha; subst hb; subst hc; subst hd; tidy, end lemma eq_one_or_neg_one_of_mul_eq_neg_one {z w : ℤ} (h : z * w = -1) : z = 1 ∨ z = -1 := or.elim (eq_one_or_neg_one_of_mul_eq_neg_one' h) (λ H, or.inl H.1) (λ H, or.inr H.1) end int
875cddf8f8e6b83ecfd7ded3e1b834957d6e9d0f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/complex/cardinality.lean
7b1ff847899bcee09a95a253a6dcacb8702fbfa7
[ "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
1,066
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import data.complex.basic import data.real.cardinality /-! # The cardinality of the complex numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file shows that the complex numbers have cardinality continuum, i.e. `#ℂ = 𝔠`. -/ open cardinal set open_locale cardinal /-- The cardinality of the complex numbers, as a type. -/ @[simp] theorem mk_complex : #ℂ = 𝔠 := by rw [mk_congr complex.equiv_real_prod, mk_prod, lift_id, mk_real, continuum_mul_self] /-- The cardinality of the complex numbers, as a set. -/ @[simp] lemma mk_univ_complex : #(set.univ : set ℂ) = 𝔠 := by rw [mk_univ, mk_complex] /-- The complex numbers are not countable. -/ lemma not_countable_complex : ¬ (set.univ : set ℂ).countable := by { rw [← le_aleph_0_iff_set_countable, not_le, mk_univ_complex], apply cantor }
550f0ee1eb04a1917838b2d12c0d38c8d89cbd5d
dc253be9829b840f15d96d986e0c13520b085033
/cohomology/gysin.hlean
4aed959723f6dc972b19244f1ee198907a30b74c
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
9,610
hlean
/- the construction of the Gysin sequence using the Serre spectral sequence -/ -- author: Floris van Doorn import .serre open eq pointed is_trunc is_conn is_equiv equiv sphere fiber chain_complex left_module spectrum nat prod nat int algebra function spectral_sequence fin group namespace cohomology universe variable u /- Given a pointed map E →* B with as fiber the sphere S^{n+1} and an abelian group A. The only nontrivial differentials in the spectral sequence of this map are the following differentials on page n: d_m = d_(m-1,n+1)^n : E_(m-1,n+1)^n → E_(m+n+1,0)^n Note that ker d_m = E_(m-1,n+1)^∞ and coker d_m = E_(m+n+1,0)^∞. Each diagonal on the ∞-page has at most two nontrivial groups, which means that coker d_{m-1} and ker d_m are the only two nontrivial groups building up D_{m+n}^∞, where D^∞ is the abutment of the spectral sequence. This gives the short exact sequences: coker d_{m-1} → D_{m+n}^∞ → ker d_m We can splice these SESs together to get a LES ... E_(m+n,0)^n → D_{m+n}^∞ → E_(m-1,n+1)^n → E_(m+n+1,0)^n → D_{m+n+1}^∞ ... Now we have E_(p,q)^n = E_(p,q)^0 = H^p(B; H^q(S^{n+1}; A)) = H^p(B; A) if q = n+1 or q = 0 and D_{n}^∞ = H^n(E; A) This gives the Gysin sequence ... H^{m+n}(B; A) → H^{m+n}(E; A) → H^{m-1}(B; A) → H^{m+n+1}(B; A) → H^{m+n+1}(E; A) ... -/ definition gysin_trivial_Epage {E B : pType.{u}} {n : ℕ} (HB : is_conn 1 B) (f : E →* B) (e : pfiber f ≃* sphere (n+1)) (A : AbGroup) (r : ℕ) (p q : ℤ) (hq : q ≠ 0) (hq' : q ≠ of_nat (n+1)): is_contr (convergent_spectral_sequence.E (serre_spectral_sequence_map_of_is_conn pt f (EM_spectrum A) 0 (is_strunc_EM_spectrum A) HB) r (p, q)) := begin intros, apply is_contr_E, apply is_contr_ordinary_cohomology, esimp, refine is_contr_equiv_closed_rev _ (unreduced_ordinary_cohomology_sphere_of_neq A hq' hq), apply group.equiv_of_isomorphism, apply unreduced_ordinary_cohomology_isomorphism, exact e⁻¹ᵉ* end definition gysin_trivial_Epage2 {E B : pType.{u}} {n : ℕ} (HB : is_conn 1 B) (f : E →* B) (e : pfiber f ≃* sphere (n+1)) (A : AbGroup) (r : ℕ) (p q : ℤ) (hq : q > n+1) : is_contr (convergent_spectral_sequence.E (serre_spectral_sequence_map_of_is_conn pt f (EM_spectrum A) 0 (is_strunc_EM_spectrum A) HB) r (p, q)) := begin intros, apply gysin_trivial_Epage HB f e A r p q, { intro h, subst h, apply not_lt_zero (n+1), exact lt_of_of_nat_lt_of_nat hq }, { intro h, subst h, exact lt.irrefl _ hq } end definition gysin_sequence' {E B : pType.{u}} {n : ℕ} (HB : is_conn 1 B) (f : E →* B) (e : pfiber f ≃* sphere (n+1)) (A : AbGroup) : module_chain_complex rℤ -3ℤ := let c := serre_spectral_sequence_map_of_is_conn pt f (EM_spectrum A) 0 (is_strunc_EM_spectrum A) HB in let cn : is_normal c := !is_normal_serre_spectral_sequence_map_of_is_conn in have deg_d_x : Π(m : ℤ), deg (convergent_spectral_sequence.d c n) ((m - 1) - 1, n + 1) = (n + m - 0, 0), begin intro m, refine deg_d_normal_eq cn _ _ ⬝ _, refine prod_eq _ !add.right_inv, refine ap (λx, x + (n+2)) !sub_sub ⬝ _, refine add.comm4 m (- 2) n 2 ⬝ _, refine ap (λx, x + 0) !add.comm end, have trivial_E : Π(r : ℕ) (p q : ℤ) (hq : q ≠ 0) (hq' : q ≠ of_nat (n+1)), is_contr (convergent_spectral_sequence.E c r (p, q)), from gysin_trivial_Epage HB f e A, have trivial_E' : Π(r : ℕ) (p q : ℤ) (hq : q > n+1), is_contr (convergent_spectral_sequence.E c r (p, q)), from gysin_trivial_Epage2 HB f e A, left_module.LES_of_SESs _ _ _ (λm, convergent_spectral_sequence.d c n (m - 1, n + 1)) begin intro m, fapply short_exact_mod_isomorphism, rotate 3, { fapply short_exact_mod_of_is_contr_submodules (convergence_0 c (n + m) (λm, neg_zero)), { exact zero_lt_succ n }, { intro k Hk0 Hkn, apply trivial_E, exact λh, Hk0 (of_nat.inj h), exact λh, Hkn (of_nat.inj h), }}, { symmetry, refine Einf_isomorphism c (n+1) _ _ ⬝lm convergent_spectral_sequence.α c n (n + m - 0, 0) ⬝lm isomorphism_of_eq (ap (graded_homology _ _) _) ⬝lm !graded_homology_isomorphism ⬝lm homology_isomorphism_cokernel_module _ _ _, { intros r Hr, apply trivial_E', apply of_nat_lt_of_nat_of_lt, rewrite [zero_add], exact lt_succ_of_le Hr }, { intros r Hr, apply is_contr_E, apply is_normal.normal2 cn, refine lt_of_le_of_lt (le_of_eq (ap (λx : ℤ × ℤ, 0 + pr2 x) (is_normal.normal3 cn r))) _, esimp, rewrite [-sub_eq_add_neg], apply sub_lt_of_pos, apply of_nat_lt_of_nat_of_lt, apply succ_pos }, { exact (deg_d_x m)⁻¹ }, { intro x, apply @eq_of_is_contr, apply is_contr_E, apply is_normal.normal2 cn, refine lt_of_le_of_lt (@le_of_eq ℤ _ _ _ (ap (pr2 ∘ deg (convergent_spectral_sequence.d c n)) (deg_d_x m) ⬝ ap pr2 (deg_d_normal_eq cn _ _))) _, refine lt_of_le_of_lt (le_of_eq (zero_add (-(n+1)))) _, apply neg_neg_of_pos, apply of_nat_succ_pos }}, { reflexivity }, { symmetry, refine Einf_isomorphism c (n+1) _ _ ⬝lm convergent_spectral_sequence.α c n (n + m - (n+1), n+1) ⬝lm graded_homology_isomorphism_kernel_module _ _ _ _ ⬝lm isomorphism_of_eq (ap (graded_kernel _) _), { intros r Hr, apply trivial_E', apply of_nat_lt_of_nat_of_lt, apply lt_add_of_pos_right, apply zero_lt_succ }, { intros r Hr, apply is_contr_E, apply is_normal.normal2 cn, refine lt_of_le_of_lt (le_of_eq (ap (λx : ℤ × ℤ, (n+1)+pr2 x) (is_normal.normal3 cn r))) _, esimp, rewrite [-sub_eq_add_neg], apply sub_lt_right_of_lt_add, apply of_nat_lt_of_nat_of_lt, rewrite [zero_add], exact lt_succ_of_le Hr }, { apply trivial_image_of_is_contr, rewrite [deg_d_inv_eq], apply trivial_E', apply of_nat_lt_of_nat_of_lt, apply lt_add_of_pos_right, apply zero_lt_succ }, { refine prod_eq _ rfl, refine ap (add _) !neg_add ⬝ _, refine add.comm4 n m (-n) (- 1) ⬝ _, refine ap (λx, x + _) !add.right_inv ⬝ !zero_add }} end definition gysin_sequence'_zero {E B : Type*} {n : ℕ} (HB : is_conn 1 B) (f : E →* B) (e : pfiber f ≃* sphere (n+1)) (A : AbGroup) (m : ℤ) : gysin_sequence' HB f e A (m, 0) ≃lm LeftModule_int_of_AbGroup (uoH^m+n+1[B, A]) := let c := serre_spectral_sequence_map_of_is_conn pt f (EM_spectrum A) 0 (is_strunc_EM_spectrum A) HB in let cn : is_normal c := !is_normal_serre_spectral_sequence_map_of_is_conn in begin refine LES_of_SESs_zero _ _ m ⬝lm _, transitivity convergent_spectral_sequence.E c n (m+n+1, 0), exact isomorphism_of_eq (ap (convergent_spectral_sequence.E c n) (deg_d_normal_eq cn _ _ ⬝ prod_eq (add.comm4 m (- 1) n 2) (add.right_inv (n+1)))), refine E_isomorphism0 _ _ _ ⬝lm lm_iso_int.mk (unreduced_ordinary_cohomology_isomorphism_right _ _ _), { intros r hr, apply is_contr_ordinary_cohomology, refine is_contr_equiv_closed_rev (equiv_of_isomorphism (cohomology_change_int _ _ _ ⬝g uoH^≃r+1[e⁻¹ᵉ*, A])) (unreduced_ordinary_cohomology_sphere_of_neq_nat A _ _), { exact !zero_sub ⬝ ap neg (deg_d_normal_pr2 cn r) ⬝ !neg_neg }, { apply ne_of_lt, apply add_lt_add_right, exact hr }, { apply succ_ne_zero }}, { intros r hr, apply is_contr_ordinary_cohomology, refine is_contr_equiv_closed_rev (equiv_of_isomorphism (cohomology_change_int _ _ (!zero_add ⬝ deg_d_normal_pr2 cn r))) (is_contr_ordinary_cohomology_of_neg _ _ _), { rewrite [-neg_zero], apply neg_lt_neg, apply of_nat_lt_of_nat_of_lt, apply zero_lt_succ }}, { exact uoH^≃ 0[e⁻¹ᵉ*, A] ⬝g unreduced_ordinary_cohomology_sphere_zero _ _ (succ_ne_zero n) } end definition gysin_sequence'_one {E B : Type*} {n : ℕ} (HB : is_conn 1 B) (f : E →* B) (e : pfiber f ≃* sphere (n+1)) (A : AbGroup) (m : ℤ) : gysin_sequence' HB f e A (m, 1) ≃lm LeftModule_int_of_AbGroup (uoH^m - 1[B, A]) := let c := serre_spectral_sequence_map_of_is_conn pt f (EM_spectrum A) 0 (is_strunc_EM_spectrum A) HB in let cn : is_normal c := !is_normal_serre_spectral_sequence_map_of_is_conn in begin refine LES_of_SESs_one _ _ m ⬝lm _, refine E_isomorphism0 _ _ _ ⬝lm lm_iso_int.mk (unreduced_ordinary_cohomology_isomorphism_right _ _ _), { intros r hr, apply is_contr_ordinary_cohomology, refine is_contr_equiv_closed_rev (equiv_of_isomorphism uoH^≃_[e⁻¹ᵉ*, A]) (unreduced_ordinary_cohomology_sphere_of_gt _ _), { apply lt_add_of_pos_right, apply zero_lt_succ }}, { intros r hr, apply is_contr_ordinary_cohomology, refine is_contr_equiv_closed_rev (equiv_of_isomorphism (cohomology_change_int _ _ _ ⬝g uoH^≃n-r[e⁻¹ᵉ*, A])) (unreduced_ordinary_cohomology_sphere_of_neq_nat A _ _), { refine ap (add _) (deg_d_normal_pr2 cn r) ⬝ add_sub_comm n 1 r 1 ⬝ !add_zero ⬝ _, symmetry, apply of_nat_sub, exact le_of_lt hr }, { apply ne_of_lt, exact lt_of_le_of_lt (nat.sub_le n r) (lt.base n) }, { apply ne_of_gt, exact nat.sub_pos_of_lt hr }}, { refine uoH^≃n+1[e⁻¹ᵉ*, A] ⬝g unreduced_ordinary_cohomology_sphere _ _ (succ_ne_zero n) } end -- todo: maybe rewrite n+m to m+n (or above rewrite m+n+1 to n+m+1 or n+(m+1))? definition gysin_sequence'_two {E B : Type*} {n : ℕ} (HB : is_conn 1 B) (f : E →* B) (e : pfiber f ≃* sphere (n+1)) (A : AbGroup) (m : ℤ) : gysin_sequence' HB f e A (m, 2) ≃lm LeftModule_int_of_AbGroup (uoH^n+m[E, A]) := LES_of_SESs_two _ _ m end cohomology
fa67f5fe3260d6ea2ca27fc0760f3519c9e1f96a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/deprecated/submonoid.lean
eddfd5ef9373bebe9900de9f9a7e1e43d7b31dd4
[ "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
16,086
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 -/ import group_theory.submonoid.basic import algebra.big_operators.basic import deprecated.group /-! # Unbundled submonoids This file defines unbundled multiplicative and additive submonoids `is_submonoid` and `is_add_submonoid`. These are not the preferred way to talk about submonoids and should not be used for any new projects. The preferred way in mathlib are the bundled versions `submonoid G` and `add_submonoid G`. ## Main definitions `is_add_submonoid (S : set G)` : the predicate that `S` is the underlying subset of an additive submonoid of `G`. The bundled variant `add_subgroup G` should be used in preference to this. `is_submonoid (S : set G)` : the predicate that `S` is the underlying subset of a submonoid of `G`. The bundled variant `submonoid G` should be used in preference to this. ## Tags subgroup, subgroups, is_subgroup ## Tags submonoid, submonoids, is_submonoid -/ open_locale big_operators variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} /-- `s` is an additive submonoid: a set containing 0 and closed under addition. Note that this structure is deprecated, and the bundled variant `add_submonoid A` should be preferred. -/ structure is_add_submonoid (s : set A) : Prop := (zero_mem : (0:A) ∈ s) (add_mem {a b} : a ∈ s → b ∈ s → a + b ∈ s) /-- `s` is a submonoid: a set containing 1 and closed under multiplication. Note that this structure is deprecated, and the bundled variant `submonoid M` should be preferred. -/ @[to_additive] structure is_submonoid (s : set M) : Prop := (one_mem : (1:M) ∈ s) (mul_mem {a b} : a ∈ s → b ∈ s → a * b ∈ s) lemma additive.is_add_submonoid {s : set M} : ∀ (is : is_submonoid s), @is_add_submonoid (additive M) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem additive.is_add_submonoid_iff {s : set M} : @is_add_submonoid (additive M) _ s ↔ is_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, additive.is_add_submonoid⟩ lemma multiplicative.is_submonoid {s : set A} : ∀ (is : is_add_submonoid s), @is_submonoid (multiplicative A) _ s | ⟨h₁, h₂⟩ := ⟨h₁, @h₂⟩ theorem multiplicative.is_submonoid_iff {s : set A} : @is_submonoid (multiplicative A) _ s ↔ is_add_submonoid s := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, @h₂⟩, multiplicative.is_submonoid⟩ /-- The intersection of two submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of two `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of M."] lemma is_submonoid.inter {s₁ s₂ : set M} (is₁ : is_submonoid s₁) (is₂ : is_submonoid s₂) : is_submonoid (s₁ ∩ s₂) := { one_mem := ⟨is₁.one_mem, is₂.one_mem⟩, mul_mem := λ x y hx hy, ⟨is₁.mul_mem hx.1 hy.1, is₂.mul_mem hx.2 hy.2⟩ } /-- The intersection of an indexed set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The intersection of an indexed set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`."] lemma is_submonoid.Inter {ι : Sort*} {s : ι → set M} (h : ∀ y : ι, is_submonoid (s y)) : is_submonoid (set.Inter s) := { one_mem := set.mem_Inter.2 $ λ y, (h y).one_mem, mul_mem := λ x₁ x₂ h₁ h₂, set.mem_Inter.2 $ λ y, (h y).mul_mem (set.mem_Inter.1 h₁ y) (set.mem_Inter.1 h₂ y) } /-- The union of an indexed, directed, nonempty set of submonoids of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The union of an indexed, directed, nonempty set of `add_submonoid`s of an `add_monoid` `M` is an `add_submonoid` of `M`. "] lemma is_submonoid_Union_of_directed {ι : Type*} [hι : nonempty ι] {s : ι → set M} (hs : ∀ i, is_submonoid (s i)) (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_submonoid (⋃i, s i) := { one_mem := let ⟨i⟩ := hι in set.mem_Union.2 ⟨i, (hs i).one_mem⟩, mul_mem := λ a b ha hb, let ⟨i, hi⟩ := set.mem_Union.1 ha in let ⟨j, hj⟩ := set.mem_Union.1 hb in let ⟨k, hk⟩ := directed i j in set.mem_Union.2 ⟨k, (hs k).mul_mem (hk.1 hi) (hk.2 hj)⟩ } section powers /-- The set of natural number powers `1, x, x², ...` of an element `x` of a monoid. -/ @[to_additive multiples "The set of natural number multiples `0, x, 2x, ...` of an element `x` of an `add_monoid`."] def powers (x : M) : set M := {y | ∃ n:ℕ, x^n = y} /-- 1 is in the set of natural number powers of an element of a monoid. -/ @[to_additive "0 is in the set of natural number multiples of an element of an `add_monoid`."] lemma powers.one_mem {x : M} : (1 : M) ∈ powers x := ⟨0, pow_zero _⟩ /-- An element of a monoid is in the set of that element's natural number powers. -/ @[to_additive "An element of an `add_monoid` is in the set of that element's natural number multiples."] lemma powers.self_mem {x : M} : x ∈ powers x := ⟨1, pow_one _⟩ /-- The set of natural number powers of an element of a monoid is closed under multiplication. -/ @[to_additive "The set of natural number multiples of an element of an `add_monoid` is closed under addition."] lemma powers.mul_mem {x y z : M} : (y ∈ powers x) → (z ∈ powers x) → (y * z ∈ powers x) := λ ⟨n₁, h₁⟩ ⟨n₂, h₂⟩, ⟨n₁ + n₂, by simp only [pow_add, *]⟩ /-- The set of natural number powers of an element of a monoid `M` is a submonoid of `M`. -/ @[to_additive "The set of natural number multiples of an element of an `add_monoid` `M` is an `add_submonoid` of `M`."] lemma powers.is_submonoid (x : M) : is_submonoid (powers x) := { one_mem := powers.one_mem, mul_mem := λ y z, powers.mul_mem } /-- A monoid is a submonoid of itself. -/ @[to_additive "An `add_monoid` is an `add_submonoid` of itself."] lemma univ.is_submonoid : is_submonoid (@set.univ M) := by split; simp /-- The preimage of a submonoid under a monoid hom is a submonoid of the domain. -/ @[to_additive "The preimage of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the domain."] lemma is_submonoid.preimage {N : Type*} [monoid N] {f : M → N} (hf : is_monoid_hom f) {s : set N} (hs : is_submonoid s) : is_submonoid (f ⁻¹' s) := { one_mem := show f 1 ∈ s, by rw is_monoid_hom.map_one hf; exact hs.one_mem, mul_mem := λ a b (ha : f a ∈ s) (hb : f b ∈ s), show f (a * b) ∈ s, by rw is_monoid_hom.map_mul hf; exact hs.mul_mem ha hb } /-- The image of a submonoid under a monoid hom is a submonoid of the codomain. -/ @[to_additive "The image of an `add_submonoid` under an `add_monoid` hom is an `add_submonoid` of the codomain."] lemma is_submonoid.image {γ : Type*} [monoid γ] {f : M → γ} (hf : is_monoid_hom f) {s : set M} (hs : is_submonoid s) : is_submonoid (f '' s) := { one_mem := ⟨1, hs.one_mem, hf.map_one⟩, mul_mem := λ a b ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, hs.mul_mem hx.1 hy.1, by rw [hf.map_mul, hx.2, hy.2]⟩ } /-- The image of a monoid hom is a submonoid of the codomain. -/ @[to_additive "The image of an `add_monoid` hom is an `add_submonoid` of the codomain."] lemma range.is_submonoid {γ : Type*} [monoid γ] {f : M → γ} (hf : is_monoid_hom f) : is_submonoid (set.range f) := by { rw ← set.image_univ, exact univ.is_submonoid.image hf } /-- Submonoids are closed under natural powers. -/ @[to_additive is_add_submonoid.smul_mem "An `add_submonoid` is closed under multiplication by naturals."] lemma is_submonoid.pow_mem {a : M} (hs : is_submonoid s) (h : a ∈ s) : ∀ {n : ℕ}, a ^ n ∈ s | 0 := by { rw pow_zero, exact hs.one_mem } | (n + 1) := by { rw pow_succ, exact hs.mul_mem h is_submonoid.pow_mem } /-- The set of natural number powers of an element of a submonoid is a subset of the submonoid. -/ @[to_additive is_add_submonoid.multiples_subset "The set of natural number multiples of an element of an `add_submonoid` is a subset of the `add_submonoid`."] lemma is_submonoid.power_subset {a : M} (hs : is_submonoid s) (h : a ∈ s) : powers a ⊆ s := assume x ⟨n, hx⟩, hx ▸ hs.pow_mem h end powers namespace is_submonoid /-- The product of a list of elements of a submonoid is an element of the submonoid. -/ @[to_additive "The sum of a list of elements of an `add_submonoid` is an element of the `add_submonoid`."] lemma list_prod_mem (hs : is_submonoid s) : ∀{l : list M}, (∀x∈l, x ∈ s) → l.prod ∈ s | [] h := hs.one_mem | (a::l) h := suffices a * l.prod ∈ s, by simpa, have a ∈ s ∧ (∀x∈l, x ∈ s), by simpa using h, hs.mul_mem this.1 (list_prod_mem this.2) /-- The product of a multiset of elements of a submonoid of a `comm_monoid` is an element of the submonoid. -/ @[to_additive "The sum of a multiset of elements of an `add_submonoid` of an `add_comm_monoid` is an element of the `add_submonoid`. "] lemma multiset_prod_mem {M} [comm_monoid M] {s : set M} (hs : is_submonoid s) (m : multiset M) : (∀a∈m, a ∈ s) → m.prod ∈ s := begin refine quotient.induction_on m (assume l hl, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod], exact list_prod_mem hs hl end /-- The product of elements of a submonoid of a `comm_monoid` indexed by a `finset` is an element of the submonoid. -/ @[to_additive "The sum of elements of an `add_submonoid` of an `add_comm_monoid` indexed by a `finset` is an element of the `add_submonoid`."] lemma finset_prod_mem {M A} [comm_monoid M] {s : set M} (hs : is_submonoid s) (f : A → M) : ∀(t : finset A), (∀b∈t, f b ∈ s) → ∏ b in t, f b ∈ s | ⟨m, hm⟩ _ := multiset_prod_mem hs _ (by simpa) end is_submonoid namespace add_monoid /-- The inductively defined membership predicate for the submonoid generated by a subset of a monoid. -/ inductive in_closure (s : set A) : A → Prop | basic {a : A} : a ∈ s → in_closure a | zero : in_closure 0 | add {a b : A} : in_closure a → in_closure b → in_closure (a + b) end add_monoid namespace monoid /-- The inductively defined membership predicate for the `submonoid` generated by a subset of an monoid. -/ @[to_additive] inductive in_closure (s : set M) : M → Prop | basic {a : M} : a ∈ s → in_closure a | one : in_closure 1 | mul {a b : M} : in_closure a → in_closure b → in_closure (a * b) /-- The inductively defined submonoid generated by a subset of a monoid. -/ @[to_additive "The inductively defined `add_submonoid` genrated by a subset of an `add_monoid`."] def closure (s : set M) : set M := {a | in_closure s a } @[to_additive] lemma closure.is_submonoid (s : set M) : is_submonoid (closure s) := { one_mem := in_closure.one, mul_mem := assume a b, in_closure.mul } /-- A subset of a monoid is contained in the submonoid it generates. -/ @[to_additive "A subset of an `add_monoid` is contained in the `add_submonoid` it generates."] theorem subset_closure {s : set M} : s ⊆ closure s := assume a, in_closure.basic /-- The submonoid generated by a set is contained in any submonoid that contains the set. -/ @[to_additive "The `add_submonoid` generated by a set is contained in any `add_submonoid` that contains the set."] theorem closure_subset {s t : set M} (ht : is_submonoid t) (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, is_submonoid.one_mem, is_submonoid.mul_mem] /-- Given subsets `t` and `s` of a monoid `M`, if `s ⊆ t`, the submonoid of `M` generated by `s` is contained in the submonoid generated by `t`. -/ @[to_additive "Given subsets `t` and `s` of an `add_monoid M`, if `s ⊆ t`, the `add_submonoid` of `M` generated by `s` is contained in the `add_submonoid` generated by `t`."] theorem closure_mono {s t : set M} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset (closure.is_submonoid t) $ set.subset.trans h subset_closure /-- The submonoid generated by an element of a monoid equals the set of natural number powers of the element. -/ @[to_additive "The `add_submonoid` generated by an element of an `add_monoid` equals the set of natural number multiples of the element."] theorem closure_singleton {x : M} : closure ({x} : set M) = powers x := set.eq_of_subset_of_subset (closure_subset (powers.is_submonoid x) $ set.singleton_subset_iff.2 $ powers.self_mem) $ is_submonoid.power_subset (closure.is_submonoid _) $ set.singleton_subset_iff.1 $ subset_closure /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set under the monoid hom. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set under the `add_monoid` hom."] lemma image_closure {A : Type*} [monoid A] {f : M → A} (hf : is_monoid_hom f) (s : set M) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [hf.map_one], apply is_submonoid.one_mem (closure.is_submonoid (f '' s))}, { rw [hf.map_mul], solve_by_elim [(closure.is_submonoid _).mul_mem] } end (closure_subset (is_submonoid.image hf (closure.is_submonoid _)) $ set.image_subset _ subset_closure) /-- Given an element `a` of the submonoid of a monoid `M` generated by a set `s`, there exists a list of elements of `s` whose product is `a`. -/ @[to_additive "Given an element `a` of the `add_submonoid` of an `add_monoid M` generated by a set `s`, there exists a list of elements of `s` whose sum is `a`."] theorem exists_list_of_mem_closure {s : set M} {a : M} (h : a ∈ closure s) : (∃l:list M, (∀x∈l, x ∈ s) ∧ l.prod = a) := begin induction h, case in_closure.basic : a ha { existsi ([a]), simp [ha] }, case in_closure.one { existsi ([]), simp }, case in_closure.mul : a b _ _ ha hb { rcases ha with ⟨la, ha, eqa⟩, rcases hb with ⟨lb, hb, eqb⟩, existsi (la ++ lb), simp [eqa.symm, eqb.symm, or_imp_distrib], exact assume a, ⟨ha a, hb a⟩ } end /-- Given sets `s, t` of a commutative monoid `M`, `x ∈ M` is in the submonoid of `M` generated by `s ∪ t` iff there exists an element of the submonoid generated by `s` and an element of the submonoid generated by `t` whose product is `x`. -/ @[to_additive "Given sets `s, t` of a commutative `add_monoid M`, `x ∈ M` is in the `add_submonoid` of `M` generated by `s ∪ t` iff there exists an element of the `add_submonoid` generated by `s` and an element of the `add_submonoid` generated by `t` whose sum is `x`."] theorem mem_closure_union_iff {M : Type*} [comm_monoid M] {s t : set M} {x : M} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := ⟨λ hx, let ⟨L, HL1, HL2⟩ := exists_list_of_mem_closure hx in HL2 ▸ list.rec_on L (λ _, ⟨1, (closure.is_submonoid _).one_mem, 1, (closure.is_submonoid _).one_mem, mul_one _⟩) (λ hd tl ih HL1, let ⟨y, hy, z, hz, hyzx⟩ := ih (list.forall_mem_of_forall_mem_cons HL1) in or.cases_on (HL1 hd $ list.mem_cons_self _ _) (λ hs, ⟨hd * y, (closure.is_submonoid _).mul_mem (subset_closure hs) hy, z, hz, by rw [mul_assoc, list.prod_cons, ← hyzx]; refl⟩) (λ ht, ⟨y, hy, z * hd, (closure.is_submonoid _).mul_mem hz (subset_closure ht), by rw [← mul_assoc, list.prod_cons, ← hyzx, mul_comm hd]; refl⟩)) HL1, λ ⟨y, hy, z, hz, hyzx⟩, hyzx ▸ (closure.is_submonoid _).mul_mem (closure_mono (set.subset_union_left _ _) hy) (closure_mono (set.subset_union_right _ _) hz)⟩ end monoid /-- Create a bundled submonoid from a set `s` and `[is_submonoid s]`. -/ @[to_additive "Create a bundled additive submonoid from a set `s` and `[is_add_submonoid s]`."] def submonoid.of {s : set M} (h : is_submonoid s) : submonoid M := ⟨s, h.1, h.2⟩ @[to_additive] lemma submonoid.is_submonoid (S : submonoid M) : is_submonoid (S : set M) := ⟨S.2, S.3⟩
8f76cd43a45f716379c0909c1a99d2536dbb50c6
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/bench/rbmap3.lean
2965f983f5eda7ed2b0eb96f4e563f4b2e4f9783
[ "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
9,012
lean
prelude import init.core init.system.io init.data.ordering universes u v w inductive Rbcolor | red | black inductive Rbnode (α : Type u) (β : α → Type v) | leaf {} : Rbnode | Node (c : Rbcolor) (lchild : Rbnode) (key : α) (val : β key) (rchild : Rbnode) : Rbnode instance Rbcolor.DecidableEq : DecidableEq Rbcolor := {decEq := fun a b => Rbcolor.casesOn a (Rbcolor.casesOn b (isTrue rfl) (isFalse (fun h => Rbcolor.noConfusion h))) (Rbcolor.casesOn b (isFalse (fun h => Rbcolor.noConfusion h)) (isTrue rfl))} namespace Rbnode variables {α : Type u} {β : α → Type v} {σ : Type w} open Rbcolor def depth (f : Nat → Nat → Nat) : Rbnode α β → Nat | leaf => 0 | Node _ l _ _ r => (f (depth l) (depth r)) + 1 protected def min : Rbnode α β → Option (Sigma (fun k => β k)) | leaf => none | Node _ leaf k v _ => some ⟨k, v⟩ | Node _ l k v _ => min l protected def max : Rbnode α β → Option (Sigma (fun k => β k)) | leaf => none | Node _ _ k v leaf => some ⟨k, v⟩ | Node _ _ k v r => max r @[specialize] def fold (f : ∀ (k : α), β k → σ → σ) : Rbnode α β → σ → σ | leaf, b => b | Node _ l k v r, b => fold r (f k v (fold l b)) @[specialize] def revFold (f : ∀ (k : α), β k → σ → σ) : Rbnode α β → σ → σ | leaf, b => b | Node _ l k v r, b => revFold l (f k v (revFold r b)) @[specialize] def all (p : ∀ (k : α), β k → Bool) : Rbnode α β → Bool | leaf => true | Node _ l k v r => p k v && all l && all r @[specialize] def any (p : ∀ (k : α), β k → Bool) : Rbnode α β → Bool | leaf => false | Node _ l k v r => p k v || any l || any r def isRed : Rbnode α β → Bool | Node red _ _ _ _ => true | _ => false def rotateLeft : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node hc hl hk hv (Node red xl xk xv xr)), _ => if !isRed hl then (Node hc (Node red hl hk hv xl) xk xv xr) else n | leaf, h => absurd rfl h | e, _ => e theorem ifNodeNodeNeLeaf {c : Prop} [Decidable c] {l1 l2 : Rbnode α β} {c1 k1 v1 r1 c2 k2 v2 r2} : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) ≠ leaf := fun h => if hc : c then have h1 : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) = Node c1 l1 k1 v1 r1 from ifPos hc; Rbnode.noConfusion (Eq.trans h1.symm h) else have h1 : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) = Node c2 l2 k2 v2 r2 from ifNeg hc; Rbnode.noConfusion (Eq.trans h1.symm h) theorem rotateLeftNeLeaf : ∀ (n : Rbnode α β) (h : n ≠ leaf), rotateLeft n h ≠ leaf | Node _ hl _ _ (Node red _ _ _ _), _, h => ifNodeNodeNeLeaf h | leaf, h, _ => absurd rfl h | Node _ _ _ _ (Node black _ _ _ _), _, h => Rbnode.noConfusion h def rotateRight : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node hc (Node red xl xk xv xr) hk hv hr), _ => if isRed xl then (Node hc xl xk xv (Node red xr hk hv hr)) else n | leaf, h => absurd rfl h | e, _ => e theorem rotateRightNeLeaf : ∀ (n : Rbnode α β) (h : n ≠ leaf), rotateRight n h ≠ leaf | Node _ (Node red _ _ _ _) _ _ _, _, h => ifNodeNodeNeLeaf h | leaf, h, _ => absurd rfl h | Node _ (Node black _ _ _ _) _ _ _, _, h => Rbnode.noConfusion h def flip : Rbcolor → Rbcolor | red => black | black => red def flipColor : Rbnode α β → Rbnode α β | Node c l k v r => Node (flip c) l k v r | leaf => leaf def flipColors : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node c l k v r), _ => if isRed l ∧ isRed r then Node (flip c) (flipColor l) k v (flipColor r) else n | leaf, h => absurd rfl h def fixup (n : Rbnode α β) (h : n ≠ leaf) : Rbnode α β := let n₁ := rotateLeft n h; let h₁ := (rotateLeftNeLeaf n h); let n₂ := rotateRight n₁ h₁; let h₂ := (rotateRightNeLeaf n₁ h₁); flipColors n₂ h₂ def setBlack : Rbnode α β → Rbnode α β | Node red l k v r => Node black l k v r | n => n section insert variables (lt : α → α → Prop) [DecidableRel lt] def ins (x : α) (vx : β x) : Rbnode α β → Rbnode α β | leaf => Node red leaf x vx leaf | Node c l k v r => if lt x k then fixup (Node c (ins l) k v r) (fun h => Rbnode.noConfusion h) else if lt k x then fixup (Node c l k v (ins r)) (fun h => Rbnode.noConfusion h) else Node c l x vx r def insert (t : Rbnode α β) (k : α) (v : β k) : Rbnode α β := setBlack (ins lt k v t) end insert section membership variable (lt : α → α → Prop) variable [DecidableRel lt] def findCore : Rbnode α β → ∀ (k : α), Option (Sigma (fun k => β k)) | leaf, x => none | Node _ a ky vy b, x => (match cmpUsing lt x ky with | Ordering.lt => findCore a x | Ordering.Eq => some ⟨ky, vy⟩ | Ordering.gt => findCore b x) def find {β : Type v} : Rbnode α (fun _ => β) → α → Option β | leaf, x => none | Node _ a ky vy b, x => (match cmpUsing lt x ky with | Ordering.lt => find a x | Ordering.Eq => some vy | Ordering.gt => find b x) def lowerBound : Rbnode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, x, lb => lb | Node _ a ky vy b, x, lb => (match cmpUsing lt x ky with | Ordering.lt => lowerBound a x lb | Ordering.Eq => some ⟨ky, vy⟩ | Ordering.gt => lowerBound b x (some ⟨ky, vy⟩)) end membership inductive WellFormed (lt : α → α → Prop) : Rbnode α β → Prop | leafWff : WellFormed leaf | insertWff {n n' : Rbnode α β} {k : α} {v : β k} [DecidableRel lt] : WellFormed n → n' = insert lt n k v → WellFormed n' end Rbnode open Rbnode /- TODO(Leo): define dRbmap -/ def Rbmap (α : Type u) (β : Type v) (lt : α → α → Prop) : Type (max u v) := {t : Rbnode α (fun _ => β) // t.WellFormed lt } @[inline] def mkRbmap (α : Type u) (β : Type v) (lt : α → α → Prop) : Rbmap α β lt := ⟨leaf, WellFormed.leafWff lt⟩ namespace Rbmap variables {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Prop} def depth (f : Nat → Nat → Nat) (t : Rbmap α β lt) : Nat := t.val.depth f @[inline] def fold (f : α → β → σ → σ) : Rbmap α β lt → σ → σ | ⟨t, _⟩, b => t.fold f b @[inline] def revFold (f : α → β → σ → σ) : Rbmap α β lt → σ → σ | ⟨t, _⟩, b => t.revFold f b @[inline] def empty : Rbmap α β lt → Bool | ⟨leaf, _⟩ => true | _ => false @[specialize] def toList : Rbmap α β lt → List (α × β) | ⟨t, _⟩ => t.revFold (fun k v ps => (k, v)::ps) [] @[inline] protected def min : Rbmap α β lt → Option (α × β) | ⟨t, _⟩ => match t.min with | some ⟨k, v⟩ => some (k, v) | none => none @[inline] protected def max : Rbmap α β lt → Option (α × β) | ⟨t, _⟩ => match t.max with | some ⟨k, v⟩ => some (k, v) | none => none instance [HasRepr α] [HasRepr β] : HasRepr (Rbmap α β lt) := ⟨fun t => "rbmapOf " ++ repr t.toList⟩ variables [DecidableRel lt] def insert : Rbmap α β lt → α → β → Rbmap α β lt | ⟨t, w⟩, k, v => ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩ @[specialize] def ofList : List (α × β) → Rbmap α β lt | [] => mkRbmap _ _ _ | ⟨k,v⟩::xs => (ofList xs).insert k v def findCore : Rbmap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.findCore lt x def find : Rbmap α β lt → α → Option β | ⟨t, _⟩, x => t.find lt x /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ def lowerBound : Rbmap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.lowerBound lt x none @[inline] def contains (t : Rbmap α β lt) (a : α) : Bool := (t.find a).isSome def fromList (l : List (α × β)) (lt : α → α → Prop) [DecidableRel lt] : Rbmap α β lt := l.foldl (fun r p => r.insert p.1 p.2) (mkRbmap α β lt) @[inline] def all : Rbmap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.all p @[inline] def any : Rbmap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.any p end Rbmap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Prop) [DecidableRel lt] : Rbmap α β lt := Rbmap.fromList l lt /- Test -/ @[reducible] def map : Type := Rbmap Nat Bool HasLess.Less def mkMapAux : Nat → map → map | 0, m => m | n+1, m => mkMapAux n (m.insert n (n % 10 = 0)) def mkMap (n : Nat) := mkMapAux n (mkRbmap Nat Bool HasLess.Less) def main (xs : List String) : IO UInt32 := let m := mkMap xs.head.toNat; let v := Rbmap.fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0; IO.println (toString v) *> pure 0
b2136e76004195d4ae08b6183e1e0980643be15a
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/even_odd.lean
b95672dfe512f85baafcf5a28149d1718435d351
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
383
lean
mutual def even, odd with even : nat → bool | 0 := tt | (a+1) := odd a with odd : nat → bool | 0 := ff | (a+1) := even a example (a : nat) : even (a + 1) = odd a := by simp [even] example (a : nat) : odd (a + 1) = even a := by simp [odd] lemma even_eq_not_odd : ∀ a, even a = bnot (odd a) := begin intro a, induction a, simp [even, odd], simph [even, odd] end
bc7f10887a480135ead4b7d2a60697f922ee2459
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/pp.lean
e40742d9b0b3eb9f72f4f6d2c66073cd73fa512f
[ "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
445
lean
prelude set_option pp.beta false check λ {A : Type.{1}} (B : Type.{1}) (a : A) (b : B), a check λ {A : Type.{1}} {B : Type.{1}} (a : A) (b : B), a check λ (A : Type.{1}) {B : Type.{1}} (a : A) (b : B), a check λ (A : Type.{1}) (B : Type.{1}) (a : A) (b : B), a check λ [A : Type.{1}] (B : Type.{1}) (a : A) (b : B), a check λ {{A : Type.{1}}} {B : Type.{1}} (a : A) (b : B), a check λ {{A : Type.{1}}} {{B : Type.{1}}} (a : A) (b : B), a
ee79025cc618735679d84f90c14fc3c573647bc8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/free_monoid.lean
bbc42c9d149a63b7c2f11e32a9294654e2359d59
[ "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
4,854
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Yury Kudryashov -/ import algebra.star.basic /-! # Free monoid over a given alphabet ## Main definitions * `free_monoid α`: free monoid over alphabet `α`; defined as a synonym for `list α` with multiplication given by `(++)`. * `free_monoid.of`: embedding `α → free_monoid α` sending each element `x` to `[x]`; * `free_monoid.lift`: natural equivalence between `α → M` and `free_monoid α →* M` * `free_monoid.map`: embedding of `α → β` into `free_monoid α →* free_monoid β` given by `list.map`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {M : Type*} [monoid M] {N : Type*} [monoid N] /-- Free monoid over a given alphabet. -/ @[to_additive "Free nonabelian additive monoid over a given alphabet"] def free_monoid (α) := list α namespace free_monoid @[to_additive] instance : monoid (free_monoid α) := { one := [], mul := λ x y, (x ++ y : list α), mul_one := by intros; apply list.append_nil, one_mul := by intros; refl, mul_assoc := by intros; apply list.append_assoc } @[to_additive] instance : inhabited (free_monoid α) := ⟨1⟩ @[to_additive] lemma one_def : (1 : free_monoid α) = [] := rfl @[to_additive] lemma mul_def (xs ys : list α) : (xs * ys : free_monoid α) = (xs ++ ys : list α) := rfl /-- Embeds an element of `α` into `free_monoid α` as a singleton list. -/ @[to_additive "Embeds an element of `α` into `free_add_monoid α` as a singleton list." ] def of (x : α) : free_monoid α := [x] @[to_additive] lemma of_def (x : α) : of x = [x] := rfl @[to_additive] lemma of_injective : function.injective (@of α) := λ a b, list.head_eq_of_cons_eq /-- Recursor for `free_monoid` using `1` and `of x * xs` instead of `[]` and `x :: xs`. -/ @[elab_as_eliminator, to_additive "Recursor for `free_add_monoid` using `0` and `of x + xs` instead of `[]` and `x :: xs`."] def rec_on {C : free_monoid α → Sort*} (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : C xs := list.rec_on xs h0 ih @[ext, to_additive] lemma hom_eq ⦃f g : free_monoid α →* M⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := monoid_hom.ext $ λ l, rec_on l (f.map_one.trans g.map_one.symm) $ λ x xs hxs, by simp only [h, hxs, monoid_hom.map_mul] /-- Equivalence between maps `α → M` and monoid homomorphisms `free_monoid α →* M`. -/ @[to_additive "Equivalence between maps `α → A` and additive monoid homomorphisms `free_add_monoid α →+ A`."] def lift : (α → M) ≃ (free_monoid α →* M) := { to_fun := λ f, ⟨λ l, (l.map f).prod, rfl, λ l₁ l₂, by simp only [mul_def, list.map_append, list.prod_append]⟩, inv_fun := λ f x, f (of x), left_inv := λ f, funext $ λ x, one_mul (f x), right_inv := λ f, hom_eq $ λ x, one_mul (f (of x)) } @[simp, to_additive] lemma lift_symm_apply (f : free_monoid α →* M) : lift.symm f = f ∘ of := rfl @[to_additive] lemma lift_apply (f : α → M) (l : free_monoid α) : lift f l = (l.map f).prod := rfl @[to_additive] lemma lift_comp_of (f : α → M) : (lift f) ∘ of = f := lift.symm_apply_apply f @[simp, to_additive] lemma lift_eval_of (f : α → M) (x : α) : lift f (of x) = f x := congr_fun (lift_comp_of f) x @[simp, to_additive] lemma lift_restrict (f : free_monoid α →* M) : lift (f ∘ of) = f := lift.apply_symm_apply f @[to_additive] lemma comp_lift (g : M →* N) (f : α → M) : g.comp (lift f) = lift (g ∘ f) := by { ext, simp } @[to_additive] lemma hom_map_lift (g : M →* N) (f : α → M) (x : free_monoid α) : g (lift f x) = lift (g ∘ f) x := monoid_hom.ext_iff.1 (comp_lift g f) x /-- The unique monoid homomorphism `free_monoid α →* free_monoid β` that sends each `of x` to `of (f x)`. -/ @[to_additive "The unique additive monoid homomorphism `free_add_monoid α →+ free_add_monoid β` that sends each `of x` to `of (f x)`."] def map (f : α → β) : free_monoid α →* free_monoid β := { to_fun := list.map f, map_one' := rfl, map_mul' := λ l₁ l₂, list.map_append _ _ _ } @[simp, to_additive] lemma map_of (f : α → β) (x : α) : map f (of x) = of (f x) := rfl @[to_additive] lemma lift_of_comp_eq_map (f : α → β) : lift (λ x, of (f x)) = map f := hom_eq $ λ x, rfl @[to_additive] lemma map_comp (g : β → γ) (f : α → β) : map (g ∘ f) = (map g).comp (map f) := hom_eq $ λ x, rfl instance : star_monoid (free_monoid α) := { star := list.reverse, star_involutive := list.reverse_reverse, star_mul := list.reverse_append, } @[simp] lemma star_of (x : α) : star (of x) = of x := rfl /-- Note that `star_one` is already a global simp lemma, but this one works with dsimp too -/ @[simp] lemma star_one : star (1 : free_monoid α) = 1 := rfl end free_monoid
2135183d3d46ddb0b05a13c567973709f4dba404
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/sheaves/of_types.lean
21b5b0762cd8022ee4d8f745f19210a8f1707ac0
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
2,318
lean
import category_theory.sheaves import category_theory.universal.continuous import category_theory.functor.isomorphism universes u v open category_theory open category_theory.limits open category_theory.examples -- We now provide an alternative 'pointwise' constructor for sheaves of types. -- This should eventually be generalised to sheaves of categories with a -- fibre functor with reflects iso and preserves limits. section variables {X : Top.{v}} structure compatible_sections (cover : cover' X) (F : presheaf (open_set X) (Type u)) := (sections : Π i : cover.I, F.obj (cover.U i)) (compatibility : Π i j : cover.I, res_left i j F (sections i) = res_right i j F (sections j)) structure gluing {cover : cover' X} {F : presheaf (open_set X) (Type u)} (s : compatible_sections cover F) := («section» : F.obj cover.union) (restrictions : ∀ i : cover.I, (F.map (cover.union_subset i)) «section» = s.sections i) (uniqueness : ∀ (Γ : F.obj cover.union) (w : ∀ i : cover.I, (F.map (cover.union_subset i)) Γ = s.sections i), Γ = «section») definition sheaf.of_types (presheaf : presheaf (open_set X) (Type v)) (sheaf_condition : Π (cover : cover' X) (s : compatible_sections cover presheaf), gluing s) : sheaf.{v+1 v} X (Type v) := { presheaf := presheaf, sheaf_condition := ⟨ λ c, let σ : Π s : fork (left c presheaf) (right c presheaf), s.X → compatible_sections c presheaf := λ s x, { sections := λ i, select_section c presheaf i (s.ι x), compatibility := λ i j, congr_fun (congr_fun s.w x) (i,j), } in { lift := λ s x, (sheaf_condition c (σ s x)).«section», fac := λ s, funext $ λ x, funext $ λ i, (sheaf_condition c (σ s x)).restrictions i, uniq := λ s m w, funext $ λ x, (sheaf_condition c (σ s x)).uniqueness (m x) (λ i, congr_fun (congr_fun w x) i), } ⟩ } end section variables {X : Top.{u}} variables {V : Type (u+1)} [𝒱 : large_category V] [has_products.{u+1 u} V] (ℱ : V ⥤ (Type u)) [faithful ℱ] [category_theory.continuous ℱ] [reflects_isos ℱ] include 𝒱 -- This is a good project! def sheaf.of_sheaf_of_types (presheaf : presheaf (open_set X) V) (underlying_is_sheaf : is_sheaf (presheaf ⋙ ℱ)) : is_sheaf presheaf := sorry end
b8df4ab8f058c97f7560ceb01cc1efe91b048d65
618003631150032a5676f229d13a079ac875ff77
/src/data/holor.lean
150dfd2ade0bd3f443651405542976cdec646cd2
[ "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
14,284
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import algebra.pi_instances /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ universes u open list /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimensions `ds` -/ def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds} namespace holor_index variables {ds₁ ds₂ ds₃ : list ℕ} def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩ def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂ | ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩ lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm) lemma take_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left]) lemma drop_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds:list ℕ) := holor_index ds → α namespace holor variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ} instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩ instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩ instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩ instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩ instance [add_semigroup α] : add_semigroup (holor α ds) := by pi_instance instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by pi_instance instance [add_monoid α] : add_monoid (holor α ds) := by pi_instance instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by pi_instance instance [add_group α] : add_group (holor α ds) := by pi_instance instance [add_comm_group α] : add_comm_group (holor α ds) := by pi_instance /- scalar product -/ instance [has_mul α] : has_scalar α (holor α ds) := ⟨λ a x, λ t, a * x t⟩ instance [semiring α] : semimodule α (holor α ds) := pi.semimodule _ _ _ /-- The tensor product of two holors. -/ def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := λ t, x (t.take) * y (t.drop) local infix ` ⊗ ` : 70 := mul lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm) lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left := funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext (λt, right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))) @[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) : (0 : holor α ds₁) ⊗ x = 0 := funext (λ t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) : x ⊗ (0 :holor α ds₂) = 0 := funext (λ t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) : x ⊗ y = x ⟨[], forall₂.nil⟩ • y := by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := (λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩) /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := λ ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) : Π (t : holor_index (d :: ds)), (∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t | ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨(i :: is), hforall₂⟩ hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis, have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forall₂_cons.1 hiisdds).1, have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 := funext $ λ t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)]) lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) : slice (0 : holor α (d :: ds)) i hid = 0 := funext (λ t, by simp [slice]; refl) lemma slice_sum [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : finset.sum s (λ x, slice (f x) i hid) = slice (finset.sum s f) i hid := begin letI := classical.dec_eq β, refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) : (finset.range d).attach.sum (λ i, unit_vec d i.1 ⊗ slice x i.1 (nat.succ_le_of_lt (finset.mem_range.1 i.2))) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i _), { simp, refl }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩), have hbi' : i ≠ b.val, { apply not.imp hbi, { assume h0 : i = b.val, apply subtype.eq, simp only [h0] }, { exact finset.mem_range.2 hid } }, simp [hbi']}, { assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop | nil (x : holor α []) : cprank_max1 x | cons {d} {ds} (x : holor α [d]) (y : holor α ds) : cprank_max1 y → cprank_max1 (x ⊗ y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop | zero {ds} : cprank_max 0 (0 : holor α ds) | succ n {ds} (x : holor α ds) (y : holor α ds) : cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid α] [add_monoid α]: ∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds}, cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hx₂ hy } end lemma cprank_max_mul [ring α] : ∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x y₂ hy₂ } end lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (finset.sum s f) := by letI := classical.dec_eq β; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x ∉ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (finset.sum s f), { apply ih, assume (x : β) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Π (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)), from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (finset.sum (finset.attach (finset.range d)) (λ (i : {x // x ∈ finset.range d}), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2))), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [ring α] (x : holor α ds) : nat := @nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod := λ ds (x : holor α ds), by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
ca9f481c2e604433b96c358ee46f980c3bc292ed
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/specialize1.lean
e2103598643f278d757f0cc11bb73f09de644d3c
[ "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
668
lean
example (x y z : Prop) (f : x → y → z) (xp : x) (yp : y) : z := by specialize f xp yp assumption example (B C : Prop) (f : forall (A : Prop), A → C) (x : B) : C := by specialize f _ x exact f example (B C : Prop) (f : forall {A : Prop}, A → C) (x : B) : C := by specialize f x exact f example (B C : Prop) (f : forall {A : Prop}, A → C) (x : B) : C := by specialize @f _ x exact f example (X : Type) [Add X] (f : forall {A : Type} [Add A], A → A → A) (x : X) : X := by specialize f x x assumption def ex (f : Nat → Nat → Nat) : Nat := by specialize f _ _ exact 10 exact 2 exact f example : ex (· - ·) = 8 := rfl
c50911b3b2c549918161f457947bb6b0b780c0b7
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/polyhedral_lattice/cosimplicial_extra.lean
037f85f0e0cc7d06ab8c3ff4f2d13abc435aecd9
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,714
lean
import polyhedral_lattice.cosimplicial import polyhedral_lattice.Hom open_locale nnreal namespace PolyhedralLattice open pseudo_normed_group polyhedral_lattice.conerve (L obj lift' lift'_w) variables (r' : ℝ≥0) (Λ : PolyhedralLattice) variables (M : ProFiltPseuNormGrpWithTinv r') (N : ℕ) [fact (0 < N)] variables (m : ℕ) (g₀ : Λ →+ M) variables (g : fin (m + 1) → (Λ.rescaled_power N →+ M)) variables (hg : ∀ i l, (g i) (Λ.diagonal_embedding N l) = g₀ l) lemma cosimplicial_lift_mk (l) : Λ.cosimplicial_lift N m g₀ g hg (quotient_add_group.mk l) = finsupp.lift_add_hom g l := begin dsimp only [cosimplicial_lift, lift'], have := quotient_add_group.lift_mk' (L (Λ.diagonal_embedding N) (m + 1)) (lift'_w (Λ.diagonal_embedding N) m g₀ g hg _) l, exact this, end lemma cosimplicial_lift_mem_filtration (c : ℝ≥0) (H : ∀ i, g i ∈ filtration ((Λ.rescaled_power N) →+ M) c) : cosimplicial_lift Λ N m g₀ g hg ∈ filtration (obj (Λ.diagonal_embedding N) (m + 1) →+ M) c := begin intros c' l' hl', rw [semi_normed_group.mem_filtration_iff] at hl', obtain ⟨l, rfl, hl⟩ := polyhedral_lattice.norm_lift _ l', erw cosimplicial_lift_mk, rw [finsupp.lift_add_hom_apply, finsupp.sum_fintype], swap, { intro, rw add_monoid_hom.map_zero }, simp only [← coe_nnnorm, nnreal.eq_iff] at hl, erw [finsupp.nnnorm_def, finsupp.sum_fintype] at hl, swap, { intro, rw nnnorm_zero }, rw ← hl at hl', replace hl' := mul_le_mul' (le_refl c) hl', rw [finset.mul_sum] at hl', apply filtration_mono hl', apply sum_mem_filtration, rintro i -, apply H, exact semi_normed_group.mem_filtration_nnnorm (l i), end end PolyhedralLattice
99ebd930f56c93c858633277adc69438e3cf797d
0c1546a496eccfb56620165cad015f88d56190c5
/library/tools/super/superposition.lean
5715aeabe4f1b40b9eb0a1205f0ae7f84ecc2381
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,946
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state .utils open tactic monad expr namespace super def position := list ℕ meta def get_rwr_positions : expr → list position | (app a b) := [[]] ++ do arg ← list.zip_with_index (get_app_args (app a b)), pos ← get_rwr_positions arg.1, [arg.2 :: pos] | (var _) := [] | e := [[]] meta def get_position : expr → position → expr | (app a b) (p::ps) := match list.nth (get_app_args (app a b)) p with | some arg := get_position arg ps | none := (app a b) end | e _ := e meta def replace_position (v : expr) : expr → position → expr | (app a b) (p::ps) := let args := get_app_args (app a b) in match args^.nth p with | some arg := app_of_list a^.get_app_fn $ args^.update_nth p $ replace_position arg ps | none := app a b end | e [] := v | e _ := e variable gt : expr → expr → bool variables (c1 c2 : clause) variables (ac1 ac2 : derived_clause) variables (i1 i2 : nat) variable pos : list ℕ variable ltr : bool variable lt_in_termorder : bool variable congr_ax : name lemma {u v w} sup_ltr (F : Sort u) (A : Sort v) (a1 a2) (f : A → Sort w) : (f a1 → F) → f a2 → a1 = a2 → F := take hnfa1 hfa2 heq, hnfa1 (@eq.rec A a2 f hfa2 a1 heq^.symm) lemma {u v w} sup_rtl (F : Sort u) (A : Sort v) (a1 a2) (f : A → Sort w) : (f a1 → F) → f a2 → a2 = a1 → F := take hnfa1 hfa2 heq, hnfa1 (@eq.rec A a2 f hfa2 a1 heq) meta def is_eq_dir (e : expr) (ltr : bool) : option (expr × expr) := match is_eq e with | some (lhs, rhs) := if ltr then some (lhs, rhs) else some (rhs, lhs) | none := none end meta def try_sup : tactic clause := do guard $ (c1^.get_lit i1)^.is_pos, qf1 ← c1^.open_metan c1^.num_quants, qf2 ← c2^.open_metan c2^.num_quants, (rwr_from, rwr_to) ← (is_eq_dir (qf1.1^.get_lit i1)^.formula ltr)^.to_monad, atom ← return (qf2.1^.get_lit i2)^.formula, eq_type ← infer_type rwr_from, atom_at_pos ← return $ get_position atom pos, atom_at_pos_type ← infer_type atom_at_pos, unify eq_type atom_at_pos_type, unify_core transparency.none rwr_from atom_at_pos, rwr_from' ← instantiate_mvars atom_at_pos, rwr_to' ← instantiate_mvars rwr_to, if lt_in_termorder then guard (gt rwr_from' rwr_to') else guard (¬gt rwr_to' rwr_from'), rwr_ctx_varn ← mk_fresh_name, abs_rwr_ctx ← return $ lam rwr_ctx_varn binder_info.default eq_type (if (qf2.1^.get_lit i2)^.is_neg then replace_position (mk_var 0) atom pos else imp (replace_position (mk_var 0) atom pos) c2^.local_false), lf_univ ← infer_univ c1^.local_false, univ ← infer_univ eq_type, atom_univ ← infer_univ atom, op1 ← qf1.1^.open_constn i1, op2 ← qf2.1^.open_constn c2^.num_lits, hi2 ← (op2.2^.nth i2)^.to_monad, new_atom ← whnf_core transparency.none $ app abs_rwr_ctx rwr_to', new_hi2 ← return $ local_const hi2^.local_uniq_name `H binder_info.default new_atom, new_fin_prf ← return $ app_of_list (const congr_ax [lf_univ, univ, atom_univ]) [c1^.local_false, eq_type, rwr_from, rwr_to, abs_rwr_ctx, (op2.1^.close_const hi2)^.proof, new_hi2], clause.meta_closure (qf1.2 ++ qf2.2) $ (op1.1^.inst new_fin_prf)^.close_constn (op1.2 ++ op2.2^.update_nth i2 new_hi2) meta def rwr_positions (c : clause) (i : nat) : list (list ℕ) := get_rwr_positions (c^.get_lit i)^.formula meta def try_add_sup : prover unit := (do c' ← try_sup gt ac1^.c ac2^.c i1 i2 pos ltr ff congr_ax, inf_score 2 [ac1^.sc, ac2^.sc] >>= mk_derived c' >>= add_inferred) <|> return () meta def superposition_back_inf : inference := take given, do active ← get_active, sequence' $ do given_i ← given^.selected, guard (given^.c^.get_lit given_i)^.is_pos, option.to_monad $ is_eq (given^.c^.get_lit given_i)^.formula, other ← rb_map.values active, guard $ ¬given^.sc^.in_sos ∨ ¬other^.sc^.in_sos, other_i ← other^.selected, pos ← rwr_positions other^.c other_i, -- FIXME(gabriel): ``sup_ltr fails to resolve at runtime [do try_add_sup gt given other given_i other_i pos tt ``super.sup_ltr, try_add_sup gt given other given_i other_i pos ff ``super.sup_rtl] meta def superposition_fwd_inf : inference := take given, do active ← get_active, sequence' $ do given_i ← given^.selected, other ← rb_map.values active, guard $ ¬given^.sc^.in_sos ∨ ¬other^.sc^.in_sos, other_i ← other^.selected, guard (other^.c^.get_lit other_i)^.is_pos, option.to_monad $ is_eq (other^.c^.get_lit other_i)^.formula, pos ← rwr_positions given^.c given_i, [do try_add_sup gt other given other_i given_i pos tt ``super.sup_ltr, try_add_sup gt other given other_i given_i pos ff ``super.sup_rtl] @[super.inf] meta def superposition_inf : inf_decl := inf_decl.mk 40 $ take given, do gt ← get_term_order, superposition_fwd_inf gt given, superposition_back_inf gt given end super
afe20dc6311ef327395a4c66ad1b8beef6971d57
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Util/Name.lean
a7c2f889f13210ffe81b08dd24d7e7f6d63f2d6e
[ "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,370
lean
/- Copyright (c) 2022 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lean.Data.NameMap import Lake.Util.Compare open Lean namespace Lake export Lean (Name NameMap) @[inline] def NameMap.empty : NameMap α := RBMap.empty instance : ForIn m (NameMap α) (Name × α) where forIn self init f := self.forIn init f /-! # Name Helpers -/ namespace Name open Lean.Name @[simp] protected theorem beq_false (m n : Name) : (m == n) = false ↔ ¬ (m = n) := by rw [← beq_iff_eq m n]; cases m == n <;> simp (config := { decide := true }) @[simp] theorem isPrefixOf_self {n : Name} : n.isPrefixOf n := by cases n <;> simp [isPrefixOf] @[simp] theorem isPrefixOf_append {n m : Name} : ¬ n.hasMacroScopes → ¬ m.hasMacroScopes → n.isPrefixOf (n ++ m) := by intro h1 h2 show n.isPrefixOf (n.append m) simp_all [Name.append] clear h2; induction m <;> simp [*, Name.appendCore, isPrefixOf] @[simp] theorem quickCmpAux_iff_eq : ∀ {n n'}, quickCmpAux n n' = .eq ↔ n = n' | .anonymous, n => by cases n <;> simp [quickCmpAux] | n, .anonymous => by cases n <;> simp [quickCmpAux] | .num .., .str .. => by simp [quickCmpAux] | .str .., .num .. => by simp [quickCmpAux] | .num p₁ n₁, .num p₂ n₂ => by simp only [quickCmpAux]; split <;> simp_all [quickCmpAux_iff_eq, show ∀ p, (p → False) ↔ ¬ p from fun _ => .rfl] | .str p₁ s₁, .str p₂ s₂ => by simp only [quickCmpAux]; split <;> simp_all [quickCmpAux_iff_eq, show ∀ p, (p → False) ↔ ¬ p from fun _ => .rfl] instance : LawfulCmpEq Name quickCmpAux where eq_of_cmp := quickCmpAux_iff_eq.mp cmp_rfl := quickCmpAux_iff_eq.mpr rfl theorem eq_of_quickCmp {n n' : Name} : n.quickCmp n' = .eq → n = n' := by unfold Name.quickCmp intro h_cmp; split at h_cmp next => exact eq_of_cmp h_cmp next => contradiction theorem quickCmp_rfl {n : Name} : n.quickCmp n = .eq := by unfold Name.quickCmp split <;> exact cmp_rfl instance : LawfulCmpEq Name Name.quickCmp where eq_of_cmp := eq_of_quickCmp cmp_rfl := quickCmp_rfl open Syntax def quoteFrom (ref : Syntax) : Name → Term | .anonymous => mkCIdentFrom ref ``anonymous | .str p s => mkApp (mkCIdentFrom ref ``mkStr) #[quoteFrom ref p, quote s] | .num p v => mkApp (mkCIdentFrom ref ``mkNum) #[quoteFrom ref p, quote v]
afca8470161cd5f14c7bbe076e48a5e9ac8da64d
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/propositional_logic/vec_lang.lean
2f961632978d61f00b1c18e7f472bdbd6b91f4b8
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
2,127
lean
import init.algebra.field import data.real namespace peirce universe u /- Typeclass: Vector space, uniquely identified by index, over a field, α, of dimension dim. -/ class vector_space (α : Type u) (dim : ℕ) (index : ℕ) : Type (u+1) := mk instance real_1_vector_space ℝ 1 0 #check vector_space structure scalar (α : Type u): Type u:= mk :: (value : α) inductive scalar_expr : Type | slit (s: scalar) | sadd : scalar_expr → scalar_expr → scalar_expr | sneg : scalar_expr → scalar_expr | smul : scalar_expr → scalar_expr → scalar_expr | sinv : scalar_expr → scalar_expr open scalar_expr notation s1 + s2 := sadd s1 s2 notation s1 * s2 := smul s1 s2 -- complete /- VECTOR -/ structure vector {α : Type u} {d : ℕ} {i : ℕ} (s : vector_space α d i) := mk structure vector_ident : Type := mk :: (index : ℕ) inductive vector_expr : Type | vlit (v : vector) | vvar (i : vector_ident) | vmul (a : scalar_expr) (e : vector_expr) | vadd (e1 e2 : vector_expr) open vector_expr notation v1 + v2 := vadd v1 v2 notation a * v := vmul a v /- PROGRAM -/ inductive vector_prog : Type | pass (i : vector_ident) (e : vector_expr) | pseq (p1 p2 : vector_prog) open vector_prog notation i = e := pass i e notation p1 ; p2 := pseq p1 p2 /- EXAMPLE -/ -- some scalars def s1 := scalar.mk 1 def s2 := scalar.mk 2 def s3 := scalar.mk 0 -- some scalar expressions def se1 := slit s1 def se2 := slit s2 def se3 := se1 + se2 def se4 := se1 * se2 -- some spaces def sp1 := space.mk 0 def sp2 := space.mk 1 -- some vectors def v1 := vector.mk sp1 def v2 := vector.mk sp2 def v3 := vector.mk sp2 -- some vector expressions def ve1 := vlit v1 def ve2 := vlit v2 def ve3 := ve1 + ve2 def ve4 := se1 * ve1 def ve5 := (se1 + se2) * ve1 def ve6 := se1 * (ve1 + ve2) -- some vector identifiers def i1 := vector_ident.mk 0 def i2 := vector_ident.mk 1 def i3 := vector_ident.mk 2 -- some vector computations def p1 := i1 = ve1 def p2 := i2 = ve2 def p3 := p1 ; p2 def p4 := i3 = ve5 ; p3 ; p2 end peirce structure identifier : Type := mk :: (index : ℕ)
7b2268583e68a0882718755d70a72632d7d56a2d
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/Tactic/Simp/Types.lean
ea9b2946704c173a6ce1a13003cc04152f48ddd4
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,172
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.AppBuilder import Lean.Meta.Tactic.Simp.SimpLemmas import Lean.Meta.Tactic.Simp.CongrLemmas namespace Lean.Meta namespace Simp structure Result where expr : Expr proof? : Option Expr := none -- If none, proof is assumed to be `refl` deriving Inhabited abbrev Cache := ExprMap Result structure Context where config : Config simpLemmas : SimpLemmas congrLemmas : CongrLemmas toUnfold : NameSet := {} parent? : Option Expr := none structure State where cache : Cache := {} numSteps : Nat := 0 abbrev SimpM := ReaderT Context $ StateRefT State MetaM inductive Step where | visit : Result → Step | done : Result → Step deriving Inhabited def Step.result : Step → Result | Step.visit r => r | Step.done r => r structure Methods where pre : Expr → SimpM Step := fun e => return Step.visit { expr := e } post : Expr → SimpM Step := fun e => return Step.done { expr := e } discharge? : Expr → SimpM (Option Expr) := fun e => return none deriving Inhabited /- Internal monad -/ abbrev M := ReaderT Methods SimpM def pre (e : Expr) : M Step := do (← read).pre e def post (e : Expr) : M Step := do (← read).post e def discharge? (e : Expr) : M (Option Expr) := do (← read).discharge? e def getConfig : M Config := return (← readThe Context).config @[inline] def withParent (parent : Expr) (f : M α) : M α := withTheReader Context (fun ctx => { ctx with parent? := parent }) f def getSimpLemmas : M SimpLemmas := return (← readThe Context).simpLemmas def getCongrLemmas : M CongrLemmas := return (← readThe Context).congrLemmas @[inline] def withSimpLemmas (s : SimpLemmas) (x : M α) : M α := do let cacheSaved := (← get).cache modify fun s => { s with cache := {} } try withTheReader Context (fun ctx => { ctx with simpLemmas := s }) x finally modify fun s => { s with cache := cacheSaved } end Simp export Simp (SimpM) end Lean.Meta
d28de1f0c206d91366ccfd0f39464bdff426574b
618003631150032a5676f229d13a079ac875ff77
/test/localized/localized.lean
ebaa342ce79ef2fbae6e99c3a30c2036cae6472c
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,419
lean
import tactic.localized open tactic local infix ` ⊹ `:59 := nat.mul local infix ` ↓ `:59 := nat.pow local infix ` ⊖ `:59 := nat.pow example : 2 ⊹ 3 = 6 := rfl example : 2 ↓ 3 = 8 := rfl example : 2 ⊖ 3 = 8 := rfl example {n m : ℕ} (h : n < m) : n ≤ m := by { success_if_fail { simp [h] }, exact le_of_lt h } section localized "infix ` ⊹ `:59 := nat.add" in nat localized "infix ` ↓ `:59 := nat.mul" in nat localized "infix ` ⊖ `:59 := nat.mul" in nat.mul localized "attribute [simp] le_of_lt" in le example : 2 ⊹ 3 = 5 := rfl example : 2 ↓ 3 = 6 := rfl example : 2 ⊖ 3 = 6 := rfl example {n m : ℕ} (h : n < m) : n ≤ m := by { simp [h] } end section example : 2 ⊹ 3 = 6 := rfl example : 2 ↓ 3 = 8 := rfl example : 2 ⊖ 3 = 8 := rfl example {n m : ℕ} (h : n < m) : n ≤ m := by { success_if_fail { simp [h] }, exact le_of_lt h } -- test that `open_locale` will fail when given a nonexistent locale run_cmd success_if_fail $ get_localized [`ceci_nest_pas_une_locale] open_locale nat example : 2 ⊹ 3 = 5 := rfl example : 2 ↓ 3 = 6 := rfl example : 2 ⊖ 3 = 8 := rfl open_locale nat.mul example : 2 ⊹ 3 = 5 := rfl example : 2 ↓ 3 = 6 := rfl example : 2 ⊖ 3 = 6 := rfl end section open_locale nat.mul nat nat.mul le example : 2 ⊹ 3 = 5 := rfl example : 2 ↓ 3 = 6 := rfl example : 2 ⊖ 3 = 6 := rfl example {n m : ℕ} (h : n < m) : n ≤ m := by { simp [h] } end
f0f08a47dc0a5346b4723897d7530b184f91816b
65b579fba1b0b66add04cccd4529add645eff597
/arith_DavidVanHorn/alang.lean
fc2f3fd8043f467400442cbd1d0b55687f17ddb6
[]
no_license
teodorov/sf_lean
ba637ca8ecc538aece4d02c8442d03ef713485db
cd4832d6bee9c606014c977951f6aebc4c8d611b
refs/heads/master
1,632,890,232,054
1,543,005,745,000
1,543,005,745,000
108,566,115
1
0
null
null
null
null
UTF-8
Lean
false
false
3,277
lean
-- https://www.youtube.com/watch?v=8upRv9wjHp0 inductive A | i : ℤ → A | pred : A → A | succ : A → A | plus : A → A → A | mult : A → A → A . open A instance : has_one A := ⟨ A.i 1 ⟩ instance : has_add A := ⟨ A.plus ⟩ -- Natural semantics -- Big-step == Binary relation ↓ ⊆ A × ℤ inductive natsem_A : A → ℤ → Prop | r1 : ∀ i : ℤ, natsem_A (A.i i) i | r2 : ∀ e i, natsem_A e i → natsem_A (pred e) (i - 1) | r3 : ∀ e i, natsem_A e i → natsem_A (succ e) (i + 1) | r4 : ∀ e₁ e₂ i j, (natsem_A e₁ i) → (natsem_A e₂ j) → natsem_A (plus e₁ e₂) (i + j) | r5 : ∀ e₁ e₂ i j, (natsem_A e₁ i) → (natsem_A e₂ j) → natsem_A (plus e₁ e₂) (i * j) notation a ` ⇓ ` b := natsem_A a b example : (plus 4 (succ 2)) ⇓ 7 := sorry --Evaluator semantics of A def eval : A → ℤ | (i x) := x | (pred e) := (eval e) - 1 | (succ e) := (eval e) + 1 | (plus e₁ e₂) := (eval e₁) + (eval e₂) | (mult e₁ e₂) := (eval e₁) * (eval e₂) #reduce eval (plus 4 (succ 2)) -- SOS semantics of A == Binary relation ⟶ ⊆ A × A inductive sossem_A : A → A → Prop --axioms | sos1 : ∀ i, sossem_A (pred (A.i i)) (A.i (i - 1)) -- i:ℤ | sos2 : ∀ i, sossem_A (succ (A.i i)) (A.i (i + 1)) | sos3 : ∀ i j, sossem_A (plus (A.i i) (A.i j)) (A.i (i + j)) | sos4 : ∀ i j, sossem_A (mult (A.i i) (A.i j)) (A.i (i * j)) --contexts -- these contexts are known are the compatible closure | sos05 : ∀ e₁ e₂, sossem_A e₁ e₂ → sossem_A (pred e₁) (pred e₂) | sos06 : ∀ e₁ e₂, sossem_A e₁ e₂ → sossem_A (succ e₁) (succ e₂) | sos07 : ∀ e₁ e₂ e₃, sossem_A e₁ e₂ → sossem_A (plus e₁ e₃) (plus e₂ e₃) | sos08 : ∀ e₁ e₂ e₃, sossem_A e₁ e₂ → sossem_A (plus e₃ e₁) (plus e₃ e₂) | sos09 : ∀ e₁ e₂ e₃, sossem_A e₁ e₂ → sossem_A (mult e₁ e₃) (mult e₂ e₃) | sos10 : ∀ e₁ e₂ e₃, sossem_A e₁ e₂ → sossem_A (mult e₃ e₁) (mult e₃ e₂) notation a ` ⟶ ` b := sossem_A a b inductive sos_closure : A → A → Prop | step : ∀ e₁ e₂, (e₁ ⟶ e₂) → sos_closure e₁ e₂ | reflexive : ∀ e, sos_closure e e | transitive : ∀ e₁ e₂ e₃, sos_closure e₁ e₂ → sos_closure e₂ e₃ → sos_closure e₁ e₃ notation a ` ⟶* ` b := sos_closure a b --I need something that extracts the value from A.i i in SOS lemma natural_imp_sos : ∀ e i, (e ⇓ i) → (e ⟶* (A.i i)) := sorry lemma sos_imp_natural : ∀ e i, (e ⟶* (A.i i)) → (e ⇓ i) := sorry theorem natural_equivalent_sos : ∀ e i, (e ⇓ i) ↔ (e ⟶* (A.i i)) := begin intros, split; apply natural_imp_sos <|> apply sos_imp_natural end -- Reduction semantics of A inductive axiom_redsem_A : A → A → Prop --axioms | red1 : ∀ i, axiom_redsem_A (pred (A.i i)) (A.i (i - 1)) -- i:ℤ | red2 : ∀ i, axiom_redsem_A (succ (A.i i)) (A.i (i + 1)) | red3 : ∀ i j, axiom_redsem_A (plus (A.i i) (A.i j)) (A.i (i + j)) | red4 : ∀ i j, axiom_redsem_A (mult (A.i i) (A.i j)) (A.i (i * j)) inductive ctx | hole | pred : ctx → ctx | succ : ctx → ctx | plus {e}: ctx → e → ctx | Plus {e}: e → ctx → ctx | mult {e}: ctx → e → ctx | Mult {e}: e → ctx → ctx
39a225dfd9705ead59f56a8498d3ab6320c518d8
a8c03ed21a1bd6fc45901943b79dd6574ea3f0c2
/misc_preprocessing.lean
c656d4eb271238ef92b40c98353b35955fe58619
[]
no_license
gebner/resolution.lean
716c355fbb5204e5c4d0c5a7f3f3cc825892a2bf
c6fafe06fba1cfad73db68f2aa474b29fe892a2b
refs/heads/master
1,601,111,444,528
1,475,256,701,000
1,475,256,701,000
67,711,151
0
0
null
null
null
null
UTF-8
Lean
false
false
914
lean
import clause prover_state open expr list monad meta def is_taut (c : clause) : tactic bool := do qf ← clause.open_constn c c↣num_quants, return $ list.bor (do l1 ← clause.get_lits qf.1, guard $ clause.literal.is_neg l1, l2 ← clause.get_lits qf.1, guard $ clause.literal.is_pos l2, [decidable.to_bool (clause.literal.formula l1 = clause.literal.formula l2)]) open tactic example (i : Type) (p : i → i → Type) (c : i) (h : ∀ (x : i), p x c → p x c) : true := by do h ← get_local `h, hcls ← clause.of_proof h, taut ← is_taut hcls, when (¬taut) failed, to_expr `(trivial) >>= apply meta def tautology_removal_pre : resolution_prover unit := preprocessing_rule $ λnew, filterM (λc, liftM bnot ↑(is_taut c)) new meta def remove_duplicates_pre : resolution_prover unit := preprocessing_rule $ λnew, return (rb_map.values (rb_map.of_list (list.map (λc:clause, (c↣type, c)) new)))
bca4f1b77c108cc868d233ca02159fe02f0dc022
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/DistributiveLattice.lean
51be96203fe5ee6970284c1b46a6f511aeb5686c
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
11,038
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section DistributiveLattice structure DistributiveLattice (A : Type) : Type := (times : (A → (A → A))) (plus : (A → (A → A))) (commutative_times : (∀ {x y : A} , (times x y) = (times y x))) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) (idempotent_times : (∀ {x : A} , (times x x) = x)) (commutative_plus : (∀ {x y : A} , (plus x y) = (plus y x))) (associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z)))) (idempotent_plus : (∀ {x : A} , (plus x x) = x)) (leftAbsorp_times_plus : (∀ {x y : A} , (times x (plus x y)) = x)) (leftAbsorp_plus_times : (∀ {x y : A} , (plus x (times x y)) = x)) (leftModular_times_plus : (∀ {x y z : A} , (plus (times x y) (times x z)) = (times x (plus y (times x z))))) (leftDistributive_times_plus : (∀ {x y z : A} , (times x (plus y z)) = (plus (times x y) (times x z)))) open DistributiveLattice structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (plusS : (AS → (AS → AS))) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (commutative_timesP : (∀ {xP yP : (Prod A A)} , (timesP xP yP) = (timesP yP xP))) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) (idempotent_timesP : (∀ {xP : (Prod A A)} , (timesP xP xP) = xP)) (commutative_plusP : (∀ {xP yP : (Prod A A)} , (plusP xP yP) = (plusP yP xP))) (associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP)))) (idempotent_plusP : (∀ {xP : (Prod A A)} , (plusP xP xP) = xP)) (leftAbsorp_times_plusP : (∀ {xP yP : (Prod A A)} , (timesP xP (plusP xP yP)) = xP)) (leftAbsorp_plus_timesP : (∀ {xP yP : (Prod A A)} , (plusP xP (timesP xP yP)) = xP)) (leftModular_times_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (timesP xP yP) (timesP xP zP)) = (timesP xP (plusP yP (timesP xP zP))))) (leftDistributive_times_plusP : (∀ {xP yP zP : (Prod A A)} , (timesP xP (plusP yP zP)) = (plusP (timesP xP yP) (timesP xP zP)))) structure Hom {A1 : Type} {A2 : Type} (Di1 : (DistributiveLattice A1)) (Di2 : (DistributiveLattice A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Di1) x1 x2)) = ((times Di2) (hom x1) (hom x2)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Di1) x1 x2)) = ((plus Di2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Di1 : (DistributiveLattice A1)) (Di2 : (DistributiveLattice A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Di1) x1 x2) ((times Di2) y1 y2)))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Di1) x1 x2) ((plus Di2) y1 y2)))))) inductive DistributiveLatticeTerm : Type | timesL : (DistributiveLatticeTerm → (DistributiveLatticeTerm → DistributiveLatticeTerm)) | plusL : (DistributiveLatticeTerm → (DistributiveLatticeTerm → DistributiveLatticeTerm)) open DistributiveLatticeTerm inductive ClDistributiveLatticeTerm (A : Type) : Type | sing : (A → ClDistributiveLatticeTerm) | timesCl : (ClDistributiveLatticeTerm → (ClDistributiveLatticeTerm → ClDistributiveLatticeTerm)) | plusCl : (ClDistributiveLatticeTerm → (ClDistributiveLatticeTerm → ClDistributiveLatticeTerm)) open ClDistributiveLatticeTerm inductive OpDistributiveLatticeTerm (n : ℕ) : Type | v : ((fin n) → OpDistributiveLatticeTerm) | timesOL : (OpDistributiveLatticeTerm → (OpDistributiveLatticeTerm → OpDistributiveLatticeTerm)) | plusOL : (OpDistributiveLatticeTerm → (OpDistributiveLatticeTerm → OpDistributiveLatticeTerm)) open OpDistributiveLatticeTerm inductive OpDistributiveLatticeTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpDistributiveLatticeTerm2) | sing2 : (A → OpDistributiveLatticeTerm2) | timesOL2 : (OpDistributiveLatticeTerm2 → (OpDistributiveLatticeTerm2 → OpDistributiveLatticeTerm2)) | plusOL2 : (OpDistributiveLatticeTerm2 → (OpDistributiveLatticeTerm2 → OpDistributiveLatticeTerm2)) open OpDistributiveLatticeTerm2 def simplifyCl {A : Type} : ((ClDistributiveLatticeTerm A) → (ClDistributiveLatticeTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpDistributiveLatticeTerm n) → (OpDistributiveLatticeTerm n)) | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpDistributiveLatticeTerm2 n A) → (OpDistributiveLatticeTerm2 n A)) | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((DistributiveLattice A) → (DistributiveLatticeTerm → A)) | Di (timesL x1 x2) := ((times Di) (evalB Di x1) (evalB Di x2)) | Di (plusL x1 x2) := ((plus Di) (evalB Di x1) (evalB Di x2)) def evalCl {A : Type} : ((DistributiveLattice A) → ((ClDistributiveLatticeTerm A) → A)) | Di (sing x1) := x1 | Di (timesCl x1 x2) := ((times Di) (evalCl Di x1) (evalCl Di x2)) | Di (plusCl x1 x2) := ((plus Di) (evalCl Di x1) (evalCl Di x2)) def evalOpB {A : Type} {n : ℕ} : ((DistributiveLattice A) → ((vector A n) → ((OpDistributiveLatticeTerm n) → A))) | Di vars (v x1) := (nth vars x1) | Di vars (timesOL x1 x2) := ((times Di) (evalOpB Di vars x1) (evalOpB Di vars x2)) | Di vars (plusOL x1 x2) := ((plus Di) (evalOpB Di vars x1) (evalOpB Di vars x2)) def evalOp {A : Type} {n : ℕ} : ((DistributiveLattice A) → ((vector A n) → ((OpDistributiveLatticeTerm2 n A) → A))) | Di vars (v2 x1) := (nth vars x1) | Di vars (sing2 x1) := x1 | Di vars (timesOL2 x1 x2) := ((times Di) (evalOp Di vars x1) (evalOp Di vars x2)) | Di vars (plusOL2 x1 x2) := ((plus Di) (evalOp Di vars x1) (evalOp Di vars x2)) def inductionB {P : (DistributiveLatticeTerm → Type)} : ((∀ (x1 x2 : DistributiveLatticeTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((∀ (x1 x2 : DistributiveLatticeTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : DistributiveLatticeTerm) , (P x)))) | ptimesl pplusl (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl pplusl x1) (inductionB ptimesl pplusl x2)) | ptimesl pplusl (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl pplusl x1) (inductionB ptimesl pplusl x2)) def inductionCl {A : Type} {P : ((ClDistributiveLatticeTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClDistributiveLatticeTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((∀ (x1 x2 : (ClDistributiveLatticeTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClDistributiveLatticeTerm A)) , (P x))))) | psing ptimescl ppluscl (sing x1) := (psing x1) | psing ptimescl ppluscl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl ppluscl x1) (inductionCl psing ptimescl ppluscl x2)) | psing ptimescl ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl ppluscl x1) (inductionCl psing ptimescl ppluscl x2)) def inductionOpB {n : ℕ} {P : ((OpDistributiveLatticeTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpDistributiveLatticeTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((∀ (x1 x2 : (OpDistributiveLatticeTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpDistributiveLatticeTerm n)) , (P x))))) | pv ptimesol pplusol (v x1) := (pv x1) | pv ptimesol pplusol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol pplusol x1) (inductionOpB pv ptimesol pplusol x2)) | pv ptimesol pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol pplusol x1) (inductionOpB pv ptimesol pplusol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpDistributiveLatticeTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpDistributiveLatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((∀ (x1 x2 : (OpDistributiveLatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpDistributiveLatticeTerm2 n A)) , (P x)))))) | pv2 psing2 ptimesol2 pplusol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 pplusol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 pplusol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 x2)) | pv2 psing2 ptimesol2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 pplusol2 x2)) def stageB : (DistributiveLatticeTerm → (Staged DistributiveLatticeTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClDistributiveLatticeTerm A) → (Staged (ClDistributiveLatticeTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpDistributiveLatticeTerm n) → (Staged (OpDistributiveLatticeTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpDistributiveLatticeTerm2 n A) → (Staged (OpDistributiveLatticeTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) end DistributiveLattice
4f10fda574b708e0b3d6bad55192dad57484bf08
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/list/perm.lean
5245463622f03aa49db8ed105769f93a08313972
[ "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
43,491
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.list.bag_inter import data.list.erase_dup import data.list.zip import logic.relation /-! # List permutations -/ namespace list universe variables uu vv variables {α : Type uu} {β : Type vv} /-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations of each other. This is defined by induction using pairwise swaps. -/ inductive perm : list α → list α → Prop | nil : perm [] [] | cons : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ open perm (swap) infix ~ := perm @[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l | [] := perm.nil | (x::xs) := (perm.refl xs).cons x @[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p perm.nil (λ x l₁ l₂ p₁ r₁, r₁.cons x) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₂.trans r₁) theorem perm_comm {l₁ l₂ : list α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨perm.symm, perm.symm⟩ theorem perm.swap' (x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ := (swap _ _ _).trans ((p.cons _).cons _) attribute [trans] perm.trans theorem perm.eqv (α) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) instance is_setoid (α) : setoid (list α) := setoid.mk (@perm α) (perm.eqv α) theorem perm.subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ := λ a, perm.rec_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim i (λ ax, by simp [ax]) (λ al₁, or.inr (r₁ al₁))) (λ x y l ayxl, or.elim ayxl (λ ay, by simp [ay]) (λ axl, or.elim axl (λ ax, by simp [ax]) (λ al, or.inr (or.inr al)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem perm.mem_iff {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ := iff.intro (λ m, h.subset m) (λ m, h.symm.subset m) theorem perm.append_right {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ := perm.rec_on p (perm.refl ([] ++ t₁)) (λ x l₁ l₂ p₁ r₁, r₁.cons x) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₁.trans r₂) theorem perm.append_left {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂ | [] p := p | (x::xs) p := (perm.append_left xs p).cons x theorem perm.append {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ := (p₁.append_right t₁).trans (p₂.append_left l₂) theorem perm.append_cons (a : α) {h₁ h₂ t₁ t₂ : list α} (p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ := p₁.append (p₂.cons a) @[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂) | [] l₂ := perm.refl _ | (b::l₁) l₂ := ((@perm_middle l₁ l₂).cons _).trans (swap a b _) @[simp] theorem perm_append_singleton (a : α) (l : list α) : l ++ [a] ~ a::l := perm_middle.trans $ by rw [append_nil] theorem perm_append_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁) | [] l₂ := by simp | (a::t) l₂ := (perm_append_comm.cons _).trans perm_middle.symm theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l := by simp theorem perm.length_eq {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ := perm.rec_on p rfl (λ x l₁ l₂ p r, by simp[r]) (λ x y l, by simp) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem perm.eq_nil {l : list α} (p : l ~ []) : l = [] := eq_nil_of_length_eq_zero p.length_eq theorem perm.nil_eq {l : list α} (p : [] ~ l) : [] = l := p.symm.eq_nil.symm theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] := ⟨λ p, p.eq_nil, λ e, e ▸ perm.refl _⟩ theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l | p := by injection p.symm.eq_nil @[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l | [] := perm.nil | (a::l) := by { rw reverse_cons, exact (perm_append_singleton _ _).trans ((reverse_perm l).cons a) } theorem perm_cons_append_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) := (p.cons a).trans perm_middle.symm @[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : l ~ repeat a n ↔ l = repeat a n := ⟨λ p, (eq_repeat.2 ⟨p.length_eq.trans $ length_repeat _ _, λ b m, eq_of_mem_repeat $ p.subset m⟩), λ h, h ▸ perm.refl _⟩ @[simp] theorem repeat_perm {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l := (perm_comm.trans perm_repeat).trans eq_comm @[simp] theorem perm_singleton {a : α} {l : list α} : l ~ [a] ↔ l = [a] := @perm_repeat α a 1 l @[simp] theorem singleton_perm {a : α} {l : list α} : [a] ~ l ↔ [a] = l := @repeat_perm α a 1 l theorem perm.eq_singleton {a : α} {l : list α} (p : l ~ [a]) : l = [a] := perm_singleton.1 p theorem perm.singleton_eq {a : α} {l : list α} (p : [a] ~ l) : [a] = l := p.symm.eq_singleton.symm theorem singleton_perm_singleton {a b : α} : [a] ~ [b] ↔ a = b := by simp theorem perm_cons_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : l ~ a :: l.erase a := let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in e₂.symm ▸ e₁.symm ▸ perm_middle @[elab_as_eliminator] theorem perm_induction_on {P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l, from assume l, list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ @[congr] theorem perm.filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : filter_map f l₁ ~ filter_map f l₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp only [filter_map], cases f x with a; simp [filter_map, IH, perm.cons] }, { simp only [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] }, { exact IH₁.trans IH₂ } end @[congr] theorem perm.map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : map f l₁ ~ map f l₂ := filter_map_eq_map f ▸ p.filter_map _ theorem perm.pmap {p : α → Prop} (f : Π a, p a → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp [IH, perm.cons] }, { simp [swap] }, { refine IH₁.trans IH₂, exact λ a m, H₂ a (p₂.subset m) } end theorem perm.filter (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ := by rw ← filter_map_eq_filter; apply s.filter_map _ theorem exists_perm_sublist {l₁ l₂ l₂' : list α} (s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s, { exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ }, { cases s with _ _ _ s l₁ _ _ s, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ }, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', p'.cons x, s'.cons2 _ _ _⟩ } }, { cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s, { exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ }, { exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ }, { exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ }, { exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } }, { exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in ⟨r₁, pr.trans pm, sr⟩ } end theorem perm.sizeof_eq_sizeof [has_sizeof α] {l₁ l₂ : list α} (h : l₁ ~ l₂) : l₁.sizeof = l₂.sizeof := begin induction h with hd l₁ l₂ h₁₂ h_sz₁₂ a b l l₁ l₂ l₃ h₁₂ h₂₃ h_sz₁₂ h_sz₂₃, { refl }, { simp only [list.sizeof, h_sz₁₂] }, { simp only [list.sizeof, add_left_comm] }, { simp only [h_sz₁₂, h_sz₂₃] } end section rel open relator variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} local infixr ` ∘r ` : 80 := relation.comp lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm := begin funext a c, apply propext, split, { exact assume ⟨b, hab, hba⟩, perm.trans hab hba }, { exact assume h, ⟨a, perm.refl a, h⟩ } end lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v := begin induction hlu generalizing v, case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ }, case perm.cons : a l u hlu ih { cases huv with _ b _ v hab huv', rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩, exact ⟨b::l₂, forall₂.cons hab h₁₂, h₂₃.cons _⟩ }, case perm.swap : a₁ a₂ l₁ l₂ h₂₃ { cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃, cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂, exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩ }, case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ { rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩, rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩, exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩ } end lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r := begin funext l₁ l₃, apply propext, split, { assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩, have : forall₂ (flip r) l₂ l₁, from h₁₂.flip , rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩, exact ⟨l', h₂.symm, h₁.flip⟩ }, { exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ } end lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm := assume a b h₁ c d h₂ h, have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩, have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d, by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this, let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in have b' = b, from right_unique_forall₂ @hr hcb hbc, this ▸ hbd lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm := assume a b hab c d hcd, iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp (assume a b c, left_unique_flip hr.1) hab.flip hcd.flip) end rel section subperm /-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects multiplicities of elements, and is used for the `≤` relation on multisets. -/ def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂ infix ` <+~ `:50 := subperm theorem nil_subperm {l : list α} : [] <+~ l := ⟨[], perm.nil, by simp⟩ theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ := suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂, from ⟨this p, this p.symm⟩, λ l₁ l₂ p ⟨u, pu, su⟩, let ⟨v, pv, sv⟩ := exists_perm_sublist su p in ⟨v, pv.trans pu, sv⟩ theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l := ⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩, λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩ theorem sublist.subperm {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ := ⟨l₁, perm.refl _, s⟩ theorem perm.subperm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ := ⟨l₂, p.symm, sublist.refl _⟩ @[refl] theorem subperm.refl (l : list α) : l <+~ l := (perm.refl _).subperm @[trans] theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃ | s ⟨l₂', p₂, s₂⟩ := let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩ theorem subperm.length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂ | ⟨l, p, s⟩ := p.length_eq ▸ length_le_of_sublist s theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂ | ⟨l, p, s⟩ h := suffices l = l₂, from this ▸ p.symm, eq_of_sublist_of_length_le s $ p.symm.length_eq ▸ h theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ := h₁.perm_of_length_le h₂.length_le theorem subperm.subset {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂ | ⟨l, p, s⟩ := subset.trans p.symm.subset s.subset end subperm theorem sublist.exists_perm_append : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l | ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩ | ._ ._ (sublist.cons l₁ l₂ a s) := let ⟨l, p⟩ := sublist.exists_perm_append s in ⟨a::l, (p.cons a).trans perm_middle.symm⟩ | ._ ._ (sublist.cons2 l₁ l₂ a s) := let ⟨l, p⟩ := sublist.exists_perm_append s in ⟨l, p.cons a⟩ theorem perm.countp_eq (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ := by rw [countp_eq_length_filter, countp_eq_length_filter]; exact (s.filter _).length_eq theorem subperm.countp_le (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂ | ⟨l, p', s⟩ := p'.countp_eq p ▸ countp_le_of_sublist s theorem perm.count_eq [decidable_eq α] {l₁ l₂ : list α} (p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ := p.countp_eq _ theorem subperm.count_le [decidable_eq α] {l₁ l₂ : list α} (s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ := s.countp_le _ theorem perm.foldl_eq' {f : β → α → β} {l₁ l₂ : list α} (p : l₁ ~ l₂) : (∀ (x ∈ l₁) (y ∈ l₁) z, f (f z x) y = f (f z y) x) → ∀ b, foldl f b l₁ = foldl f b l₂ := perm_induction_on p (λ H b, rfl) (λ x t₁ t₂ p r H b, r (λ x hx y hy, H _ (or.inr hx) _ (or.inr hy)) _) (λ x y t₁ t₂ p r H b, begin simp only [foldl], rw [H x (or.inr $ or.inl rfl) y (or.inl rfl)], exact r (λ x hx y hy, H _ (or.inr $ or.inr hx) _ (or.inr $ or.inr hy)) _ end) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ H b, eq.trans (r₁ H b) (r₂ (λ x hx y hy, H _ (p₁.symm.subset hx) _ (p₁.symm.subset hy)) b)) theorem perm.foldl_eq {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) : ∀ b, foldl f b l₁ = foldl f b l₂ := p.foldl_eq' $ λ x hx y hy z, rcomm z x y theorem perm.foldr_eq {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) : ∀ b, foldr f b l₁ = foldr f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, by simp; rw [r b]) (λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b]) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) lemma perm.rec_heq {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α} (hl : perm l l') (f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b') (f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) : @list.rec α β b f l == @list.rec α β b f l' := begin induction hl, case list.perm.nil { refl }, case list.perm.cons : a l l' h ih { exact f_congr h ih }, case list.perm.swap : a a' l { exact f_swap }, case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ } end section variables {op : α → α → α} [is_associative α op] [is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l lemma perm.fold_op_eq {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a := h.foldl_eq (right_comm _ is_commutative.comm is_associative.assoc) _ end section comm_monoid /-- If elements of a list commute with each other, then their product does not depend on the order of elements-/ @[to_additive] lemma perm.prod_eq' [monoid α] {l₁ l₂ : list α} (h : l₁ ~ l₂) (hc : l₁.pairwise (λ x y, x * y = y * x)) : l₁.prod = l₂.prod := h.foldl_eq' (forall_of_forall_of_pairwise (λ x y h z, (h z).symm) (λ x hx z, rfl) $ hc.imp $ λ x y h z, by simp only [mul_assoc, h]) _ variable [comm_monoid α] @[to_additive] lemma perm.prod_eq {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ := h.fold_op_eq @[to_additive] lemma prod_reverse (l : list α) : prod l.reverse = prod l := (reverse_perm l).prod_eq end comm_monoid theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ := begin generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂, intro p, revert l₁ l₂ r₁ r₂ e₁ e₂, refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _) (λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂, { apply (not_mem_nil a).elim, rw ← e₁, simp }, { cases l₁ with y l₁; cases l₂ with z l₂; dsimp at e₁ e₂; injections; subst x, { substs t₁ t₂, exact p }, { substs z t₁ t₂, exact p.trans perm_middle }, { substs y t₁ t₂, exact perm_middle.symm.trans p }, { substs z t₁ t₂, exact (IH rfl rfl).cons y } }, { rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩; dsimp at e₁ e₂; injections; substs x y, { substs r₁ r₂, exact p.cons a }, { substs r₁ r₂, exact p.cons u }, { substs r₁ v t₂, exact (p.trans perm_middle).cons u }, { substs r₁ r₂, exact p.cons y }, { substs r₁ r₂ y u, exact p.cons a }, { substs r₁ u v t₂, exact ((p.trans perm_middle).cons y).trans (swap _ _ _) }, { substs r₂ z t₁, exact (perm_middle.symm.trans p).cons y }, { substs r₂ y z t₁, exact (swap _ _ _).trans ((perm_middle.symm.trans p).cons u) }, { substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } }, { substs t₁ t₃, have : a ∈ t₂ := p₁.subset (by simp), rcases mem_split this with ⟨l₂, r₂, e₂⟩, subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) } end theorem perm.cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := @perm_inv_core _ _ [] [] _ _ @[simp] theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ := ⟨perm.cons_inv, perm.cons a⟩ theorem perm_append_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂ | [] := iff.rfl | (a::l) := (perm_cons a).trans (perm_append_left_iff l) theorem perm_append_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ := ⟨λ p, (perm_append_left_iff _).1 $ perm_append_comm.trans $ p.trans perm_append_comm, perm.append_right _⟩ theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ := begin refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩, cases o₁ with a; cases o₂ with b, {refl}, { cases p.length_eq }, { cases p.length_eq }, { exact option.mem_to_list.1 (p.symm.subset $ by simp) } end theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ := ⟨λ ⟨l, p, s⟩, begin cases s with _ _ _ s' u _ _ s', { exact (p.subperm_left.2 $ (sublist_cons _ _).subperm).trans s'.subperm }, { exact ⟨u, p.cons_inv, s'⟩ } end, λ ⟨l, p, s⟩, ⟨a::l, p.cons a, s.cons2 _ _ _⟩⟩ theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂) (s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ := begin rcases s with ⟨l, p, s⟩, induction s generalizing l₁, case list.sublist.slnil { cases h₂ }, case list.sublist.cons : r₁ r₂ b s' ih { simp at h₂, cases h₂ with e m, { subst b, exact ⟨a::r₁, p.cons a, s'.cons2 _ _ _⟩ }, { rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } }, case list.sublist.cons2 : r₁ r₂ b s' ih { have bm : b ∈ l₁ := (p.subset $ mem_cons_self _ _), have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm), rcases mem_split bm with ⟨t₁, t₂, rfl⟩, have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp, rcases ih am (nodup_of_sublist st d₁) (mt (λ x, st.subset x) h₁) (perm.cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩, exact ⟨b::t, (p'.cons b).trans $ (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons2 _ _ _⟩ } end theorem subperm_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂ | [] := iff.rfl | (a::l) := (subperm_cons a).trans (subperm_append_left l) theorem subperm_append_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ := (perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l) theorem subperm.exists_of_length_lt {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂ | ⟨l, p, s⟩ h := suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from (this $ p.symm.length_eq ▸ h).imp (λ a, (p.cons a).subperm_right.1), begin clear subperm.exists_of_length_lt p h l₁, rename l₂ u, induction s with l₁ l₂ a s IH _ _ b s IH; intro h, { cases h }, { cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h, { exact (IH h).imp (λ a s, s.trans (sublist_cons _ _).subperm) }, { exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } }, { exact (IH $ nat.lt_of_succ_lt_succ h).imp (λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) } end theorem subperm_of_subset_nodup {l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ := begin induction d with a l₁' h d IH, { exact ⟨nil, perm.nil, nil_sublist _⟩ }, { cases forall_mem_cons.1 H with H₁ H₂, simp at h, exact cons_subperm_of_mem d h H₁ (IH H₂) } end theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) : l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ := ⟨λ p a, p.mem_iff, λ H, subperm.antisymm (subperm_of_subset_nodup d₁ (λ a, (H a).1)) (subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩ theorem nodup.sublist_ext {l₁ l₂ l : list α} (d : nodup l) (s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ := ⟨λ h, begin induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁, { exact h.eq_nil }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { exact IH d.2 s₁ h }, { apply d.1.elim, exact subperm.subset ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { apply d.1.elim, exact subperm.subset ⟨_, h, s₁⟩ (mem_cons_self _ _) }, { rw IH d.2 s₁ h.cons_inv } } end, λ h, by rw h⟩ section variable [decidable_eq α] -- attribute [congr] theorem perm.erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁.erase a ~ l₂.erase a := if h₁ : a ∈ l₁ then have h₂ : a ∈ l₂, from p.subset h₁, perm.cons_inv $ (perm_cons_erase h₁).symm.trans $ p.trans (perm_cons_erase h₂) else have h₂ : a ∉ l₂, from mt p.mem_iff.2 h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p theorem subperm_cons_erase (a : α) (l : list α) : l <+~ a :: l.erase a := begin by_cases h : a ∈ l, { exact (perm_cons_erase h).subperm }, { rw [erase_of_not_mem h], exact (sublist_cons _ _).subperm } end theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l := (erase_sublist _ _).subperm theorem subperm.erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a := let ⟨l, hp, hs⟩ := h in ⟨l.erase a, hp.erase _, hs.erase _⟩ theorem perm.diff_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, perm.erase] theorem perm.diff_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ := by induction h generalizing l; simp [*, perm.erase, erase_comm] <|> exact (ih_1 _).trans (ih_2 _) theorem perm.diff {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.diff t₁ ~ l₂.diff t₂ := ht.diff_left l₂ ▸ hl.diff_right _ theorem subperm.diff_right {l₁ l₂ : list α} (h : l₁ <+~ l₂) (t : list α) : l₁.diff t <+~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, subperm.erase] theorem erase_cons_subperm_cons_erase (a b : α) (l : list α) : (a :: l).erase b <+~ a :: l.erase b := begin by_cases h : a = b, { subst b, rw [erase_cons_head], apply subperm_cons_erase }, { rw [erase_cons_tail _ h] } end theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂ | l₁ [] := ⟨a::l₁, by simp⟩ | l₁ (b::l₂) := begin simp only [diff_cons], refine ((erase_cons_subperm_cons_erase a b l₁).diff_right l₂).trans _, apply subperm_cons_diff end theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ := subperm_cons_diff.subset theorem perm.bag_inter_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.bag_inter t ~ l₂.bag_inter t := begin induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp}, { by_cases x ∈ t; simp [*, perm.cons] }, { by_cases x = y, {simp [h]}, by_cases xt : x ∈ t; by_cases yt : y ∈ t, { simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] }, { simp [xt, yt, mt mem_of_mem_erase, perm.cons] }, { simp [xt, yt, mt mem_of_mem_erase, perm.cons] }, { simp [xt, yt] } }, { exact (ih_1 _).trans (ih_2 _) } end theorem perm.bag_inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l.bag_inter t₁ = l.bag_inter t₂ := begin induction l with a l IH generalizing t₁ t₂ p, {simp}, by_cases a ∈ t₁, { simp [h, p.subset h, IH (p.erase _)] }, { simp [h, mt p.mem_iff.2 h, IH p] } end theorem perm.bag_inter {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.bag_inter t₁ ~ l₂.bag_inter t₂ := ht.bag_inter_left l₂ ▸ hl.bag_inter_right _ theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a := ⟨λ h, have a ∈ l₂, from h.subset (mem_cons_self a l₁), ⟨this, (h.trans $ perm_cons_erase this).cons_inv⟩, λ ⟨m, h⟩, (h.cons a).trans (perm_cons_erase m).symm⟩ theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ := ⟨perm.count_eq, λ H, begin induction l₁ with a l₁ IH generalizing l₂, { cases l₂ with b l₂, {refl}, specialize H b, simp at H, contradiction }, { have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos), refine ((IH $ λ b, _).cons a).trans (perm_cons_erase this).symm, specialize H b, rw (perm_cons_erase this).count_eq at H, by_cases b = a; simp [h] at H ⊢; assumption } end⟩ instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) | [] [] := is_true $ perm.refl _ | [] (b::l₂) := is_false $ λ h, by have := h.nil_eq; contradiction | (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a); exact decidable_of_iff' _ cons_perm_iff_perm_erase -- @[congr] theorem perm.erase_dup {l₁ l₂ : list α} (p : l₁ ~ l₂) : erase_dup l₁ ~ erase_dup l₂ := perm_iff_count.2 $ λ a, if h : a ∈ l₁ then by simp [nodup_erase_dup, h, p.subset h] else by simp [h, mt p.mem_iff.2 h] -- attribute [congr] theorem perm.insert (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ := if h : a ∈ l₁ then by simpa [h, p.subset h] using p else by simpa [h, mt p.mem_iff.2 h] using p.cons a theorem perm_insert_swap (x y : α) (l : list α) : insert x (insert y l) ~ insert y (insert x l) := begin by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl], by_cases xy : x = y, { simp [xy] }, simp [not_mem_cons_of_ne_of_not_mem xy xl, not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl], constructor end theorem perm.union_right {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ := begin induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp}, { exact ih.insert a }, { apply perm_insert_swap }, { exact ih_1.trans ih_2 } end theorem perm.union_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ := by induction l; simp [*, perm.insert] -- @[congr] theorem perm.union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ := (p₁.union_right t₁).trans (p₂.union_left l₂) theorem perm.inter_right {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ := perm.filter _ theorem perm.inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ := by { dsimp [(∩), list.inter], congr, funext a, rw [p.mem_iff] } -- @[congr] theorem perm.inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ := p₂.inter_left l₂ ▸ p₁.inter_right t₁ end theorem perm.pairwise_iff {R : α → α → Prop} (S : symmetric R) : ∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ := suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩, λ l₁ l₂ p d, begin induction d with a l₁ h d IH generalizing l₂, { rw ← p.nil_eq, constructor }, { have : a ∈ l₂ := p.subset (mem_cons_self _ _), rcases mem_split this with ⟨s₂, t₂, rfl⟩, have p' := (p.trans perm_middle).cons_inv, refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩), exact h _ (p'.symm.subset m) } end theorem perm.nodup_iff {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) := perm.pairwise_iff $ @ne.symm α theorem perm.bind_right {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) : l₁.bind f ~ l₂.bind f := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact IH.append_left _ }, { simp, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end theorem perm.bind_left (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) : l.bind f ~ l.bind g := by induction l with a l IH; simp; exact (h a).append IH theorem perm.product_right {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) : product l₁ t₁ ~ product l₂ t₁ := p.bind_right _ theorem perm.product_left (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) : product l t₁ ~ product l t₂ := perm.bind_left _ $ λ a, p.map _ @[congr] theorem perm.product {l₁ l₂ : list α} {t₁ t₂ : list β} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ := (p₁.product_right t₁).trans (p₂.product_left l₂) theorem sublists_cons_perm_append (a : α) (l : list α) : sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) := begin simp only [sublists, sublists_aux_cons_cons, cons_append, perm_cons], refine (perm.cons _ _).trans perm_middle.symm, induction sublists_aux l cons with b l IH; simp, exact (IH.cons _).trans perm_middle.symm end theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l | [] := perm.refl _ | (a::l) := let IH := sublists_perm_sublists' l in by rw sublists'_cons; exact (sublists_cons_perm_append _ _).trans (IH.append (IH.map _)) theorem revzip_sublists (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l := begin rw revzip, apply list.reverse_rec_on l, { intros l₁ l₂ h, simp at h, simp [h] }, { intros l a IH l₁ l₂ h, rw [sublists_concat, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [skip, {simp}], simp only [prod.mk.inj_iff, mem_map, mem_append, prod.map_mk, prod.exists] at h, rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { rw ← append_assoc, exact (IH _ _ h).append_right _ }, { rw append_assoc, apply (perm_append_comm.append_left _).trans, rw ← append_assoc, exact (IH _ _ h).append_right _ } } end theorem revzip_sublists' (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l := begin rw revzip, induction l with a l IH; intros l₁ l₂ h, { simp at h, simp [h] }, { rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [simp at h, simp], rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { exact perm_middle.trans ((IH _ _ h).cons _) }, { exact (IH _ _ h).cons _ } } end theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α} (H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁) (p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ := begin let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { cases h : f a, { simp [h], exact IH (pairwise_cons.1 H).2 }, { simp [lookmap_cons_some _ _ h, p] } }, { cases h₁ : f a with c; cases h₂ : f b with d, { simp [h₁, h₂], apply swap }, { simp [h₁, lookmap_cons_some _ _ h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂], rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩, refl } }, { refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)), exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm } end theorem perm.erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α} (H : pairwise (λ a b, f a → f b → false) l₁) (p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ := begin let F := λ a b, f a → f b → false, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { by_cases h : f a, { simp [h, p] }, { simp [h], exact IH (pairwise_cons.1 H).2 } }, { by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂], { cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ }, { apply swap } }, { refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)), exact λ a b h h₁ h₂, h h₂ h₁ } end /- enumerating permutations -/ section permutations theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β), (permutations_aux2 t ts r ys f).1 = ys ++ ts | [] f := rfl | (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with | ⟨_, zs⟩, rfl := rfl end @[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) : (permutations_aux2 t ts r [] f).2 = r := rfl @[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α) (f : list α → β) : (permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) :: (permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 := match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with | ⟨_, zs⟩, rfl := rfl end theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) : (permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 := by induction ys generalizing f; simp * theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} : l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts := begin induction ys with y ys ih generalizing l, { simp {contextual := tt} }, { rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]), by funext; simp, mem_cons_iff, ih], split; intro h, { rcases h with e | ⟨l₁, l₂, l0, ye, _⟩, { subst l', exact ⟨[], y::ys, by simp⟩ }, { substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } }, { rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩, { simp [ye] }, { simp at ye, rcases ye with ⟨rfl, rfl⟩, exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } } end theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} : l ∈ (permutations_aux2 t ts [] ys id).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts := by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2 theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) : length (permutations_aux2 t ts [] ys f).2 = length ys := by induction ys generalizing f; simp * theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : foldr (λy r, (permutations_aux2 t ts r y id).2) r L = L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r := by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}] theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} : l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts := have (∃ (a : list α), a ∈ L ∧ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts), from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩, λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩, by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this, or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc] theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r := by simp [foldr_permutations_aux2, (∘), length_permutations_aux2] theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α)) (n) (H : ∀ l ∈ L, length l = n) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r := begin rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)], induction L with l L ih, {simp}, have sum_map : sum (map length L) = n * length L := ih (λ l m, H l (mem_cons_of_mem _ m)), have length_l : length l = n := H _ (mem_cons_self _ _), simp [sum_map, length_l, mul_add, add_comm] end theorem perm_of_mem_permutations_aux : ∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2 m, rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m, rcases m with m | ⟨l₁, l₂, m, _, e⟩, { exact (IH1 m).trans perm_middle }, { subst e, have p : l₁ ++ l₂ ~ is, { simp [permutations] at m, cases m with e m, {simp [e]}, exact is.append_nil ▸ IH2 m }, exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) } end theorem perm_of_mem_permutations {l₁ l₂ : list α} (h : l₁ ∈ permutations l₂) : l₁ ~ l₂ := (eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _) (λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m) theorem length_permutations_aux : ∀ ts is : list α, length (permutations_aux ts is) + is.length.fact = (length ts + length is).fact := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2, have IH2 : length (permutations_aux is nil) + 1 = is.length.fact, { simpa using IH2 }, simp [-add_comm, nat.fact, nat.add_succ, mul_comm] at IH1, rw [permutations_aux_cons, length_foldr_permutations_aux2' _ _ _ _ _ (λ l m, (perm_of_mem_permutations m).length_eq), permutations, length, length, IH2, nat.succ_add, nat.fact_succ, mul_comm (nat.succ _), ← IH1, add_comm (_*_), add_assoc, nat.mul_succ, mul_comm] end theorem length_permutations (l : list α) : length (permutations l) = (length l).fact := length_permutations_aux l [] theorem mem_permutations_of_perm_lemma {is l : list α} (H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is []) : l ~ is → l ∈ permutations is := by simpa [permutations, perm_nil] using H theorem mem_permutations_aux_of_perm : ∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2 l p, rw [permutations_aux_cons, mem_foldr_permutations_aux2], rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m, { clear p, subst e, rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩, subst is', have p := (perm_middle.symm.trans p').cons_inv, cases l₂ with a l₂', { exact or.inl ⟨l₁, by simpa using p⟩ }, { exact or.inr (or.inr ⟨l₁, a::l₂', mem_permutations_of_perm_lemma IH2 p, by simp⟩) } }, { exact or.inr (or.inl m) } end @[simp] theorem mem_permutations (s t : list α) : s ∈ permutations t ↔ s ~ t := ⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩ end permutations end list
f3f9cd1114bd8f8cdc2cd68326282184f5a2f6d2
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tmp/new-frontend/parser/parsec.lean
0256f5ea624fe2986dbc5965cbef7ea94d949eae
[ "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
22,949
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich Implementation for the Parsec Parser Combinators described in the paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/Parsec-paper-letter.pdf -/ prelude import init.data.tostring init.data.string.basic init.data.list.basic init.control.except import init.data.repr init.lean.name init.data.dlist init.control.monadfail init.control.combinators import init.lean.format /- Old String iterator -/ namespace String structure OldIterator := (s : String) (offset : Nat) (i : Nat) def mkOldIterator (s : String) : OldIterator := ⟨s, 0, 0⟩ namespace OldIterator def remaining : OldIterator → Nat | ⟨s, o, _⟩ := s.length - o def toString : OldIterator → String | ⟨s, _, _⟩ := s def remainingBytes : OldIterator → Nat | ⟨s, _, i⟩ := s.bsize - i def curr : OldIterator → Char | ⟨s, _, i⟩ := get s i def next : OldIterator → OldIterator | ⟨s, o, i⟩ := ⟨s, o+1, s.next i⟩ def prev : OldIterator → OldIterator | ⟨s, o, i⟩ := ⟨s, o-1, s.prev i⟩ def hasNext : OldIterator → Bool | ⟨s, _, i⟩ := i < utf8ByteSize s def hasPrev : OldIterator → Bool | ⟨s, _, i⟩ := i > 0 def setCurr : OldIterator → Char → OldIterator | ⟨s, o, i⟩ c := ⟨s.set i c, o, i⟩ def toEnd : OldIterator → OldIterator | ⟨s, o, _⟩ := ⟨s, s.length, s.bsize⟩ def extract : OldIterator → OldIterator → String | ⟨s₁, _, b⟩ ⟨s₂, _, e⟩ := if s₁ ≠ s₂ || b > e then "" else s₁.extract b e def forward : OldIterator → Nat → OldIterator | it 0 := it | it (n+1) := forward it.next n def remainingToString : OldIterator → String | ⟨s, _, i⟩ := s.extract i s.bsize /- (isPrefixOfRemaining it₁ it₂) is `true` Iff `it₁.remainingToString` is a prefix of `it₂.remainingToString`. -/ def isPrefixOfRemaining : OldIterator → OldIterator → Bool | ⟨s₁, _, i₁⟩ ⟨s₂, _, i₂⟩ := s₁.extract i₁ s₁.bsize = s₂.extract i₂ (i₂ + (s₁.bsize - i₁)) def nextn : OldIterator → Nat → OldIterator | it 0 := it | it (i+1) := nextn it.next i def prevn : OldIterator → Nat → OldIterator | it 0 := it | it (i+1) := prevn it.prev i end OldIterator private def oldLineColumnAux : Nat → String.OldIterator → Nat × Nat → Nat × Nat | 0 it r := r | (k+1) it r@(line, col) := if it.hasNext = false then r else match it.curr with | '\n' := oldLineColumnAux k it.next (line+1, 0) | other := oldLineColumnAux k it.next (line, col+1) def oldLineColumn (s : String) (offset : Nat) : Nat × Nat := oldLineColumnAux offset s.mkOldIterator (1, 0) end String namespace Lean namespace Parser open String (OldIterator) namespace Parsec @[reducible] def Position : Type := Nat structure Message (μ : Type := Unit) := (it : OldIterator) (unexpected : String := "") -- unexpected input (expected : DList String := ∅) -- expected productions (custom : Option μ) def expected.toString : List String → String | [] := "" | [e] := e | [e1, e2] := e1 ++ " or " ++ e2 | (e::es) := e ++ ", " ++ expected.toString es def Message.text {μ : Type} (msg : Message μ) : String := let unexpected := (if msg.unexpected = "" then [] else ["unexpected " ++ msg.unexpected]) in let exList := msg.expected.toList in let expected := if exList = [] then [] else ["expected " ++ expected.toString exList] in "\n".intercalate $ unexpected ++ expected protected def Message.toString {μ : Type} (msg : Message μ) : String := let (line, col) := msg.it.toString.oldLineColumn msg.it.offset in -- always print ":"; we assume at least one of `unexpected` and `expected` to be non-Empty "error at line " ++ toString line ++ ", column " ++ toString col ++ ":\n" ++ msg.text instance {μ : Type} : HasToString (Message μ) := ⟨Message.toString⟩ -- use for e.g. upcasting Parsec errors with `MonadExcept.liftExcept` instance {μ : Type} : HasLift (Message μ) String := ⟨toString⟩ /- Remark: we store expected "error" messages in `okEps` results. They contain the error that would have occurred if a successful "epsilon" Alternative was not taken. -/ inductive Result (μ α : Type) | ok {} (a : α) (it : OldIterator) (expected : Option $ DList String) : Result | error {} (msg : Message μ) (consumed : Bool) : Result @[inline] def Result.mkEps {μ α : Type} (a : α) (it : OldIterator) : Result μ α := Result.ok a it (some ∅) end Parsec open Parsec def ParsecT (μ : Type) (m : Type → Type) (α : Type) := OldIterator → m (Result μ α) abbrev Parsec (μ : Type) := ParsecT μ Id /-- `Parsec` without custom error Message Type -/ abbrev Parsec' := Parsec Unit namespace ParsecT open Parsec.Result variables {m : Type → Type} [Monad m] {μ α β : Type} def run (p : ParsecT μ m α) (s : String) (fname := "") : m (Except (Message μ) α) := do r ← p s.mkOldIterator, pure $ match r with | ok a _ _ := Except.ok a | error msg _ := Except.error msg def runFrom (p : ParsecT μ m α) (it : OldIterator) (fname := "") : m (Except (Message μ) α) := do r ← p it, pure $ match r with | ok a _ _ := Except.ok a | error msg _ := Except.error msg @[inline] protected def pure (a : α) : ParsecT μ m α := λ it, pure (mkEps a it) def eps : ParsecT μ m Unit := ParsecT.pure () protected def failure : ParsecT μ m α := λ it, pure (error { unexpected := "failure", it := it, custom := none } false) def merge (msg₁ msg₂ : Message μ) : Message μ := { expected := msg₁.expected ++ msg₂.expected, ..msg₁ } @[inlineIfReduce] def bindMkRes (ex₁ : Option (DList String)) (r : Result μ β) : Result μ β := match ex₁, r with | none, ok b it _ := ok b it none | none, error msg _ := error msg true | some ex₁, ok b it (some ex₂) := ok b it (some $ ex₁ ++ ex₂) | some ex₁, error msg₂ false := error { expected := ex₁ ++ msg₂.expected, .. msg₂ } false | some ex₁, other := other /-- The `bind p q` Combinator behaves as follows: 1- If `p` fails, then it fails. 2- If `p` succeeds and consumes input, then execute `q` 3- If `q` succeeds but does not consume input, then execute `q` and merge error messages if both do not consume any input. -/ @[inline] protected def bind (p : ParsecT μ m α) (q : α → ParsecT μ m β) : ParsecT μ m β := λ it, do r ← p it, match r with | ok a it ex₁ := bindMkRes ex₁ <$> q a it | error msg c := pure (error msg c) /-- More efficient `bind` that does not correctly merge `expected` and `consumed` information. -/ @[inline] def bind' (p : ParsecT μ m α) (q : α → ParsecT μ m β) : ParsecT μ m β := λ it, do r ← p it, match r with | ok a it ex₁ := q a it | error msg c := pure (error msg c) instance : Monad (ParsecT μ m) := { bind := λ _ _, ParsecT.bind, pure := λ _, ParsecT.pure } /-- `Monad` instance using `bind'`. -/ def Monad' : Monad (ParsecT μ m) := { bind := λ _ _, ParsecT.bind', pure := λ _, ParsecT.pure } instance : MonadFail Parsec' := { fail := λ _ s it, error { unexpected := s, it := it, custom := () } false } instance : MonadExcept (Message μ) (ParsecT μ m) := { throw := λ _ msg it, pure (error msg false), catch := λ _ p c it, do r ← p it, match r with | error msg cns := do { r ← c msg msg.it, pure $ match r with | error msg' cns' := error msg' (cns || cns') | other := other } | other := pure other } instance : HasMonadLift m (ParsecT μ m) := { monadLift := λ α x it, do a ← x, pure (mkEps a it) } def expect (msg : Message μ) (exp : String) : Message μ := {expected := DList.singleton exp, ..msg} @[inlineIfReduce] def labelsMkRes (r : Result μ α) (lbls : DList String) : Result μ α := match r with | ok a it (some _) := ok a it (some lbls) | error msg false := error {expected := lbls, ..msg} false | other := other @[inline] def labels (p : ParsecT μ m α) (lbls : DList String) : ParsecT μ m α := λ it, do r ← p it, pure $ labelsMkRes r lbls @[inlineIfReduce] def tryMkRes (r : Result μ α) : Result μ α := match r with | error msg _ := error msg false | other := other /-- `try p` behaves like `p`, but it pretends `p` hasn't consumed any input when `p` fails. It is useful for implementing infinite lookahead. The Parser `try p <|> q` will try `q` even when `p` has consumed input. It is also useful for specifying both the lexer and Parser together. ``` (do try (ch 'l' >> ch 'e' >> ch 't'), whitespace, ...) <|> ... ``` Without the `try` Combinator we will not be able to backtrack on the `let` keyword. -/ @[inline] def try (p : ParsecT μ m α) : ParsecT μ m α := λ it, do r ← p it, pure $ tryMkRes r @[inlineIfReduce] def orelseMkRes (msg₁ : Message μ) (r : Result μ α) : Result μ α := match r with | ok a it' (some ex₂) := ok a it' (some $ msg₁.expected ++ ex₂) | error msg₂ false := error (merge msg₁ msg₂) false | other := other /-- The `orelse p q` Combinator behaves as follows: 1- If `p` succeeds *or* consumes input, return its Result. Otherwise, execute `q` and return its Result. Recall that the `try p` Combinator can be used to pretend that `p` did not consume any input, and simulate infinite lookahead. 2- If both `p` and `q` did not consume any input, then combine their error messages (even if one of them succeeded). -/ @[inline] protected def orelse (p q : ParsecT μ m α) : ParsecT μ m α := λ it, do r ← p it, match r with | error msg₁ false := do { r ← q it, pure $ orelseMkRes msg₁ r } | other := pure other instance : Alternative (ParsecT μ m) := { orelse := λ _, ParsecT.orelse, failure := λ _, ParsecT.failure, ..ParsecT.Monad } /-- Run `p`, but do not consume any input when `p` succeeds. -/ @[specialize] def lookahead (p : ParsecT μ m α) : ParsecT μ m α := λ it, do r ← p it, pure $ match r with | ok a s' _ := mkEps a it | other := other end ParsecT /- Type class for abstracting from concrete Monad stacks containing a `Parsec` somewhere. -/ class MonadParsec (μ : outParam Type) (m : Type → Type) := -- analogous to e.g. `MonadReader.lift` before simplification (see there) (lift {} {α : Type} : Parsec μ α → m α) -- Analogous to e.g. `MonadReaderAdapter.map` before simplification (see there). -- Its usage seems to be way too common to justify moving it into a separate type class. (map {} {α : Type} : (∀ {m'} [Monad m'] {α}, ParsecT μ m' α → ParsecT μ m' α) → m α → m α) /-- `Parsec` without custom error Message Type -/ abbrev MonadParsec' := MonadParsec Unit variables {μ : Type} instance {m : Type → Type} [Monad m] : MonadParsec μ (ParsecT μ m) := { lift := λ α p it, pure (p it), map := λ α f x, f x } instance monadParsecTrans {m n : Type → Type} [HasMonadLift m n] [MonadFunctor m m n n] [MonadParsec μ m] : MonadParsec μ n := { lift := λ α p, monadLift (MonadParsec.lift p : m α), map := λ α f x, monadMap (λ β x, (MonadParsec.map @f x : m β)) x } namespace MonadParsec open ParsecT variables {m : Type → Type} [Monad m] [MonadParsec μ m] {α β : Type} def error {α : Type} (unexpected : String) (expected : DList String := ∅) (it : Option OldIterator := none) (custom : Option μ := none) : m α := lift $ λ it', Result.error { unexpected := unexpected, expected := expected, it := it.getOrElse it', custom := custom } false @[inline] def leftOver : m OldIterator := lift $ λ it, Result.mkEps it it /-- Return the number of characters left to be parsed. -/ @[inline] def remaining : m Nat := String.OldIterator.remaining <$> leftOver @[inline] def labels (p : m α) (lbls : DList String) : m α := map (λ m' inst β p, @ParsecT.labels m' inst μ β p lbls) p @[inline] def label (p : m α) (lbl : String) : m α := labels p (DList.singleton lbl) infixr ` <?> `:2 := label @[inline] def hidden (p : m α) : m α := labels p ∅ /-- `try p` behaves like `p`, but it pretends `p` hasn't consumed any input when `p` fails. It is useful for implementing infinite lookahead. The Parser `try p <|> q` will try `q` even when `p` has consumed input. It is also useful for specifying both the lexer and Parser together. ``` (do try (ch 'l' >> ch 'e' >> ch 't'), whitespace, ...) <|> ... ``` Without the `try` Combinator we will not be able to backtrack on the `let` keyword. -/ @[inline] def try (p : m α) : m α := map (λ m' inst β p, @ParsecT.try m' inst μ β p) p /-- Parse `p` without consuming any input. -/ @[inline] def lookahead (p : m α) : m α := map (λ m' inst β p, @ParsecT.lookahead m' inst μ β p) p /-- Faster version of `notFollowedBy (satisfy p)` -/ @[inline] def notFollowedBySat (p : Char → Bool) : m Unit := do it ← leftOver, if !it.hasNext then pure () else let c := it.curr in if p c then error (repr c) else pure () def eoiError (it : OldIterator) : Result μ α := Result.error { it := it, unexpected := "end of input", custom := default _ } false def curr : m Char := String.OldIterator.curr <$> leftOver @[inline] def cond (p : Char → Bool) (t : m α) (e : m α) : m α := mcond (p <$> curr) t e /-- If the next character `c` satisfies `p`, then update Position and return `c`. Otherwise, generate error Message with current Position and character. -/ @[inline] def satisfy (p : Char → Bool) : m Char := do it ← leftOver, if !it.hasNext then error "end of input" else let c := it.curr in if p c then lift $ λ _, Result.ok c it.next none else error (repr c) def ch (c : Char) : m Char := satisfy (= c) def alpha : m Char := satisfy Char.isAlpha def digit : m Char := satisfy Char.isDigit def upper : m Char := satisfy Char.isUpper def lower : m Char := satisfy Char.isLower def any : m Char := satisfy (λ _, True) private def strAux : Nat → OldIterator → OldIterator → Option OldIterator | 0 _ it := some it | (n+1) sIt it := if it.hasNext ∧ sIt.curr = it.curr then strAux n sIt.next it.next else none /-- `str s` parses a sequence of elements that match `s`. Returns the parsed String (i.e. `s`). This Parser consumes no input if it fails (even if a partial match). Note: The behaviour of this Parser is different to that the `String` Parser in the ParsecT Μ M Haskell library, as this one is all-or-nothing. -/ def strCore (s : String) (ex : DList String) : m String := if s.isEmpty then pure "" else lift $ λ it, match strAux s.length s.mkOldIterator it with | some it' := Result.ok s it' none | none := Result.error { it := it, expected := ex, custom := none } false @[inline] def str (s : String) : m String := strCore s (DList.singleton (repr s)) private def takeAux : Nat → String → OldIterator → Result μ String | 0 r it := Result.ok r it none | (n+1) r it := if !it.hasNext then eoiError it else takeAux n (r.push (it.curr)) it.next /-- Consume `n` characters. -/ def take (n : Nat) : m String := if n = 0 then pure "" else lift $ takeAux n "" private def mkStringResult (r : String) (it : OldIterator) : Result μ String := if r.isEmpty then Result.mkEps r it else Result.ok r it none @[specialize] private def takeWhileAux (p : Char → Bool) : Nat → String → OldIterator → Result μ String | 0 r it := mkStringResult r it | (n+1) r it := if !it.hasNext then mkStringResult r it else let c := it.curr in if p c then takeWhileAux n (r.push c) it.next else mkStringResult r it /-- Consume input as long as the predicate returns `true`, and return the consumed input. This Parser does not fail. It will return an Empty String if the predicate returns `false` on the current character. -/ @[specialize] def takeWhile (p : Char → Bool) : m String := lift $ λ it, takeWhileAux p it.remaining "" it @[specialize] def takeWhileCont (p : Char → Bool) (ini : String) : m String := lift $ λ it, takeWhileAux p it.remaining ini it /-- Consume input as long as the predicate returns `true`, and return the consumed input. This Parser requires the predicate to succeed on at least once. -/ @[specialize] def takeWhile1 (p : Char → Bool) : m String := do c ← satisfy p, takeWhileCont p (toString c) /-- Consume input as long as the predicate returns `false` (i.e. until it returns `true`), and return the consumed input. This Parser does not fail. -/ @[inline] def takeUntil (p : Char → Bool) : m String := takeWhile (λ c, !p c) @[inline] def takeUntil1 (p : Char → Bool) : m String := takeWhile1 (λ c, !p c) private def mkConsumedResult (consumed : Bool) (it : OldIterator) : Result μ Unit := if consumed then Result.ok () it none else Result.mkEps () it @[specialize] private def takeWhileAux' (p : Char → Bool) : Nat → Bool → OldIterator → Result μ Unit | 0 consumed it := mkConsumedResult consumed it | (n+1) consumed it := if !it.hasNext then mkConsumedResult consumed it else let c := it.curr in if p c then takeWhileAux' n true it.next else mkConsumedResult consumed it /-- Similar to `takeWhile` but it does not return the consumed input. -/ @[specialize] def takeWhile' (p : Char → Bool) : m Unit := lift $ λ it, takeWhileAux' p it.remaining false it /-- Similar to `takeWhile1` but it does not return the consumed input. -/ @[specialize] def takeWhile1' (p : Char → Bool) : m Unit := satisfy p *> takeWhile' p /-- Consume zero or more whitespaces. -/ @[noinline] def whitespace : m Unit := takeWhile' Char.isWhitespace /-- Shorthand for `p <* whitespace` -/ @[inline] def lexeme (p : m α) : m α := p <* whitespace /-- Parse a numeral in decimal. -/ @[noinline] def num : m Nat := String.toNat <$> (takeWhile1 Char.isDigit) /-- Succeed only if there are at least `n` characters left. -/ def ensure (n : Nat) : m Unit := do it ← leftOver, if n ≤ it.remaining then pure () else error "end of input" (DList.singleton ("at least " ++ toString n ++ " characters")) /-- Return the current Position. -/ def pos : m Position := String.OldIterator.offset <$> leftOver /-- `notFollowedBy p` succeeds when Parser `p` fails -/ @[inline] def notFollowedBy [MonadExcept (Message μ) m] (p : m α) (msg : String := "input") : m Unit := do it ← leftOver, b ← lookahead $ catch (p *> pure false) (λ _, pure true), if b then pure () else error msg ∅ it def eoi : m Unit := do it ← leftOver, if it.remaining = 0 then pure () else error (repr it.curr) (DList.singleton ("end of input")) @[specialize] def many1Aux [Alternative m] (p : m α) : Nat → m (List α) | 0 := do a ← p, pure [a] | (n+1) := do a ← p, as ← (many1Aux n <|> pure []), pure (a::as) @[specialize] def many1 [Alternative m] (p : m α) : m (List α) := do r ← remaining, many1Aux p r @[specialize] def many [Alternative m] (p : m α) : m (List α) := many1 p <|> pure [] @[specialize] def many1Aux' [Alternative m] (p : m α) : Nat → m Unit | 0 := p *> pure () | (n+1) := p *> (many1Aux' n <|> pure ()) @[inline] def many1' [Alternative m] (p : m α) : m Unit := do r ← remaining, many1Aux' p r @[specialize] def many' [Alternative m] (p : m α) : m Unit := many1' p <|> pure () @[specialize] def sepBy1 [Alternative m] (p : m α) (sep : m β) : m (List α) := (::) <$> p <*> many (sep *> p) @[specialize] def SepBy [Alternative m] (p : m α) (sep : m β) : m (List α) := sepBy1 p sep <|> pure [] @[specialize] def fixAux [Alternative m] (f : m α → m α) : Nat → m α | 0 := error "fixAux: no progress" | (n+1) := f (fixAux n) @[specialize] def fix [Alternative m] (f : m α → m α) : m α := do n ← remaining, fixAux f (n+1) @[specialize] def foldrAux [Alternative m] (f : α → β → β) (p : m α) (b : β) : Nat → m β | 0 := pure b | (n+1) := (f <$> p <*> foldrAux n) <|> pure b /-- Matches zero or more occurrences of `p`, and folds the Result. -/ @[specialize] def foldr [Alternative m] (f : α → β → β) (p : m α) (b : β) : m β := do it ← leftOver, foldrAux f p b it.remaining @[specialize] def foldlAux [Alternative m] (f : α → β → α) (p : m β) : α → Nat → m α | a 0 := pure a | a (n+1) := (do x ← p, foldlAux (f a x) n) <|> pure a /-- Matches zero or more occurrences of `p`, and folds the Result. -/ @[specialize] def foldl [Alternative m] (f : α → β → α) (a : α) (p : m β) : m α := do it ← leftOver, foldlAux f p a it.remaining def unexpected (msg : String) : m α := error msg def unexpectedAt (msg : String) (it : OldIterator) : m α := error msg ∅ it /- Execute all parsers in `ps` and return the Result of the longest parse(s) if any, or else the Result of the furthest error. If there are two parses of equal length, the first parse wins. -/ @[specialize] def longestMatch [MonadExcept (Message μ) m] (ps : List (m α)) : m (List α) := do it ← leftOver, r ← ps.mfoldr (λ p (r : Result μ (List α)), lookahead $ catch (do a ← p, it ← leftOver, pure $ match r with | Result.ok as it' none := if it'.offset > it.offset then r else if it.offset > it'.offset then Result.ok [a] it none else Result.ok (a::as) it none | _ := Result.ok [a] it none) (λ msg, pure $ match r with | Result.error msg' _ := if msg'.it.offset > msg.it.offset then r else if msg.it.offset > msg'.it.offset then Result.error msg true else Result.error (merge msg msg') (msg.it.offset > it.offset) | _ := r)) ((error "longestMatch: Empty List" : Parsec _ _) it), lift $ λ _, r @[specialize] def observing [MonadExcept (Message μ) m] (p : m α) : m (Except (Message μ) α) := catch (Except.ok <$> p) $ λ msg, pure (Except.error msg) end MonadParsec namespace MonadParsec open ParsecT variables {m : Type → Type} [Monad m] [MonadParsec Unit m] {α β : Type} end MonadParsec namespace ParsecT open MonadParsec variables {m : Type → Type} [Monad m] {α β : Type} def parse (p : ParsecT μ m α) (s : String) (fname := "") : m (Except (Message μ) α) := run p s fname def parseWithEoi (p : ParsecT μ m α) (s : String) (fname := "") : m (Except (Message μ) α) := run (p <* eoi) s fname def parseWithLeftOver (p : ParsecT μ m α) (s : String) (fname := "") : m (Except (Message μ) (α × OldIterator)) := run (Prod.mk <$> p <*> leftOver) s fname end ParsecT def Parsec.parse {α : Type} (p : Parsec μ α) (s : String) (fname := "") : Except (Message μ) α := ParsecT.parse p s fname end Parser end Lean
7a215726b24c3def31153ebd8b7fe00a0dfc62dd
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Init/Control/Id.lean
55126d1f125267a26d26f4f1d62d1b2e70acaf22
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
504
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich The identity Monad. -/ prelude import Init.Core universe u def Id (type : Type u) : Type u := type namespace Id instance : Monad Id := { pure := fun x => x bind := fun x f => f x map := fun f x => f x } @[inline] protected def run (x : Id α) : α := x instance [OfNat α] : OfNat (Id α) := inferInstanceAs (OfNat α) end Id
322f9f56fc83c4e450f462ec119d20aedca10b9d
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/calculus/parametric_interval_integral.lean
b5cfe97ee45fac400dfcdb6133aa3437cf1b9ea0
[ "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,532
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.parametric_integral import measure_theory.integral.interval_integral /-! # Derivatives of interval integrals depending on parameters In this file we restate theorems about derivatives of integrals depending on parameters for interval integrals. -/ open topological_space measure_theory filter metric open_locale topological_space filter interval variables {𝕜 : Type*} [is_R_or_C 𝕜] {μ : measure ℝ} {E : Type*} [normed_group E] [normed_space ℝ E] [normed_space 𝕜 E] [complete_space E] {H : Type*} [normed_group H] [normed_space 𝕜 H] {a b ε : ℝ} {bound : ℝ → ℝ} namespace interval_integral /-- Differentiation under integral of `x ↦ ∫ t in a..b, F x t` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_integral_of_dominated_loc_of_lip {F : H → ℝ → E} {F' : ℝ → (H →L[𝕜] E)} {x₀ : H} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable F' (μ.restrict (Ι a b))) (h_lip : ∀ᵐ t ∂μ, t ∈ Ι a b → lipschitz_on_with (real.nnabs $ bound t) (λ x, F x t) (ball x₀ ε)) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → has_fderiv_at (λ x, F x t) (F' t) x₀) : interval_integrable F' μ a b ∧ has_fderiv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, have := has_fderiv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas h_lip bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_integral_of_dominated_of_fderiv_le {F : H → ℝ → E} {F' : H → ℝ → (H →L[𝕜] E)} {x₀ : H} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable (F' x₀) (μ.restrict (Ι a b))) (h_bound : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, ∥F' x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x t) (F' x t) x) : has_fderiv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' x₀ t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, exact (has_fderiv_at_integral_of_dominated_of_fderiv_le ε_pos hF_meas hF_int hF'_meas h_bound bound_integrable h_diff).const_smul _ end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : 𝕜`, `𝕜 = ℝ` or `𝕜 = ℂ`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_integral_of_dominated_loc_of_lip {F : 𝕜 → ℝ → E} {F' : ℝ → E} {x₀ : 𝕜} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable F' (μ.restrict (Ι a b))) (h_lipsch : ∀ᵐ t ∂μ, t ∈ Ι a b → lipschitz_on_with (real.nnabs $ bound t) (λ x, F x t) (ball x₀ ε)) (bound_integrable : interval_integrable (bound : ℝ → ℝ) μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → has_deriv_at (λ x, F x t) (F' t) x₀) : (interval_integrable F' μ a b) ∧ has_deriv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, have := has_deriv_at_integral_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas h_lipsch bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : 𝕜`, `𝕜 = ℝ` or `𝕜 = ℂ`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_integral_of_dominated_loc_of_deriv_le {F : 𝕜 → ℝ → E} {F' : 𝕜 → ℝ → E} {x₀ : 𝕜} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict (Ι a b))) (hF_int : interval_integrable (F x₀) μ a b) (hF'_meas : ae_strongly_measurable (F' x₀) (μ.restrict (Ι a b))) (h_bound : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, ∥F' x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_diff : ∀ᵐ t ∂μ, t ∈ Ι a b → ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x t) (F' x t) x) : (interval_integrable (F' x₀) μ a b) ∧ has_deriv_at (λ x, ∫ t in a..b, F x t ∂μ) (∫ t in a..b, F' x₀ t ∂μ) x₀ := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, have := has_deriv_at_integral_of_dominated_loc_of_deriv_le ε_pos hF_meas hF_int hF'_meas h_bound bound_integrable h_diff, exact ⟨this.1, this.2.const_smul _⟩ end end interval_integral
6a715bc65c5617c45e2fa07b6a4e9a6bffbc62ea
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tmp/new-frontend/frontend.lean
5147e49261afbc5f06f432f85e06243ef2a42025
[ "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
4,233
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich -/ import init.lean.parser.module init.lean.expander init.lean.elaborator init.lean.util init.io namespace Lean open Lean.Parser open Lean.Expander open Lean.Elaborator def mkConfig (filename := "<unknown>") (input := "") : Except String ModuleParserConfig := do t ← Parser.mkTokenTrie $ Parser.tokens Module.header.Parser ++ Parser.tokens command.builtinCommandParsers ++ Parser.tokens Term.builtinLeadingParsers ++ Parser.tokens Term.builtinTrailingParsers, pure $ { filename := filename, input := input, tokens := t, fileMap := FileMap.fromString input, commandParsers := command.builtinCommandParsers, leadingTermParsers := Term.builtinLeadingParsers, trailingTermParsers := Term.builtinTrailingParsers, } def runFrontend (filename input : String) (printMsg : Message → IO Unit) (collectOutputs : Bool) : StateT Environment IO (List Syntax) := λ env, do parserCfg ← ioOfExcept $ mkConfig filename input, -- TODO(Sebastian): `parseHeader` should be called directly by Lean.cpp match parseHeader parserCfg with | (_, Except.error msg) := printMsg msg *> pure ([], env) | (_, Except.ok (pSnap, msgs)) := do msgs.toList.mfor printMsg, let expanderCfg : ExpanderConfig := {transformers := builtinTransformers, ..parserCfg}, let elabCfg : ElaboratorConfig := {filename := filename, input := input, initialParserCfg := parserCfg, ..parserCfg}, let opts := Options.empty.setBool `trace.as_messages true, let elabSt := Elaborator.mkState elabCfg env opts, let addOutput (out : Syntax) outs := if collectOutputs then out::outs else [], IO.Prim.iterate (pSnap, elabSt, parserCfg, expanderCfg, ([] : List Syntax)) $ λ ⟨pSnap, elabSt, parserCfg, expanderCfg, outs⟩, do { let pos := parserCfg.fileMap.toPosition pSnap.it.offset, r ← monadLift $ profileitPure "parsing" pos $ λ _, parseCommand parserCfg pSnap, match r with | (cmd, Except.error msg) := do { -- fatal error (should never happen?) printMsg msg, msgs.toList.mfor printMsg, pure $ Sum.inr ((addOutput cmd outs).reverse, elabSt.env) } | (cmd, Except.ok (pSnap, msgs)) := do { msgs.toList.mfor printMsg, r ← monadLift $ profileitPure "expanding" pos $ λ _, (expand cmd).run expanderCfg, match r with | Except.ok cmd' := do { --IO.println cmd', elabSt ← monadLift $ profileitPure "elaborating" pos $ λ _, Elaborator.processCommand elabCfg elabSt cmd', elabSt.messages.toList.mfor printMsg, if cmd'.isOfKind Module.eoi then /-printMsg {filename := filename, severity := MessageSeverity.information, pos := ⟨1, 0⟩, text := "Parser cache hit rate: " ++ toString out.cache.hit ++ "/" ++ toString (out.cache.hit + out.cache.miss)},-/ pure $ Sum.inr ((addOutput cmd outs).reverse, elabSt.env) else pure (Sum.inl (pSnap, elabSt, elabSt.parserCfg, elabSt.expanderCfg, addOutput cmd outs)) } | Except.error e := printMsg e *> pure (Sum.inl (pSnap, elabSt, parserCfg, expanderCfg, addOutput cmd outs)) } } @[export lean_process_file] def processFile (f s : String) (json : Bool) : StateT Environment IO Unit := do let printMsg : Message → IO Unit := λ msg, if json then IO.println $ "{\"file_name\": \"<stdin>\", \"pos_line\": " ++ toString msg.pos.line ++ ", \"pos_col\": " ++ toString msg.pos.column ++ ", \"severity\": " ++ repr (match msg.severity with | MessageSeverity.information := "information" | MessageSeverity.warning := "warning" | MessageSeverity.error := "error") ++ ", \"caption\": " ++ repr msg.caption ++ ", \"text\": " ++ repr msg.text ++ "}" else IO.println msg.toString, -- print and erase uncaught exceptions catch (runFrontend f s printMsg false *> pure ()) (λ e, do monadLift (printMsg {filename := f, severity := MessageSeverity.error, pos := ⟨1, 0⟩, text := e}), throw e) end Lean
35060812c78b81ebfa32c9799da32a13b3ea73f0
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/sig_noc.hlean
90c3c798e59946aed11a7ca96767a232d8207142
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
2,139
hlean
namespace sigma open lift open sigma.ops sigma variables {A : Type} {B : A → Type} variables {a₁ a₂ : A} {b₁ : B a₁} {b₂ : B a₂} definition dpair.inj (H : ⟨a₁, b₁⟩ = ⟨a₂, b₂⟩) : Σ (e₁ : a₁ = a₂), eq.rec b₁ e₁ = b₂ := down (sigma.no_confusion H (λ e₁ e₂, ⟨e₁, e₂⟩)) definition dpair.inj₁ (H : ⟨a₁, b₁⟩ = ⟨a₂, b₂⟩) : a₁ = a₂ := (dpair.inj H).1 definition dpair.inj₂ (H : ⟨a₁, b₁⟩ = ⟨a₂, b₂⟩) : eq.rec b₁ (dpair.inj₁ H) = b₂ := (dpair.inj H).2 end sigma structure foo := mk :: (A : Type) (B : A → Type) (a : A) (b : B a) set_option pp.implicit true namespace foo open lift sigma sigma.ops universe variables l₁ l₂ variables {A₁ : Type.{l₁}} {B₁ : A₁ → Type.{l₂}} {a₁ : A₁} {b₁ : B₁ a₁} variables {A₂ : Type.{l₁}} {B₂ : A₂ → Type.{l₂}} {a₂ : A₂} {b₂ : B₂ a₂} definition foo.inj (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : Σ (e₁ : A₁ = A₂) (e₂ : eq.rec B₁ e₁ = B₂) (e₃ : eq.rec a₁ e₁ = a₂), eq.rec (eq.rec (eq.rec b₁ e₁) e₂) e₃ = b₂ := down (foo.no_confusion H (λ e₁ e₂ e₃ e₄, ⟨e₁, e₂, e₃, e₄⟩)) definition foo.inj₁ (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : A₁ = A₂ := (foo.inj H).1 definition foo.inj₂ (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : eq.rec B₁ (foo.inj₁ H) = B₂ := (foo.inj H).2.1 definition foo.inj₃ (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : eq.rec a₁ (foo.inj₁ H) = a₂ := (foo.inj H).2.2.1 definition foo.inj₄ (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : eq.rec (eq.rec (eq.rec b₁ (foo.inj₁ H)) (foo.inj₂ H)) (foo.inj₃ H) = b₂ := (foo.inj H).2.2.2 definition foo.inj_inv (e₁ : A₁ = A₂) (e₂ : eq.rec B₁ e₁ = B₂) (e₃ : eq.rec a₁ e₁ = a₂) (e₄ : eq.rec (eq.rec (eq.rec b₁ e₁) e₂) e₃ = b₂) : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂ := eq.rec_on e₄ (eq.rec_on e₃ (eq.rec_on e₂ (eq.rec_on e₁ rfl))) end foo
9053be7a47a3300ab2bd0b0016b0cc8978b187d3
ebfc36a919e0b75a83886ec635f471d7f2dca171
/archive/2021/AoC/Day2.lean
c75375f380dc144057e12b1b63ca9fc89e56cdb5
[]
no_license
kaychaks/AoC
b933a125e2c55f632c7728eea841d827d1b5ef38
962cc536dda5156ac0b624f156146bf6d12ad8d2
refs/heads/master
1,671,715,037,914
1,671,632,408,000
1,671,632,408,000
160,005,656
0
0
null
null
null
null
UTF-8
Lean
false
false
2,640
lean
namespace Day2 inductive Command where | forward | up | down deriving Repr structure CommandWithVal where command: Command val: Nat structure Location where horizontal: Nat depth: Nat deriving Repr structure LocationEnhanced extends Location where aim: Nat deriving Repr namespace Location def default (h: Nat := 0) (d: Nat := 0) (a: Nat := 0): Location := {horizontal := h, depth := d} def locToString (l: Location): String := s!"\{horizontal: {l.horizontal}, depth: {l.depth} }" instance : ToString Location where toString := locToString end Location namespace LocationEnhanced def default (l: Location := Location.default) (a: Nat := 0): LocationEnhanced := { horizontal := l.horizontal, depth := l.depth, aim := a} end LocationEnhanced namespace Command def fromString (s:String): OptionM Command := match s with | "forward" => some forward | "up" => some up | "down" => some down | _ => none end Command namespace CommandWithVal def fromString (s:String): OptionM CommandWithVal := let xs := s.splitOn (fun x y => {command := x, val := y}) <$> (xs.head?.bind Command.fromString) <*> xs.getLast?.map String.toNat! def operation (loc: Location) (c: CommandWithVal): Location := match c.command with | Command.forward => { horizontal := loc.horizontal + c.val, depth := loc.depth } | Command.down => { horizontal := loc.horizontal, depth := loc.depth + c.val } | Command.up => { horizontal := loc.horizontal, depth := loc.depth - c.val } def operationEnhanced (loc: LocationEnhanced) (c: CommandWithVal): LocationEnhanced := match c.command with | Command.forward => { horizontal := loc.horizontal + c.val, depth := loc.depth + (loc.aim * c.val), aim := loc.aim } | Command.down => { horizontal := loc.horizontal, depth := loc.depth, aim := loc.aim + c.val } | Command.up => { horizontal := loc.horizontal, depth := loc.depth, aim := loc.aim - c.val } end CommandWithVal def commands (xs: Array String): Array CommandWithVal := xs.filterMap CommandWithVal.fromString def solvePart1 (xs: Array CommandWithVal): Nat := let loc := xs.foldl CommandWithVal.operation Location.default loc.horizontal * loc.depth def solvePart2 (xs: Array CommandWithVal): Nat := let loc := xs.foldl CommandWithVal.operationEnhanced LocationEnhanced.default loc.horizontal * loc.depth open IO.FS def run: IO Unit := do let day2 := "./data/day2.txt" let readings <- lines day2 let parsedCommands := commands readings let part1 := solvePart1 parsedCommands let part2 := solvePart2 parsedCommands IO.println (part1, part2) end Day2
0c7a0330500885a2b51cb3b7c9c09599e424b1e2
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/list/of_fn.lean
4040aed404721f29117f63bfb8d8c11f26edf624
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,082
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.basic import data.fin /-! # Lists from functions Theorems and lemmas for dealing with `list.of_fn`, which converts a function on `fin n` to a list of length `n`. ## Main Definitions The main definitions pertain to lists generated using `of_fn` - `list.length_of_fn`, which tells us the length of such a list - `list.nth_of_fn`, which tells us the nth element of such a list - `list.array_eq_of_fn`, which interprets the list form of an array as such a list. -/ universes u variables {α : Type u} open nat namespace list lemma 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 _ _) /-- The length of a list converted from a function is the size of the domain. -/ @[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) lemma 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, add_succ, succ_add] } end /-- The `n`th element of a list -/ @[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 (nat.le_add_left n i))]; refl theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) : nth_le (of_fn f) i ((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.is_lt] @[simp] theorem nth_le_of_fn' {n} (f : fin n → α) {i : ℕ} (h : i < (of_fn f).length) : nth_le (of_fn f) i h = f ⟨i, ((length_of_fn f) ▸ h)⟩ := nth_le_of_fn f ⟨i, ((length_of_fn f) ▸ h)⟩ @[simp] lemma map_of_fn {β : Type*} {n : ℕ} (f : fin n → α) (g : α → β) : map g (of_fn f) = of_fn (g ∘ f) := ext_le (by simp) (λ i h h', by simp) /-- Arrays converted to lists are the same as `of_fn` on the indexing function of the array. -/ 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 /-- `of_fn` on an empty domain is the empty list. -/ @[simp] theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl @[simp] 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 i.2) = l | [] := rfl | (a::l) := by { rw of_fn_succ, congr, simp only [fin.coe_succ], exact of_fn_nth_le l } -- not registered as a simp lemma, as otherwise it fires before `forall_mem_of_fn_iff` which -- is much more useful lemma mem_of_fn {n} (f : fin n → α) (a : α) : a ∈ of_fn f ↔ a ∈ set.range f := begin simp only [mem_iff_nth_le, set.mem_range, nth_le_of_fn'], exact ⟨λ ⟨i, hi, h⟩, ⟨_, h⟩, λ ⟨i, hi⟩, ⟨i.1, (length_of_fn f).symm ▸ i.2, by simpa using hi⟩⟩ end @[simp] lemma forall_mem_of_fn_iff {n : ℕ} {f : fin n → α} {P : α → Prop} : (∀ i ∈ of_fn f, P i) ↔ ∀ j : fin n, P (f j) := by simp only [mem_of_fn, set.forall_range_iff] @[simp] lemma of_fn_const (n : ℕ) (c : α) : of_fn (λ i : fin n, c) = repeat c n := nat.rec_on n (by simp) $ λ n ihn, by simp [ihn] end list
c7a6db1b2b015651e40c81200b2ff2170f0918a6
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/algebra/uniform_ring.lean
12ddd8bd7967e385c841d432a17f598a3cf576d9
[ "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
8,718
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 -/ import topology.algebra.group_completion import topology.algebra.ring /-! # Completion of topological rings: This files endows the completion of a topological ring with a ring structure. More precisely the instance `uniform_space.completion.ring` builds a ring structure on the completion of a ring endowed with a compatible uniform structure in the sense of `uniform_add_group`. There is also a commutative version when the original ring is commutative. The last part of the file builds a ring structure on the biggest separated quotient of a ring. ## Main declarations: Beyond the instances explained above (that don't have to be explicitly invoked), the main constructions deal with continuous ring morphisms. * `uniform_space.completion.extension_hom`: extends a continuous ring morphism from `R` to a complete separated group `S` to `completion R`. * `uniform_space.completion.map_ring_hom` : promotes a continuous ring morphism from `R` to `S` into a continuous ring morphism from `completion R` to `completion S`. -/ open classical set filter topological_space add_comm_group open_locale classical noncomputable theory universes u namespace uniform_space.completion open dense_inducing uniform_space function variables (α : Type*) [ring α] [uniform_space α] instance : has_one (completion α) := ⟨(1:α)⟩ instance : has_mul (completion α) := ⟨curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (coe ∘ uncurry (*))⟩ @[norm_cast] lemma coe_one : ((1 : α) : completion α) = 1 := rfl variables {α} [topological_ring α] @[norm_cast] lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b := ((dense_inducing_coe.prod dense_inducing_coe).extend_eq ((continuous_coe α).comp (@continuous_mul α _ _ _)) (a, b)).symm variables [uniform_add_group α] lemma continuous_mul : continuous (λ p : completion α × completion α, p.1 * p.2) := begin let m := (add_monoid_hom.mul : α →+ α →+ α).compr₂ to_compl, have : continuous (λ p : α × α, m p.1 p.2), from (continuous_coe α).comp continuous_mul, have di : dense_inducing (to_compl : α → completion α), from dense_inducing_coe, convert di.extend_Z_bilin di this, ext ⟨x, y⟩, refl end lemma continuous.mul {β : Type*} [topological_space β] {f g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) := continuous_mul.comp (hf.prod_mk hg : _) instance : ring (completion α) := { one_mul := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_const continuous_id) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, one_mul]), mul_one := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_id continuous_const) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, mul_one]), mul_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.mul continuous_fst (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]), left_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul continuous_fst (continuous.add (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))) (continuous.add (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]), right_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.add continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.add (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)) (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]), .. add_monoid_with_one.unary, ..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α } /-- The map from a uniform ring to its completion, as a ring homomorphism. -/ def coe_ring_hom : α →+* completion α := ⟨coe, coe_one α, assume a b, coe_mul a b, coe_zero, assume a b, coe_add a b⟩ lemma continuous_coe_ring_hom : continuous (coe_ring_hom : α → completion α) := continuous_coe α variables {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] (f : α →+* β) (hf : continuous f) /-- The completion extension as a ring morphism. -/ def extension_hom [complete_space β] [separated_space β] : completion α →+* β := have hf' : continuous (f : α →+ β), from hf, -- helping the elaborator have hf : uniform_continuous f, from uniform_continuous_add_monoid_hom_of_continuous hf', { to_fun := completion.extension f, map_zero' := by rw [← coe_zero, extension_coe hf, f.map_zero], map_add' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add) ((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, f.map_add]), map_one' := by rw [← coe_one, extension_coe hf, f.map_one], map_mul' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_mul) ((continuous_extension.comp continuous_fst).mul (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, f.map_mul]) } instance top_ring_compl : topological_ring (completion α) := { continuous_add := continuous_add, continuous_mul := continuous_mul } /-- The completion map as a ring morphism. -/ def map_ring_hom (hf : continuous f) : completion α →+* completion β := extension_hom (coe_ring_hom.comp f) (continuous_coe_ring_hom.comp hf) variables (R : Type*) [comm_ring R] [uniform_space R] [uniform_add_group R] [topological_ring R] instance : comm_ring (completion R) := { mul_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_fst.mul continuous_snd) (continuous_snd.mul continuous_fst)) (assume a b, by rw [← coe_mul, ← coe_mul, mul_comm]), ..completion.ring } end uniform_space.completion namespace uniform_space variables {α : Type*} lemma ring_sep_rel (α) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) := setoid.ext $ λ x y, (add_group_separation_rel x y).trans $ iff.trans (by refl) (submodule.quotient_rel_r_def _).symm lemma ring_sep_quot (α : Type u) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = (α ⧸ (⊥ : ideal α).closure) := by rw [@ring_sep_rel α r]; refl /-- Given a topological ring `α` equipped with a uniform structure that makes subtraction uniformly continuous, get an equivalence between the separated quotient of `α` and the quotient ring corresponding to the closure of zero. -/ def sep_quot_equiv_ring_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) ≃ (α ⧸ (⊥ : ideal α).closure) := quotient.congr_right $ λ x y, (add_group_separation_rel x y).trans $ iff.trans (by refl) (submodule.quotient_rel_r_def _).symm /- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/ instance comm_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : comm_ring (quotient (separation_setoid α)) := by rw ring_sep_quot α; apply_instance instance topological_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : topological_ring (quotient (separation_setoid α)) := begin convert topological_ring_quotient (⊥ : ideal α).closure; try {apply ring_sep_rel}, simp [uniform_space.comm_ring] end end uniform_space
16ae0b3438e7ffc574162107e40af9b303c9f326
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/adjunction/whiskering.lean
8238ecbf9a50e7a115119d8bb6b0442d149232b4
[ "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,496
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.whiskering import category_theory.adjunction.basic /-! Given categories `C D E`, functors `F : D ⥤ E` and `G : E ⥤ D` with an adjunction `F ⊣ G`, we provide the induced adjunction between the functor categories `C ⥤ D` and `C ⥤ E`, and the functor categories `E ⥤ C` and `D ⥤ C`. -/ namespace category_theory.adjunction open category_theory variables (C : Type*) {D E : Type*} [category C] [category D] [category E] {F : D ⥤ E} {G : E ⥤ D} -- `tidy` works for all the proofs in this definition, but it's fairly slow. /-- Given an adjunction `F ⊣ G`, this provides the natural adjunction `(whiskering_right C _ _).obj F ⊣ (whiskering_right C _ _).obj G`. -/ @[simps unit_app_app counit_app_app] protected def whisker_right (adj : F ⊣ G) : (whiskering_right C D E).obj F ⊣ (whiskering_right C E D).obj G := mk_of_unit_counit { unit := { app := λ X, (functor.right_unitor _).inv ≫ whisker_left X adj.unit ≫ (functor.associator _ _ _).inv, naturality' := by { intros, ext, dsimp, simp } }, counit := { app := λ X, (functor.associator _ _ _).hom ≫ whisker_left X adj.counit ≫ (functor.right_unitor _).hom, naturality' := by { intros, ext, dsimp, simp } }, left_triangle' := by { ext, dsimp, simp }, right_triangle' := by { ext, dsimp, simp } } -- `tidy` gets stuck for `left_triangle'` and `right_triangle'`. /-- Given an adjunction `F ⊣ G`, this provides the natural adjunction `(whiskering_left _ _ C).obj G ⊣ (whiskering_left _ _ C).obj F`. -/ @[simps unit_app_app counit_app_app] protected def whisker_left (adj : F ⊣ G) : (whiskering_left E D C).obj G ⊣ (whiskering_left D E C).obj F := mk_of_unit_counit { unit := { app := λ X, (functor.left_unitor _).inv ≫ whisker_right adj.unit X ≫ (functor.associator _ _ _).hom, naturality' := by { intros, ext, dsimp, simp } }, counit := { app := λ X, (functor.associator _ _ _).inv ≫ whisker_right adj.counit X ≫ (functor.left_unitor _).hom, naturality' := by { intros, ext, dsimp, simp } }, left_triangle' := by { ext x, dsimp, simp only [category.id_comp, category.comp_id, ← x.map_comp], simp }, right_triangle' := by { ext x, dsimp, simp only [category.id_comp, category.comp_id, ← x.map_comp], simp } } end category_theory.adjunction
8f34e0cae07fc9f8c31a8a20c007d5008f215f16
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/schur_zassenhaus.lean
58c68bd95b0b2374791eca300867e84e0c95a0ba
[ "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,768
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import group_theory.sylow import group_theory.transfer /-! # The Schur-Zassenhaus Theorem In this file we prove the Schur-Zassenhaus theorem. ## Main results - `exists_right_complement'_of_coprime` : The **Schur-Zassenhaus** theorem: If `H : subgroup G` is normal and has order coprime to its index, then there exists a subgroup `K` which is a (right) complement of `H`. - `exists_left_complement'_of_coprime` The **Schur-Zassenhaus** theorem: If `H : subgroup G` is normal and has order coprime to its index, then there exists a subgroup `K` which is a (left) complement of `H`. -/ open_locale big_operators namespace subgroup section schur_zassenhaus_abelian open mul_opposite mul_action subgroup.left_transversals mem_left_transversals variables {G : Type*} [group G] (H : subgroup G) [is_commutative H] [finite_index H] (α β : left_transversals (H : set G)) /-- The quotient of the transversals of an abelian normal `N` by the `diff` relation. -/ def quotient_diff := quotient (setoid.mk (λ α β, diff (monoid_hom.id H) α β = 1) ⟨λ α, diff_self (monoid_hom.id H) α, λ α β h, by rw [←diff_inv, h, inv_one], λ α β γ h h', by rw [←diff_mul_diff, h, h', one_mul]⟩) instance : inhabited H.quotient_diff := quotient.inhabited _ lemma smul_diff_smul' [hH : normal H] (g : Gᵐᵒᵖ) : diff (monoid_hom.id H) (g • α) (g • β) = ⟨g.unop⁻¹ * (diff (monoid_hom.id H) α β : H) * g.unop, hH.mem_comm ((congr_arg (∈ H) (mul_inv_cancel_left _ _)).mpr (set_like.coe_mem _))⟩ := begin letI := H.fintype_quotient_of_finite_index, let ϕ : H →* H := { to_fun := λ h, ⟨g.unop⁻¹ * h * g.unop, hH.mem_comm ((congr_arg (∈ H) (mul_inv_cancel_left _ _)).mpr (set_like.coe_mem _))⟩, map_one' := by rw [subtype.ext_iff, coe_mk, coe_one, mul_one, inv_mul_self], map_mul' := λ h₁ h₂, by rw [subtype.ext_iff, coe_mk, coe_mul, coe_mul, coe_mk, coe_mk, mul_assoc, mul_assoc, mul_assoc, mul_assoc, mul_assoc, mul_inv_cancel_left] }, refine eq.trans (finset.prod_bij' (λ q _, g⁻¹ • q) (λ q _, finset.mem_univ _) (λ q _, subtype.ext _) (λ q _, g • q) (λ q _, finset.mem_univ _) (λ q _, smul_inv_smul g q) (λ q _, inv_smul_smul g q)) (map_prod ϕ _ _).symm, simp_rw [monoid_hom.id_apply, monoid_hom.coe_mk, coe_mk, smul_apply_eq_smul_apply_inv_smul, smul_eq_mul_unop, mul_inv_rev, mul_assoc], end variables {H} [normal H] instance : mul_action G H.quotient_diff := { smul := λ g, quotient.map' (λ α, op g⁻¹ • α) (λ α β h, subtype.ext (by rwa [smul_diff_smul', coe_mk, coe_one, mul_eq_one_iff_eq_inv, mul_right_eq_self, ←coe_one, ←subtype.ext_iff])), mul_smul := λ g₁ g₂ q, quotient.induction_on' q (λ T, congr_arg quotient.mk' (by rw mul_inv_rev; exact mul_smul (op g₁⁻¹) (op g₂⁻¹) T)), one_smul := λ q, quotient.induction_on' q (λ T, congr_arg quotient.mk' (by rw inv_one; apply one_smul Gᵐᵒᵖ T)) } lemma smul_diff' (h : H) : diff (monoid_hom.id H) α ((op (h : G)) • β) = diff (monoid_hom.id H) α β * h ^ H.index := begin letI := H.fintype_quotient_of_finite_index, rw [diff, diff, index_eq_card, ←finset.card_univ, ←finset.prod_const, ←finset.prod_mul_distrib], refine finset.prod_congr rfl (λ q _, _), simp_rw [subtype.ext_iff, monoid_hom.id_apply, coe_mul, coe_mk, mul_assoc, mul_right_inj], rw [smul_apply_eq_smul_apply_inv_smul, smul_eq_mul_unop, unop_op, mul_left_inj, ←subtype.ext_iff, equiv.apply_eq_iff_eq, inv_smul_eq_iff], exact self_eq_mul_right.mpr ((quotient_group.eq_one_iff _).mpr h.2), end lemma eq_one_of_smul_eq_one (hH : nat.coprime (nat.card H) H.index) (α : H.quotient_diff) (h : H) : h • α = α → h = 1 := quotient.induction_on' α $ λ α hα, (pow_coprime hH).injective $ calc h ^ H.index = diff (monoid_hom.id H) ((op ((h⁻¹ : H) : G)) • α) α : by rw [←diff_inv, smul_diff', diff_self, one_mul, inv_pow, inv_inv] ... = 1 ^ H.index : (quotient.exact' hα).trans (one_pow H.index).symm lemma exists_smul_eq (hH : nat.coprime (nat.card H) H.index) (α β : H.quotient_diff) : ∃ h : H, h • α = β := quotient.induction_on' α (quotient.induction_on' β (λ β α, exists_imp_exists (λ n, quotient.sound') ⟨(pow_coprime hH).symm (diff (monoid_hom.id H) β α), (diff_inv _ _ _).symm.trans (inv_eq_one.mpr ((smul_diff' β α ((pow_coprime hH).symm (diff (monoid_hom.id H) β α))⁻¹).trans (by rw [inv_pow, ←pow_coprime_apply hH, equiv.apply_symm_apply, mul_inv_self])))⟩)) lemma is_complement'_stabilizer_of_coprime {α : H.quotient_diff} (hH : nat.coprime (nat.card H) H.index) : is_complement' H (stabilizer G α) := is_complement'_stabilizer α (eq_one_of_smul_eq_one hH α) (λ g, exists_smul_eq hH (g • α) α) /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ private lemma exists_right_complement'_of_coprime_aux (hH : nat.coprime (nat.card H) H.index) : ∃ K : subgroup G, is_complement' H K := nonempty_of_inhabited.elim (λ α, ⟨stabilizer G α, is_complement'_stabilizer_of_coprime hH⟩) end schur_zassenhaus_abelian open_locale classical universe u namespace schur_zassenhaus_induction /-! ## Proof of the Schur-Zassenhaus theorem In this section, we prove the Schur-Zassenhaus theorem. The proof is by contradiction. We assume that `G` is a minimal counterexample to the theorem. -/ variables {G : Type u} [group G] [fintype G] {N : subgroup G} [normal N] (h1 : nat.coprime (fintype.card N) N.index) (h2 : ∀ (G' : Type u) [group G'] [fintype G'], by exactI ∀ (hG'3 : fintype.card G' < fintype.card G) {N' : subgroup G'} [N'.normal] (hN : nat.coprime (fintype.card N') N'.index), ∃ H' : subgroup G', is_complement' N' H') (h3 : ∀ H : subgroup G, ¬ is_complement' N H) include h1 h2 h3 /-! We will arrive at a contradiction via the following steps: * step 0: `N` (the normal Hall subgroup) is nontrivial. * step 1: If `K` is a subgroup of `G` with `K ⊔ N = ⊤`, then `K = ⊤`. * step 2: `N` is a minimal normal subgroup, phrased in terms of subgroups of `G`. * step 3: `N` is a minimal normal subgroup, phrased in terms of subgroups of `N`. * step 4: `p` (`min_fact (fintype.card N)`) is prime (follows from step0). * step 5: `P` (a Sylow `p`-subgroup of `N`) is nontrivial. * step 6: `N` is a `p`-group (applies step 1 to the normalizer of `P` in `G`). * step 7: `N` is abelian (applies step 3 to the center of `N`). -/ /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ @[nolint unused_arguments] private lemma step0 : N ≠ ⊥ := begin unfreezingI { rintro rfl }, exact h3 ⊤ is_complement'_bot_top, end /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ private lemma step1 (K : subgroup G) (hK : K ⊔ N = ⊤) : K = ⊤ := begin contrapose! h3, have h4 : (N.comap K.subtype).index = N.index, { rw [←N.relindex_top_right, ←hK], exact (relindex_sup_right K N).symm }, have h5 : fintype.card K < fintype.card G, { rw ← K.index_mul_card, exact lt_mul_of_one_lt_left fintype.card_pos (one_lt_index_of_ne_top h3) }, have h6 : nat.coprime (fintype.card (N.comap K.subtype)) (N.comap K.subtype).index, { rw h4, exact h1.coprime_dvd_left (card_comap_dvd_of_injective N K.subtype subtype.coe_injective) }, obtain ⟨H, hH⟩ := h2 K h5 h6, replace hH : fintype.card (H.map K.subtype) = N.index := ((set.card_image_of_injective _ subtype.coe_injective).trans (mul_left_injective₀ fintype.card_ne_zero (hH.symm.card_mul.trans (N.comap K.subtype).index_mul_card.symm))).trans h4, have h7 : fintype.card N * fintype.card (H.map K.subtype) = fintype.card G, { rw [hH, ←N.index_mul_card, mul_comm] }, have h8 : (fintype.card N).coprime (fintype.card (H.map K.subtype)), { rwa hH }, exact ⟨H.map K.subtype, is_complement'_of_coprime h7 h8⟩, end /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ private lemma step2 (K : subgroup G) [K.normal] (hK : K ≤ N) : K = ⊥ ∨ K = N := begin have : function.surjective (quotient_group.mk' K) := quotient.surjective_quotient_mk', have h4 := step1 h1 h2 h3, contrapose! h4, have h5 : fintype.card (G ⧸ K) < fintype.card G, { rw [←index_eq_card, ←K.index_mul_card], refine lt_mul_of_one_lt_right (nat.pos_of_ne_zero index_ne_zero_of_finite) (K.one_lt_card_iff_ne_bot.mpr h4.1) }, have h6 : nat.coprime (fintype.card (N.map (quotient_group.mk' K))) (N.map (quotient_group.mk' K)).index, { have index_map := N.index_map_eq this (by rwa quotient_group.ker_mk), have index_pos : 0 < N.index := nat.pos_of_ne_zero index_ne_zero_of_finite, rw index_map, refine h1.coprime_dvd_left _, rw [←nat.mul_dvd_mul_iff_left index_pos, index_mul_card, ←index_map, index_mul_card], exact K.card_quotient_dvd_card }, obtain ⟨H, hH⟩ := h2 (G ⧸ K) h5 h6, refine ⟨H.comap (quotient_group.mk' K), _, _⟩, { have key : (N.map (quotient_group.mk' K)).comap (quotient_group.mk' K) = N, { refine comap_map_eq_self _, rwa quotient_group.ker_mk }, rwa [←key, comap_sup_eq, hH.symm.sup_eq_top, comap_top] }, { rw ← comap_top (quotient_group.mk' K), intro hH', rw [comap_injective this hH', is_complement'_top_right, map_eq_bot_iff, quotient_group.ker_mk] at hH, { exact h4.2 (le_antisymm hK hH) } }, end /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ private lemma step3 (K : subgroup N) [(K.map N.subtype).normal] : K = ⊥ ∨ K = ⊤ := begin have key := step2 h1 h2 h3 (K.map N.subtype) K.map_subtype_le, rw ← map_bot N.subtype at key, conv at key { congr, skip, to_rhs, rw [←N.subtype_range, N.subtype.range_eq_map] }, have inj := map_injective N.subtype_injective, rwa [inj.eq_iff, inj.eq_iff] at key, end /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ private lemma step4 : (fintype.card N).min_fac.prime := (nat.min_fac_prime (N.one_lt_card_iff_ne_bot.mpr (step0 h1 h2 h3)).ne') /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ private lemma step5 {P : sylow (fintype.card N).min_fac N} : P.1 ≠ ⊥ := begin haveI : fact ((fintype.card N).min_fac.prime) := ⟨step4 h1 h2 h3⟩, exact P.ne_bot_of_dvd_card (fintype.card N).min_fac_dvd, end /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ private lemma step6 : is_p_group (fintype.card N).min_fac N := begin haveI : fact ((fintype.card N).min_fac.prime) := ⟨step4 h1 h2 h3⟩, refine sylow.nonempty.elim (λ P, P.2.of_surjective P.1.subtype _), rw [←monoid_hom.range_top_iff_surjective, subtype_range], haveI : (P.1.map N.subtype).normal := normalizer_eq_top.mp (step1 h1 h2 h3 (P.1.map N.subtype).normalizer P.normalizer_sup_eq_top), exact (step3 h1 h2 h3 P.1).resolve_left (step5 h1 h2 h3), end /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ lemma step7 : is_commutative N := begin haveI := N.bot_or_nontrivial.resolve_left (step0 h1 h2 h3), haveI : fact ((fintype.card N).min_fac.prime) := ⟨step4 h1 h2 h3⟩, exact ⟨⟨λ g h, eq_top_iff.mp ((step3 h1 h2 h3 N.center).resolve_left (step6 h1 h2 h3).bot_lt_center.ne') (mem_top h) g⟩⟩, end end schur_zassenhaus_induction variables {n : ℕ} {G : Type u} [group G] /-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/ private lemma exists_right_complement'_of_coprime_aux' [fintype G] (hG : fintype.card G = n) {N : subgroup G} [N.normal] (hN : nat.coprime (fintype.card N) N.index) : ∃ H : subgroup G, is_complement' N H := begin unfreezingI { revert G }, apply nat.strong_induction_on n, rintros n ih G _ _ rfl N _ hN, refine not_forall_not.mp (λ h3, _), haveI := by exactI schur_zassenhaus_induction.step7 hN (λ G' _ _ hG', by { apply ih _ hG', refl }) h3, rw ← nat.card_eq_fintype_card at hN, exact not_exists_of_forall_not h3 (exists_right_complement'_of_coprime_aux hN), end /-- **Schur-Zassenhaus** for normal subgroups: If `H : subgroup G` is normal, and has order coprime to its index, then there exists a subgroup `K` which is a (right) complement of `H`. -/ theorem exists_right_complement'_of_coprime_of_fintype [fintype G] {N : subgroup G} [N.normal] (hN : nat.coprime (fintype.card N) N.index) : ∃ H : subgroup G, is_complement' N H := exists_right_complement'_of_coprime_aux' rfl hN /-- **Schur-Zassenhaus** for normal subgroups: If `H : subgroup G` is normal, and has order coprime to its index, then there exists a subgroup `K` which is a (right) complement of `H`. -/ theorem exists_right_complement'_of_coprime {N : subgroup G} [N.normal] (hN : nat.coprime (nat.card N) N.index) : ∃ H : subgroup G, is_complement' N H := begin by_cases hN1 : nat.card N = 0, { rw [hN1, nat.coprime_zero_left, index_eq_one] at hN, rw hN, exact ⟨⊥, is_complement'_top_bot⟩ }, by_cases hN2 : N.index = 0, { rw [hN2, nat.coprime_zero_right] at hN, haveI := (cardinal.to_nat_eq_one_iff_unique.mp hN).1, rw N.eq_bot_of_subsingleton, exact ⟨⊤, is_complement'_bot_top⟩ }, have hN3 : nat.card G ≠ 0, { rw ← N.card_mul_index, exact mul_ne_zero hN1 hN2 }, haveI := (cardinal.lt_aleph_0_iff_fintype.mp (lt_of_not_ge (mt cardinal.to_nat_apply_of_aleph_0_le hN3))).some, rw nat.card_eq_fintype_card at hN, exact exists_right_complement'_of_coprime_of_fintype hN, end /-- **Schur-Zassenhaus** for normal subgroups: If `H : subgroup G` is normal, and has order coprime to its index, then there exists a subgroup `K` which is a (left) complement of `H`. -/ theorem exists_left_complement'_of_coprime_of_fintype [fintype G] {N : subgroup G} [N.normal] (hN : nat.coprime (fintype.card N) N.index) : ∃ H : subgroup G, is_complement' H N := Exists.imp (λ _, is_complement'.symm) (exists_right_complement'_of_coprime_of_fintype hN) /-- **Schur-Zassenhaus** for normal subgroups: If `H : subgroup G` is normal, and has order coprime to its index, then there exists a subgroup `K` which is a (left) complement of `H`. -/ theorem exists_left_complement'_of_coprime {N : subgroup G} [N.normal] (hN : nat.coprime (nat.card N) N.index) : ∃ H : subgroup G, is_complement' H N := Exists.imp (λ _, is_complement'.symm) (exists_right_complement'_of_coprime hN) end subgroup
b19304046c02015b3f68395c2d92c0090bcadc17
bd12a817ba941113eb7fdb7ddf0979d9ed9386a0
/src/category_theory/products/associator.lean
a5bcd72d9ccb0e0aae6073d0953a3207a24b48e7
[ "Apache-2.0" ]
permissive
flypitch/mathlib
563d9c3356c2885eb6cefaa704d8d86b89b74b15
70cd00bc20ad304f2ac0886b2291b44261787607
refs/heads/master
1,590,167,818,658
1,557,762,121,000
1,557,762,121,000
186,450,076
0
0
Apache-2.0
1,557,762,289,000
1,557,762,288,000
null
UTF-8
Lean
false
false
1,653
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.products import category_theory.equivalence import category_theory.eq_to_hom universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory namespace category_theory.prod variables (C : Type u₁) [𝒞 : category.{v₁+1} C] (D : Type u₂) [𝒟 : category.{v₂+1} D] include 𝒞 𝒟 variables (E : Type u₃) [ℰ : category.{v₃+1} E] include ℰ def associator : ((C × D) × E) ⥤ (C × (D × E)) := { obj := λ X, (X.1.1, (X.1.2, X.2)), map := λ _ _ f, (f.1.1, (f.1.2, f.2)) } @[simp] lemma associator_obj (X) : (associator C D E).obj X = (X.1.1, (X.1.2, X.2)) := rfl @[simp] lemma associator_map {X Y} (f : X ⟶ Y) : (associator C D E).map f = (f.1.1, (f.1.2, f.2)) := rfl def inverse_associator : (C × (D × E)) ⥤ ((C × D) × E) := { obj := λ X, ((X.1, X.2.1), X.2.2), map := λ _ _ f, ((f.1, f.2.1), f.2.2) } @[simp] lemma inverse_associator_obj (X) : (inverse_associator C D E).obj X = ((X.1, X.2.1), X.2.2) := rfl @[simp] lemma inverse_associator_map {X Y} (f : X ⟶ Y) : (inverse_associator C D E).map f = ((f.1, f.2.1), f.2.2) := rfl def associativity : equivalence ((C × D) × E) (C × (D × E)) := { functor := associator C D E, inverse := inverse_associator C D E, fun_inv_id' := nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy), inv_fun_id' := nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy) } -- TODO pentagon natural transformation? ...satisfying? end category_theory.prod
38ba6f09a7e5a9d27322baa76c34c64c3229f931
b147e1312077cdcfea8e6756207b3fa538982e12
/linear_algebra/multivariate_polynomial.lean
db713e74fc8ff9fef2a8bc8fdfefed4af1483f4e
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,986
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 Multivariate Polynomial -/ import data.finsupp linear_algebra.basic algebra.ring open set function finsupp lattice universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Multivariate polynomial, where `σ` is the index set of the variables and `α` is the coefficient ring -/ def mv_polynomial (σ : Type*) (α : Type*) [comm_semiring α] := (σ →₀ ℕ) →₀ α namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} variables [decidable_eq σ] [decidable_eq α] section comm_semiring variables [comm_semiring α] {p q : mv_polynomial σ α} instance : has_zero (mv_polynomial σ α) := finsupp.has_zero instance : has_one (mv_polynomial σ α) := finsupp.has_one instance : has_add (mv_polynomial σ α) := finsupp.has_add instance : has_mul (mv_polynomial σ α) := finsupp.has_mul instance : comm_semiring (mv_polynomial σ α) := finsupp.to_comm_semiring /-- `monomial s a` is the monomial `a * X^s` -/ def monomial (s : σ →₀ ℕ) (a : α) : mv_polynomial σ α := single s a /-- `C a` is the constant polynomial with value `a` -/ def C (a : α) : mv_polynomial σ α := monomial 0 a /-- `X n` is the polynomial with value X_n -/ def X (n : σ) : mv_polynomial σ α := monomial (single n 1) 1 @[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ α) := by simp [C, monomial]; refl @[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ α) := rfl @[simp] lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by simp [C, monomial, single_mul_single] lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : α) := begin induction e, { simp [X], refl }, { simp [pow_succ, e_ih], simp [X, monomial, single_mul_single, nat.succ_eq_add_one] } end lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e):= by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a):= by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ α) := begin apply @finsupp.induction σ ℕ _ _ _ _ s, { simp [C, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, simp [prod_add_index, prod_single_index, pow_zero, pow_add, (mul_assoc _ _ _).symm, ih.symm, monomial_add_single] } end @[recursor 7] lemma induction_on {M : mv_polynomial σ α → Prop} (p : mv_polynomial σ α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) : M p := have ∀s a, M (monomial s a), begin assume s a, apply @finsupp.induction σ ℕ _ _ _ _ s, { show M (monomial 0 a), from h_C a, }, { assume n e p hpn he ih, have : ∀e:ℕ, M (monomial p a * X n ^ e), { intro e, induction e, { simp [ih] }, { simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } }, simp [monomial_add_single, this] } end, finsupp.induction p (by have : M (C 0) := h_C 0; rwa [C_0] at this) (assume s a p hsp ha hp, h_add _ _ (this s a) hp) section eval variables {f : σ → α} /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval (f : σ → α) (p : mv_polynomial σ α) : α := p.sum (λs a, a * s.prod (λn e, f n ^ e)) @[simp] lemma eval_zero : (0 : mv_polynomial σ α).eval f = 0 := finsupp.sum_zero_index lemma eval_add : (p + q).eval f = p.eval f + q.eval f := finsupp.sum_add_index (by simp) (by simp [add_mul]) lemma eval_monomial : (monomial s a).eval f = a * s.prod (λn e, f n ^ e) := finsupp.sum_single_index (zero_mul _) @[simp] lemma eval_C : (C a).eval f = a := by simp [eval_monomial, C, prod_zero_index] @[simp] lemma eval_X : (X n).eval f = f n := by simp [eval_monomial, X, prod_single_index, pow_one] lemma eval_mul_monomial : ∀{s a}, (p * monomial s a).eval f = p.eval f * a * s.prod (λn e, f n ^ e) := begin apply mv_polynomial.induction_on p, { assume a' s a, by simp [C_mul_monomial, eval_monomial] }, { assume p q ih_p ih_q, simp [add_mul, eval_add, ih_p, ih_q] }, { assume p n ih s a, from calc (p * X n * monomial s a).eval f = (p * monomial (single n 1 + s) a).eval f : by simp [monomial_single_add, -add_comm, pow_one, mul_assoc] ... = (p * monomial (single n 1) 1).eval f * a * s.prod (λn e, f n ^ e) : by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm, -add_comm] } end lemma eval_mul : ∀{p}, (p * q).eval f = p.eval f * q.eval f := begin apply mv_polynomial.induction_on q, { simp [C, eval_monomial, eval_mul_monomial, prod_zero_index] }, { simp [mul_add, eval_add] {contextual := tt} }, { simp [X, eval_monomial, eval_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} } end end eval section vars /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars (p : mv_polynomial σ α) : finset σ := p.support.bind finsupp.support @[simp] lemma vars_0 : (0 : mv_polynomial σ α).vars = ∅ := show (0 : (σ →₀ ℕ) →₀ α).support.bind finsupp.support = ∅, by simp @[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support := show (single s a : (σ →₀ ℕ) →₀ α).support.bind finsupp.support = s.support, by simp [support_single_ne_zero, h] @[simp] lemma vars_C : (C a : mv_polynomial σ α).vars = ∅ := decidable.by_cases (assume h : a = 0, by simp [h]) (assume h : a ≠ 0, by simp [C, h]) @[simp] lemma vars_X (h : 0 ≠ (1 : α)) : (X n : mv_polynomial σ α).vars = {n} := calc (X n : mv_polynomial σ α).vars = (single n 1).support : vars_monomial h.symm ... = {n} : by rw [support_single_ne_zero nat.zero_ne_one.symm] end vars section degree_of /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of (n : σ) (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s n) end degree_of section total_degree /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s.sum $ λn e, e) end total_degree end comm_semiring section comm_ring variable [comm_ring α] instance : ring (mv_polynomial σ α) := finsupp.to_ring instance : has_scalar α (mv_polynomial σ α) := finsupp.to_has_scalar instance : module α (mv_polynomial σ α) := finsupp.to_module instance {f : σ → α} : is_ring_hom (eval f) := ⟨λ x y, eval_add, λ x y, eval_mul, eval_C⟩ -- `mv_polynomial σ` is a functor (incomplete) definition functorial [decidable_eq β] [comm_ring β] (i : α → β) [is_ring_hom i] : mv_polynomial σ α → mv_polynomial σ β := map_range i (is_ring_hom.map_zero i) end comm_ring end mv_polynomial
ecf4e83237cd6178244d7d0c48da788e661fe62a
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/adjunction/reflective.lean
f2d01f82e680a55062441bf1463272c78c879b0a
[ "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
4,311
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.preserves.shapes.binary_products import category_theory.limits.preserves.shapes.terminal import category_theory.adjunction.fully_faithful /-! # Reflective functors Basic properties of reflective functors, especially those relating to their essential image. Note properties of reflective functors relating to limits and colimits are included in `category_theory.monad.limits`. -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open limits category variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₂} D] /-- A functor is *reflective*, or *a reflective inclusion*, if it is fully faithful and right adjoint. -/ class reflective (R : D ⥤ C) extends is_right_adjoint R, full R, faithful R. variables {i : D ⥤ C} /-- For a reflective functor `i` (with left adjoint `L`), with unit `η`, we have `η_iL = iL η`. -/ -- TODO: This holds more generally for idempotent adjunctions, not just reflective adjunctions. lemma unit_obj_eq_map_unit [reflective i] (X : C) : (adjunction.of_right_adjoint i).unit.app (i.obj ((left_adjoint i).obj X)) = i.map ((left_adjoint i).map ((adjunction.of_right_adjoint i).unit.app X)) := begin rw [←cancel_mono (i.map ((adjunction.of_right_adjoint i).counit.app ((left_adjoint i).obj X))), ←i.map_comp], simp, end /-- When restricted to objects in `D` given by `i : D ⥤ C`, the unit is an isomorphism. In other words, `η_iX` is an isomorphism for any `X` in `D`. More generally this applies to objects essentially in the reflective subcategory, see `functor.ess_image.unit_iso`. -/ instance is_iso_unit_obj [reflective i] {B : D} : is_iso ((adjunction.of_right_adjoint i).unit.app (i.obj B)) := begin have : (adjunction.of_right_adjoint i).unit.app (i.obj B) = inv (i.map ((adjunction.of_right_adjoint i).counit.app B)), { rw ← comp_hom_eq_id, apply (adjunction.of_right_adjoint i).right_triangle_components }, rw this, exact is_iso.inv_is_iso, end /-- If `A` is essentially in the image of a reflective functor `i`, then `η_A` is an isomorphism. This gives that the "witness" for `A` being in the essential image can instead be given as the reflection of `A`, with the isomorphism as `η_A`. (For any `B` in the reflective subcategory, we automatically have that `ε_B` is an iso.) -/ def functor.ess_image.unit_is_iso [reflective i] {A : C} (h : A ∈ i.ess_image) : is_iso ((adjunction.of_right_adjoint i).unit.app A) := begin suffices : (adjunction.of_right_adjoint i).unit.app A = h.get_iso.inv ≫ (adjunction.of_right_adjoint i).unit.app (i.obj h.witness) ≫ (left_adjoint i ⋙ i).map h.get_iso.hom, { rw this, apply_instance }, rw ← nat_trans.naturality, simp, end /-- If `η_A` is an isomorphism, then `A` is in the essential image of `i`. -/ lemma mem_ess_image_of_unit_is_iso [is_right_adjoint i] (A : C) [is_iso ((adjunction.of_right_adjoint i).unit.app A)] : A ∈ i.ess_image := ⟨(left_adjoint i).obj A, ⟨(as_iso ((adjunction.of_right_adjoint i).unit.app A)).symm⟩⟩ /-- If `η_A` is a split monomorphism, then `A` is in the reflective subcategory. -/ lemma mem_ess_image_of_unit_split_mono [reflective i] {A : C} [split_mono ((adjunction.of_right_adjoint i).unit.app A)] : A ∈ i.ess_image := begin let η : 𝟭 C ⟶ left_adjoint i ⋙ i := (adjunction.of_right_adjoint i).unit, haveI : is_iso (η.app (i.obj ((left_adjoint i).obj A))) := (i.obj_mem_ess_image _).unit_is_iso, have : epi (η.app A), { apply epi_of_epi (retraction (η.app A)) _, rw (show retraction _ ≫ η.app A = _, from η.naturality (retraction (η.app A))), apply epi_comp (η.app (i.obj ((left_adjoint i).obj A))) }, resetI, haveI := is_iso_of_epi_of_split_mono (η.app A), exact mem_ess_image_of_unit_is_iso A, end universes v₃ u₃ variables {E : Type u₃} [category.{v₃} E] /-- Composition of reflective functors. -/ instance reflective.comp (F : C ⥤ D) (G : D ⥤ E) [Fr : reflective F] [Gr : reflective G] : reflective (F ⋙ G) := { to_faithful := faithful.comp F G, } end category_theory
12f07aa27f6956d9aad4aaffd05afd5655b6865d
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/ind1.lean
cc19630514ab71cf3d8b4d77c5e823feae4405b2
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
163
lean
inductive List (A : Sort*) : Sort* | nil : List | cons : A → List → List namespace List end List open List check List.{1} check cons.{1} check List.rec.{1 1}
dd54097ab2c25de74a2d060dc6fc0971cb28cede
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean/Elab/Alias.lean
bac3ab4f0a677a3d9a55261fd0e026a51972658f
[ "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
1,261
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Environment namespace Lean /- We use aliases to implement the `export <id> (<id>+)` command. -/ abbrev AliasState := SMap Name (List Name) abbrev AliasEntry := Name × Name def addAliasEntry (s : AliasState) (e : AliasEntry) : AliasState := match s.find? e.1 with | none => s.insert e.1 [e.2] | some es => if es.elem e.2 then s else s.insert e.1 (e.2 :: es) def mkAliasExtension : IO (SimplePersistentEnvExtension AliasEntry AliasState) := registerSimplePersistentEnvExtension { name := `aliasesExt, addEntryFn := addAliasEntry, addImportedFn := fun es => (mkStateFromImportedEntries addAliasEntry {} es).switch } @[init mkAliasExtension] constant aliasExtension : SimplePersistentEnvExtension AliasEntry AliasState := arbitrary _ /- Add alias `a` for `e` -/ @[export lean_add_alias] def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) def getAliases (env : Environment) (a : Name) : List Name := match (aliasExtension.getState env).find? a with | none => [] | some es => es end Lean
91fcb73e0c0db6e9a45fbf0636cbd2354cf96545
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/geo/src/types.lean
07db897a511f4f3a971520c6cdda0c2e876eb719
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
3,567
lean
import category_theory.limits.shapes import category_theory.limits.types import category_theory.types import pullbacks import subobject_classifier import locally_cartesian_closed universes v v₂ u /-! # Types Show that Type has a subobject classifier (assuming choice). -/ open category_theory category_theory.category category_theory.limits instance types_has_pullbacks: has_pullbacks.{u} (Type u) := ⟨limits.has_limits_of_shape_of_has_limits⟩ lemma set_classifier {U X : Type} {f : U ⟶ X} {χ₁ : X ⟶ Prop} (q : @classifying _ category_theory.types _ unit _ _ (λ _, true) f χ₁) : ∀ x, χ₁ x ↔ ∃ a, f a = x := begin obtain ⟨ka, la, ma⟩ := q, intro x, split, intro, have: ((𝟙 _ : unit ⟶ unit) ≫ λ (_ : unit), true) = (λ (_ : unit), x) ≫ χ₁, ext y, simp, show true ↔ χ₁ x, simpa, set new_cone := pullback_cone.mk (𝟙 unit) (λ _, x) this, set g := ma.lift new_cone, use g (), have := ma.fac new_cone walking_cospan.right, simp at this, have := congr_fun this (), simp at this, exact this, rintro ⟨t, rfl⟩, have := congr_fun la t, simp at this, exact this, end -- -- TODO: can we make this computable? noncomputable instance types_has_subobj_classifier : @has_subobject_classifier Type category_theory.types := { Ω := Prop, Ω₀ := unit, truth := λ _, true, truth_mono' := ⟨λ A f g _, begin ext i, apply subsingleton.elim end⟩, classifier_of := λ A B f mon, λ b, ∃ (a : A), f a = b, classifies' := begin intros A B f mon, refine {k := λ _, (), commutes := _, forms_pullback' := _}, funext, simp, use x, refine ⟨λ c i, _, _, _⟩, show A, have: pullback_cone.fst c ≫ _ = pullback_cone.snd c ≫ _ := pullback_cone.condition c, have: (pullback_cone.snd c ≫ (λ (b : B), ∃ (a : A), f a = b)) i, rw ← this, dsimp, trivial, dsimp at this, exact classical.some this_1, intros c, apply pi_app_left, ext, apply subsingleton.elim, ext, dunfold pullback_cone.snd pullback_cone.mk, simp, have: (pullback_cone.snd c ≫ (λ (b : B), ∃ (a : A), f a = b)) x, rw ← pullback_cone.condition c, trivial, apply classical.some_spec this, intros c m J, resetI, rw ← cancel_mono f, ext, simp, have: (pullback_cone.snd c ≫ (λ (b : B), ∃ (a : A), f a = b)) x, rw ← pullback_cone.condition c, trivial, erw classical.some_spec this, simp at J, have Jl := congr_fun (J walking_cospan.right) x, simp at Jl, exact Jl, end, uniquely' := begin introv _ fst, ext x, rw set_classifier fst x end } @[simps] def currying_equiv (A X Y : Type u) : ((prodinl A).obj X ⟶ Y) ≃ (X ⟶ A → Y) := { to_fun := λ f b a, begin refine f ⟨λ j, walking_pair.cases_on j a b, λ j₁ j₂, _⟩, rintros ⟨⟨rfl⟩⟩, refl end, inv_fun := λ g ab, g (ab.1 walking_pair.right) (ab.1 walking_pair.left), left_inv := λ f, by { ext ⟨ba⟩, dsimp, congr, ext ⟨j⟩, simp }, right_inv := λ _, rfl } instance type_exponentials (A : Type u) : exponentiable A := { exponentiable := { right := adjunction.right_adjoint_of_equiv (currying_equiv _) ( begin intros X X' Y f g, ext, dsimp [currying_equiv], congr, show lim.map (@map_pair (Type u) _ _ _ _ _ id f) _ = _, rw types.types_limit_map, congr, ext ⟨j⟩, simp, simp end), adj := adjunction.adjunction_of_equiv_right _ _ } } instance type_cc : is_cartesian_closed (Type u) := begin split, intro A, apply_instance end
f208be6c378e683237cd06613752948cb7501ace
94e33a31faa76775069b071adea97e86e218a8ee
/src/number_theory/divisors.lean
edfb0e5ced1eb3d42728e11f715acea1e30159cd
[ "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
16,001
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.order import data.nat.interval import data.nat.prime /-! # Divisor finsets This file defines sets of divisors of a natural number. This is particularly useful as background for defining Dirichlet convolution. ## Main Definitions Let `n : ℕ`. All of the following definitions are in the `nat` namespace: * `divisors n` is the `finset` of natural numbers that divide `n`. * `proper_divisors n` is the `finset` of natural numbers that divide `n`, other than `n`. * `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. * `perfect n` is true when `n` is positive and the sum of `proper_divisors n` is `n`. ## Implementation details * `divisors 0`, `proper_divisors 0`, and `divisors_antidiagonal 0` are defined to be `∅`. ## Tags divisors, perfect numbers -/ open_locale classical open_locale big_operators open finset namespace nat variable (n : ℕ) /-- `divisors n` is the `finset` of divisors of `n`. As a special case, `divisors 0 = ∅`. -/ def divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.Ico 1 (n + 1)) /-- `proper_divisors n` is the `finset` of divisors of `n`, other than `n`. As a special case, `proper_divisors 0 = ∅`. -/ def proper_divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.Ico 1 n) /-- `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. As a special case, `divisors_antidiagonal 0 = ∅`. -/ def divisors_antidiagonal : finset (ℕ × ℕ) := ((finset.Ico 1 (n + 1)).product (finset.Ico 1 (n + 1))).filter (λ x, x.fst * x.snd = n) variable {n} @[simp] lemma filter_dvd_eq_divisors (h : n ≠ 0) : (finset.range n.succ).filter (∣ n) = n.divisors := begin ext, simp only [divisors, mem_filter, mem_range, mem_Ico, and.congr_left_iff, iff_and_self], exact λ ha _, succ_le_iff.mpr (pos_of_dvd_of_pos ha h.bot_lt), end @[simp] lemma filter_dvd_eq_proper_divisors (h : n ≠ 0) : (finset.range n).filter (∣ n) = n.proper_divisors := begin ext, simp only [proper_divisors, mem_filter, mem_range, mem_Ico, and.congr_left_iff, iff_and_self], exact λ ha _, succ_le_iff.mpr (pos_of_dvd_of_pos ha h.bot_lt), end lemma proper_divisors.not_self_mem : ¬ n ∈ proper_divisors n := by simp [proper_divisors] @[simp] lemma mem_proper_divisors {m : ℕ} : n ∈ proper_divisors m ↔ n ∣ m ∧ n < m := begin rcases eq_or_ne m 0 with rfl | hm, { simp [proper_divisors] }, simp only [and_comm, ←filter_dvd_eq_proper_divisors hm, mem_filter, mem_range], end lemma divisors_eq_proper_divisors_insert_self_of_pos (h : 0 < n): divisors n = has_insert.insert n (proper_divisors n) := by rw [divisors, proper_divisors, Ico_succ_right_eq_insert_Ico h, finset.filter_insert, if_pos (dvd_refl n)] @[simp] lemma mem_divisors {m : ℕ} : n ∈ divisors m ↔ (n ∣ m ∧ m ≠ 0) := begin rcases eq_or_ne m 0 with rfl | hm, { simp [divisors] }, simp only [hm, ne.def, not_false_iff, and_true, ←filter_dvd_eq_divisors hm, mem_filter, mem_range, and_iff_right_iff_imp, lt_succ_iff], exact le_of_dvd hm.bot_lt, end lemma mem_divisors_self (n : ℕ) (h : n ≠ 0) : n ∈ n.divisors := mem_divisors.2 ⟨dvd_rfl, h⟩ lemma dvd_of_mem_divisors {m : ℕ} (h : n ∈ divisors m) : n ∣ m := begin cases m, { apply dvd_zero }, { simp [mem_divisors.1 h], } end @[simp] lemma mem_divisors_antidiagonal {x : ℕ × ℕ} : x ∈ divisors_antidiagonal n ↔ x.fst * x.snd = n ∧ n ≠ 0 := begin simp only [divisors_antidiagonal, finset.mem_Ico, ne.def, finset.mem_filter, finset.mem_product], rw and_comm, apply and_congr_right, rintro rfl, split; intro h, { contrapose! h, simp [h], }, { rw [nat.lt_add_one_iff, nat.lt_add_one_iff], rw [mul_eq_zero, decidable.not_or_iff_and_not] at h, simp only [succ_le_of_lt (nat.pos_of_ne_zero h.1), succ_le_of_lt (nat.pos_of_ne_zero h.2), true_and], exact ⟨le_mul_of_pos_right (nat.pos_of_ne_zero h.2), le_mul_of_pos_left (nat.pos_of_ne_zero h.1)⟩ } end variable {n} lemma divisor_le {m : ℕ}: n ∈ divisors m → n ≤ m := begin cases m, { simp }, simp only [mem_divisors, m.succ_ne_zero, and_true, ne.def, not_false_iff], exact nat.le_of_dvd (nat.succ_pos m), end lemma divisors_subset_of_dvd {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) : divisors m ⊆ divisors n := finset.subset_iff.2 $ λ x hx, nat.mem_divisors.mpr (⟨(nat.mem_divisors.mp hx).1.trans h, hzero⟩) lemma divisors_subset_proper_divisors {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) (hdiff : m ≠ n) : divisors m ⊆ proper_divisors n := begin apply finset.subset_iff.2, intros x hx, exact nat.mem_proper_divisors.2 (⟨(nat.mem_divisors.1 hx).1.trans h, lt_of_le_of_lt (divisor_le hx) (lt_of_le_of_ne (divisor_le (nat.mem_divisors.2 ⟨h, hzero⟩)) hdiff)⟩) end @[simp] lemma divisors_zero : divisors 0 = ∅ := by { ext, simp } @[simp] lemma proper_divisors_zero : proper_divisors 0 = ∅ := by { ext, simp } lemma proper_divisors_subset_divisors : proper_divisors n ⊆ divisors n := begin cases n, { simp }, rw [divisors_eq_proper_divisors_insert_self_of_pos (nat.succ_pos _)], apply subset_insert, end @[simp] lemma divisors_one : divisors 1 = {1} := by { ext, simp } @[simp] lemma proper_divisors_one : proper_divisors 1 = ∅ := begin ext, simp only [finset.not_mem_empty, nat.dvd_one, not_and, not_lt, mem_proper_divisors, iff_false], apply ge_of_eq, end lemma pos_of_mem_divisors {m : ℕ} (h : m ∈ n.divisors) : 0 < m := begin cases m, { rw [mem_divisors, zero_dvd_iff] at h, cases h.2 h.1 }, apply nat.succ_pos, end lemma pos_of_mem_proper_divisors {m : ℕ} (h : m ∈ n.proper_divisors) : 0 < m := pos_of_mem_divisors (proper_divisors_subset_divisors h) lemma one_mem_proper_divisors_iff_one_lt : 1 ∈ n.proper_divisors ↔ 1 < n := by rw [mem_proper_divisors, and_iff_right (one_dvd _)] @[simp] lemma divisors_antidiagonal_zero : divisors_antidiagonal 0 = ∅ := by { ext, simp } @[simp] lemma divisors_antidiagonal_one : divisors_antidiagonal 1 = {(1,1)} := by { ext, simp [nat.mul_eq_one_iff, prod.ext_iff], } lemma swap_mem_divisors_antidiagonal {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.swap ∈ divisors_antidiagonal n := begin rw [mem_divisors_antidiagonal, mul_comm] at h, simp [h.1, h.2], end lemma fst_mem_divisors_of_mem_antidiagonal {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.fst ∈ divisors n := begin rw mem_divisors_antidiagonal at h, simp [dvd.intro _ h.1, h.2], end lemma snd_mem_divisors_of_mem_antidiagonal {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.snd ∈ divisors n := begin rw mem_divisors_antidiagonal at h, simp [dvd.intro_left _ h.1, h.2], end @[simp] lemma map_swap_divisors_antidiagonal : (divisors_antidiagonal n).map ⟨prod.swap, prod.swap_right_inverse.injective⟩ = divisors_antidiagonal n := begin ext, simp only [exists_prop, mem_divisors_antidiagonal, finset.mem_map, function.embedding.coe_fn_mk, ne.def, prod.swap_prod_mk, prod.exists], split, { rintros ⟨x, y, ⟨⟨rfl, h⟩, rfl⟩⟩, simp [mul_comm, h], }, { rintros ⟨rfl, h⟩, use [a.snd, a.fst], rw mul_comm, simp [h] } end lemma sum_divisors_eq_sum_proper_divisors_add_self : ∑ i in divisors n, i = ∑ i in proper_divisors n, i + n := begin cases n, { simp }, { rw [divisors_eq_proper_divisors_insert_self_of_pos (nat.succ_pos _), finset.sum_insert (proper_divisors.not_self_mem), add_comm] } end /-- `n : ℕ` is perfect if and only the sum of the proper divisors of `n` is `n` and `n` is positive. -/ def perfect (n : ℕ) : Prop := (∑ i in proper_divisors n, i = n) ∧ 0 < n theorem perfect_iff_sum_proper_divisors (h : 0 < n) : perfect n ↔ ∑ i in proper_divisors n, i = n := and_iff_left h theorem perfect_iff_sum_divisors_eq_two_mul (h : 0 < n) : perfect n ↔ ∑ i in divisors n, i = 2 * n := begin rw [perfect_iff_sum_proper_divisors h, sum_divisors_eq_sum_proper_divisors_add_self, two_mul], split; intro h, { rw h }, { apply add_right_cancel h } end lemma mem_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) {x : ℕ} : x ∈ divisors (p ^ k) ↔ ∃ (j : ℕ) (H : j ≤ k), x = p ^ j := by rw [mem_divisors, nat.dvd_prime_pow pp, and_iff_left (ne_of_gt (pow_pos pp.pos k))] lemma prime.divisors {p : ℕ} (pp : p.prime) : divisors p = {1, p} := begin ext, rw [mem_divisors, dvd_prime pp, and_iff_left pp.ne_zero, finset.mem_insert, finset.mem_singleton] end lemma prime.proper_divisors {p : ℕ} (pp : p.prime) : proper_divisors p = {1} := by rw [← erase_insert (proper_divisors.not_self_mem), ← divisors_eq_proper_divisors_insert_self_of_pos pp.pos, pp.divisors, pair_comm, erase_insert (λ con, pp.ne_one (mem_singleton.1 con))] lemma divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) : divisors (p ^ k) = (finset.range (k + 1)).map ⟨pow p, pow_right_injective pp.two_le⟩ := by { ext, simp [mem_divisors_prime_pow, pp, nat.lt_succ_iff, @eq_comm _ a] } lemma eq_proper_divisors_of_subset_of_sum_eq_sum {s : finset ℕ} (hsub : s ⊆ n.proper_divisors) : ∑ x in s, x = ∑ x in n.proper_divisors, x → s = n.proper_divisors := begin cases n, { rw [proper_divisors_zero, subset_empty] at hsub, simp [hsub] }, classical, rw [← sum_sdiff hsub], intros h, apply subset.antisymm hsub, rw [← sdiff_eq_empty_iff_subset], contrapose h, rw [← ne.def, ← nonempty_iff_ne_empty] at h, apply ne_of_lt, rw [← zero_add (∑ x in s, x), ← add_assoc, add_zero], apply add_lt_add_right, have hlt := sum_lt_sum_of_nonempty h (λ x hx, pos_of_mem_proper_divisors (sdiff_subset _ _ hx)), simp only [sum_const_zero] at hlt, apply hlt end lemma sum_proper_divisors_dvd (h : ∑ x in n.proper_divisors, x ∣ n) : (∑ x in n.proper_divisors, x = 1) ∨ (∑ x in n.proper_divisors, x = n) := begin cases n, { simp }, cases n, { contrapose! h, simp, }, rw or_iff_not_imp_right, intro ne_n, have hlt : ∑ x in n.succ.succ.proper_divisors, x < n.succ.succ := lt_of_le_of_ne (nat.le_of_dvd (nat.succ_pos _) h) ne_n, symmetry, rw [← mem_singleton, eq_proper_divisors_of_subset_of_sum_eq_sum (singleton_subset_iff.2 (mem_proper_divisors.2 ⟨h, hlt⟩)) sum_singleton, mem_proper_divisors], refine ⟨one_dvd _, nat.succ_lt_succ (nat.succ_pos _)⟩, end @[simp, to_additive] lemma prime.prod_proper_divisors {α : Type*} [comm_monoid α] {p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in p.proper_divisors, f x = f 1 := by simp [h.proper_divisors] @[simp, to_additive] lemma prime.prod_divisors {α : Type*} [comm_monoid α] {p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in p.divisors, f x = f p * f 1 := by rw [divisors_eq_proper_divisors_insert_self_of_pos h.pos, prod_insert proper_divisors.not_self_mem, h.prod_proper_divisors] lemma proper_divisors_eq_singleton_one_iff_prime : n.proper_divisors = {1} ↔ n.prime := ⟨λ h, begin have h1 := mem_singleton.2 rfl, rw [← h, mem_proper_divisors] at h1, refine nat.prime_def_lt''.mpr ⟨h1.2, λ m hdvd, _⟩, rw [← mem_singleton, ← h, mem_proper_divisors], have hle := nat.le_of_dvd (lt_trans (nat.succ_pos _) h1.2) hdvd, exact or.imp_left (λ hlt, ⟨hdvd, hlt⟩) hle.lt_or_eq end, prime.proper_divisors⟩ lemma sum_proper_divisors_eq_one_iff_prime : ∑ x in n.proper_divisors, x = 1 ↔ n.prime := begin cases n, { simp [nat.not_prime_zero] }, cases n, { simp [nat.not_prime_one] }, rw [← proper_divisors_eq_singleton_one_iff_prime], refine ⟨λ h, _, λ h, h.symm ▸ sum_singleton⟩, rw [@eq_comm (finset ℕ) _ _], apply eq_proper_divisors_of_subset_of_sum_eq_sum (singleton_subset_iff.2 (one_mem_proper_divisors_iff_one_lt.2 (succ_lt_succ (nat.succ_pos _)))) (eq.trans sum_singleton h.symm) end lemma mem_proper_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) {x : ℕ} : x ∈ proper_divisors (p ^ k) ↔ ∃ (j : ℕ) (H : j < k), x = p ^ j := begin rw [mem_proper_divisors, nat.dvd_prime_pow pp, ← exists_and_distrib_right], simp only [exists_prop, and_assoc], apply exists_congr, intro a, split; intro h, { rcases h with ⟨h_left, rfl, h_right⟩, rwa pow_lt_pow_iff pp.one_lt at h_right, simpa, }, { rcases h with ⟨h_left, rfl⟩, rwa pow_lt_pow_iff pp.one_lt, simp [h_left, le_of_lt], }, end lemma proper_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) : proper_divisors (p ^ k) = (finset.range k).map ⟨pow p, pow_right_injective pp.two_le⟩ := by { ext, simp [mem_proper_divisors_prime_pow, pp, nat.lt_succ_iff, @eq_comm _ a], } @[simp, to_additive] lemma prod_proper_divisors_prime_pow {α : Type*} [comm_monoid α] {k p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in (p ^ k).proper_divisors, f x = ∏ x in range k, f (p ^ x) := by simp [h, proper_divisors_prime_pow] @[simp, to_additive sum_divisors_prime_pow] lemma prod_divisors_prime_pow {α : Type*} [comm_monoid α] {k p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in (p ^ k).divisors, f x = ∏ x in range (k + 1), f (p ^ x) := by simp [h, divisors_prime_pow] @[to_additive] lemma prod_divisors_antidiagonal {M : Type*} [comm_monoid M] (f : ℕ → ℕ → M) {n : ℕ} : ∏ i in n.divisors_antidiagonal, f i.1 i.2 = ∏ i in n.divisors, f i (n / i) := begin refine prod_bij (λ i _, i.1) _ _ _ _, { intro i, apply fst_mem_divisors_of_mem_antidiagonal }, { rintro ⟨i, j⟩ hij, simp only [mem_divisors_antidiagonal, ne.def] at hij, rw [←hij.1, nat.mul_div_cancel_left], apply nat.pos_of_ne_zero, rintro rfl, simp only [zero_mul] at hij, apply hij.2 hij.1.symm }, { simp only [and_imp, prod.forall, mem_divisors_antidiagonal, ne.def], rintro i₁ j₁ ⟨i₂, j₂⟩ h - (rfl : i₂ * j₂ = _) h₁ (rfl : _ = i₂), simp only [nat.mul_eq_zero, not_or_distrib, ←ne.def] at h₁, rw mul_right_inj' h₁.1 at h, simp [h] }, simp only [and_imp, exists_prop, mem_divisors_antidiagonal, exists_and_distrib_right, ne.def, exists_eq_right', mem_divisors, prod.exists], rintro _ ⟨k, rfl⟩ hn, exact ⟨⟨k, rfl⟩, hn⟩, end @[to_additive] lemma prod_divisors_antidiagonal' {M : Type*} [comm_monoid M] (f : ℕ → ℕ → M) {n : ℕ} : ∏ i in n.divisors_antidiagonal, f i.1 i.2 = ∏ i in n.divisors, f (n / i) i := begin rw [←map_swap_divisors_antidiagonal, finset.prod_map], exact prod_divisors_antidiagonal (λ i j, f j i), end /-- The factors of `n` are the prime divisors -/ lemma prime_divisors_eq_to_filter_divisors_prime (n : ℕ) : n.factors.to_finset = (divisors n).filter prime := begin rcases n.eq_zero_or_pos with rfl | hn, { simp }, { ext q, simpa [hn, hn.ne', mem_factors] using and_comm (prime q) (q ∣ n) } end @[simp] lemma image_div_divisors_eq_divisors (n : ℕ) : image (λ (x : ℕ), n / x) n.divisors = n.divisors := begin by_cases hn : n = 0, { simp [hn] }, ext, split, { rw mem_image, rintros ⟨x, hx1, hx2⟩, rw mem_divisors at *, refine ⟨_,hn⟩, rw ←hx2, exact div_dvd_of_dvd hx1.1 }, { rw [mem_divisors, mem_image], rintros ⟨h1, -⟩, exact ⟨n/a, mem_divisors.mpr ⟨div_dvd_of_dvd h1, hn⟩, nat.div_div_self h1 (pos_iff_ne_zero.mpr hn)⟩ }, end @[simp, to_additive sum_div_divisors] lemma prod_div_divisors {α : Type*} [comm_monoid α] (n : ℕ) (f : ℕ → α) : ∏ d in n.divisors, f (n/d) = n.divisors.prod f := begin by_cases hn : n = 0, { simp [hn] }, rw ←prod_image, { exact prod_congr (image_div_divisors_eq_divisors n) (by simp) }, { intros x hx y hy h, rw mem_divisors at hx hy, exact (div_eq_iff_eq_of_dvd_dvd hn hx.1 hy.1).mp h } end end nat
c0195bc1ac9843f72cac6be9dcdc731af8ab0ce7
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Elab/Syntax.lean
7de8968c2abe1b6329552913bb35450ff8cb7644
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,525
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.Elab.Command import Lean.Elab.Quotation namespace Lean.Elab.Term /- Expand `optional «precedence»` where «precedence» := parser! " : " >> precedenceLit precedenceLit : Parser := numLit <|> maxSymbol maxSymbol := parser! nonReservedSymbol "max" -/ def expandOptPrecedence (stx : Syntax) : Option Nat := if stx.isNone then none else match stx[0][1].isNatLit? with | some v => some v | _ => some Parser.maxPrec private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := do if ds.size == 0 then throwUnsupportedSyntax else if ds.size == 1 then pure ds[0] else let mut r := ds[0] for d in ds[1:ds.size] do r ← `(ParserDescr.andthen $r $d) return r structure ToParserDescrContext := (catName : Name) (first : Bool) (leftRec : Bool) -- true iff left recursion is allowed /- When `leadingIdentAsSymbol == true` we convert `Lean.Parser.Syntax.atom` into `Lean.ParserDescr.nonReservedSymbol` See comment at `Parser.ParserCategory`. -/ (leadingIdentAsSymbol : Bool) abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT Bool TermElabM) private def markAsTrailingParser : ToParserDescrM Unit := set true @[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with first := false }) x @[inline] private def withoutLeftRec {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with leftRec := false }) x def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do let ctx ← read if ctx.first && stx.getKind == `Lean.Parser.Syntax.cat then let cat := stx[0].getId.eraseMacroScopes if cat == ctx.catName then let prec? : Option Nat := expandOptPrecedence stx[1] unless prec?.isNone do throwErrorAt stx[1] ("invalid occurrence of ':<num>' modifier in head") unless ctx.leftRec do throwErrorAt! stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion" markAsTrailingParser -- mark as trailing par pure true else pure false else pure false partial def toParserDescrAux (stx : Syntax) : ToParserDescrM Syntax := do let kind := stx.getKind if kind == nullKind then let args := stx.getArgs if (← checkLeftRec stx[0]) then if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax" let args := args.eraseIdx 0 let args ← args.mapIdxM fun i arg => withNotFirst $ toParserDescrAux arg mkParserSeq args else let args ← args.mapIdxM fun i arg => withNotFirst $ toParserDescrAux arg mkParserSeq args else if kind == choiceKind then toParserDescrAux stx[0] else if kind == `Lean.Parser.Syntax.paren then toParserDescrAux stx[1] else if kind == `Lean.Parser.Syntax.cat then let cat := stx[0].getId.eraseMacroScopes let ctx ← read if ctx.first && cat == ctx.catName then throwErrorAt stx "invalid atomic left recursive syntax" else let prec? : Option Nat := expandOptPrecedence stx[1] let env ← getEnv if Parser.isParserCategory env cat then let prec := prec?.getD 0 `(ParserDescr.cat $(quote cat) $(quote prec)) else -- `cat` is not a valid category name. Thus, we test whether it is a valid constant let candidates ← resolveGlobalConst cat let candidates := candidates.filter fun c => match env.find? c with | none => false | some info => match info.type with | Expr.const `Lean.Parser.TrailingParser _ _ => true | Expr.const `Lean.Parser.Parser _ _ => true | Expr.const `Lean.ParserDescr _ _ => true | Expr.const `Lean.TrailingParserDescr _ _ => true | _ => false match candidates with | [] => throwErrorAt! stx[3] "unknown category '{cat}' or parser declaration" | [c] => unless prec?.isNone do throwErrorAt stx[3] "unexpected precedence" `(ParserDescr.parser $(quote c)) | cs => throwErrorAt! stx[3] "ambiguous parser declaration {cs}" else if kind == `Lean.Parser.Syntax.atom then match stx[0].isStrLit? with | some atom => if (← read).leadingIdentAsSymbol then `(ParserDescr.nonReservedSymbol $(quote atom) false) else `(ParserDescr.symbol $(quote atom)) | none => throwUnsupportedSyntax else if kind == `Lean.Parser.Syntax.num then `(ParserDescr.numLit) else if kind == `Lean.Parser.Syntax.str then `(ParserDescr.strLit) else if kind == `Lean.Parser.Syntax.char then `(ParserDescr.charLit) else if kind == `Lean.Parser.Syntax.ident then `(ParserDescr.ident) else if kind == `Lean.Parser.Syntax.noWs then `(ParserDescr.noWs) else if kind == `Lean.Parser.Syntax.try then let d ← withoutLeftRec $ toParserDescrAux stx[1] `(ParserDescr.try $d) else if kind == `Lean.Parser.Syntax.withPosition then let d ← withoutLeftRec $ toParserDescrAux stx[1] `(ParserDescr.withPosition $d) else if kind == `Lean.Parser.Syntax.checkColGt then `(ParserDescr.checkCol true) else if kind == `Lean.Parser.Syntax.checkColGe then `(ParserDescr.checkCol false) else if kind == `Lean.Parser.Syntax.notFollowedBy then let d ← withoutLeftRec $ toParserDescrAux stx[1] `(ParserDescr.notFollowedBy $d) else if kind == `Lean.Parser.Syntax.lookahead then let d ← withoutLeftRec $ toParserDescrAux stx[1] `(ParserDescr.lookahead $d) else if kind == `Lean.Parser.Syntax.interpolatedStr then let d ← withoutLeftRec $ toParserDescrAux stx[1] `(ParserDescr.interpolatedStr $d) else if kind == `Lean.Parser.Syntax.sepBy then let allowTrailingSep := !stx[1].isNone let d₁ ← withoutLeftRec $ toParserDescrAux stx[2] let d₂ ← withoutLeftRec $ toParserDescrAux stx[3] `(ParserDescr.sepBy $d₁ $d₂ $(quote allowTrailingSep)) else if kind == `Lean.Parser.Syntax.sepBy1 then let allowTrailingSep := !stx[1].isNone let d₁ ← withoutLeftRec $ toParserDescrAux stx[2] let d₂ ← withoutLeftRec $ toParserDescrAux stx[3] `(ParserDescr.sepBy1 $d₁ $d₂ $(quote allowTrailingSep)) else if kind == `Lean.Parser.Syntax.many then let d ← withoutLeftRec $ toParserDescrAux stx[0] `(ParserDescr.many $d) else if kind == `Lean.Parser.Syntax.many1 then let d ← withoutLeftRec $ toParserDescrAux stx[0] `(ParserDescr.many1 $d) else if kind == `Lean.Parser.Syntax.optional then let d ← withoutLeftRec $ toParserDescrAux stx[0] `(ParserDescr.optional $d) else if kind == `Lean.Parser.Syntax.orelse then let d₁ ← withoutLeftRec $ toParserDescrAux stx[0] let d₂ ← withoutLeftRec $ toParserDescrAux stx[2] `(ParserDescr.orelse $d₁ $d₂) else let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _) match stxNew? with | some stxNew => toParserDescrAux stxNew | none => throwErrorAt! stx "unexpected syntax kind of category `syntax`: {kind}" /-- Given a `stx` of category `syntax`, return a pair `(newStx, trailingParser)`, where `newStx` is of category `term`. After elaboration, `newStx` should have type `TrailingParserDescr` if `trailingParser == true`, and `ParserDescr` otherwise. -/ def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Bool) := do let env ← getEnv let leadingIdentAsSymbol := Parser.leadingIdentAsSymbol env catName (toParserDescrAux stx { catName := catName, first := true, leftRec := true, leadingIdentAsSymbol := leadingIdentAsSymbol }).run false end Term namespace Command private def getCatSuffix (catName : Name) : String := match catName with | Name.str _ s _ => s | _ => unreachable! private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do let quotSymbol := "`(" ++ getCatSuffix catName ++ "|" let kind := catName ++ `quot let cmd ← `( @[termParser] def $(mkIdent kind) : Lean.ParserDescr := Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec) (Lean.ParserDescr.andthen (Lean.ParserDescr.symbol $(quote quotSymbol)) (Lean.ParserDescr.andthen (Lean.ParserDescr.cat $(quote catName) 0) (Lean.ParserDescr.symbol ")")))) elabCommand cmd @[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do let catName := stx[1].getId let attrName := catName.appendAfter "Parser" let env ← getEnv let env ← liftIO $ Parser.registerParserCategory env attrName catName setEnv env declareSyntaxCatQuotParser catName def mkFreshKind (catName : Name) : MacroM Name := Macro.addMacroScope (`_kind ++ catName.eraseMacroScopes) private def elabKindPrio (stx : Syntax) (catName : Name) : CommandElabM (Name × Nat) := do if stx.isNone then let k ← liftMacroM $ mkFreshKind catName pure (k, 0) else let arg := stx[1] if arg.getKind == `Lean.Parser.Command.parserKind then let k := arg[0].getId pure (k, 0) else if arg.getKind == `Lean.Parser.Command.parserPrio then let k ← liftMacroM $ mkFreshKind catName let prio := arg[0].isNatLit?.getD 0 pure (k, prio) else if arg.getKind == `Lean.Parser.Command.parserKindPrio then let k := arg[0].getId let prio := arg[2].isNatLit?.getD 0 pure (k, prio) else throwError "unexpected syntax kind/priority" /- We assume a new syntax can be treated as an atom when it starts and ends with a token. Here are examples of atom-like syntax. ``` syntax "(" term ")" : term syntax "[" (sepBy term ",") "]" : term syntax "foo" : term ``` -/ private partial def isAtomLikeSyntax (stx : Syntax) : Bool := let kind := stx.getKind if kind == nullKind then isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1] else if kind == choiceKind then isAtomLikeSyntax stx[0] -- see toParserDescrAux else if kind == `Lean.Parser.Syntax.paren then isAtomLikeSyntax stx[1] else kind == `Lean.Parser.Syntax.atom /- def «syntax» := parser! "syntax " >> optPrecedence >> optKindPrio >> many1 syntaxParser >> " : " >> ident -/ @[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do let env ← getEnv let cat := stx[5].getId.eraseMacroScopes unless (Parser.isParserCategory env cat) do throwErrorAt stx[5] ("unknown category '" ++ cat ++ "'") let syntaxParser := stx[3] -- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise. let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec let prec := (Term.expandOptPrecedence stx[1]).getD precDefault let (kind, prio) ← elabKindPrio stx[2] cat /- The declaration name and the syntax node kind should be the same. We are using `def $kind ...`. So, we must append the current namespace to create the name fo the Syntax `node`. -/ let stxNodeKind := (← getCurrNamespace) ++ kind let catParserId := mkIdentFrom stx (cat.appendAfter "Parser") let (val, trailingParser) ← runTermElabM none fun _ => Term.toParserDescr syntaxParser cat let d ← if trailingParser then `(@[$catParserId:ident $(quote prio):numLit] def $(mkIdentFrom stx kind) : Lean.TrailingParserDescr := ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $val) else `(@[$catParserId:ident $(quote prio):numLit] def $(mkIdentFrom stx kind) : Lean.ParserDescr := ParserDescr.node $(quote stxNodeKind) $(quote prec) $val) trace `Elab fun _ => d withMacroExpansion stx d $ elabCommand d /- def syntaxAbbrev := parser! "syntax " >> ident >> " := " >> many1 syntaxParser -/ @[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do let declName := stx[1] let (val, _) ← runTermElabM none $ fun _ => Term.toParserDescr stx[3] Name.anonymous let stx' ← `(def $declName : Lean.ParserDescr := $val) withMacroExpansion stx stx' $ elabCommand stx' /- Remark: `k` is the user provided kind with the current namespace included. Recall that syntax node kinds contain the current namespace. -/ def elabMacroRulesAux (k : SyntaxNodeKind) (alts : Array Syntax) : CommandElabM Syntax := do let alts ← alts.mapSepElemsM fun alt => do let lhs := alt[0] let pat := lhs[0] if !pat.isQuot then throwUnsupportedSyntax let quot := pat[1] let k' := quot.getKind if k' == k then pure alt else if k' == choiceKind then match quot.getArgs.find? fun quotAlt => quotAlt.getKind == k with | none => throwErrorAt! alt "invalid macro_rules alternative, expected syntax node kind '{k}'" | some quot => let pat := pat.setArg 1 quot let lhs := lhs.setArg 0 pat pure $ alt.setArg 0 lhs else throwErrorAt! alt "invalid macro_rules alternative, unexpected syntax node kind '{k'}'" `(@[macro $(Lean.mkIdent k)] def myMacro : Macro := fun stx => match_syntax stx with $alts:matchAlt* | _ => throw Lean.Macro.Exception.unsupportedSyntax) def inferMacroRulesAltKind (alt : Syntax) : CommandElabM SyntaxNodeKind := do let lhs := alt[0] let pat := lhs[0] if !pat.isQuot then throwUnsupportedSyntax let quot := pat[1] pure quot.getKind def elabNoKindMacroRulesAux (alts : Array Syntax) : CommandElabM Syntax := do let k ← inferMacroRulesAltKind (alts.get! 0) if k == choiceKind then throwErrorAt! alts[0] "invalid macro_rules alternative, multiple interpretations for pattern (solution: specify node kind using `macro_rules [<kind>] ...`)" else let altsK ← alts.filterSepElemsM fun alt => do pure $ k == (← inferMacroRulesAltKind alt) let altsNotK ← alts.filterSepElemsM fun alt => do pure $ k != (← inferMacroRulesAltKind alt) let defCmd ← elabMacroRulesAux k altsK if altsNotK.isEmpty then pure defCmd else `($defCmd:command macro_rules $altsNotK:matchAlt*) @[builtinCommandElab «macro_rules»] def elabMacroRules : CommandElab := adaptExpander fun stx => match_syntax stx with | `(macro_rules $alts:matchAlt*) => elabNoKindMacroRulesAux alts | `(macro_rules | $alts:matchAlt*) => elabNoKindMacroRulesAux alts | `(macro_rules [$kind] $alts:matchAlt*) => do elabMacroRulesAux ((← getCurrNamespace) ++ kind.getId) alts | `(macro_rules [$kind] | $alts:matchAlt*) => do elabMacroRulesAux ((← getCurrNamespace) ++ kind.getId) alts | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Command.mixfix] def expandMixfix : Macro := fun stx => match_syntax stx with | `(infix:$prec $op => $f) => `(infixl:$prec $op => $f) | `(infixr:$prec $op => $f) => `(notation:$prec lhs $op:strLit rhs:$prec => $f lhs rhs) | `(infixl:$prec $op => $f) => let prec1 : Syntax := quote (prec.toNat+1); `(notation:$prec lhs $op:strLit rhs:$prec1 => $f lhs rhs) | `(prefix:$prec $op => $f) => `(notation:$prec $op:strLit arg:$prec => $f arg) | `(postfix:$prec $op => $f) => `(notation:$prec arg $op:strLit => $f arg) | _ => Macro.throwUnsupported /- Wrap all occurrences of the given `ident` nodes in antiquotations -/ private partial def antiquote (vars : Array Syntax) : Syntax → Syntax | stx => match_syntax stx with | `($id:ident) => if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then Syntax.node `antiquot #[mkAtom "$", mkNullNode, id, mkNullNode, mkNullNode] else stx | _ => match stx with | Syntax.node k args => Syntax.node k (args.map (antiquote vars)) | stx => stx /- Convert `notation` command lhs item into a `syntax` command item -/ def expandNotationItemIntoSyntaxItem (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then pure $ Syntax.node `Lean.Parser.Syntax.cat #[mkIdentFrom stx `term, stx[1]] else if k == strLitKind then pure $ Syntax.node `Lean.Parser.Syntax.atom #[stx] else Macro.throwUnsupported def strLitToPattern (stx: Syntax) : MacroM Syntax := match stx.isStrLit? with | some str => pure $ mkAtomFrom stx str | none => Macro.throwUnsupported /- Convert `notation` command lhs item a pattern element -/ def expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then let item := stx[0] pure $ mkNode `antiquot #[mkAtom "$", mkNullNode, item, mkNullNode, mkNullNode] else if k == strLitKind then strLitToPattern stx else Macro.throwUnsupported private def expandNotationAux (ref : Syntax) (currNamespace : Name) (prec? : Option Syntax) (items : Array Syntax) (rhs : Syntax) : MacroM Syntax := do let kind ← mkFreshKind `term -- build parser let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem let cat := mkIdentFrom ref `term -- build macro rules let vars := items.filter fun item => item.getKind == `Lean.Parser.Command.identPrec let vars := vars.map fun var => var[0] let rhs := antiquote vars rhs let patArgs ← items.mapM expandNotationItemIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let pat := Syntax.node (currNamespace ++ kind) patArgs match prec? with | none => `(syntax [$(mkIdentFrom ref kind):ident] $syntaxParts* : $cat macro_rules | `($pat) => `($rhs)) | some prec => `(syntax:$prec [$(mkIdentFrom ref kind):ident] $syntaxParts* : $cat macro_rules | `($pat) => `($rhs)) @[builtinCommandElab «notation»] def expandNotation : CommandElab := adaptExpander fun stx => do let currNamespace ← getCurrNamespace match_syntax stx with | `(notation:$prec $items* => $rhs) => liftMacroM $ expandNotationAux stx currNamespace prec items rhs | `(notation $items:notationItem* => $rhs) => liftMacroM $ expandNotationAux stx currNamespace none items rhs | _ => throwUnsupportedSyntax /- Convert `macro` argument into a `syntax` command item -/ def expandMacroArgIntoSyntaxItem (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.macroArgSimple then pure stx[2] else if k == strLitKind then pure $ Syntax.node `Lean.Parser.Syntax.atom #[stx] else Macro.throwUnsupported /- Convert `macro` head into a `syntax` command item -/ def expandMacroHeadIntoSyntaxItem (stx : Syntax) : MacroM Syntax := if stx.isIdent then let info := stx.getHeadInfo.getD {} let id := stx.getId pure $ Syntax.node `Lean.Parser.Syntax.atom #[Syntax.mkStrLit (toString id) info] else expandMacroArgIntoSyntaxItem stx /- Convert `macro` arg into a pattern element -/ def expandMacroArgIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.macroArgSimple then let item := stx[0] pure $ mkNode `antiquot #[mkAtom "$", mkNullNode, item, mkNullNode, mkNullNode] else if k == strLitKind then strLitToPattern stx else Macro.throwUnsupported /- Convert `macro` head into a pattern element -/ def expandMacroHeadIntoPattern (stx : Syntax) : MacroM Syntax := if stx.isIdent then pure $ mkAtomFrom stx (toString stx.getId) else expandMacroArgIntoPattern stx def expandOptPrio (stx : Syntax) : Nat := if stx.isNone then 0 else stx[1].isNatLit?.getD 0 def expandMacro (currNamespace : Name) (stx : Syntax) : MacroM Syntax := do let prec := stx[1].getArgs let prio := expandOptPrio stx[2] let head := stx[3] let args := stx[4].getArgs let cat := stx[6] let kind ← mkFreshKind cat.getId -- build parser let stxPart ← expandMacroHeadIntoSyntaxItem head let stxParts ← args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- build macro rules let patHead ← expandMacroHeadIntoPattern head let patArgs ← args.mapM expandMacroArgIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let pat := Syntax.node (currNamespace ++ kind) (#[patHead] ++ patArgs) if stx.getArgs.size == 9 then -- `stx` is of the form `macro $head $args* : $cat => term` let rhs := stx[8] `(syntax $prec* [$(mkIdentFrom stx kind):ident, $(quote prio):numLit] $stxParts* : $cat macro_rules | `($pat) => $rhs) else -- `stx` is of the form `macro $head $args* : $cat => `( $body )` let rhsBody := stx[9] `(syntax $prec* [$(mkIdentFrom stx kind):ident, $(quote prio):numLit] $stxParts* : $cat macro_rules | `($pat) => `($rhsBody)) @[builtinCommandElab «macro»] def elabMacro : CommandElab := adaptExpander fun stx => do liftMacroM $ expandMacro (← getCurrNamespace) stx builtin_initialize registerTraceClass `Elab.syntax @[inline] def withExpectedType (expectedType? : Option Expr) (x : Expr → TermElabM Expr) : TermElabM Expr := do Term.tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "expected type must be known" x expectedType /- def elabTail := try (" : " >> ident) >> darrow >> termParser parser! "elab " >> optPrecedence >> elabHead >> many elabArg >> elabTail -/ def expandElab (currNamespace : Name) (stx : Syntax) : MacroM Syntax := do let ref := stx let prec := stx[1].getArgs let prio := expandOptPrio stx[2] let head := stx[3] let args := stx[4].getArgs let cat := stx[6] let expectedTypeSpec := stx[7] let rhs := stx[9] let catName := cat.getId let kind ← mkFreshKind catName -- build parser let stxPart ← expandMacroHeadIntoSyntaxItem head let stxParts ← args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- build pattern for `martch_syntax let patHead ← expandMacroHeadIntoPattern head let patArgs ← args.mapM expandMacroArgIntoPattern let pat := Syntax.node (currNamespace ++ kind) (#[patHead] ++ patArgs) let kindId := mkIdentFrom ref kind if expectedTypeSpec.hasArgs then if catName == `term then let expId := expectedTypeSpec[1] `(syntax $prec* [$kindId:ident, $(quote prio):numLit] $stxParts* : $cat @[termElab $kindId:ident] def elabFn : Lean.Elab.Term.TermElab := fun stx expectedType? => match_syntax stx with | `($pat) => Lean.Elab.Command.withExpectedType expectedType? fun $expId => $rhs | _ => throwUnsupportedSyntax) else Macro.throwError expectedTypeSpec s!"syntax category '{catName}' does not support expected type specification" else if catName == `term then `(syntax $prec* [$kindId:ident, $(quote prio):numLit] $stxParts* : $cat @[termElab $kindId:ident] def elabFn : Lean.Elab.Term.TermElab := fun stx _ => match_syntax stx with | `($pat) => $rhs | _ => throwUnsupportedSyntax) else if catName == `command then `(syntax $prec* [$kindId:ident, $(quote prio):numLit] $stxParts* : $cat @[commandElab $kindId:ident] def elabFn : Lean.Elab.Command.CommandElab := fun stx => match_syntax stx with | `($pat) => $rhs | _ => throwUnsupportedSyntax) else if catName == `tactic then `(syntax $prec* [$kindId:ident, $(quote prio):numLit] $stxParts* : $cat @[tactic $kindId:ident] def elabFn : Lean.Elab.Tactic.Tactic := fun stx => match_syntax stx with | `(tactic|$pat) => $rhs | _ => throwUnsupportedSyntax) else -- We considered making the command extensible and support new user-defined categories. We think it is unnecessary. -- If users want this feature, they add their own `elab` macro that uses this one as a fallback. Macro.throwError ref s!"unsupported syntax category '{catName}'" @[builtinCommandElab «elab»] def elabElab : CommandElab := adaptExpander fun stx => do liftMacroM $ expandElab (← getCurrNamespace) stx end Lean.Elab.Command
f6621e3635926757af76714363f71d48ec96c886
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monad/algebra.lean
4f034f3323988f59e62d2eb2438bb2e76a90ae78
[ "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
13,081
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.monad.basic import category_theory.adjunction.basic import category_theory.functor.epi_mono /-! # Eilenberg-Moore (co)algebras for a (co)monad > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines Eilenberg-Moore (co)algebras for a (co)monad, and provides the category instance for them. Further it defines the adjoint pair of free and forgetful functors, respectively from and to the original category, as well as the adjoint pair of forgetful and cofree functors, respectively from and to the original category. ## References * [Riehl, *Category theory in context*, Section 5.2.4][riehl2017] -/ namespace category_theory open category universes v₁ u₁ -- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u₁} [category.{v₁} C] namespace monad /-- An Eilenberg-Moore algebra for a monad `T`. cf Definition 5.2.3 in [Riehl][riehl2017]. -/ structure algebra (T : monad C) : Type (max u₁ v₁) := (A : C) (a : (T : C ⥤ C).obj A ⟶ A) (unit' : T.η.app A ≫ a = 𝟙 A . obviously) (assoc' : T.μ.app A ≫ a = (T : C ⥤ C).map a ≫ a . obviously) restate_axiom algebra.unit' restate_axiom algebra.assoc' attribute [reassoc] algebra.unit algebra.assoc namespace algebra variables {T : monad C} /-- A morphism of Eilenberg–Moore algebras for the monad `T`. -/ @[ext] structure hom (A B : algebra T) := (f : A.A ⟶ B.A) (h' : (T : C ⥤ C).map f ≫ B.a = A.a ≫ f . obviously) restate_axiom hom.h' attribute [simp, reassoc] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore algebra. -/ def id (A : algebra T) : hom A A := { f := 𝟙 A.A } instance (A : algebra T) : inhabited (hom A A) := ⟨{ f := 𝟙 _ }⟩ /-- Composition of Eilenberg–Moore algebra homomorphisms. -/ def comp {P Q R : algebra T} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f } end hom instance : category_struct (algebra T) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ } @[simp] lemma comp_eq_comp {A A' A'' : algebra T} (f : A ⟶ A') (g : A' ⟶ A'') : algebra.hom.comp f g = f ≫ g := rfl @[simp] lemma id_eq_id (A : algebra T) : algebra.hom.id A = 𝟙 A := rfl @[simp] lemma id_f (A : algebra T) : (𝟙 A : A ⟶ A).f = 𝟙 A.A := rfl @[simp] lemma comp_f {A A' A'' : algebra T} (f : A ⟶ A') (g : A' ⟶ A'') : (f ≫ g).f = f.f ≫ g.f := rfl /-- The category of Eilenberg-Moore algebras for a monad. cf Definition 5.2.4 in [Riehl][riehl2017]. -/ instance EilenbergMoore : category (algebra T) := {}. /-- To construct an isomorphism of algebras, it suffices to give an isomorphism of the carriers which commutes with the structure morphisms. -/ @[simps] def iso_mk {A B : algebra T} (h : A.A ≅ B.A) (w : (T : C ⥤ C).map h.hom ≫ B.a = A.a ≫ h.hom) : A ≅ B := { hom := { f := h.hom }, inv := { f := h.inv, h' := by { rw [h.eq_comp_inv, category.assoc, ←w, ←functor.map_comp_assoc], simp } } } end algebra variables (T : monad C) /-- The forgetful functor from the Eilenberg-Moore category, forgetting the algebraic structure. -/ @[simps] def forget : algebra T ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } /-- The free functor from the Eilenberg-Moore category, constructing an algebra for any object. -/ @[simps] def free : C ⥤ algebra T := { obj := λ X, { A := T.obj X, a := T.μ.app X, assoc' := (T.assoc _).symm }, map := λ X Y f, { f := T.map f, h' := T.μ.naturality _ } } instance [inhabited C] : inhabited (algebra T) := ⟨(free T).obj default⟩ /-- The adjunction between the free and forgetful constructions for Eilenberg-Moore algebras for a monad. cf Lemma 5.2.8 of [Riehl][riehl2017]. -/ -- The other two `simps` projection lemmas can be derived from these two, so `simp_nf` complains if -- those are added too @[simps unit counit] def adj : T.free ⊣ T.forget := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, T.η.app X ≫ f.f, inv_fun := λ f, { f := T.map f ≫ Y.a, h' := by { dsimp, simp [←Y.assoc, ←T.μ.naturality_assoc] } }, left_inv := λ f, by { ext, dsimp, simp }, right_inv := λ f, begin dsimp only [forget_obj, monad_to_functor_eq_coe], rw [←T.η.naturality_assoc, Y.unit], apply category.comp_id, end }} /-- Given an algebra morphism whose carrier part is an isomorphism, we get an algebra isomorphism. -/ lemma algebra_iso_of_iso {A B : algebra T} (f : A ⟶ B) [is_iso f.f] : is_iso f := ⟨⟨{ f := inv f.f, h' := by { rw [is_iso.eq_comp_inv f.f, category.assoc, ← f.h], simp } }, by tidy⟩⟩ instance forget_reflects_iso : reflects_isomorphisms T.forget := { reflects := λ A B, algebra_iso_of_iso T } instance forget_faithful : faithful T.forget := {} /-- Given an algebra morphism whose carrier part is an epimorphism, we get an algebra epimorphism. -/ lemma algebra_epi_of_epi {X Y : algebra T} (f : X ⟶ Y) [h : epi f.f] : epi f := (forget T).epi_of_epi_map h /-- Given an algebra morphism whose carrier part is a monomorphism, we get an algebra monomorphism. -/ lemma algebra_mono_of_mono {X Y : algebra T} (f : X ⟶ Y) [h : mono f.f] : mono f := (forget T).mono_of_mono_map h instance : is_right_adjoint T.forget := ⟨T.free, T.adj⟩ @[simp] lemma left_adjoint_forget : left_adjoint T.forget = T.free := rfl @[simp] lemma of_right_adjoint_forget : adjunction.of_right_adjoint T.forget = T.adj := rfl /-- Given a monad morphism from `T₂` to `T₁`, we get a functor from the algebras of `T₁` to algebras of `T₂`. -/ @[simps] def algebra_functor_of_monad_hom {T₁ T₂ : monad C} (h : T₂ ⟶ T₁) : algebra T₁ ⥤ algebra T₂ := { obj := λ A, { A := A.A, a := h.app A.A ≫ A.a, unit' := by { dsimp, simp [A.unit] }, assoc' := by { dsimp, simp [A.assoc] } }, map := λ A₁ A₂ f, { f := f.f } } /-- The identity monad morphism induces the identity functor from the category of algebras to itself. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_id {T₁ : monad C} : algebra_functor_of_monad_hom (𝟙 T₁) ≅ 𝟭 _ := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp, })) (λ X Y f, by { ext, dsimp, simp }) /-- A composition of monad morphisms gives the composition of corresponding functors. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_comp {T₁ T₂ T₃ : monad C} (f : T₁ ⟶ T₂) (g : T₂ ⟶ T₃) : algebra_functor_of_monad_hom (f ≫ g) ≅ algebra_functor_of_monad_hom g ⋙ algebra_functor_of_monad_hom f := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp })) (λ X Y f, by { ext, dsimp, simp }) /-- If `f` and `g` are two equal morphisms of monads, then the functors of algebras induced by them are isomorphic. We define it like this as opposed to using `eq_to_iso` so that the components are nicer to prove lemmas about. -/ @[simps {rhs_md := semireducible}] def algebra_functor_of_monad_hom_eq {T₁ T₂ : monad C} {f g : T₁ ⟶ T₂} (h : f = g) : algebra_functor_of_monad_hom f ≅ algebra_functor_of_monad_hom g := nat_iso.of_components (λ X, algebra.iso_mk (iso.refl _) (by { dsimp, simp [h] })) (λ X Y f, by { ext, dsimp, simp }) /-- Isomorphic monads give equivalent categories of algebras. Furthermore, they are equivalent as categories over `C`, that is, we have `algebra_equiv_of_iso_monads h ⋙ forget = forget`. -/ @[simps] def algebra_equiv_of_iso_monads {T₁ T₂ : monad C} (h : T₁ ≅ T₂) : algebra T₁ ≌ algebra T₂ := { functor := algebra_functor_of_monad_hom h.inv, inverse := algebra_functor_of_monad_hom h.hom, unit_iso := algebra_functor_of_monad_hom_id.symm ≪≫ algebra_functor_of_monad_hom_eq (by simp) ≪≫ algebra_functor_of_monad_hom_comp _ _, counit_iso := (algebra_functor_of_monad_hom_comp _ _).symm ≪≫ algebra_functor_of_monad_hom_eq (by simp) ≪≫ algebra_functor_of_monad_hom_id } @[simp] lemma algebra_equiv_of_iso_monads_comp_forget {T₁ T₂ : monad C} (h : T₁ ⟶ T₂) : algebra_functor_of_monad_hom h ⋙ forget _ = forget _ := rfl end monad namespace comonad /-- An Eilenberg-Moore coalgebra for a comonad `T`. -/ @[nolint has_nonempty_instance] structure coalgebra (G : comonad C) : Type (max u₁ v₁) := (A : C) (a : A ⟶ (G : C ⥤ C).obj A) (counit' : a ≫ G.ε.app A = 𝟙 A . obviously) (coassoc' : a ≫ G.δ.app A = a ≫ G.map a . obviously) restate_axiom coalgebra.counit' restate_axiom coalgebra.coassoc' attribute [reassoc] coalgebra.counit coalgebra.coassoc namespace coalgebra variables {G : comonad C} /-- A morphism of Eilenberg-Moore coalgebras for the comonad `G`. -/ @[ext, nolint has_nonempty_instance] structure hom (A B : coalgebra G) := (f : A.A ⟶ B.A) (h' : A.a ≫ (G : C ⥤ C).map f = f ≫ B.a . obviously) restate_axiom hom.h' attribute [simp, reassoc] hom.h namespace hom /-- The identity homomorphism for an Eilenberg–Moore coalgebra. -/ def id (A : coalgebra G) : hom A A := { f := 𝟙 A.A } /-- Composition of Eilenberg–Moore coalgebra homomorphisms. -/ def comp {P Q R : coalgebra G} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f } end hom /-- The category of Eilenberg-Moore coalgebras for a comonad. -/ instance : category_struct (coalgebra G) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ } @[simp] lemma comp_eq_comp {A A' A'' : coalgebra G} (f : A ⟶ A') (g : A' ⟶ A'') : coalgebra.hom.comp f g = f ≫ g := rfl @[simp] lemma id_eq_id (A : coalgebra G) : coalgebra.hom.id A = 𝟙 A := rfl @[simp] lemma id_f (A : coalgebra G) : (𝟙 A : A ⟶ A).f = 𝟙 A.A := rfl @[simp] lemma comp_f {A A' A'' : coalgebra G} (f : A ⟶ A') (g : A' ⟶ A'') : (f ≫ g).f = f.f ≫ g.f := rfl /-- The category of Eilenberg-Moore coalgebras for a comonad. -/ instance EilenbergMoore : category (coalgebra G) := {}. /-- To construct an isomorphism of coalgebras, it suffices to give an isomorphism of the carriers which commutes with the structure morphisms. -/ @[simps] def iso_mk {A B : coalgebra G} (h : A.A ≅ B.A) (w : A.a ≫ (G : C ⥤ C).map h.hom = h.hom ≫ B.a) : A ≅ B := { hom := { f := h.hom }, inv := { f := h.inv, h' := by { rw [h.eq_inv_comp, ←reassoc_of w, ←functor.map_comp], simp } } } end coalgebra variables (G : comonad C) /-- The forgetful functor from the Eilenberg-Moore category, forgetting the coalgebraic structure. -/ @[simps] def forget : coalgebra G ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } /-- The cofree functor from the Eilenberg-Moore category, constructing a coalgebra for any object. -/ @[simps] def cofree : C ⥤ coalgebra G := { obj := λ X, { A := G.obj X, a := G.δ.app X, coassoc' := (G.coassoc _).symm }, map := λ X Y f, { f := G.map f, h' := (G.δ.naturality _).symm } } /-- The adjunction between the cofree and forgetful constructions for Eilenberg-Moore coalgebras for a comonad. -/ -- The other two `simps` projection lemmas can be derived from these two, so `simp_nf` complains if -- those are added too @[simps unit counit] def adj : G.forget ⊣ G.cofree := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, { f := X.a ≫ G.map f, h' := by { dsimp, simp [←coalgebra.coassoc_assoc] } }, inv_fun := λ g, g.f ≫ G.ε.app Y, left_inv := λ f, by { dsimp, rw [category.assoc, G.ε.naturality, functor.id_map, X.counit_assoc] }, right_inv := λ g, begin ext1, dsimp, rw [functor.map_comp, g.h_assoc, cofree_obj_a, comonad.right_counit], apply comp_id, end }} /-- Given a coalgebra morphism whose carrier part is an isomorphism, we get a coalgebra isomorphism. -/ lemma coalgebra_iso_of_iso {A B : coalgebra G} (f : A ⟶ B) [is_iso f.f] : is_iso f := ⟨⟨{ f := inv f.f, h' := by { rw [is_iso.eq_inv_comp f.f, ←f.h_assoc], simp } }, by tidy⟩⟩ instance forget_reflects_iso : reflects_isomorphisms G.forget := { reflects := λ A B, coalgebra_iso_of_iso G } instance forget_faithful : faithful (forget G) := {} /-- Given a coalgebra morphism whose carrier part is an epimorphism, we get an algebra epimorphism. -/ lemma algebra_epi_of_epi {X Y : coalgebra G} (f : X ⟶ Y) [h : epi f.f] : epi f := (forget G).epi_of_epi_map h /-- Given a coalgebra morphism whose carrier part is a monomorphism, we get an algebra monomorphism. -/ lemma algebra_mono_of_mono {X Y : coalgebra G} (f : X ⟶ Y) [h : mono f.f] : mono f := (forget G).mono_of_mono_map h instance : is_left_adjoint G.forget := ⟨_, G.adj⟩ @[simp] lemma right_adjoint_forget : right_adjoint G.forget = G.cofree := rfl @[simp] lemma of_left_adjoint_forget : adjunction.of_left_adjoint G.forget = G.adj := rfl end comonad end category_theory
a40354f2a5fa320d083a7f6cc51978af1042c188
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/num3.lean
077543149d6f7adc03190270c32778caec7dee02
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
217
lean
import data.num set_option pp.notation false set_option pp.implicit true constant N : Type.{1} constant z : N constant o : N constant a : N notation 0 := z notation 1 := o check a = 0 check 2 = 1 check (2:num) = 1
323527bb5985d4d6d4befa91a9efefacdb25656f
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/special_functions/pow_deriv.lean
018aff857af47a2321ce592b57a8d455ba3d2cc5
[ "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
25,236
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.pow import analysis.special_functions.complex.log_deriv import analysis.calculus.extend_deriv import analysis.special_functions.log.deriv import analysis.special_functions.trigonometric.deriv /-! # Derivatives of power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We also prove differentiability and provide derivatives for the power functions `x ^ y`. -/ noncomputable theory open_locale classical real topological_space nnreal ennreal filter open filter namespace complex lemma has_strict_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := begin have A : p.1 ≠ 0, by { intro h, simpa [h, lt_irrefl] using hp }, have : (λ x : ℂ × ℂ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from ((is_open_ne.preimage continuous_fst).eventually_mem A).mono (λ p hp, cpow_def_of_ne_zero hp _), rw [cpow_sub _ _ A, cpow_one, mul_div_left_comm, mul_smul, mul_smul, ← smul_add], refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, simpa only [cpow_def_of_ne_zero A, div_eq_mul_inv, mul_smul, add_comm] using ((has_strict_fderiv_at_fst.clog hp).mul has_strict_fderiv_at_snd).cexp end lemma has_strict_fderiv_at_cpow' {x y : ℂ} (hp : 0 < x.re ∨ x.im ≠ 0) : has_strict_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((y * x ^ (y - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (x ^ y * log x) • continuous_linear_map.snd ℂ ℂ ℂ) (x, y) := @has_strict_fderiv_at_cpow (x, y) hp lemma has_strict_deriv_at_const_cpow {x y : ℂ} (h : x ≠ 0 ∨ y ≠ 0) : has_strict_deriv_at (λ y, x ^ y) (x ^ y * log x) y := begin rcases em (x = 0) with rfl|hx, { replace h := h.neg_resolve_left rfl, rw [log_zero, mul_zero], refine (has_strict_deriv_at_const _ 0).congr_of_eventually_eq _, exact (is_open_ne.eventually_mem h).mono (λ y hy, (zero_cpow hy).symm) }, { simpa only [cpow_def_of_ne_zero hx, mul_one] using ((has_strict_deriv_at_id y).const_mul (log x)).cexp } end lemma has_fderiv_at_cpow {p : ℂ × ℂ} (hp : 0 < p.1.re ∨ p.1.im ≠ 0) : has_fderiv_at (λ x : ℂ × ℂ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℂ ℂ ℂ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℂ ℂ ℂ) p := (has_strict_fderiv_at_cpow hp).has_fderiv_at end complex section fderiv open complex variables {E : Type*} [normed_group E] [normed_space ℂ E] {f g : E → ℂ} {f' g' : E →L[ℂ] ℂ} {x : E} {s : set E} {c : ℂ} lemma has_strict_fderiv_at.cpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@has_strict_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_strict_fderiv_at.const_cpow (hf : has_strict_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).comp_has_strict_fderiv_at x hf lemma has_fderiv_at.cpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp x (hf.prod hg) lemma has_fderiv_at.const_cpow (hf : has_fderiv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_at x hf lemma has_fderiv_within_at.cpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := by convert (@complex.has_fderiv_at_cpow ((λ x, (f x, g x)) x) h0).comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_within_at.const_cpow (hf : has_fderiv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_fderiv_within_at x hf lemma differentiable_at.cpow (hf : differentiable_at ℂ f x) (hg : differentiable_at ℂ g x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_at ℂ (λ x, f x ^ g x) x := (hf.has_fderiv_at.cpow hg.has_fderiv_at h0).differentiable_at lemma differentiable_at.const_cpow (hf : differentiable_at ℂ f x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_at ℂ (λ x, c ^ f x) x := (hf.has_fderiv_at.const_cpow h0).differentiable_at lemma differentiable_within_at.cpow (hf : differentiable_within_at ℂ f s x) (hg : differentiable_within_at ℂ g s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : differentiable_within_at ℂ (λ x, f x ^ g x) s x := (hf.has_fderiv_within_at.cpow hg.has_fderiv_within_at h0).differentiable_within_at lemma differentiable_within_at.const_cpow (hf : differentiable_within_at ℂ f s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : differentiable_within_at ℂ (λ x, c ^ f x) s x := (hf.has_fderiv_within_at.const_cpow h0).differentiable_within_at end fderiv section deriv open complex variables {f g : ℂ → ℂ} {s : set ℂ} {f' g' x c : ℂ} /-- A private lemma that rewrites the output of lemmas like `has_fderiv_at.cpow` to the form expected by lemmas like `has_deriv_at.cpow`. -/ private lemma aux : ((g x * f x ^ (g x - 1)) • (1 : ℂ →L[ℂ] ℂ).smul_right f' + (f x ^ g x * log (f x)) • (1 : ℂ →L[ℂ] ℂ).smul_right g') 1 = g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g' := by simp only [algebra.id.smul_eq_mul, one_mul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.add_apply, pi.smul_apply, continuous_linear_map.coe_smul'] lemma has_strict_deriv_at.cpow (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.cpow hg h0).has_strict_deriv_at lemma has_strict_deriv_at.const_cpow (hf : has_strict_deriv_at f f' x) (h : c ≠ 0 ∨ f x ≠ 0) : has_strict_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h).comp x hf lemma complex.has_strict_deriv_at_cpow_const (h : 0 < x.re ∨ x.im ≠ 0) : has_strict_deriv_at (λ z : ℂ, z ^ c) (c * x ^ (c - 1)) x := by simpa only [mul_zero, add_zero, mul_one] using (has_strict_deriv_at_id x).cpow (has_strict_deriv_at_const x c) h lemma has_strict_deriv_at.cpow_const (hf : has_strict_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_strict_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).comp x hf lemma has_deriv_at.cpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') x := by simpa only [aux] using (hf.has_fderiv_at.cpow hg h0).has_deriv_at lemma has_deriv_at.const_cpow (hf : has_deriv_at f f' x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_at (λ x, c ^ f x) (c ^ f x * log c * f') x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp x hf lemma has_deriv_at.cpow_const (hf : has_deriv_at f f' x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp x hf lemma has_deriv_within_at.cpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ g x) (g x * f x ^ (g x - 1) * f' + f x ^ g x * log (f x) * g') s x := by simpa only [aux] using (hf.has_fderiv_within_at.cpow hg h0).has_deriv_within_at lemma has_deriv_within_at.const_cpow (hf : has_deriv_within_at f f' s x) (h0 : c ≠ 0 ∨ f x ≠ 0) : has_deriv_within_at (λ x, c ^ f x) (c ^ f x * log c * f') s x := (has_strict_deriv_at_const_cpow h0).has_deriv_at.comp_has_deriv_within_at x hf lemma has_deriv_within_at.cpow_const (hf : has_deriv_within_at f f' s x) (h0 : 0 < (f x).re ∨ (f x).im ≠ 0) : has_deriv_within_at (λ x, f x ^ c) (c * f x ^ (c - 1) * f') s x := (complex.has_strict_deriv_at_cpow_const h0).has_deriv_at.comp_has_deriv_within_at x hf end deriv namespace real variables {x y z : ℝ} /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `0 < p.fst`. -/ lemma has_strict_fderiv_at_rpow_of_pos (p : ℝ × ℝ) (hp : 0 < p.1) : has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1) • continuous_linear_map.snd ℝ ℝ ℝ) p := begin have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2)), from (continuous_at_fst.eventually (lt_mem_nhds hp)).mono (λ p hp, rpow_def_of_pos hp _), refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, convert ((has_strict_fderiv_at_fst.log hp.ne').mul has_strict_fderiv_at_snd).exp, rw [rpow_sub_one hp.ne', ← rpow_def_of_pos hp, smul_add, smul_smul, mul_div_left_comm, div_eq_mul_inv, smul_smul, smul_smul, mul_assoc, add_comm] end /-- `(x, y) ↦ x ^ y` is strictly differentiable at `p : ℝ × ℝ` such that `p.fst < 0`. -/ lemma has_strict_fderiv_at_rpow_of_neg (p : ℝ × ℝ) (hp : p.1 < 0) : has_strict_fderiv_at (λ x : ℝ × ℝ, x.1 ^ x.2) ((p.2 * p.1 ^ (p.2 - 1)) • continuous_linear_map.fst ℝ ℝ ℝ + (p.1 ^ p.2 * log p.1 - exp (log p.1 * p.2) * sin (p.2 * π) * π) • continuous_linear_map.snd ℝ ℝ ℝ) p := begin have : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] (λ x, exp (log x.1 * x.2) * cos (x.2 * π)), from (continuous_at_fst.eventually (gt_mem_nhds hp)).mono (λ p hp, rpow_def_of_neg hp _), refine has_strict_fderiv_at.congr_of_eventually_eq _ this.symm, convert ((has_strict_fderiv_at_fst.log hp.ne).mul has_strict_fderiv_at_snd).exp.mul (has_strict_fderiv_at_snd.mul_const _).cos using 1, simp_rw [rpow_sub_one hp.ne, smul_add, ← add_assoc, smul_smul, ← add_smul, ← mul_assoc, mul_comm (cos _), ← rpow_def_of_neg hp], rw [div_eq_mul_inv, add_comm], congr' 2; ring end /-- The function `λ (x, y), x ^ y` is infinitely smooth at `(x, y)` unless `x = 0`. -/ lemma cont_diff_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) {n : with_top ℕ} : cont_diff_at ℝ n (λ p : ℝ × ℝ, p.1 ^ p.2) p := begin cases hp.lt_or_lt with hneg hpos, exacts [(((cont_diff_at_fst.log hneg.ne).mul cont_diff_at_snd).exp.mul (cont_diff_at_snd.mul cont_diff_at_const).cos).congr_of_eventually_eq ((continuous_at_fst.eventually (gt_mem_nhds hneg)).mono (λ p hp, rpow_def_of_neg hp _)), ((cont_diff_at_fst.log hpos.ne').mul cont_diff_at_snd).exp.congr_of_eventually_eq ((continuous_at_fst.eventually (lt_mem_nhds hpos)).mono (λ p hp, rpow_def_of_pos hp _))] end lemma differentiable_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) : differentiable_at ℝ (λ p : ℝ × ℝ, p.1 ^ p.2) p := (cont_diff_at_rpow_of_ne p hp).differentiable_at le_rfl lemma _root_.has_strict_deriv_at.rpow {f g : ℝ → ℝ} {f' g' : ℝ} (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) (h : 0 < f x) : has_strict_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x := begin convert (has_strict_fderiv_at_rpow_of_pos ((λ x, (f x, g x)) x) h).comp_has_strict_deriv_at _ (hf.prod hg) using 1, simp [mul_assoc, mul_comm, mul_left_comm] end lemma has_strict_deriv_at_rpow_const_of_ne {x : ℝ} (hx : x ≠ 0) (p : ℝ) : has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := begin cases hx.lt_or_lt with hx hx, { have := (has_strict_fderiv_at_rpow_of_neg (x, p) hx).comp_has_strict_deriv_at x ((has_strict_deriv_at_id x).prod (has_strict_deriv_at_const _ _)), convert this, simp }, { simpa using (has_strict_deriv_at_id x).rpow (has_strict_deriv_at_const x p) hx } end lemma has_strict_deriv_at_const_rpow {a : ℝ} (ha : 0 < a) (x : ℝ) : has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a) x := by simpa using (has_strict_deriv_at_const _ _).rpow (has_strict_deriv_at_id x) ha /-- This lemma says that `λ x, a ^ x` is strictly differentiable for `a < 0`. Note that these values of `a` are outside of the "official" domain of `a ^ x`, and we may redefine `a ^ x` for negative `a` if some other definition will be more convenient. -/ lemma has_strict_deriv_at_const_rpow_of_neg {a x : ℝ} (ha : a < 0) : has_strict_deriv_at (λ x, a ^ x) (a ^ x * log a - exp (log a * x) * sin (x * π) * π) x := by simpa using (has_strict_fderiv_at_rpow_of_neg (a, x) ha).comp_has_strict_deriv_at x ((has_strict_deriv_at_const _ _).prod (has_strict_deriv_at_id _)) end real namespace real variables {z x y : ℝ} lemma has_deriv_at_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : has_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := begin rcases ne_or_eq x 0 with hx | rfl, { exact (has_strict_deriv_at_rpow_const_of_ne hx _).has_deriv_at }, replace h : 1 ≤ p := h.neg_resolve_left rfl, apply has_deriv_at_of_has_deriv_at_of_ne (λ x hx, (has_strict_deriv_at_rpow_const_of_ne hx p).has_deriv_at), exacts [continuous_at_id.rpow_const (or.inr (zero_le_one.trans h)), continuous_at_const.mul (continuous_at_id.rpow_const (or.inr (sub_nonneg.2 h)))] end lemma differentiable_rpow_const {p : ℝ} (hp : 1 ≤ p) : differentiable ℝ (λ x : ℝ, x ^ p) := λ x, (has_deriv_at_rpow_const (or.inr hp)).differentiable_at lemma deriv_rpow_const {x p : ℝ} (h : x ≠ 0 ∨ 1 ≤ p) : deriv (λ x : ℝ, x ^ p) x = p * x ^ (p - 1) := (has_deriv_at_rpow_const h).deriv lemma deriv_rpow_const' {p : ℝ} (h : 1 ≤ p) : deriv (λ x : ℝ, x ^ p) = λ x, p * x ^ (p - 1) := funext $ λ x, deriv_rpow_const (or.inr h) lemma cont_diff_at_rpow_const_of_ne {x p : ℝ} {n : with_top ℕ} (h : x ≠ 0) : cont_diff_at ℝ n (λ x, x ^ p) x := (cont_diff_at_rpow_of_ne (x, p) h).comp x (cont_diff_at_id.prod cont_diff_at_const) lemma cont_diff_rpow_const_of_le {p : ℝ} {n : ℕ} (h : ↑n ≤ p) : cont_diff ℝ n (λ x : ℝ, x ^ p) := begin induction n with n ihn generalizing p, { exact cont_diff_zero.2 (continuous_id.rpow_const (λ x, by exact_mod_cast or.inr h)) }, { have h1 : 1 ≤ p, from le_trans (by simp) h, rw [nat.cast_succ, ← le_sub_iff_add_le] at h, rw [cont_diff_succ_iff_deriv, deriv_rpow_const' h1], refine ⟨differentiable_rpow_const h1, cont_diff_const.mul (ihn h)⟩ } end lemma cont_diff_at_rpow_const_of_le {x p : ℝ} {n : ℕ} (h : ↑n ≤ p) : cont_diff_at ℝ n (λ x : ℝ, x ^ p) x := (cont_diff_rpow_const_of_le h).cont_diff_at lemma cont_diff_at_rpow_const {x p : ℝ} {n : ℕ} (h : x ≠ 0 ∨ ↑n ≤ p) : cont_diff_at ℝ n (λ x : ℝ, x ^ p) x := h.elim cont_diff_at_rpow_const_of_ne cont_diff_at_rpow_const_of_le lemma has_strict_deriv_at_rpow_const {x p : ℝ} (hx : x ≠ 0 ∨ 1 ≤ p) : has_strict_deriv_at (λ x, x ^ p) (p * x ^ (p - 1)) x := cont_diff_at.has_strict_deriv_at' (cont_diff_at_rpow_const (by rwa nat.cast_one)) (has_deriv_at_rpow_const hx) le_rfl end real section differentiability open real section fderiv variables {E : Type*} [normed_group E] [normed_space ℝ E] {f g : E → ℝ} {f' g' : E →L[ℝ] ℝ} {x : E} {s : set E} {c p : ℝ} {n : with_top ℕ} lemma has_fderiv_within_at.rpow (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) (h : 0 < f x) : has_fderiv_within_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') s x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp_has_fderiv_within_at x (hf.prod hg) lemma has_fderiv_at.rpow (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) (h : 0 < f x) : has_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).has_fderiv_at.comp x (hf.prod hg) lemma has_strict_fderiv_at.rpow (hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) (h : 0 < f x) : has_strict_fderiv_at (λ x, f x ^ g x) ((g x * f x ^ (g x - 1)) • f' + (f x ^ g x * log (f x)) • g') x := (has_strict_fderiv_at_rpow_of_pos (f x, g x) h).comp x (hf.prod hg) lemma differentiable_within_at.rpow (hf : differentiable_within_at ℝ f s x) (hg : differentiable_within_at ℝ g s x) (h : f x ≠ 0) : differentiable_within_at ℝ (λ x, f x ^ g x) s x := (differentiable_at_rpow_of_ne (f x, g x) h).comp_differentiable_within_at x (hf.prod hg) lemma differentiable_at.rpow (hf : differentiable_at ℝ f x) (hg : differentiable_at ℝ g x) (h : f x ≠ 0) : differentiable_at ℝ (λ x, f x ^ g x) x := (differentiable_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg) lemma differentiable_on.rpow (hf : differentiable_on ℝ f s) (hg : differentiable_on ℝ g s) (h : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ x, f x ^ g x) s := λ x hx, (hf x hx).rpow (hg x hx) (h x hx) lemma differentiable.rpow (hf : differentiable ℝ f) (hg : differentiable ℝ g) (h : ∀ x, f x ≠ 0) : differentiable ℝ (λ x, f x ^ g x) := λ x, (hf x).rpow (hg x) (h x) lemma has_fderiv_within_at.rpow_const (hf : has_fderiv_within_at f f' s x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_fderiv_within_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') s x := (has_deriv_at_rpow_const h).comp_has_fderiv_within_at x hf lemma has_fderiv_at.rpow_const (hf : has_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x := (has_deriv_at_rpow_const h).comp_has_fderiv_at x hf lemma has_strict_fderiv_at.rpow_const (hf : has_strict_fderiv_at f f' x) (h : f x ≠ 0 ∨ 1 ≤ p) : has_strict_fderiv_at (λ x, f x ^ p) ((p * f x ^ (p - 1)) • f') x := (has_strict_deriv_at_rpow_const h).comp_has_strict_fderiv_at x hf lemma differentiable_within_at.rpow_const (hf : differentiable_within_at ℝ f s x) (h : f x ≠ 0 ∨ 1 ≤ p) : differentiable_within_at ℝ (λ x, f x ^ p) s x := (hf.has_fderiv_within_at.rpow_const h).differentiable_within_at @[simp] lemma differentiable_at.rpow_const (hf : differentiable_at ℝ f x) (h : f x ≠ 0 ∨ 1 ≤ p) : differentiable_at ℝ (λ x, f x ^ p) x := (hf.has_fderiv_at.rpow_const h).differentiable_at lemma differentiable_on.rpow_const (hf : differentiable_on ℝ f s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 1 ≤ p) : differentiable_on ℝ (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const (h x hx) lemma differentiable.rpow_const (hf : differentiable ℝ f) (h : ∀ x, f x ≠ 0 ∨ 1 ≤ p) : differentiable ℝ (λ x, f x ^ p) := λ x, (hf x).rpow_const (h x) lemma has_fderiv_within_at.const_rpow (hf : has_fderiv_within_at f f' s x) (hc : 0 < c) : has_fderiv_within_at (λ x, c ^ f x) ((c ^ f x * log c) • f') s x := (has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_within_at x hf lemma has_fderiv_at.const_rpow (hf : has_fderiv_at f f' x) (hc : 0 < c) : has_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_rpow hc (f x)).has_deriv_at.comp_has_fderiv_at x hf lemma has_strict_fderiv_at.const_rpow (hf : has_strict_fderiv_at f f' x) (hc : 0 < c) : has_strict_fderiv_at (λ x, c ^ f x) ((c ^ f x * log c) • f') x := (has_strict_deriv_at_const_rpow hc (f x)).comp_has_strict_fderiv_at x hf lemma cont_diff_within_at.rpow (hf : cont_diff_within_at ℝ n f s x) (hg : cont_diff_within_at ℝ n g s x) (h : f x ≠ 0) : cont_diff_within_at ℝ n (λ x, f x ^ g x) s x := (cont_diff_at_rpow_of_ne (f x, g x) h).comp_cont_diff_within_at x (hf.prod hg) lemma cont_diff_at.rpow (hf : cont_diff_at ℝ n f x) (hg : cont_diff_at ℝ n g x) (h : f x ≠ 0) : cont_diff_at ℝ n (λ x, f x ^ g x) x := (cont_diff_at_rpow_of_ne (f x, g x) h).comp x (hf.prod hg) lemma cont_diff_on.rpow (hf : cont_diff_on ℝ n f s) (hg : cont_diff_on ℝ n g s) (h : ∀ x ∈ s, f x ≠ 0) : cont_diff_on ℝ n (λ x, f x ^ g x) s := λ x hx, (hf x hx).rpow (hg x hx) (h x hx) lemma cont_diff.rpow (hf : cont_diff ℝ n f) (hg : cont_diff ℝ n g) (h : ∀ x, f x ≠ 0) : cont_diff ℝ n (λ x, f x ^ g x) := cont_diff_iff_cont_diff_at.mpr $ λ x, hf.cont_diff_at.rpow hg.cont_diff_at (h x) lemma cont_diff_within_at.rpow_const_of_ne (hf : cont_diff_within_at ℝ n f s x) (h : f x ≠ 0) : cont_diff_within_at ℝ n (λ x, f x ^ p) s x := hf.rpow cont_diff_within_at_const h lemma cont_diff_at.rpow_const_of_ne (hf : cont_diff_at ℝ n f x) (h : f x ≠ 0) : cont_diff_at ℝ n (λ x, f x ^ p) x := hf.rpow cont_diff_at_const h lemma cont_diff_on.rpow_const_of_ne (hf : cont_diff_on ℝ n f s) (h : ∀ x ∈ s, f x ≠ 0) : cont_diff_on ℝ n (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const_of_ne (h x hx) lemma cont_diff.rpow_const_of_ne (hf : cont_diff ℝ n f) (h : ∀ x, f x ≠ 0) : cont_diff ℝ n (λ x, f x ^ p) := hf.rpow cont_diff_const h variable {m : ℕ} lemma cont_diff_within_at.rpow_const_of_le (hf : cont_diff_within_at ℝ m f s x) (h : ↑m ≤ p) : cont_diff_within_at ℝ m (λ x, f x ^ p) s x := (cont_diff_at_rpow_const_of_le h).comp_cont_diff_within_at x hf lemma cont_diff_at.rpow_const_of_le (hf : cont_diff_at ℝ m f x) (h : ↑m ≤ p) : cont_diff_at ℝ m (λ x, f x ^ p) x := by { rw ← cont_diff_within_at_univ at *, exact hf.rpow_const_of_le h } lemma cont_diff_on.rpow_const_of_le (hf : cont_diff_on ℝ m f s) (h : ↑m ≤ p) : cont_diff_on ℝ m (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const_of_le h lemma cont_diff.rpow_const_of_le (hf : cont_diff ℝ m f) (h : ↑m ≤ p) : cont_diff ℝ m (λ x, f x ^ p) := cont_diff_iff_cont_diff_at.mpr $ λ x, hf.cont_diff_at.rpow_const_of_le h end fderiv section deriv variables {f g : ℝ → ℝ} {f' g' x y p : ℝ} {s : set ℝ} lemma has_deriv_within_at.rpow (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) (h : 0 < f x) : has_deriv_within_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) s x := begin convert (hf.has_fderiv_within_at.rpow hg.has_fderiv_within_at h).has_deriv_within_at using 1, dsimp, ring end lemma has_deriv_at.rpow (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) (h : 0 < f x) : has_deriv_at (λ x, f x ^ g x) (f' * g x * (f x) ^ (g x - 1) + g' * f x ^ g x * log (f x)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow hg h end lemma has_deriv_within_at.rpow_const (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0 ∨ 1 ≤ p) : has_deriv_within_at (λ y, (f y)^p) (f' * p * (f x) ^ (p - 1)) s x := begin convert (has_deriv_at_rpow_const hx).comp_has_deriv_within_at x hf using 1, ring end lemma has_deriv_at.rpow_const (hf : has_deriv_at f f' x) (hx : f x ≠ 0 ∨ 1 ≤ p) : has_deriv_at (λ y, (f y)^p) (f' * p * (f x)^(p-1)) x := begin rw ← has_deriv_within_at_univ at *, exact hf.rpow_const hx end lemma deriv_within_rpow_const (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0 ∨ 1 ≤ p) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, (f x) ^ p) s x = (deriv_within f s x) * p * (f x) ^ (p - 1) := (hf.has_deriv_within_at.rpow_const hx).deriv_within hxs @[simp] lemma deriv_rpow_const (hf : differentiable_at ℝ f x) (hx : f x ≠ 0 ∨ 1 ≤ p) : deriv (λx, (f x)^p) x = (deriv f x) * p * (f x)^(p-1) := (hf.has_deriv_at.rpow_const hx).deriv end deriv end differentiability section limits open real filter /-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞`. -/ lemma tendsto_one_plus_div_rpow_exp (t : ℝ) : tendsto (λ (x : ℝ), (1 + t / x) ^ x) at_top (𝓝 (exp t)) := begin apply ((real.continuous_exp.tendsto _).comp (tendsto_mul_log_one_plus_div_at_top t)).congr' _, have h₁ : (1:ℝ)/2 < 1 := by linarith, have h₂ : tendsto (λ x : ℝ, 1 + t / x) at_top (𝓝 1) := by simpa using (tendsto_inv_at_top_zero.const_mul t).const_add 1, refine (eventually_ge_of_tendsto_gt h₁ h₂).mono (λ x hx, _), have hx' : 0 < 1 + t / x := by linarith, simp [mul_comm x, exp_mul, exp_log hx'], end /-- The function `(1 + t/x) ^ x` tends to `exp t` at `+∞` for naturals `x`. -/ lemma tendsto_one_plus_div_pow_exp (t : ℝ) : tendsto (λ (x : ℕ), (1 + t / (x:ℝ)) ^ x) at_top (𝓝 (real.exp t)) := ((tendsto_one_plus_div_rpow_exp t).comp tendsto_coe_nat_at_top_at_top).congr (by simp) end limits
372e20efd1aab79757caf9040fa457bf0b57a591
4c630d016e43ace8c5f476a5070a471130c8a411
/tactic/basic.lean
2a771c3013263a97e8383354ba7bebb411def919
[ "Apache-2.0" ]
permissive
ngamt/mathlib
9a510c391694dc43eec969914e2a0e20b272d172
58909bd424209739a2214961eefaa012fb8a18d2
refs/heads/master
1,585,942,993,674
1,540,739,585,000
1,540,916,815,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,946
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison -/ import data.dlist.basic category.basic namespace name meta def deinternalize_field : name → 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 end name namespace name_set meta def filter (s : name_set) (P : name → bool) : name_set := s.fold s (λ a m, if P a then m else m.erase a) meta def mfilter {m} [monad m] (s : name_set) (P : name → m bool) : m name_set := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) meta def union (s t : name_set) : name_set := s.fold t (λ a t, t.insert a) end name_set namespace expr open tactic attribute [derive has_reflect] binder_info 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 protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] meta def is_meta_var : expr → bool | (mvar _ _ _) := tt | e := ff meta def is_sort : expr → bool | (sort _) := tt | e := ff meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) 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) meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_meta_var then insert e' es else es) 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 /- only traverses the direct descendents -/ meta def {u} traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) end expr namespace environment meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) meta def is_structure_like (env : environment) (n : name) : option (nat × name) := do guardb (env.is_inductive n), d ← (env.get n).to_option, [intro] ← pure (env.constructors_of n) | none, guard (env.inductive_num_indices n = 0), some (env.inductive_num_params n, intro) meta def is_structure (env : environment) (n : name) : bool := option.is_some $ do (nparams, intro) ← env.is_structure_like n, di ← (env.get intro).to_option, expr.pi x _ _ _ ← nparams.iterate (λ e : option expr, do expr.pi _ _ _ body ← e | none, some body) (some di.type) | none, env.is_projection (n ++ x.deinternalize_field) end environment namespace interaction_monad open result meta def get_result {σ α} (tac : interaction_monad σ α) : interaction_monad σ (interaction_monad.result σ α) | s := match tac s with | r@(success _ s') := success r s' | r@(exception _ _ s') := success r s' end end interaction_monad namespace lean.parser open lean interaction_monad.result meta def of_tactic' {α} (tac : tactic α) : parser α := do r ← of_tactic (interaction_monad.get_result tac), match r with | (success a _) := return a | (exception f pos _) := exception f pos end end lean.parser namespace tactic meta def is_simp_lemma : name → tactic bool := succeeds ∘ tactic.has_attribute `simp meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file' e d.to_name then s.insert d.to_name d else s), pure xs meta def simp_lemmas_from_file : tactic name_set := do s ← local_decls, let s := s.map (expr.list_constant ∘ declaration.value), xs ← s.to_list.mmap ((<$>) name_set.of_list ∘ mfilter tactic.is_simp_lemma ∘ name_set.to_list ∘ prod.snd), return $ name_set.filter (xs.foldl name_set.union mk_name_set) (λ x, ¬ s.contains x) meta def file_simp_attribute_decl (attr : name) : tactic unit := do s ← simp_lemmas_from_file, trace format!"run_cmd mk_simp_attr `{attr}", let lmms := format.join $ list.intersperse " " $ s.to_list.map to_fmt, trace format!"local attribute [{attr}] {lmms}" meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) meta def local_def_value (e : expr) : tactic expr := do do (v,_) ← solve_aux `(true) (do (expr.elet n t v _) ← (revert e >> target) | fail format!"{e} is not a local definition", return v), return v meta def check_defn (n : name) (e : pexpr) : tactic unit := do (declaration.defn _ _ _ d _ _) ← get_decl n, e' ← to_expr e, guard (d =ₐ e') <|> trace d >> failed -- meta def compile_eqn (n : name) (univ : list name) (args : list expr) (val : expr) (num : ℕ) : tactic unit := -- do let lhs := (expr.const n $ univ.map level.param).mk_app args, -- stmt ← mk_app `eq [lhs,val], -- let vs := stmt.list_local_const, -- let stmt := stmt.pis vs, -- (_,pr) ← solve_aux stmt (tactic.intros >> reflexivity), -- add_decl $ declaration.thm (n <.> "equations" <.> to_string (format!"_eqn_{num}")) univ stmt (pure pr) meta def to_implicit : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map to_implicit <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least m times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) end instance_cache /-- Reset the instance cache for the main goal. -/ meta def reset_instance_cache : tactic unit := unfreeze_local_instances meta def match_head (e : expr) : expr → tactic unit | e' := unify e e' <|> do `(_ → %%e') ← whnf e', v ← mk_mvar, match_head (e'.instantiate_var v) meta def find_matching_head : expr → list expr → tactic (list expr) | e [] := return [] | e (H :: Hs) := do t ← infer_type H, ((::) H <$ match_head e t <|> pure id) <*> find_matching_head e Hs meta def subst_locals (s : list (expr × expr)) (e : expr) : expr := (e.abstract_locals (s.map (expr.local_uniq_name ∘ prod.fst)).reverse).instantiate_vars (s.map prod.snd) meta def set_binder : expr → list binder_info → expr | e [] := e | (expr.pi v _ d b) (bi :: bs) := expr.pi v bi d (set_binder b bs) | e _ := e meta def last_explicit_arg : expr → tactic expr | (expr.app f e) := do t ← infer_type f >>= whnf, if t.binding_info = binder_info.default then pure e else last_explicit_arg f | e := pure e private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of the given (Pi-)type -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of the given function -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity /-- variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] meta def drop_binders : expr → tactic expr | (expr.pi n bi t b) := b.instantiate_var <$> mk_local' n bi t >>= drop_binders | e := pure e meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, [c] ← pure $ env.constructors_of struct_n | fail "too many constructors", vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do e ← mk_const (n.update_prefix struct_n) >>= infer_type >>= drop_binders, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) open nat meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /--`iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /--`iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /--`apply_list l`: try to apply the tactics in the list `l` on the first goal, and fail if none succeeds -/ meta def apply_list_expr : list expr → tactic unit | [] := fail "no matching rule" | (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t /-- constructs a list of expressions given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list.-/ meta def build_list_expr_for_apply : list pexpr → tactic (list expr) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← list.mmap mk_const l, return (m.append tail)) <|> return (a::tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times -/ meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit := do l ← build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l) meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' meta def symm_apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := tactic.apply e cfg <|> (symmetry >> tactic.apply e cfg) meta def apply_assumption (asms : tactic (list expr) := local_context) (tac : tactic unit := skip) : tactic unit := do { ctx ← asms, ctx.any_of (λ H, symm_apply H >> tac) } <|> do { exfalso, ctx ← asms, ctx.any_of (λ H, symm_apply H >> tac) } <|> fail "assumption tactic failed" open nat meta def solve_by_elim_aux (discharger : tactic unit) (asms : tactic (list expr)) : ℕ → tactic unit | 0 := done | (succ n) := discharger <|> (apply_assumption asms $ solve_by_elim_aux n) meta structure by_elim_opt := (discharger : tactic unit := done) (assumptions : tactic (list expr) := local_context) (max_rep : ℕ := 3) meta def solve_by_elim (opt : by_elim_opt := { }) : tactic unit := do tactic.fail_if_no_goals, focus1 $ solve_by_elim_aux opt.discharger opt.assumptions opt.max_rep meta def metavariables : tactic (list expr) := do r ← result, pure (r.list_meta_vars) /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do goals ← get_goals, p ← is_proof goals.head, guard p variable {α : Type} private meta def iterate_aux (t : tactic α) : list α → tactic (list α) | L := (do r ← t, iterate_aux (r :: L)) <|> return L /-- Apply a tactic as many times as possible, collecting the results in a list. -/ meta def iterate' (t : tactic α) : tactic (list α) := list.reverse <$> iterate_aux t [] /-- Like iterate', but fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (α × list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate' t, return (r, L) meta def intros1 : tactic (list expr) := iterate1 intro1 >>= λ p, return (p.1 :: p.2) /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Return target after instantiating metavars and whnf -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | tactic.fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] meta def note_anon (e : expr) : tactic unit := do n ← get_unused_name "lh", note n none e, skip meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, prod.snd <$> solve_aux t' assumption /-- `dependent_pose_core l`: introduce dependent hypothesis, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), t ← target, new_goal ← mk_meta_var (t.pis lc), old::other_goals ← get_goals, set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- like `mk_local_pis` but translating into weak head normal form before checking if it is a Π. -/ meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do (expr.pi n bi d b) ← whnf e | return ([], e), p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) /-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g` -/ meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do t ← infer_type h, (ctxt, t) ← mk_local_pis_whnf t, `(@Exists %%α %%p) ← whnf t transparency.all | fail "expected a term of the shape ∀xs, ∃a, p xs a", α_t ← infer_type α, expr.sort u ← whnf α_t transparency.all, value ← mk_local_def data (α.pis ctxt), t' ← head_beta (p.app (value.mk_app ctxt)), spec ← mk_local_def spec (t'.pis ctxt), dependent_pose_core [ (value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt), (spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)], try (tactic.clear h), intro1, intro1 /-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`, an a final hypothesis on `p as` -/ meta def choose : expr → list name → tactic unit | h [] := fail "expect list of variables" | h [n] := do cnt ← revert h, intro n, intron (cnt - 1), return () | h (n::ns) := do v ← get_unused_name >>= choose1 h n, choose v ns /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ``` instance : monad id := {! !} ``` invoking hole command `Instance Stub` produces: ``` instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := list.intersperse (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {format.join fs} }", return [(out,"")] } meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache end tactic
081ac9dea6b645ade7e8efbd24ff469df47c740c
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/congr_tactic.lean
a5ba2a7377a418ffa2c2f89d38b241eb4df3edf4
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
2,684
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam -/ open tactic namespace test1 -- Recursive with props and subsingletons constants (α β γ : Type) (P : α → Prop) (Q : β → Prop) (SS : α → Type) (SS_ss : ∀ (x : α), subsingleton (SS x)) (f : Π (x : α), P x → β → SS x → γ) (p₁ p₂ : ∀ (x : α), P x) (h : β → β) (k₁ k₂ : ∀ (x : α), SS x) attribute [instance] SS_ss example (x₁ x₂ x₁' x₂' x₃ x₃' : α) (y₁ y₁' : β) (H : y₁ = y₁') : f x₁ (p₁ x₁) (h $ h $ h y₁) (k₁ x₁) = f x₁ (p₂ x₁) (h $ h $ h y₁') (k₂ x₁) := begin congr, exact H, end end test1 namespace test2 -- Specializing to the prefix with props and subsingletons constants (γ : Type) (f : Π (α : Type*) (β : Sort*), α → β → γ) (X : Type) (X_ss : subsingleton X) (Y : Prop) attribute [instance] X_ss example (x₁ x₂ : X) (y₁ y₂ : Y) : f X Y x₁ y₁ = f X Y x₂ y₂ := by congr end test2 namespace test3 -- Edge case: goal proved by apply, not refl constants (f : ℕ → ℕ) example (n : ℕ) : f n = f n := by congr end test3 namespace test4 -- Heq result constants (α : Type) (β : α → Type) (γ : Type) (f : Π (x : α) (y : β x), γ) example (x x' : α) (y : β x) (y' : β x') (H_x : x = x') (H_y : y == y') : f x y = f x' y' := begin congr, exact H_x, exact H_y end end test4 namespace test5 -- heq in the goal constants (α : Type) (β : α → Type) (γ : Π (x : α), β x → Type) (f : Π (x : α) (y : β x), γ x y) example (x x' : α) (y : β x) (y' : β x') (H_x : x = x') (H_y : y == y') : f x y == f x' y' := begin congr, exact H_x, exact H_y end end test5 namespace test6 -- iff relation constants (α : Type*) (R : α → α → Prop) (R_refl : ∀ x, R x x) (R_symm : ∀ x y, R x y → R y x) (R_trans : ∀ x y z, R x y → R y z → R x z) attribute [refl] R_refl attribute [symm] R_symm attribute [trans] R_trans example (x₁ x₁' x₂ x₂' : α) (H₁ : R x₁ x₁') (H₂ : R x₂ x₂') : R x₁ x₂ ↔ R x₁' x₂' := begin rel_congr, exact H₁, exact H₂ end -- eq relation example (x₁ x₁' x₂ x₂' : α) (H₁ : R x₁ x₁') (H₂ : R x₂ x₂') : R x₁ x₂ = R x₁' x₂' := begin rel_congr, exact H₁, exact H₂ end end test6 namespace test7 variables (A : Type) (B : A → Type) (a a' : A) (b : B a) (b' : B a') example : (⟨a, b⟩ : Σ a : A, B a) = ⟨a', b'⟩ := begin congr, show a = a', from sorry, show b == b', from sorry, end end test7
46e8fa0706c22655e5654fc2cc302327fd9a8f6e
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/synth1.lean
28faf0b0838110fad85aa45829abf8c4ece65893
[ "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,380
lean
import Lean.Meta open Lean open Lean.Meta class HasCoerce (a b : Type) := (coerce : a → b) def coerce {a b : Type} [HasCoerce a b] : a → b := @HasCoerce.coerce a b _ instance coerceTrans {a b c : Type} [HasCoerce b c] [HasCoerce a b] : HasCoerce a c := ⟨fun x => coerce (coerce x : b)⟩ instance coerceBoolToProp : HasCoerce Bool Prop := ⟨fun y => y = true⟩ instance coerceDecidableEq (x : Bool) : Decidable (coerce x) := inferInstanceAs (Decidable (x = true)) instance coerceNatToBool : HasCoerce Nat Bool := ⟨fun x => x == 0⟩ instance coerceNatToInt : HasCoerce Nat Int := ⟨fun x => Int.ofNat x⟩ def print {α} [HasToString α] (a : α) : MetaM Unit := trace! `Meta.synthInstance (toString a) set_option trace.Meta.synthInstance true set_option trace.Meta.synthInstance.tryResolve false def tst1 : MetaM Unit := do inst ← mkAppM `HasCoerce #[mkConst `Nat, mkSort levelZero]; r ← synthInstance inst; print r #eval tst1 def tst2 : MetaM Unit := do inst ← mkAppM `HasBind #[mkConst `IO]; -- globalInstances ← getGlobalInstances; -- print (format globalInstances); -- result ← globalInstances.getUnify inst; -- print result; r ← synthInstance inst; print r; pure () #eval tst2 def tst3 : MetaM Unit := do inst ← mkAppM `HasBeq #[mkConst `Nat]; r ← synthInstance inst; print r; pure () #eval tst3
52ba2e64005a1b8da006dd6a397d283ef3949628
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/set/basic.lean
9e1ae8c6af16a52f90b0279311ab0bdb6364b3b3
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
44,396
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import tactic.ext tactic.finish data.subtype tactic.interactive open function /- set coercion to a type -/ namespace set instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ end set section set_coe universe u variables {α : Type u} @[simp] theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.property namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[extensionality] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨begin intros h x, rw h end, ext⟩ @[trans] theorem mem_of_mem_of_subset {α : Type u} {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /- mem and set_of -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {α} {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl @[simp] lemma set_of_mem {α} {s : set α} : {a | a ∈ s} = s := rfl /- subset -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {α : Type u} {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alterantive name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a, a ∈ s ∧ a ∉ t := by simp [subset_def, classical.not_forall] /- strict subset -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ s ≠ t instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ s ≠ t) := rfl lemma exists_of_ssubset {α : Type u} {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := classical.by_contradiction $ assume hn, have t ⊆ s, from assume a hat, classical.by_contradiction $ assume has, hn ⟨a, hat, has⟩, h.2 $ subset.antisymm h.1 this lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : ¬ (a ∉ s) ↔ a ∈ s := not_not /- empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] theorem ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := by { intro hs, rw hs at h, apply not_mem_empty _ h } @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem] theorem exists_mem_of_ne_empty {s : set α} : s ≠ ∅ → ∃ x, x ∈ s := ne_empty_iff_exists_mem.1 theorem coe_nonempty_iff_ne_empty {s : set α} : nonempty s ↔ s ≠ ∅ := nonempty_subtype.trans ne_empty_iff_exists_mem.symm -- TODO: remove when simplifier stops rewriting `a ≠ b` to `¬ a = b` theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem subset_ne_empty {s t : set α} (h : t ⊆ s) : t ≠ ∅ → s ≠ ∅ := mt (subset_eq_empty h) theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /- universal set -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : inhabited α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma nonempty_iff_univ_ne_empty {α : Type*} : nonempty α ↔ (univ : set α) ≠ ∅ := begin split, { rintro ⟨a⟩ H2, show a ∈ (∅ : set α), by rw ←H2 ; trivial }, { intro H, cases exists_mem_of_ne_empty H with a _, exact ⟨a⟩ } end instance univ_decidable : decidable_pred (@set.univ α) := λ x, is_true trivial /- union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /- intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set α} (h : s ∩ t ≠ ∅) : t ≠ ∅ := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set α} (h : s ∩ t ≠ ∅) : s ≠ ∅ := by finish [ext_iff, iff_def] /- distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /- insert -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_def, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] -- TODO(Jeremy): make this automatic theorem insert_ne_empty (a : α) (s : set α) : insert a s ≠ ∅ := by safe [ext_iff, iff_def]; have h' := a_1 a; finish -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /- singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := insert_ne_empty _ _ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := ext $ by simp @[simp] theorem union_singleton : s ∪ {a} = insert a s := by simp [singleton_def] @[simp] theorem singleton_union : {a} ∪ s = insert a s := by rw [union_comm, union_singleton] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] /- separation -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := set.ext $ by simp /- complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h lemma compl_set_of {α} (p : α → Prop) : - {a | p a} = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff /- set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := ext $ by simp /- powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /- inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage_eq {s : set β} {a : α} : (a ∈ f ⁻¹' s) = (f a ∈ s) := rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : α → β) (a : set α) : Prop := ∀ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem mono_image {f : α → β} {s t : set α} (h : s ⊆ t) : f '' s ⊆ f '' t := assume x ⟨y, hy, y_eq⟩, y_eq ▸ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] theorem image_eq_image_of_eq_on {f₁ f₂ : α → β} {s : set α} (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := ext $ λ x, by simp [image]; rw eq_comm lemma inter_singleton_ne_empty {α : Type*} {s : set α} {a : α} : s ∩ {a} ≠ ∅ ↔ a ∈ s := by finish [set.inter_singleton_eq_empty] theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set α) : id '' s = s := ext $ by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq]) (assume eq, eq ▸ rfl) lemma surjective_preimage {f : β → α} (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma subtype_val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma injective_image {f : α → β} (hf : injective f) : injective (('') f) := assume s t, (image_eq_image hf).1 lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := ⟨assume ⟨a, ⟨i, eq⟩, h⟩, ⟨i, eq.symm ▸ h⟩, assume ⟨i, h⟩, ⟨f i, mem_range_self _, h⟩⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := ext $ by simp [image, range] theorem image_subset_range {ι : Type*} (f : ι → β) (s : set ι) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {ι : Type*} {f : ι → β} {s : set β} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma nonempty_of_nonempty_range {α : Type*} {β : Type*} {f : α → β} (H : ¬range f = ∅) : nonempty α := begin cases exists_mem_of_ne_empty H with x h, cases mem_range.1 h with y _, exact ⟨y⟩ end theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma subtype_val_range {p : α → Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype_val_image] end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y theorem pairwise_on.mono {s t : set α} {r} (h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r := λ x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop} (H : ∀ a b, r a b → r' a b) (hp : pairwise_on s r) : pairwise_on s r' := λ x xs y ys h, H _ _ (hp x xs y ys h) end set namespace set section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ @[simp] theorem prod_empty {s : set α} : set.prod s ∅ = (∅ : set (α × β)) := ext $ by simp [set.prod] @[simp] theorem empty_prod {t : set β} : set.prod ∅ t = (∅ : set (α × β)) := ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := ext $ by simp [set.prod] theorem prod_neq_empty_iff {s : set α} {t : set β} : set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := by simp [not_eq_empty_iff_exists] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] end prod section pi variables {α : Type*} {π : α → Type*} def pi (i : set α) (s : Πa, set (π a)) : set (Πa, π a) := { f | ∀a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Πa, set (π a)) : pi ∅ s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : α) (i : set α) (s : Πa, set (π a)) : pi (insert a i) s = ((λf, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : α) (s : Πa, set (π a)) : pi {a} s = ((λf:(Πa, π a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : α → Prop} [h : decidable_pred p] (i : set α) (s t : Πa, set (π a)) : pi i (λa, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | ¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi end set
1126fabb7acff81823907a8a412d8ca039ed4e1f
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/number_theory/bernoulli_polynomials.lean
3778b2a1e70fefe0af9cb908f37acad1ca2c4c94
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,144
lean
/- Copyright (c) 2021 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ashvni Narayanan -/ import number_theory.bernoulli /-! # Bernoulli polynomials The Bernoulli polynomials (defined here : https://en.wikipedia.org/wiki/Bernoulli_polynomials) are an important tool obtained from Bernoulli numbers. ## Mathematical overview The $n$-th Bernoulli polynomial is defined as $$ B_n(X) = ∑_{k = 0}^n {n \choose k} (-1)^k * B_k * X^{n - k} $$ where $B_k$ is the $k$-th Bernoulli number. The Bernoulli polynomials are generating functions, $$ t * e^{tX} / (e^t - 1) = ∑_{n = 0}^{\infty} B_n(X) * \frac{t^n}{n!} $$ ## Implementation detail Bernoulli polynomials are defined using `bernoulli`, the Bernoulli numbers. ## Main theorems - `sum_bernoulli_poly`: The sum of the $k^\mathrm{th}$ Bernoulli polynomial with binomial coefficients up to n is `(n + 1) * X^n`. - `exp_bernoulli_poly`: The Bernoulli polynomials act as generating functions for the exponential. ## TODO - `bernoulli_poly_eval_one_neg` : $$ B_n(1 - x) = (-1)^n*B_n(x) $$ - ``bernoulli_poly_eval_one` : Follows as a consequence of `bernoulli_poly_eval_one_neg`. -/ noncomputable theory open_locale big_operators open_locale nat open nat finset /-- The Bernoulli polynomials are defined in terms of the negative Bernoulli numbers. -/ def bernoulli_poly (n : ℕ) : polynomial ℚ := ∑ i in range (n + 1), polynomial.monomial (n - i) ((bernoulli i) * (choose n i)) lemma bernoulli_poly_def (n : ℕ) : bernoulli_poly n = ∑ i in range (n + 1), polynomial.monomial i ((bernoulli (n - i)) * (choose n i)) := begin rw [←sum_range_reflect, add_succ_sub_one, add_zero, bernoulli_poly], apply sum_congr rfl, rintros x hx, rw mem_range_succ_iff at hx, rw [choose_symm hx, nat.sub_sub_self hx], end namespace bernoulli_poly /- ### examples -/ section examples @[simp] lemma bernoulli_poly_zero : bernoulli_poly 0 = 1 := by simp [bernoulli_poly] @[simp] lemma bernoulli_poly_eval_zero (n : ℕ) : (bernoulli_poly n).eval 0 = bernoulli n := begin rw [bernoulli_poly, polynomial.eval_finset_sum, sum_range_succ], have : ∑ (x : ℕ) in range n, bernoulli x * (n.choose x) * 0 ^ (n - x) = 0, { apply sum_eq_zero (λ x hx, _), have h : 0 < n - x := nat.sub_pos_of_lt (mem_range.1 hx), simp [h] }, simp [this], end @[simp] lemma bernoulli_poly_eval_one (n : ℕ) : (bernoulli_poly n).eval 1 = bernoulli' n := begin simp only [bernoulli_poly, polynomial.eval_finset_sum], simp only [←succ_eq_add_one, sum_range_succ, mul_one, cast_one, choose_self, (bernoulli _).mul_comm, sum_bernoulli, one_pow, mul_one, polynomial.eval_C, polynomial.eval_monomial], by_cases h : n = 1, { norm_num [h], }, { simp [h], exact bernoulli_eq_bernoulli'_of_ne_one h, } end end examples @[simp] theorem sum_bernoulli_poly (n : ℕ) : ∑ k in range (n + 1), ((n + 1).choose k : ℚ) • bernoulli_poly k = polynomial.monomial n (n + 1 : ℚ) := begin simp_rw [bernoulli_poly_def, finset.smul_sum, finset.range_eq_Ico, ←finset.sum_Ico_Ico_comm, finset.sum_Ico_eq_sum_range], simp only [cast_succ, nat.add_sub_cancel_left, nat.sub_zero, zero_add, linear_map.map_add], simp_rw [polynomial.smul_monomial, mul_comm (bernoulli _) _, smul_eq_mul, ←mul_assoc], conv_lhs { apply_congr, skip, conv { apply_congr, skip, rw [choose_mul ((nat.le_sub_left_iff_add_le (mem_range_le H)).1 (mem_range_le H_1)) (le.intro rfl), add_comm x x_1, nat.add_sub_cancel, mul_assoc, mul_comm, ←smul_eq_mul, ←polynomial.smul_monomial], }, rw [←sum_smul], }, rw sum_range_succ, simp only [add_right_eq_self, cast_succ, mul_one, cast_one, cast_add, nat.add_sub_cancel_left, choose_succ_self_right, one_smul, bernoulli_zero, sum_singleton, zero_add, linear_map.map_add, range_one], apply sum_eq_zero (λ x hx, _), have f : ∀ x ∈ range n, ¬ n + 1 - x = 1, { rintros x H, rw [mem_range] at H, rw [eq_comm], exact ne_of_lt (nat.lt_of_lt_of_le one_lt_two (nat.le_sub_left_of_add_le (succ_le_succ H))), }, rw [sum_bernoulli], have g : (ite (n + 1 - x = 1) (1 : ℚ) 0) = 0, { simp only [ite_eq_right_iff, one_ne_zero], intro h₁, exact (f x hx) h₁, }, rw [g, zero_smul], end open power_series open polynomial (aeval) variables {A : Type*} [comm_ring A] [algebra ℚ A] -- TODO: define exponential generating functions, and use them here -- This name should probably be updated afterwards /-- The theorem that `∑ Bₙ(t)X^n/n!)(e^X-1)=Xe^{tX}` -/ theorem exp_bernoulli_poly' (t : A) : mk (λ n, aeval t ((1 / n! : ℚ) • bernoulli_poly n)) * (exp A - 1) = X * rescale t (exp A) := begin -- check equality of power series by checking coefficients of X^n ext n, -- n = 0 case solved by `simp` cases n, { simp }, -- n ≥ 1, the coefficients is a sum to n+2, so use `sum_range_succ` to write as -- last term plus sum to n+1 rw [coeff_succ_X_mul, coeff_rescale, coeff_exp, coeff_mul, nat.sum_antidiagonal_eq_sum_range_succ_mk, sum_range_succ], -- last term is zero so kill with `zero_add` simp only [ring_hom.map_sub, nat.sub_self, constant_coeff_one, constant_coeff_exp, coeff_zero_eq_constant_coeff, mul_zero, sub_self, zero_add], -- Let's multiply both sides by (n+1)! (OK because it's a unit) set u : units ℚ := ⟨(n+1)!, (n+1)!⁻¹, mul_inv_cancel (by exact_mod_cast factorial_ne_zero (n+1)), inv_mul_cancel (by exact_mod_cast factorial_ne_zero (n+1))⟩ with hu, rw ←units.mul_right_inj (units.map (algebra_map ℚ A).to_monoid_hom u), -- now tidy up unit mess and generally do trivial rearrangements -- to make RHS (n+1)*t^n rw [units.coe_map, mul_left_comm, ring_hom.to_monoid_hom_eq_coe, ring_hom.coe_monoid_hom, ←ring_hom.map_mul, hu, units.coe_mk], change _ = t^n * algebra_map ℚ A (((n+1)*n! : ℕ)*(1/n!)), rw [cast_mul, mul_assoc, mul_one_div_cancel (show (n! : ℚ) ≠ 0, from cast_ne_zero.2 (factorial_ne_zero n)), mul_one, mul_comm (t^n), ← polynomial.aeval_monomial, cast_add, cast_one], -- But this is the RHS of `sum_bernoulli_poly` rw [← sum_bernoulli_poly, finset.mul_sum, alg_hom.map_sum], -- and now we have to prove a sum is a sum, but all the terms are equal. apply finset.sum_congr rfl, -- The rest is just trivialities, hampered by the fact that we're coercing -- factorials and binomial coefficients between ℕ and ℚ and A. intros i hi, -- NB prime.choose_eq_factorial_div_factorial' is in the wrong namespace -- deal with coefficients of e^X-1 simp only [choose_eq_factorial_div_factorial' (mem_range_le hi), coeff_mk, if_neg (mem_range_sub_ne_zero hi), one_div, alg_hom.map_smul, coeff_one, units.coe_mk, coeff_exp, sub_zero, linear_map.map_sub, algebra.smul_mul_assoc, algebra.smul_def, mul_right_comm _ ((aeval t) _), ←mul_assoc, ← ring_hom.map_mul, succ_eq_add_one], -- finally cancel the Bernoulli polynomial and the algebra_map congr', apply congr_arg, rw [mul_assoc, div_eq_mul_inv, ← mul_inv'], end end bernoulli_poly
7ee2bbab8f31ad0790f541ae313ffbab2b738ed7
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/algebra/field.lean
2906a5428b48cc64e5fbf86b97b44f4dcae72b5b
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
18,265
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura Structures with multiplicative and additive components, including division rings and fields. The development is modeled after Isabelle's library. -/ prelude import init.algebra.ring universe u /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 class division_ring (α : Type u) extends ring α, has_inv α, zero_ne_one_class α := (mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1) (inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1) variable {α : Type u} section division_ring variables [division_ring α] protected definition algebra.div (a b : α) : α := a * b⁻¹ instance division_ring_has_div [division_ring α] : has_div α := ⟨algebra.div⟩ lemma division_def (a b : α) : a / b = a * b⁻¹ := rfl @[simp] lemma mul_inv_cancel {a : α} (h : a ≠ 0) : a * a⁻¹ = 1 := division_ring.mul_inv_cancel h @[simp] lemma inv_mul_cancel {a : α} (h : a ≠ 0) : a⁻¹ * a = 1 := division_ring.inv_mul_cancel h @[simp] lemma one_div_eq_inv (a : α) : 1 / a = a⁻¹ := one_mul a⁻¹ lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := by simp local attribute [simp] division_def mul_comm mul_assoc mul_left_comm mul_inv_cancel inv_mul_cancel lemma div_eq_mul_one_div (a b : α) : a / b = a * (1 / b) := by simp lemma mul_one_div_cancel {a : α} (h : a ≠ 0) : a * (1 / a) = 1 := by simp [h] lemma one_div_mul_cancel {a : α} (h : a ≠ 0) : (1 / a) * a = 1 := by simp [h] lemma div_self {a : α} (h : a ≠ 0) : a / a = 1 := by simp [h] lemma one_div_one : 1 / 1 = (1:α) := div_self (ne.symm zero_ne_one) lemma mul_div_assoc (a b c : α) : (a * b) / c = a * (b / c) := by simp lemma one_div_ne_zero {a : α} (h : a ≠ 0) : 1 / a ≠ 0 := suppose 1 / a = 0, have 0 = (1:α), from eq.symm (by rw [-(mul_one_div_cancel h), this, mul_zero]), absurd this zero_ne_one lemma one_inv_eq : 1⁻¹ = (1:α) := calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul] ... = (1:α) : by simp local attribute [simp] one_inv_eq lemma div_one (a : α) : a / 1 = a := by simp lemma zero_div (a : α) : 0 / a = 0 := by simp -- note: integral domain has a "mul_ne_zero". α commutative division ring is an integral -- domain, but let's not define that class for now. lemma division_ring.mul_ne_zero {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := suppose a * b = 0, have a * 1 = 0, by rw [-(mul_one_div_cancel hb), -mul_assoc, this, zero_mul], have a = 0, by rwa mul_one at this, absurd this ha lemma mul_ne_zero_comm {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := have h₁ : a ≠ 0, from ne_zero_of_mul_ne_zero_right h, have h₂ : b ≠ 0, from ne_zero_of_mul_ne_zero_left h, division_ring.mul_ne_zero h₂ h₁ lemma eq_one_div_of_mul_eq_one {a b : α} (h : a * b = 1) : b = 1 / a := have a ≠ 0, from suppose a = 0, have 0 = (1:α), by rwa [this, zero_mul] at h, absurd this zero_ne_one, have b = (1 / a) * a * b, by rw [one_div_mul_cancel this, one_mul], show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this lemma eq_one_div_of_mul_eq_one_left {a b : α} (h : b * a = 1) : b = 1 / a := have a ≠ 0, from suppose a = 0, have 0 = (1:α), by rwa [this, mul_zero] at h, absurd this zero_ne_one, by rw [-h, mul_div_assoc, div_self this, mul_one] lemma division_ring.one_div_mul_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (b * a) := have (b * a) * ((1 / a) * (1 / b)) = 1, by rw [mul_assoc, -(mul_assoc a), mul_one_div_cancel ha, one_mul, mul_one_div_cancel hb], eq_one_div_of_mul_eq_one this lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 := have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one this) lemma division_ring.one_div_neg_eq_neg_one_div {a : α} (h : a ≠ 0) : 1 / (- a) = - (1 / a) := have -1 ≠ (0:α), from (suppose -1 = 0, absurd (eq.symm (calc 1 = -(-1) : (neg_neg (1:α)).symm ... = -0 : by rw this ... = (0:α) : neg_zero)) zero_ne_one), calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw (division_ring.one_div_mul_one_div h this) ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one] lemma div_neg_eq_neg_div {a : α} (b : α) (ha : a ≠ 0) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [-inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw (division_ring.one_div_neg_eq_neg_one_div ha) ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b * a⁻¹) : by rw inv_eq_one_div lemma neg_div (a b : α) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, -neg_eq_neg_one_mul] lemma division_ring.neg_div_neg_eq (a : α) {b : α} (hb : b ≠ 0) : (-a) / (-b) = a / b := by rw [(div_neg_eq_neg_div _ hb), neg_div, neg_neg] lemma division_ring.one_div_one_div {a : α} (h : a ≠ 0) : 1 / (1 / a) = a := eq.symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel h)) lemma division_ring.eq_of_one_div_eq_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) (h : 1 / a = 1 / b) : a = b := by rw [-(division_ring.one_div_one_div ha), h, (division_ring.one_div_one_div hb)] lemma mul_inv_eq {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := eq.symm $ calc a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by simp ... = (1 / (b * a)) : division_ring.one_div_mul_one_div ha hb ... = (b * a)⁻¹ : by simp lemma mul_div_cancel (a : α) {b : α} (hb : b ≠ 0) : a * b / b = a := by simp [hb] lemma div_mul_cancel (a : α) {b : α} (hb : b ≠ 0) : a / b * b = a := by simp [hb] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, -neg_div, div_add_div_same, sub_eq_add_neg] lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] lemma div_eq_one_iff_eq (a : α) {b : α} (hb : b ≠ 0) : a / b = 1 ↔ a = b := iff.intro (suppose a / b = 1, calc a = a / b * b : by simp [hb] ... = 1 * b : by rw this ... = b : by simp) (suppose a = b, by simp [this, hb]) lemma eq_of_div_eq_one (a : α) {b : α} (Hb : b ≠ 0) : a / b = 1 → a = b := iff.mp $ div_eq_one_iff_eq a Hb lemma eq_div_iff_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a = b / c ↔ a * c = b := iff.intro (suppose a = b / c, by rw [this, (div_mul_cancel _ hc)]) (suppose a * c = b, by rw [-this, mul_div_cancel _ hc]) lemma eq_div_of_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a * c = b → a = b / c := iff.mpr $ eq_div_iff_mul_eq a b hc lemma mul_eq_of_eq_div (a b: α) {c : α} (hc : c ≠ 0) : a = b / c → a * c = b := iff.mp $ eq_div_iff_mul_eq a b hc lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c := have (a + b / c) * c = a * c + b, by rw [right_distrib, (div_mul_cancel _ hc)], (iff.mpr (eq_div_iff_mul_eq _ _ hc)) this lemma mul_mul_div (a : α) {c : α} (hc : c ≠ 0) : a = a * c * (1 / c) := by simp [hc] end division_ring class field (α : Type u) extends division_ring α, comm_ring α section field variable [field α] lemma field.one_div_mul_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [(division_ring.one_div_mul_one_div ha hb), mul_comm b] lemma field.div_mul_right {a b : α} (hb : b ≠ 0) (h : a * b ≠ 0) : a / (a * b) = 1 / b := have a ≠ 0, from ne_zero_of_mul_ne_zero_right h, eq.symm (calc 1 / b = a * ((1 / a) * (1 / b)) : by rw [-mul_assoc, mul_one_div_cancel this, one_mul] ... = a * (1 / (b * a)) : by rw (division_ring.one_div_mul_one_div this hb) ... = a * (a * b)⁻¹ : by rw [inv_eq_one_div, mul_comm a b]) lemma field.div_mul_left {a b : α} (ha : a ≠ 0) (h : a * b ≠ 0) : b / (a * b) = 1 / a := have b * a ≠ 0, from mul_ne_zero_comm h, by rw [mul_comm a, (field.div_mul_right ha this)] lemma mul_div_cancel_left {a : α} (b : α) (ha : a ≠ 0) : a * b / a = b := by rw [mul_comm a, (mul_div_cancel _ ha)] lemma mul_div_cancel' (a : α) {b : α} (hb : b ≠ 0) : b * (a / b) = a := by rw [mul_comm, (div_mul_cancel _ hb)] lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := have a * b ≠ 0, from (division_ring.mul_ne_zero ha hb), by rw [add_comm, -(field.div_mul_left ha this), -(field.div_mul_right hb this), division_def, division_def, division_def, -right_distrib] lemma field.div_mul_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) * (c / d) = (a * c) / (b * d) := begin simp [division_def], rw [mul_inv_eq hd hb, mul_comm d⁻¹] end lemma mul_div_mul_left (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (c * a) / (c * b) = a / b := by rw [-(field.div_mul_div _ _ hc hb), div_self hc, one_mul] lemma mul_div_mul_right (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rw [mul_comm a, mul_comm b, mul_div_mul_left _ hb hc] lemma div_mul_eq_mul_div (a b c : α) : (b / c) * a = (b * a) / c := by simp [division_def] lemma field.div_mul_eq_mul_div_comm (a b : α) {c : α} (hc : c ≠ 0) : (b / c) * a = b * (a / c) := by rw [div_mul_eq_mul_div, -(one_mul c), -(field.div_mul_div _ _ (ne.symm zero_ne_one) hc), div_one, one_mul] lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := by rw [-(mul_div_mul_right _ hb hd), -(mul_div_mul_left _ hd hb), div_add_div_same] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := begin simp [sub_eq_add_neg], rw [neg_eq_neg_one_mul, -mul_div_assoc, div_add_div _ _ hb hd, -mul_assoc, mul_comm b, mul_assoc, -neg_eq_neg_one_mul] end lemma mul_eq_mul_of_div_eq_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b := by rw [-(mul_one (a*d)), mul_assoc, (mul_comm d), -mul_assoc, -(div_self hb), -(field.div_mul_eq_mul_div_comm _ _ hb), h, div_mul_eq_mul_div, div_mul_cancel _ hd] lemma field.one_div_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / (a / b) = b / a := have (a / b) * (b / a) = 1, from calc (a / b) * (b / a) = (a * b) / (b * a) : field.div_mul_div _ _ hb ha ... = (a * b) / (a * b) : by rw mul_comm ... = 1 : div_self (division_ring.mul_ne_zero ha hb), eq.symm (eq_one_div_of_mul_eq_one this) lemma field.div_div_eq_mul_div (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, field.one_div_div hb hc, -mul_div_assoc] lemma field.div_div_eq_div_mul (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, field.div_mul_div _ _ hb hc, mul_one] lemma field.div_div_div_div_eq (a : α) {b c d : α} (hb : b ≠ 0) (hc : c ≠ 0) (hd : d ≠ 0) : (a / b) / (c / d) = (a * d) / (b * c) := by rw [field.div_div_eq_mul_div _ hc hd, div_mul_eq_mul_div, field.div_div_eq_div_mul _ hb hc] lemma field.div_mul_eq_div_mul_one_div (a : α) {b c : α} (hb : b ≠ 0) (hc : c ≠ 0) : a / (b * c) = (a / b) * (1 / c) := by rw [-(field.div_div_eq_div_mul _ hb hc), -div_eq_mul_one_div] lemma eq_of_mul_eq_mul_of_nonzero_left {a b c : α} (h : a ≠ 0) (h₂ : a * b = a * c) : b = c := by rw [-one_mul b, -div_self h, div_mul_eq_mul_div, h₂, mul_div_cancel_left _ h] lemma eq_of_mul_eq_mul_of_nonzero_right {a b c : α} (h : c ≠ 0) (h2 : a * c = b * c) : a = b := by rw [-mul_one a, -div_self h, -mul_div_assoc, h2, mul_div_cancel _ h] end field class discrete_field (α : Type u) extends field α := (has_decidable_eq : decidable_eq α) (inv_zero : inv zero = zero) attribute [instance] discrete_field.has_decidable_eq section discrete_field variable [discrete_field α] -- many of the lemmas in discrete_field are the same as lemmas in field or division ring, -- but with fewer hypotheses since 0⁻¹ = 0 and equality is decidable. lemma discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero (a b : α) (h : a * b = 0) : a = 0 ∨ b = 0 := decidable.by_cases (suppose a = 0, or.inl this) (suppose a ≠ 0, or.inr (by rw [-(one_mul b), -(inv_mul_cancel this), mul_assoc, h, mul_zero])) instance discrete_field.to_integral_domain [s : discrete_field α] : integral_domain α := {s with eq_zero_or_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero} lemma inv_zero : 0⁻¹ = (0:α) := discrete_field.inv_zero α lemma one_div_zero : 1 / 0 = (0:α) := calc 1 / 0 = (1:α) * 0⁻¹ : by rw division_def ... = 1 * 0 : by rw inv_zero ... = (0:α) : by rw mul_zero lemma div_zero (a : α) : a / 0 = 0 := by rw [div_eq_mul_one_div, one_div_zero, mul_zero] lemma ne_zero_of_one_div_ne_zero {a : α} (h : 1 / a ≠ 0) : a ≠ 0 := assume ha : a = 0, begin rw [ha, one_div_zero] at h, contradiction end lemma eq_zero_of_one_div_eq_zero {a : α} (h : 1 / a = 0) : a = 0 := decidable.by_cases (assume ha, ha) (assume ha, false.elim ((one_div_ne_zero ha) h)) lemma one_div_mul_one_div' (a b : α) : (1 / a) * (1 / b) = 1 / (b * a) := decidable.by_cases (suppose a = 0, by rw [this, div_zero, zero_mul, mul_zero, div_zero]) (assume ha : a ≠ 0, decidable.by_cases (suppose b = 0, by rw [this, div_zero, mul_zero, zero_mul, div_zero]) (suppose b ≠ 0, division_ring.one_div_mul_one_div ha this)) lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) := decidable.by_cases (suppose a = 0, by rw [this, neg_zero, div_zero, neg_zero]) (suppose a ≠ 0, division_ring.one_div_neg_eq_neg_one_div this) lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b := decidable.by_cases (assume hb : b = 0, by rw [hb, neg_zero, div_zero, div_zero]) (assume hb : b ≠ 0, division_ring.neg_div_neg_eq _ hb) lemma one_div_one_div (a : α) : 1 / (1 / a) = a := decidable.by_cases (assume ha : a = 0, by rw [ha, div_zero, div_zero]) (assume ha : a ≠ 0, division_ring.one_div_one_div ha) lemma eq_of_one_div_eq_one_div {a b : α} (h : 1 / a = 1 / b) : a = b := decidable.by_cases (assume ha : a = 0, have hb : b = 0, from eq_zero_of_one_div_eq_zero (by rw [-h, ha, div_zero]), hb.symm ▸ ha) (assume ha : a ≠ 0, have hb : b ≠ 0, from ne_zero_of_one_div_ne_zero (h ▸ (one_div_ne_zero ha)), division_ring.eq_of_one_div_eq_one_div ha hb h) lemma mul_inv' (a b : α) : (b * a)⁻¹ = a⁻¹ * b⁻¹ := decidable.by_cases (assume ha : a = 0, by rw [ha, mul_zero, inv_zero, zero_mul]) (assume ha : a ≠ 0, decidable.by_cases (assume hb : b = 0, by rw [hb, zero_mul, inv_zero, mul_zero]) (assume hb : b ≠ 0, mul_inv_eq ha hb)) -- the following are specifically for fields lemma one_div_mul_one_div (a b : α) : (1 / a) * (1 / b) = 1 / (a * b) := by rw [one_div_mul_one_div', mul_comm b] lemma div_mul_right {a : α} (b : α) (ha : a ≠ 0) : a / (a * b) = 1 / b := decidable.by_cases (assume hb : b = 0, by rw [hb, mul_zero, div_zero, div_zero]) (assume hb : b ≠ 0, field.div_mul_right hb (mul_ne_zero ha hb)) lemma div_mul_left (a : α) {b : α} (hb : b ≠ 0) : b / (a * b) = 1 / a := by rw [mul_comm a, div_mul_right _ hb] lemma div_mul_div (a b c d : α) : (a / b) * (c / d) = (a * c) / (b * d) := decidable.by_cases (assume hb : b = 0, by rw [hb, div_zero, zero_mul, zero_mul, div_zero]) (assume hb : b ≠ 0, decidable.by_cases (assume hd : d = 0, by rw [hd, div_zero, mul_zero, mul_zero, div_zero]) (assume hd : d ≠ 0, field.div_mul_div _ _ hb hd)) lemma mul_div_mul_left' (a b : α) {c : α} (hc : c ≠ 0) : (c * a) / (c * b) = a / b := decidable.by_cases (assume hb : b = 0, by rw [hb, mul_zero, div_zero, div_zero]) (assume hb : b ≠ 0, mul_div_mul_left _ hb hc) lemma mul_div_mul_right' (a b : α) {c : α} (hc : c ≠ 0) : (a * c) / (b * c) = a / b := by rw [mul_comm a, mul_comm b, (mul_div_mul_left' _ _ hc)] lemma div_mul_eq_mul_div_comm (a b c : α) : (b / c) * a = b * (a / c) := decidable.by_cases (assume hc : c = 0, by rw [hc, div_zero, zero_mul, div_zero, mul_zero]) (assume hc : c ≠ 0, field.div_mul_eq_mul_div_comm _ _ hc) lemma one_div_div (a b : α) : 1 / (a / b) = b / a := decidable.by_cases (assume ha : a = 0, by rw [ha, zero_div, div_zero, div_zero]) (assume ha : a ≠ 0, decidable.by_cases (assume hb : b = 0, by rw [hb, div_zero, zero_div, div_zero]) (assume hb : b ≠ 0, field.one_div_div ha hb)) lemma div_div_eq_mul_div (a b c : α) : a / (b / c) = (a * c) / b := by rw [div_eq_mul_one_div, one_div_div, -mul_div_assoc] lemma div_div_eq_div_mul (a b c : α) : (a / b) / c = a / (b * c) := by rw [div_eq_mul_one_div, div_mul_div, mul_one] lemma div_div_div_div_eq (a b c d : α) : (a / b) / (c / d) = (a * d) / (b * c) := by rw [div_div_eq_mul_div, div_mul_eq_mul_div, div_div_eq_div_mul] lemma div_helper {a : α} (b : α) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b := by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h] lemma div_mul_eq_div_mul_one_div (a b c : α) : a / (b * c) = (a / b) * (1 / c) := by rw [-div_div_eq_div_mul, -div_eq_mul_one_div] end discrete_field
373c71251c9704a0417dbbc6dcfc7390273d99c5
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean.lean
05d39440c85a738de8f1f21d4a76bcd48e58bd8c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
895
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.Data import Lean.Compiler import Lean.Environment import Lean.Modifiers import Lean.ProjFns import Lean.Runtime import Lean.ResolveName import Lean.Attributes import Lean.Parser import Lean.ReducibilityAttrs import Lean.Elab import Lean.Class import Lean.LocalContext import Lean.MetavarContext import Lean.AuxRecursor import Lean.Meta import Lean.Util import Lean.Eval import Lean.Structure import Lean.PrettyPrinter import Lean.CoreM import Lean.InternalExceptionId import Lean.Server import Lean.ScopedEnvExtension import Lean.DocString import Lean.DeclarationRange import Lean.LazyInitExtension import Lean.LoadDynlib import Lean.Widget import Lean.Log import Lean.Linter import Lean.SubExpr import Lean.Deprecated
3c3bb9f38aeb12fd5bf1e2bce5beade893f1448b
f1a12d4db0f46eee317d703e3336d33950a2fe7e
/common/int.lean
0f7969a74cdef0537b3010d2884884ba8f4ef0d8
[ "Apache-2.0" ]
permissive
avigad/qelim
bce89b79c717b7649860d41a41a37e37c982624f
b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60
refs/heads/master
1,584,548,938,232
1,526,773,708,000
1,526,773,708,000
134,967,693
2
0
null
null
null
null
UTF-8
Lean
false
false
8,462
lean
import .nat ...mathlib.data.int.basic namespace int lemma le_iff_zero_le_sub (a b) : a ≤ b ↔ (0 : int) ≤ b - a := begin rewrite le_sub, simp end lemma abs_dvd (x y : int) : has_dvd.dvd (abs x) y ↔ has_dvd.dvd x y := begin rewrite abs_eq_nat_abs, apply nat_abs_dvd end lemma mul_nonzero {z y : int} : z ≠ 0 → y ≠ 0 → z * y ≠ 0 := begin intros hm hn hc, apply hm, apply eq.trans, apply eq.symm, apply int.mul_div_cancel, apply hn, rewrite hc, apply int.zero_div end lemma div_nonzero (z y : int) : z ≠ 0 → has_dvd.dvd y z → (z / y) ≠ 0 := begin intros hz hy hc, apply hz, apply eq.trans, apply eq.symm, apply int.div_mul_cancel, apply hy, rewrite hc, apply zero_mul, end lemma nat_abs_nonzero (z : int) : z ≠ 0 → int.nat_abs z ≠ 0 := begin intro hz, cases z with n n, simp, apply nat.neq_zero_of_of_nat_neq_zero hz, simp, intro hc, cases hc end lemma dvd_iff_nat_abs_dvd_nat_abs {x y : int} : (has_dvd.dvd x y) ↔ (has_dvd.dvd (int.nat_abs x) (int.nat_abs y)) := begin rewrite iff.symm int.coe_nat_dvd, rewrite int.nat_abs_dvd, rewrite int.dvd_nat_abs end def lcm (x y : int) : int := (nat.lcm (nat_abs x) (nat_abs y)) lemma lcm_dvd {x y z : int} (hx : has_dvd.dvd x z) (hy : y ∣ z) : lcm x y ∣ z := begin rewrite dvd_iff_nat_abs_dvd_nat_abs, rewrite dvd_iff_nat_abs_dvd_nat_abs at hx, rewrite dvd_iff_nat_abs_dvd_nat_abs at hy, unfold lcm, rewrite nat_abs_of_nat, apply nat.lcm_dvd; assumption end lemma lcm_one_right (z : int) : lcm z 1 = abs z := begin unfold lcm, simp, rewrite nat.lcm_one_right, cases (classical.em (0 ≤ z)) with hz hz, rewrite abs_eq_nat_abs, rewrite not_le at hz, apply @eq.trans _ _ (↑(nat_abs z)), refl, rewrite (@of_nat_nat_abs_of_nonpos z _), rewrite abs_of_neg, apply hz, apply le_of_lt hz end def lcms : list int → int | [] := 1 | (z::zs) := lcm z (lcms zs) lemma dvd_lcm_left : ∀ (x y : int), has_dvd.dvd x (lcm x y) := begin intros x y, unfold lcm, rewrite iff.symm (abs_dvd _ _), rewrite abs_eq_nat_abs, rewrite coe_nat_dvd, apply nat.dvd_lcm_left end lemma dvd_lcm_right : ∀ (x y : int), has_dvd.dvd y (lcm x y) := begin intros x y, unfold lcm, rewrite iff.symm (abs_dvd _ _), rewrite abs_eq_nat_abs, rewrite coe_nat_dvd, apply nat.dvd_lcm_right end lemma dvd_lcms {x : int} : ∀ {zs : list int}, x ∈ zs → has_dvd.dvd x (lcms zs) | [] hm := by cases hm | (z::zs) hm := begin unfold lcms, rewrite list.mem_cons_iff at hm, cases hm with hm hm, subst hm, apply dvd_lcm_left, apply dvd_trans, apply @dvd_lcms zs hm, apply dvd_lcm_right, end lemma nonzero_of_pos {z : int} : z > 0 → z ≠ 0 := begin intros hgt heq, subst heq, cases hgt end lemma lcm_nonneg (x y : int) : lcm x y ≥ 0 := by unfold lcm lemma lcms_nonneg : ∀ (zs : list int), lcms zs ≥ 0 | [] := by unfold lcms | (z::zs) := by unfold lcms lemma lcm_pos (x y : int) : x ≠ 0 → y ≠ 0 → lcm x y > 0 := begin intros hx hy, unfold lcm, unfold gt, rewrite coe_nat_pos, let h := @nat.pos_iff_ne_zero, unfold gt at h, rewrite h, apply nat.lcm_nonzero; apply nat_abs_nonzero; assumption end lemma lcms_pos : ∀ {zs : list int}, (∀ z : int, z ∈ zs → z ≠ 0) → lcms zs > 0 | [] _ := coe_succ_pos _ | (z::zs) hnzs := begin unfold lcms, apply lcm_pos, apply hnzs _ (or.inl rfl), apply nonzero_of_pos, apply lcms_pos, apply list.forall_mem_of_forall_mem_cons hnzs end lemma lcms_dvd {k : int} : ∀ {zs : list int}, (∀ z ∈ zs, has_dvd.dvd z k) → (has_dvd.dvd (lcms zs) k) | [] hk := one_dvd _ | (z::zs) hk := begin unfold lcms, apply lcm_dvd, apply hk _ (or.inl rfl), apply lcms_dvd, apply list.forall_mem_of_forall_mem_cons hk end lemma lcms_distrib (xs ys zs : list int) : list.equiv zs (xs ∪ ys) → lcms zs = lcm (lcms xs) (lcms ys) := begin intro heqv, apply dvd_antisymm, apply lcms_nonneg, apply lcm_nonneg, apply lcms_dvd, intros z hz, rewrite (list.mem_iff_mem_of_equiv heqv) at hz, rewrite list.mem_union at hz, cases hz with hz hz, apply dvd_trans (dvd_lcms _) (dvd_lcm_left _ _); assumption, apply dvd_trans (dvd_lcms _) (dvd_lcm_right _ _); assumption, apply lcm_dvd; apply lcms_dvd; intros z hz; apply dvd_lcms; rewrite (list.mem_iff_mem_of_equiv heqv), apply list.mem_union_left hz, apply list.mem_union_right _ hz end -- lemma dvd_of_mul_dvd_mul_left : ∀ {x y z : int}, -- z ≠ 0 → has_dvd.dvd (z * x) (z * y) → has_dvd.dvd x y := sorry lemma eq_zero_of_nonpos_of_nonzero (z : int) : (¬ z < 0) → (¬ z > 0) → z = 0 := begin cases (lt_trichotomy z 0) with h h, intro hc, cases (hc h), cases h with h h, intros _ _, apply h, intros _ hc, cases (hc h) end lemma sign_split (z) : sign z = -1 ∨ sign z = 0 ∨ sign z = 1 := begin cases z with n n, cases n, apply or.inr (or.inl rfl), apply or.inr (or.inr rfl), apply or.inl rfl end -- lemma abs_neq_zero_of_neq_zero {z : int} (h : z ≠ 0) : abs z ≠ 0 := -- begin -- intro hc, apply h, apply eq_zero_of_abs_eq_zero, apply hc -- end lemma mul_le_mul_iff_le_of_pos_left (x y z : int) : z > 0 → (z * x ≤ z * y ↔ x ≤ y) := begin intro hz, apply iff.intro; intro h, let h' := @int.div_le_div _ _ z hz h, repeat {rewrite mul_comm z at h', rewrite int.mul_div_cancel _ (nonzero_of_pos hz) at h'}, apply h', repeat {rewrite mul_comm z}, apply int.mul_le_of_le_div hz, rewrite int.mul_div_cancel _ (nonzero_of_pos hz), apply h end lemma mul_le_mul_iff_le_of_neg_left (x y z : int) : z < 0 → (z * x ≤ z * y ↔ y ≤ x) := begin intros hz, rewrite eq.symm (neg_neg z), repeat {rewrite eq.symm (neg_mul_eq_neg_mul (-z) _)}, rewrite neg_le_neg_iff, apply mul_le_mul_iff_le_of_pos_left, unfold gt, rewrite lt_neg, apply hz end lemma dvd_iff_exists (x y) : has_dvd.dvd x y ↔ ∃ (z : int), z * x = y := begin apply iff.intro; intro h, existsi (y / x), apply int.div_mul_cancel h, cases h with z hz, subst hz, apply dvd_mul_left end lemma div_mul_comm (x y z : int) : has_dvd.dvd y x → (x / y) * z = x * z / y := begin intro h, rewrite mul_comm x, rewrite int.mul_div_assoc _ h, rewrite mul_comm, end lemma nonneg_iff_exists (z : int) : 0 ≤ z ↔ ∃ (n : nat), z = ↑n := begin cases z with m m, apply true_iff_true, constructor, existsi m, refl, apply false_iff_false; intro hc, cases hc, cases hc with m hm, cases hm end lemma exists_nat_diff (x y : int) (n : nat) : x ≤ y → y < x + ↑n → ∃ (m : nat), m < n ∧ y = x + ↑m := begin intros hxy hyx, rewrite iff.symm (sub_nonneg) at hxy, rewrite nonneg_iff_exists at hxy, cases hxy with m hm, existsi m, rewrite iff.symm sub_lt_iff_lt_add' at hyx, apply and.intro, rewrite iff.symm coe_nat_lt, rewrite eq.symm hm, apply hyx, rewrite eq.symm hm, rewrite add_sub, simp, end lemma exists_lt_and_lt (x y : int) : ∃ z, z < x ∧ z < y := begin cases (lt_trichotomy x y), existsi (pred x), apply and.intro (pred_self_lt _) (lt_trans (pred_self_lt _) h), cases h with h h, subst h, existsi (pred x), apply and.intro (pred_self_lt _) (pred_self_lt _), existsi (pred y), apply and.intro (lt_trans (pred_self_lt _) h) (pred_self_lt _) end lemma le_mul_of_pos_left : ∀ {x y : int}, y ≥ 0 → x > 0 → y ≤ x * y := begin intros x y hy hx, have hx' : x ≥ 1 := add_one_le_of_lt hx, let h := mul_le_mul hx' (le_refl y) hy _, rewrite one_mul at h, apply h, apply le_of_lt hx end lemma lt_mul_of_nonneg_right : ∀ {x y z : int}, x < y → y ≥ 0 → z > 0 → x < y * z := begin intros x y z hxy hy hz, have h := @mul_lt_mul _ _ x 1 y z hxy, rewrite mul_one at h, apply h, apply add_one_le_of_lt hz, apply int.zero_lt_one, apply hy end lemma zero_mul (z : int) : int.of_nat 0 * z = 0 := eq.trans (refl _) (zero_mul _) lemma mul_zero (z : int) : z * int.of_nat 0 = 0 := eq.trans (refl _) (mul_zero _) lemma one_mul (z : int) : int.of_nat 1 * z = z := eq.trans (refl _) (one_mul _) lemma neg_one_mul (z : int) : (int.neg_succ_of_nat 0) * z = -z := eq.trans (refl _) (neg_one_mul _) lemma zero_add (z : int) : int.of_nat 0 + z = z := eq.trans (refl _) (zero_add _) lemma coe_eq_of_nat {n : nat} : ↑n = int.of_nat n := refl _ lemma coe_neg_succ_eq_neg_succ_of_nat {n : nat} : -↑(nat.succ n) = int.neg_succ_of_nat n := refl _ end int
a080c28d5c254d50c0570cb16276d256d7f91206
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/category/constructions/default.hlean
d517ab117b74d06e8faed5f519a8530a58e3bc57
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
307
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import .functor .set .opposite .product .comma .sum .discrete .indiscrete .terminal .initial .order .pushout .fundamental_groupoid .pullback
f484c775e6da57b12d3db014568159ad4bb996d0
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/idempotents/biproducts.lean
1607c66a2faeb02266a64c1ee48d2f260f8cb218
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,075
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.karoubi import category_theory.additive.basic /-! # Biproducts in the idempotent completion of a preadditive category In this file, we define an instance expressing that if `C` is an additive category, then `karoubi C` is also an additive category. We also obtain that for all `P : karoubi C` where `C` is a preadditive category `C`, there is a canonical isomorphism `P ⊞ P.complement ≅ (to_karoubi C).obj P.X` in the category `karoubi C` where `P.complement` is the formal direct factor of `P.X` corresponding to the idempotent endomorphism `𝟙 P.X - P.p`. -/ noncomputable theory open category_theory.category open category_theory.limits open category_theory.preadditive universes v namespace category_theory namespace idempotents namespace karoubi variables {C : Type*} [category.{v} C] [preadditive C] namespace biproducts /-- The `bicone` used in order to obtain the existence of the biproduct of a functor `J ⥤ karoubi C` when the category `C` is additive. -/ @[simps] def bicone [has_finite_biproducts C] {J : Type} [fintype J] (F : J → karoubi C) : bicone F := { X := { X := biproduct (λ j, (F j).X), p := biproduct.map (λ j, (F j).p), idem := begin ext j, simp only [biproduct.ι_map_assoc, biproduct.ι_map], slice_lhs 1 2 { rw (F j).idem, }, end, }, π := λ j, { f := biproduct.map (λ j, (F j).p) ≫ bicone.π _ j, comm := by simp only [assoc, biproduct.bicone_π, biproduct.map_π, biproduct.map_π_assoc, (F j).idem], }, ι := λ j, { f := (by exact bicone.ι _ j) ≫ biproduct.map (λ j, (F j).p), comm := by rw [biproduct.ι_map, ← assoc, ← assoc, (F j).idem, assoc, biproduct.ι_map, ← assoc, (F j).idem], }, ι_π := λ j j', begin split_ifs, { subst h, simp only [biproduct.bicone_ι, biproduct.ι_map, biproduct.bicone_π, biproduct.ι_π_self_assoc, comp, category.assoc, eq_to_hom_refl, id_eq, biproduct.map_π, (F j).idem], }, { simpa only [hom_ext, biproduct.ι_π_ne_assoc _ h, assoc, biproduct.map_π, biproduct.map_π_assoc, zero_comp, comp], }, end, } end biproducts lemma karoubi_has_finite_biproducts [has_finite_biproducts C] : has_finite_biproducts (karoubi C) := { has_biproducts_of_shape := λ J hJ, { has_biproduct := λ F, begin classical, letI := hJ, apply has_biproduct_of_total (biproducts.bicone F), ext1, ext1, simp only [id_eq, comp_id, biproducts.bicone_X_p, biproduct.ι_map], rw [sum_hom, comp_sum, finset.sum_eq_single j], rotate, { intros j' h1 h2, simp only [biproduct.ι_map, biproducts.bicone_ι_f, biproducts.bicone_π_f, assoc, comp, biproduct.map_π], slice_lhs 1 2 { rw biproduct.ι_π, }, split_ifs, { exfalso, exact h2 h.symm, }, { simp only [zero_comp], } }, { intro h, exfalso, simpa only [finset.mem_univ, not_true] using h, }, { simp only [biproducts.bicone_π_f, comp, biproduct.ι_map, assoc, biproducts.bicone_ι_f, biproduct.map_π], slice_lhs 1 2 { rw biproduct.ι_π, }, split_ifs, swap, { exfalso, exact h rfl, }, simp only [eq_to_hom_refl, id_comp, (F j).idem], }, end, } } instance {D : Type*} [category D] [additive_category D] : additive_category (karoubi D) := { to_preadditive := infer_instance, to_has_finite_biproducts := karoubi_has_finite_biproducts } /-- `P.complement` is the formal direct factor of `P.X` given by the idempotent endomorphism `𝟙 P.X - P.p` -/ @[simps] def complement (P : karoubi C) : karoubi C := { X := P.X, p := 𝟙 _ - P.p, idem := idem_of_id_sub_idem P.p P.idem, } instance (P : karoubi C) : has_binary_biproduct P P.complement := has_binary_biproduct_of_total { X := P.X, fst := P.decomp_id_p, snd := P.complement.decomp_id_p, inl := P.decomp_id_i, inr := P.complement.decomp_id_i, inl_fst' := P.decomp_id.symm, inl_snd' := begin simp only [decomp_id_i_f, decomp_id_p_f, complement_p, comp_sub, comp, hom_ext, quiver.hom.add_comm_group_zero_f, P.idem], erw [comp_id, sub_self], end, inr_fst' := begin simp only [decomp_id_i_f, complement_p, decomp_id_p_f, sub_comp, comp, hom_ext, quiver.hom.add_comm_group_zero_f, P.idem], erw [id_comp, sub_self], end, inr_snd' := P.complement.decomp_id.symm, } (by simp only [hom_ext, ← decomp_p, quiver.hom.add_comm_group_add_f, to_karoubi_map_f, id_eq, coe_p, complement_p, add_sub_cancel'_right]) /-- A formal direct factor `P : karoubi C` of an object `P.X : C` in a preadditive category is actually a direct factor of the image `(to_karoubi C).obj P.X` of `P.X` in the category `karoubi C` -/ def decomposition (P : karoubi C) : P ⊞ P.complement ≅ (to_karoubi _).obj P.X := { hom := biprod.desc P.decomp_id_i P.complement.decomp_id_i, inv := biprod.lift P.decomp_id_p P.complement.decomp_id_p, hom_inv_id' := begin ext1, { simp only [← assoc, biprod.inl_desc, comp_id, biprod.lift_eq, comp_add, ← decomp_id, id_comp, add_right_eq_self], convert zero_comp, ext, simp only [decomp_id_i_f, decomp_id_p_f, complement_p, comp_sub, comp, quiver.hom.add_comm_group_zero_f, P.idem], erw [comp_id, sub_self], }, { simp only [← assoc, biprod.inr_desc, biprod.lift_eq, comp_add, ← decomp_id, comp_id, id_comp, add_left_eq_self], convert zero_comp, ext, simp only [decomp_id_i_f, decomp_id_p_f, complement_p, sub_comp, comp, quiver.hom.add_comm_group_zero_f, P.idem], erw [id_comp, sub_self], } end, inv_hom_id' := begin rw biprod.lift_desc, simp only [← decomp_p], ext, dsimp only [complement, to_karoubi], simp only [quiver.hom.add_comm_group_add_f, add_sub_cancel'_right, id_eq], end, } end karoubi end idempotents end category_theory
f96e63553a64ee1342f02618ab181f60a50b236d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/dedekind_domain/S_integer.lean
a3cdfe38b254703e823f59013cd6ddd3a347838d
[ "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,054
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 ring_theory.dedekind_domain.adic_valuation /-! # `S`-integers and `S`-units 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`, and let `S` be a set of prime ideals in the height one spectrum of `R`. An `S`-integer of `K` is defined to have `v`-adic valuation at most one for all primes ideals `v` away from `S`, whereas an `S`-unit of `Kˣ` is defined to have `v`-adic valuation exactly one for all prime ideals `v` away from `S`. This file defines the subalgebra of `S`-integers of `K` and the subgroup of `S`-units of `Kˣ`, where `K` can be specialised to the case of a number field or a function field separately. ## Main definitions * `set.integer`: `S`-integers. * `set.unit`: `S`-units. * TODO: localised notation for `S`-integers. ## Main statements * `set.unit_equiv_units_integer`: `S`-units are units of `S`-integers. * TODO: proof that `S`-units is the kernel of a map to a product. * TODO: proof that `∅`-integers is the usual ring of integers. * TODO: finite generation of `S`-units and Dirichlet's `S`-unit theorem. ## References * [D Marcus, *Number Fields*][marcus1977number] * [J W S Cassels, A Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags S integer, S-integer, S unit, S-unit -/ namespace set noncomputable theory open is_dedekind_domain open_locale non_zero_divisors universes u v variables {R : Type u} [comm_ring R] [is_domain R] [is_dedekind_domain R] (S : set $ height_one_spectrum R) (K : Type v) [field K] [algebra R K] [is_fraction_ring R K] /-! ## `S`-integers -/ /-- The `R`-subalgebra of `S`-integers of `K`. -/ @[simps] def integer : subalgebra R K := { algebra_map_mem' := λ x v _, v.valuation_le_one x, .. (⨅ v ∉ S, (v : height_one_spectrum R).valuation.valuation_subring.to_subring).copy {x : K | ∀ v ∉ S, (v : height_one_spectrum R).valuation x ≤ 1} $ set.ext $ λ _, by simpa only [set_like.mem_coe, subring.mem_infi] } lemma integer_eq : (S.integer K).to_subring = ⨅ v ∉ S, (v : height_one_spectrum R).valuation.valuation_subring.to_subring := set_like.ext' $ by simpa only [integer, subring.copy_eq] lemma integer_valuation_le_one (x : S.integer K) {v : height_one_spectrum R} (hv : v ∉ S) : v.valuation (x : K) ≤ 1 := x.property v hv /-! ## `S`-units -/ /-- The subgroup of `S`-units of `Kˣ`. -/ @[simps] def unit : subgroup Kˣ := (⨅ v ∉ S, (v : height_one_spectrum R).valuation.valuation_subring.unit_group).copy {x : Kˣ | ∀ v ∉ S, (v : height_one_spectrum R).valuation (x : K) = 1} $ set.ext $ λ _, by simpa only [set_like.mem_coe, subgroup.mem_infi, valuation.mem_unit_group_iff] lemma unit_eq : S.unit K = ⨅ v ∉ S, (v : height_one_spectrum R).valuation.valuation_subring.unit_group := subgroup.copy_eq _ _ _ lemma unit_valuation_eq_one (x : S.unit K) {v : height_one_spectrum R} (hv : v ∉ S) : v.valuation (x : K) = 1 := x.property v hv /-- The group of `S`-units is the group of units of the ring of `S`-integers. -/ @[simps] def unit_equiv_units_integer : S.unit K ≃* (S.integer K)ˣ := { to_fun := λ x, ⟨⟨x, λ v hv, (x.property v hv).le⟩, ⟨↑x⁻¹, λ v hv, ((x⁻¹).property v hv).le⟩, subtype.ext x.val.val_inv, subtype.ext x.val.inv_val⟩, inv_fun := λ x, ⟨units.mk0 x $ λ hx, x.ne_zero ((subring.coe_eq_zero_iff _).mp hx), λ v hv, eq_one_of_one_le_mul_left (x.val.property v hv) (x.inv.property v hv) $ eq.ge $ by { rw [← map_mul], convert v.valuation.map_one, exact subtype.mk_eq_mk.mp x.val_inv }⟩, left_inv := λ _, by { ext, refl }, right_inv := λ _, by { ext, refl }, map_mul' := λ _ _, by { ext, refl } } end set
c08a02e44792669b6303331338d946b383ec4ee0
ea11767c9c6a467c4b7710ec6f371c95cfc023fd
/src/monoidal_categories/util/data/bin_tree/cong_clos.lean
a1035ef0353bf431e3e4947e9c50f0b66053a5ca
[]
no_license
RitaAhmadi/lean-monoidal-categories
68a23f513e902038e44681336b87f659bbc281e0
81f43e1e0d623a96695aa8938951d7422d6d7ba6
refs/heads/master
1,651,458,686,519
1,529,824,613,000
1,529,824,613,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,975
lean
import ..bin_tree import ..nonempty_list open util.data.nonempty_list open util.data.bin_tree' open util.data.bin_tree'.bin_tree' universes u v variable {α : Type u} -- https://ncatlab.org/nlab/show/Mac+Lane%27s+proof+of+the+coherence+theorem+for+monoidal+categories -- TODO(tim): do we really need two definitions of the congruence closure or can we just delete this one? inductive cong_clos' (R : bin_tree' α → bin_tree' α → Type u) : bin_tree' α → bin_tree' α → Type u | lift : Π s t, R s t → cong_clos' s t | refl : Π t, cong_clos' t t | trans : Π r s t, cong_clos' r s → cong_clos' s t → cong_clos' r t | cong : Π l₁ r₁ l₂ r₂, cong_clos' l₁ l₂ → cong_clos' r₁ r₂ → cong_clos' (branch l₁ r₁) (branch l₂ r₂) namespace cong_clos' variable {R : bin_tree' α → bin_tree' α → Type u} def sym (R_sym : Π s t, R s t → R t s) : Π {s t}, cong_clos' R s t → cong_clos' R t s | ._ ._ (lift _ _ p) := lift _ _ (R_sym _ _ p) | ._ ._ (refl ._ t) := refl R t | ._ ._ (trans _ _ _ p q) := trans _ _ _ (sym q) (sym p) | ._ ._ (cong _ _ _ _ l r) := cong _ _ _ _ (sym l) (sym r) def transport {S : bin_tree' α → bin_tree' α → Type u} (f : Π s t, R s t → S s t) : Π {s t}, cong_clos' R s t → cong_clos' S s t | ._ ._ (lift _ _ p) := lift _ _ (f _ _ p) | ._ ._ (refl ._ t) := refl S t | ._ ._ (trans _ _ _ p q) := trans _ _ _ (transport p) (transport q) | ._ ._ (cong _ _ _ _ l r) := cong _ _ _ _ (transport l) (transport r) lemma respects_to_list (R_to_list : Π s t, R s t → s.to_list = t.to_list) : Π {s t}, cong_clos' R s t → s.to_list = t.to_list | ._ ._ (lift _ _ p) := R_to_list _ _ p | ._ ._ (refl ._ _) := eq.refl _ | ._ ._ (trans _ _ _ p q) := eq.trans (respects_to_list p) (respects_to_list q) | ._ ._ (cong l₁ r₁ l₂ r₂ l r) := begin unfold bin_tree'.to_list, rewrite (respects_to_list l), rewrite (respects_to_list r) end end cong_clos' inductive cong_clos_step (R : bin_tree' α → bin_tree' α → Type u) : bin_tree' α → bin_tree' α → Type u | lift : Π s t, R s t → cong_clos_step s t | left : Π l₁ l₂ r, cong_clos_step l₁ l₂ → cong_clos_step (branch l₁ r) (branch l₂ r) | right : Π l r₁ r₂, cong_clos_step r₁ r₂ → cong_clos_step (branch l r₁) (branch l r₂) namespace cong_clos_step variable {R : bin_tree' α → bin_tree' α → Type u} -- the equation compiler somehow can't handle the next definitions ~> turn it off -- TODO(tim): report bug set_option eqn_compiler.lemmas false def sym (R_sym : Π s t, R s t → R t s) : Π {s t}, cong_clos_step R s t → cong_clos_step R t s | ._ ._ (lift _ _ p) := lift _ _ (R_sym _ _ p) | ._ ._ (left _ _ _ l) := left _ _ _ (sym l) | ._ ._ (right _ _ _ r) := right _ _ _ (sym r) def transport {S : bin_tree' α → bin_tree' α → Type u} (f : Π s t, R s t → S s t) : Π {s t}, cong_clos_step R s t → cong_clos_step S s t | ._ ._ (lift _ _ p) := lift _ _ (f _ _ p) | ._ ._ (left _ _ _ l) := left _ _ _ (transport l) | ._ ._ (right _ _ _ r) := right _ _ _ (transport r) lemma respects_to_list (R_to_list : Π s t, R s t → s.to_list = t.to_list) : Π {s t}, cong_clos_step R s t → s.to_list = t.to_list | ._ ._ (lift _ _ p) := R_to_list _ _ p | ._ ._ (left _ _ _ l) := by unfold bin_tree'.to_list; rewrite (respects_to_list l) | ._ ._ (right _ _ _ r) := by unfold bin_tree'.to_list; rewrite (respects_to_list r) lemma respects_lopsided (R_to_list : Π s t, R s t → s.to_list = t.to_list) {s t} (p : cong_clos_step R s t) : s.lopsided = t.lopsided := by unfold lopsided; rewrite respects_to_list R_to_list p set_option eqn_compiler.lemmas true end cong_clos_step -- smallest reflexive, transitive, congruent (but not necessarily symmetric) relation that includes R inductive cong_clos (R : bin_tree' α → bin_tree' α → Type u) : bin_tree' α → bin_tree' α → Type u | refl : Π t, cong_clos t t | step : Π r s t, cong_clos_step R r s → cong_clos s t → cong_clos r t namespace cong_clos variable {R : bin_tree' α → bin_tree' α → Type u} open cong_clos_step def lift {s t : bin_tree' α} (p : R s t) : cong_clos R s t := step _ _ _ (cong_clos_step.lift _ _ p) (refl R _) def trans : Π {r s t : bin_tree' α}, cong_clos R r s → cong_clos R s t → cong_clos R r t | ._ ._ _ (refl ._ t) qs := qs | ._ ._ _ (step _ _ _ p ps) qs := step _ _ _ p (trans ps qs) lemma trans_refl_right : Π {s t : bin_tree' α} (p : cong_clos R s t), trans p (refl R t) = p | ._ ._ (refl ._ t) := by reflexivity | ._ ._ (step _ _ _ p ps) := by unfold trans; rewrite (trans_refl_right ps) def inject_left (r : bin_tree' α) : Π {l₁ l₂ : bin_tree' α}, cong_clos R l₁ l₂ → cong_clos R (branch l₁ r) (branch l₂ r) | ._ ._ (refl ._ t) := refl R _ | ._ ._ (step _ _ _ p ps) := step _ _ _ (left _ _ _ p) (inject_left ps) def inject_right (l : bin_tree' α) : Π {r₁ r₂ : bin_tree' α}, cong_clos R r₁ r₂ → cong_clos R (branch l r₁) (branch l r₂) | ._ ._ (refl ._ _) := refl R _ | ._ ._ (step _ _ _ p ps) := step _ _ _ (right _ _ _ p) (inject_right ps) def cong {l₁ l₂ r₁ r₂ : bin_tree' α} (l : cong_clos R l₁ l₂) (r : cong_clos R r₁ r₂) : cong_clos R (branch l₁ r₁) (branch l₂ r₂) := trans (inject_left _ l) (inject_right _ r) def convert : Π (s t : bin_tree' α), cong_clos' R s t → cong_clos R s t | ._ ._ (cong_clos'.refl ._ _) := refl R _ | ._ ._ (cong_clos'.lift _ _ p) := lift p | ._ ._ (cong_clos'.trans _ _ _ p q) := trans (convert _ _ p) (convert _ _ q) | ._ ._ (cong_clos'.cong _ _ _ _ l r) := cong (convert _ _ l) (convert _ _ r) def sym_helper (R_sym : Π s t, R s t → R t s) : Π {s t u}, cong_clos R s t → cong_clos R s u → cong_clos R t u | ._ ._ _ (refl ._ t) qs := qs | ._ ._ _ (step _ _ _ p ps) qs := sym_helper ps (step _ _ _ (cong_clos_step.sym R_sym p) qs) def sym (R_sym : Π s t, R s t → R t s) {s t} (ps : cong_clos R s t) : cong_clos R t s := sym_helper R_sym ps (refl R _) def transport {S : bin_tree' α → bin_tree' α → Type u} (f : Π s t, R s t → S s t) : Π {s t}, cong_clos R s t → cong_clos S s t | ._ ._ (refl ._ t) := refl S t | ._ ._ (step _ _ _ p ps) := step _ _ _ (cong_clos_step.transport f p) (transport ps) lemma respects_to_list (R_to_list : Π s t, R s t → s.to_list = t.to_list) : Π {s t}, cong_clos R s t → s.to_list = t.to_list | ._ ._ (refl ._ t) := by reflexivity | ._ ._ (step r s t p ps) := begin transitivity, exact (cong_clos_step.respects_to_list R_to_list p), exact (respects_to_list ps) end lemma respects_lopsided (R_to_list : Π s t, R s t → s.to_list = t.to_list) {s t} (p : cong_clos R s t) : s.lopsided = t.lopsided := by unfold lopsided; rewrite respects_to_list R_to_list p end cong_clos
8bdb11ea0615d14196dc1263d91c09463e41ae9d
dcf093fda1f51c094394c50e182cfb9dec39635a
/graph.lean
05c4633118d33db81945c6a5244ea88519948bd5
[]
no_license
dselsam/cs103
7ac496d0293befca95d3045add91c5270a5d291f
31ab9784a6f65f226efb702a0da52f907c616a71
refs/heads/master
1,611,092,644,140
1,492,571,015,000
1,492,571,015,000
88,693,969
1
0
null
null
null
null
UTF-8
Lean
false
false
7,815
lean
-- Keith -- Chapter 2 import data.fin data.list algebra.binary algebra.group classical open nat fin list definition no_dup {V : Type} : list V → Prop | [] := true | (x :: xs) := ¬ x ∈ xs ∧ no_dup xs definition rcons {V : Type} : list V → V → list V | [] v := [v] | (x :: xs) v := x :: (rcons xs v) lemma rcons_reverse {V : Type} (u : V) (xs : list V) : reverse (u :: xs) = rcons (reverse xs) u := sorry definition relation V := V → V → Prop -- definition graph n := relation (fin n) definition graph V := relation V -- for now, until we need finiteness section V variables {V : Type} (g : graph V) variables [V_decidable : decidable_eq V] variables [g_decidable : decidable_rel g] include V_decidable g_decidable inductive path : V → list V → V → Prop := | edge : ∀ {x y}, g x y → path x [] y | trans : ∀ {x xs1 y xs2 z}, path x xs1 y → path y xs2 z → path x (xs1 ++ (y :: xs2)) z -- There must be an easier way to do this! /- theorem decidable_path [instance] : ∀ (x_start : V) (xs : list V) (x_end : V), decidable (path g x_start xs x_end) | x_start [] x_end := decidable.rec_on (prop_decidable (x_start = x_end)) (take yes, decidable.inl yes) (take no, decidable.inr no) | x_start (x :: xs) x_end := decidable.rec_on (prop_decidable (g x_start x ∧ path g x xs x_end)) (take yes, decidable.inl yes) (take no, decidable.inr no) definition simple {x_start : V} {xs : list V} {x_end : V} (p : path g x_start xs x_end) : Prop := no_dup (x_start :: xs) definition cycle {x_start : V} {xs : list V} {x_end : V} (p : path g x_start xs x_end) : Prop := x_start = x_end definition simple_cycle {x_start : V} {xs : list V} {x_end : V} (p : path g x_start xs x_end) : Prop := (simple g p) ∧ (cycle g p) -/ definition connected (u v : V) := u = v ∨ ∃ xs, path g u xs v /- [KS] Theorem: Let G = (V, E) be an undirected graph. Then: (1) If v ∈ V, then v ↔ v. (2) If u, v ∈ V and u ↔ v, then v ↔ u. (3) If u, v, w ∈ V, then if u ↔ v and v ↔ w, then u ↔ w. Proof: We prove each part independently. To prove (1), note that for any v ∈ V, the trivial path (v) is a path from v to itself. Thus v ↔ v. To prove (2), consider any u, v ∈ V where u ↔ v. Then there must be some path (u, x1, x2, …, xn, v). Since G is an undirected graph, this means v, xn, …, x1, u is a path from v to u. Thus v ↔ u. To prove (3), consider any u, v, w ∈ V where u ↔ v and v ↔ w. Then there must be paths u, x1, x2, …, xn, v and v, y1, y2, …, ym, w. Consequently, (u, x1, …, xn, v, y1, …, ym, w) is a path from u to w. Thus u ↔ w. -/ local notation a ↔ b := @connected V g V_decidable g_decidable a b variable [g_undirected : symmetric g] open eq.ops theorem connected_refl : ∀ (v : V), v ↔ v := take v, or.inl rfl lemma path_edge_inv : ∀ (u v : V), path g u [] v → g u v := check @path.edge lemma path_reverse {xs : list V} : ∀ {u v : V}, path g u xs v → path g v (reverse xs) u := list.induction_on xs (show ∀ (u v : V), path g u [] v → path g v [] u, from take (u v : V), assume (u_path_v : path g u [] v), path.cases_on u_path_v _ _) sorry /- (take (x : V) (xs : list V), assume (IHxs : ∀ {u v : V}, path g u xs v → path g v (reverse xs) u), show ∀ (u v : V), path g u (x :: xs) v → path g v (reverse (x :: xs)) u, from take (u v : V), assume (u_path_v : path g u (x :: xs) v), have g_u_x : g u x, from and.elim_left u_path_v, have x_path_v : path g x xs v, from and.elim_right u_path_v, have v_path_x : path g v (reverse xs) x, from IHxs x_path_v, have g_x_u : g x u, from g_undirected g_u_x, have x_path_u : path g x [] u, from have v_path_u : path g v (reverse xs) x) u, from rcons_path g v_path_x g_x_u, show path g v (reverse (x :: xs)) u, from (rcons_reverse x xs)⁻¹ ▸ v_path_u) -/ theorem connected_sym : ∀ (u v : V), u ↔ v → v ↔ u := take u v, assume u_conn_v : u ↔ v, or.elim u_conn_v (take u_eq_v : u = v, or.inl u_eq_v⁻¹) (take H_uv : ∃ xs, path g u xs v, obtain xs (u_path_v : path g u xs v), from H_uv, have v_path_u : path g v (reverse xs) u, from @path_reverse V g V_decidable g_decidable g_undirected xs u v u_path_v, or.inr (exists.intro _ v_path_u)) lemma path_reverse_nil (u v : V) : ¬ path g u [] v := λ H,H lemma path_reverse_one (x u v : V) (u_path_v : path g u [x] v) : path g v [x] u := iff.elim_left and.comm u_path_v lemma path_reverse (xs : list V) : ∀ (u v : V), path g u xs v → path g v (reverse xs) u := list.induction_on xs (take (u v : V), assume (u_path_v : path g u [] v), false.rec _ u_path_v) (take (x1 : V) (xs : list V), assume (IHxs : ∀ (u v : V), path g u xs v → path g v (reverse xs) u), show ∀ (u v : V), path g u (x1 :: xs) v → path g v (reverse (x1 :: xs)) u, from list.cases_on xs (take (u v : V), assume (u_path_v : path g u [x1] v), show path g v [x1] u, from iff.elim_left and.comm u_path_v) (take (x2 : V) (xs : list V), take (u v : V), list.cases_on xs (assume u_path_v : path g u [x1,x2] v, show path g v [x2,x1] u, from sorry) (take (x3 : V) (xs : list V), assume (u_path_v : path g u (x1 :: x2 :: x3 :: xs) v), have H_u_path_v : u = x1 ∧ g x1 x2 ∧ path g x2 (x2 :: xs) v, from u_path_v, have u_eq_x2 : u = x1, from and.elim_left H_u_path_v, have g_x2_x1 : g x1 x2, from and.elim_left (and.elim_right H_u_path_v), have g_x1_x2 : g x2 x1, from g_undirected g_x2_x1, have x2_path_v : path g x2 (x2 :: x3 :: xs) v, from and.elim_right (and.elim_right H_u_path_v), have v_path_x2 : path g v (reverse (x2 :: xs)) x2, from IHxs x2 v x2_path_v, have v_path_x1 : path g v (rcons (reverse (x2 :: xs)) x1) x1, from rcons_path v_path_x2 g_x2_x1, show path g v (reverse (x2 :: x1 :: xs)) u, from (rcons_reverse x2 (x1 :: xs))⁻¹ ▸ v_path_x2)) /- have x1_path_v : path g x1 (x1 :: xs) v, from and.elim_right (and.elim_right H_u_path_v), -/ theorem graph_theorems1b_dep : ∀ (u v : V), u ↔ v → v ↔ u := -- To prove (2), consider any u, v ∈ V where u ↔ v. take u v, assume u_conn_v : u ↔ v, -- Then there must be some path (u, x1, x2, …, xn, v). obtain (xs : list V) (u_path_v : path g u xs v), from u_conn_v, -- Since G is an undirected graph, this means v, xn, …, x1, u is a path from v to u. have v_conn_u : ∀ (u v : V), path g u xs v → path g v (reverse xs) u, from list.induction_on xs (take (u v : V), assume (u_path_v : path g u [] v), false.rec _ u_path_v) (take (x : V) (xs : list V), assume IHxs : ∀ (u v : V), path g u xs v → path g v (reverse xs) u, take (u v : V), assume u_path_v : path g u (x :: xs) v, show path g v (reverse (x :: xs)) u, from sorry), -- Thus v ↔ u. show v ↔ u, from exists.intro _ (v_conn_u _ _ u_path_v) end V
55d71552dc36839c925193cccaa8f5c341cf3bbf
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/hf.lean
858871a3fd79c96efa8e08af633e0366e1519154
[ "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
25,521
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Hereditarily finite sets: finite sets whose elements are all hereditarily finite sets. Remark: all definitions compute, however the performace is quite poor since we implement this module using a bijection from (finset nat) to nat, and this bijection is implemeted using the Ackermann coding. -/ import data.nat data.finset.equiv data.list open nat binary open - [notation] finset definition hf := nat namespace hf local attribute hf [reducible] protected definition prio : num := num.succ std.priority.default attribute [instance] protected definition is_inhabited : inhabited hf := nat.is_inhabited attribute [instance] protected definition has_decidable_eq : decidable_eq hf := nat.has_decidable_eq definition of_finset (s : finset hf) : hf := @equiv.to_fun _ _ finset_nat_equiv_nat s definition to_finset (h : hf) : finset hf := @equiv.inv _ _ finset_nat_equiv_nat h definition to_nat (h : hf) : nat := h definition of_nat (n : nat) : hf := n lemma to_finset_of_finset (s : finset hf) : to_finset (of_finset s) = s := @equiv.left_inv _ _ finset_nat_equiv_nat s lemma of_finset_to_finset (s : hf) : of_finset (to_finset s) = s := @equiv.right_inv _ _ finset_nat_equiv_nat s lemma to_finset_inj {s₁ s₂ : hf} : to_finset s₁ = to_finset s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse of_finset_to_finset h lemma of_finset_inj {s₁ s₂ : finset hf} : of_finset s₁ = of_finset s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse to_finset_of_finset h /- empty -/ definition empty : hf := of_finset (finset.empty) notation `∅` := hf.empty /- insert -/ definition insert (a s : hf) : hf := of_finset (finset.insert a (to_finset s)) /- mem -/ definition mem (a : hf) (s : hf) : Prop := finset.mem a (to_finset s) infix ∈ := mem notation [priority finset.prio] a ∉ b := ¬ mem a b lemma insert_lt_of_not_mem {a s : hf} : a ∉ s → s < insert a s := begin unfold [insert, of_finset, equiv.to_fun, finset_nat_equiv_nat, mem, to_finset, equiv.inv], intro h, rewrite [finset.to_nat_insert h], rewrite [to_nat_of_nat, -zero_add s at {1}], apply add_lt_add_right, apply pow_pos_of_pos _ dec_trivial end lemma insert_lt_insert_of_not_mem_of_not_mem_of_lt {a s₁ s₂ : hf} : a ∉ s₁ → a ∉ s₂ → s₁ < s₂ → insert a s₁ < insert a s₂ := begin unfold [insert, of_finset, equiv.to_fun, finset_nat_equiv_nat, mem, to_finset, equiv.inv], intro h₁ h₂ h₃, rewrite [finset.to_nat_insert h₁], rewrite [finset.to_nat_insert h₂, *to_nat_of_nat], apply add_lt_add_left h₃ end open decidable attribute [instance] protected definition decidable_mem : ∀ a s, decidable (a ∈ s) := λ a s, finset.decidable_mem a (to_finset s) lemma insert_le (a s : hf) : s ≤ insert a s := by_cases (suppose a ∈ s, by rewrite [↑insert, insert_eq_of_mem this, of_finset_to_finset]) (suppose a ∉ s, le_of_lt (insert_lt_of_not_mem this)) lemma not_mem_empty (a : hf) : a ∉ ∅ := begin unfold [mem, empty], rewrite to_finset_of_finset, apply finset.not_mem_empty end lemma mem_insert (a s : hf) : a ∈ insert a s := begin unfold [mem, insert], rewrite to_finset_of_finset, apply finset.mem_insert end lemma mem_insert_of_mem {a s : hf} (b : hf) : a ∈ s → a ∈ insert b s := begin unfold [mem, insert], intros, rewrite to_finset_of_finset, apply finset.mem_insert_of_mem, assumption end lemma eq_or_mem_of_mem_insert {a b s : hf} : a ∈ insert b s → a = b ∨ a ∈ s := begin unfold [mem, insert], rewrite to_finset_of_finset, intros, apply eq_or_mem_of_mem_insert, assumption end theorem mem_of_mem_insert_of_ne {x a : hf} {s : hf} : x ∈ insert a s → x ≠ a → x ∈ s := begin unfold [mem, insert], rewrite to_finset_of_finset, intros, apply mem_of_mem_insert_of_ne, repeat assumption end protected theorem ext {s₁ s₂ : hf} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := assume h, have to_finset s₁ = to_finset s₂, from finset.ext h, have of_finset (to_finset s₁) = of_finset (to_finset s₂), by rewrite this, by rewrite [*of_finset_to_finset at this]; exact this theorem insert_eq_of_mem {a : hf} {s : hf} : a ∈ s → insert a s = s := begin unfold mem, intro h, unfold [mem, insert], rewrite (finset.insert_eq_of_mem h), rewrite of_finset_to_finset end attribute [recursor 4] protected theorem induction {P : hf → Prop} (h₁ : P empty) (h₂ : ∀ (a s : hf), a ∉ s → P s → P (insert a s)) (s : hf) : P s := have P (of_finset (to_finset s)), from @finset.induction _ _ _ h₁ (λ a s nain ih, begin unfold [mem, insert] at h₂, rewrite -(to_finset_of_finset s) at nain, have P (insert a (of_finset s)), by exact h₂ a (of_finset s) nain ih, rewrite [↑insert at this, to_finset_of_finset at this], exact this end) (to_finset s), by rewrite of_finset_to_finset at this; exact this lemma insert_le_insert_of_le {a s₁ s₂ : hf} : a ∈ s₁ ∨ a ∉ s₂ → s₁ ≤ s₂ → insert a s₁ ≤ insert a s₂ := suppose a ∈ s₁ ∨ a ∉ s₂, suppose s₁ ≤ s₂, by_cases (suppose s₁ = s₂, by rewrite this) (suppose s₁ ≠ s₂, have s₁ < s₂, from lt_of_le_of_ne `s₁ ≤ s₂` `s₁ ≠ s₂`, by_cases (suppose a ∈ s₁, by_cases (suppose a ∈ s₂, by rewrite [insert_eq_of_mem `a ∈ s₁`, insert_eq_of_mem `a ∈ s₂`]; assumption) (suppose a ∉ s₂, by rewrite [insert_eq_of_mem `a ∈ s₁`]; exact le.trans `s₁ ≤ s₂` !insert_le)) (suppose a ∉ s₁, by_cases (suppose a ∈ s₂, or.elim `a ∈ s₁ ∨ a ∉ s₂` (by contradiction) (by contradiction)) (suppose a ∉ s₂, le_of_lt (insert_lt_insert_of_not_mem_of_not_mem_of_lt `a ∉ s₁` `a ∉ s₂` `s₁ < s₂`)))) /- union -/ definition union (s₁ s₂ : hf) : hf := of_finset (finset.union (to_finset s₁) (to_finset s₂)) infix [priority hf.prio] ∪ := union theorem mem_union_left {a : hf} {s₁ : hf} (s₂ : hf) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := begin unfold mem, intro h, unfold union, rewrite to_finset_of_finset, apply finset.mem_union_left _ h end theorem mem_union_l {a : hf} {s₁ : hf} {s₂ : hf} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : hf} {s₂ : hf} (s₁ : hf) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := begin unfold mem, intro h, unfold union, rewrite to_finset_of_finset, apply finset.mem_union_right _ h end theorem mem_union_r {a : hf} {s₂ : hf} {s₁ : hf} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := begin unfold [mem, union], rewrite to_finset_of_finset, intro h, apply finset.mem_or_mem_of_mem_union h end theorem mem_union_iff {a : hf} (s₁ s₂ : hf) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq {a : hf} (s₁ s₂ : hf) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext !mem_union_iff theorem union_comm (s₁ s₂ : hf) : s₁ ∪ s₂ = s₂ ∪ s₁ := hf.ext (λ a, by rewrite [*mem_union_eq]; exact or.comm) theorem union_assoc (s₁ s₂ s₃ : hf) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := hf.ext (λ a, by rewrite [*mem_union_eq]; exact or.assoc) theorem union_left_comm (s₁ s₂ s₃ : hf) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : hf) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union_comm union_assoc s₁ s₂ s₃ theorem union_self (s : hf) : s ∪ s = s := hf.ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : hf) : s ∪ ∅ = s := hf.ext (λ a, iff.intro (suppose a ∈ s ∪ ∅, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i !not_mem_empty)) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : hf) : ∅ ∪ s = s := calc ∅ ∪ s = s ∪ ∅ : union_comm ... = s : union_empty /- inter -/ definition inter (s₁ s₂ : hf) : hf := of_finset (finset.inter (to_finset s₁) (to_finset s₂)) infix [priority hf.prio] ∩ := inter theorem mem_of_mem_inter_left {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := begin unfold mem, unfold inter, rewrite to_finset_of_finset, intro h, apply finset.mem_of_mem_inter_left h end theorem mem_of_mem_inter_right {a : hf} {s₁ s₂ : hf} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := begin unfold mem, unfold inter, rewrite to_finset_of_finset, intro h, apply finset.mem_of_mem_inter_right h end theorem mem_inter {a : hf} {s₁ s₂ : hf} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := begin unfold mem, intro h₁ h₂, unfold inter, rewrite to_finset_of_finset, apply finset.mem_inter h₁ h₂ end theorem mem_inter_iff (a : hf) (s₁ s₂ : hf) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : hf) (s₁ s₂ : hf) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext !mem_inter_iff theorem inter_comm (s₁ s₂ : hf) : s₁ ∩ s₂ = s₂ ∩ s₁ := hf.ext (λ a, by rewrite [*mem_inter_eq]; exact and.comm) theorem inter_assoc (s₁ s₂ s₃ : hf) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := hf.ext (λ a, by rewrite [*mem_inter_eq]; exact and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : hf) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : hf) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_self (s : hf) : s ∩ s = s := hf.ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : hf) : s ∩ ∅ = ∅ := hf.ext (λ a, iff.intro (suppose a ∈ s ∩ ∅, absurd (mem_of_mem_inter_right this) !not_mem_empty) (suppose a ∈ ∅, absurd this !not_mem_empty)) theorem empty_inter (s : hf) : ∅ ∩ s = ∅ := calc ∅ ∩ s = s ∩ ∅ : inter_comm ... = ∅ : inter_empty /- card -/ definition card (s : hf) : nat := finset.card (to_finset s) theorem card_empty : card ∅ = 0 := rfl lemma ne_empty_of_card_eq_succ {s : hf} {n : nat} : card s = succ n → s ≠ ∅ := by intros; substvars; contradiction /- erase -/ definition erase (a : hf) (s : hf) : hf := of_finset (erase a (to_finset s)) theorem not_mem_erase (a : hf) (s : hf) : a ∉ erase a s := begin unfold [mem, erase], rewrite to_finset_of_finset, apply finset.not_mem_erase end theorem card_erase_of_mem {a : hf} {s : hf} : a ∈ s → card (erase a s) = pred (card s) := begin unfold mem, intro h, unfold [erase, card], rewrite to_finset_of_finset, apply finset.card_erase_of_mem h end theorem card_erase_of_not_mem {a : hf} {s : hf} : a ∉ s → card (erase a s) = card s := begin unfold [mem], intro h, unfold [erase, card], rewrite to_finset_of_finset, apply finset.card_erase_of_not_mem h end theorem erase_empty (a : hf) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : hf} {s : hf} : b ∈ erase a s → b ≠ a := by intro h beqa; subst b; exact absurd h !not_mem_erase theorem mem_of_mem_erase {a b : hf} {s : hf} : b ∈ erase a s → b ∈ s := begin unfold [erase, mem], rewrite to_finset_of_finset, intro h, apply mem_of_mem_erase h end theorem mem_erase_of_ne_of_mem {a b : hf} {s : hf} : a ≠ b → a ∈ s → a ∈ erase b s := begin intro h₁, unfold mem, intro h₂, unfold erase, rewrite to_finset_of_finset, apply mem_erase_of_ne_of_mem h₁ h₂ end theorem mem_erase_iff (a b : hf) (s : hf) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : hf) (s : hf) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext !mem_erase_iff theorem erase_insert {a : hf} {s : hf} : a ∉ s → erase a (insert a s) = s := begin unfold [mem, erase, insert], intro h, rewrite [to_finset_of_finset, finset.erase_insert h, of_finset_to_finset] end theorem insert_erase {a : hf} {s : hf} : a ∈ s → insert a (erase a s) = s := begin unfold mem, intro h, unfold [insert, erase], rewrite [to_finset_of_finset, finset.insert_erase h, of_finset_to_finset] end /- subset -/ definition subset (s₁ s₂ : hf) : Prop := finset.subset (to_finset s₁) (to_finset s₂) infix [priority hf.prio] ⊆ := subset theorem empty_subset (s : hf) : ∅ ⊆ s := begin unfold [empty, subset], rewrite to_finset_of_finset, apply finset.empty_subset (to_finset s) end theorem subset.refl (s : hf) : s ⊆ s := begin unfold [subset], apply finset.subset.refl (to_finset s) end theorem subset.trans {s₁ s₂ s₃ : hf} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := begin unfold [subset], intro h₁ h₂, apply finset.subset.trans h₁ h₂ end theorem mem_of_subset_of_mem {s₁ s₂ : hf} {a : hf} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := begin unfold [subset, mem], intro h₁ h₂, apply finset.mem_of_subset_of_mem h₁ h₂ end theorem subset.antisymm {s₁ s₂ : hf} : s₁ ⊆ s₂ → s₂ ⊆ s₁ → s₁ = s₂ := begin unfold [subset], intro h₁ h₂, apply to_finset_inj (finset.subset.antisymm h₁ h₂) end -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : hf} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : hf} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := begin unfold [mem, subset], intro h, apply finset.subset_of_forall h end theorem subset_insert (s : hf) (a : hf) : s ⊆ insert a s := begin unfold [subset, insert], rewrite to_finset_of_finset, apply finset.subset_insert (to_finset s) end theorem eq_empty_of_subset_empty {x : hf} (H : x ⊆ ∅) : x = ∅ := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : hf) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) theorem erase_subset_erase (a : hf) {s t : hf} : s ⊆ t → erase a s ⊆ erase a t := begin unfold [subset, erase], intro h, rewrite *to_finset_of_finset, apply finset.erase_subset_erase a h end theorem erase_subset (a : hf) (s : hf) : erase a s ⊆ s := begin unfold [subset, erase], rewrite to_finset_of_finset, apply finset.erase_subset a (to_finset s) end theorem erase_eq_of_not_mem {a : hf} {s : hf} : a ∉ s → erase a s = s := begin unfold [mem, erase], intro h, rewrite [finset.erase_eq_of_not_mem h, of_finset_to_finset] end theorem erase_insert_subset (a : hf) (s : hf) : erase a (insert a s) ⊆ s := begin unfold [erase, insert, subset], rewrite [*to_finset_of_finset], apply finset.erase_insert_subset a (to_finset s) end theorem erase_subset_of_subset_insert {a : hf} {s t : hf} (H : s ⊆ insert a t) : erase a s ⊆ t := hf.subset.trans (!hf.erase_subset_erase H) (erase_insert_subset a t) theorem insert_erase_subset (a : hf) (s : hf) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [!insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, suffices s ⊆ insert a s, by rewrite [erase_eq_of_not_mem nains]; assumption, subset_insert s a) theorem insert_subset_insert (a : hf) {s t : hf} : s ⊆ t → insert a s ⊆ insert a t := begin unfold [subset, insert], intro h, rewrite *to_finset_of_finset, apply finset.insert_subset_insert a h end theorem subset_insert_of_erase_subset {s t : hf} {a : hf} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (!insert_subset_insert H) theorem subset_insert_iff (s t : hf) (a : hf) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro !erase_subset_of_subset_insert !subset_insert_of_erase_subset theorem le_of_subset {s₁ s₂ : hf} : s₁ ⊆ s₂ → s₁ ≤ s₂ := begin revert s₂, induction s₁ with a s₁ nain ih, take s₂, suppose ∅ ⊆ s₂, !zero_le, take s₂, suppose insert a s₁ ⊆ s₂, have a ∈ s₂, from mem_of_subset_of_mem this !mem_insert, have a ∉ erase a s₂, from !not_mem_erase, have s₁ ⊆ erase a s₂, from subset_of_forall (take x xin, by_cases (suppose x = a, by subst x; contradiction) (suppose x ≠ a, have x ∈ s₂, from mem_of_subset_of_mem `insert a s₁ ⊆ s₂` (mem_insert_of_mem _ `x ∈ s₁`), mem_erase_of_ne_of_mem `x ≠ a` `x ∈ s₂`)), have s₁ ≤ erase a s₂, from ih _ this, have insert a s₁ ≤ insert a (erase a s₂), from insert_le_insert_of_le (or.inr `a ∉ erase a s₂`) this, by rewrite [insert_erase `a ∈ s₂` at this]; exact this end /- image -/ definition image (f : hf → hf) (s : hf) : hf := of_finset (finset.image f (to_finset s)) theorem image_empty (f : hf → hf) : image f ∅ = ∅ := rfl theorem mem_image_of_mem (f : hf → hf) {s : hf} {a : hf} : a ∈ s → f a ∈ image f s := begin unfold [mem, image], intro h, rewrite to_finset_of_finset, apply finset.mem_image_of_mem f h end theorem mem_image {f : hf → hf} {s : hf} {a : hf} {b : hf} (H1 : a ∈ s) (H2 : f a = b) : b ∈ image f s := eq.subst H2 (mem_image_of_mem f H1) theorem exists_of_mem_image {f : hf → hf} {s : hf} {b : hf} : b ∈ image f s → ∃a, a ∈ s ∧ f a = b := begin unfold [mem, image], rewrite to_finset_of_finset, intro h, apply finset.exists_of_mem_image h end theorem mem_image_iff (f : hf → hf) {s : hf} {y : hf} : y ∈ image f s ↔ ∃x, x ∈ s ∧ f x = y := begin unfold [mem, image], rewrite to_finset_of_finset, apply finset.mem_image_iff end theorem mem_image_eq (f : hf → hf) {s : hf} {y : hf} : y ∈ image f s = ∃x, x ∈ s ∧ f x = y := propext (mem_image_iff f) theorem mem_image_of_mem_image_of_subset {f : hf → hf} {s t : hf} {y : hf} (H1 : y ∈ image f s) (H2 : s ⊆ t) : y ∈ image f t := obtain x `x ∈ s` `f x = y`, from exists_of_mem_image H1, have x ∈ t, from mem_of_subset_of_mem H2 `x ∈ s`, show y ∈ image f t, from mem_image `x ∈ t` `f x = y` theorem image_insert (f : hf → hf) (s : hf) (a : hf) : image f (insert a s) = insert (f a) (image f s) := begin unfold [image, insert], rewrite [*to_finset_of_finset, finset.image_insert] end open function lemma image_comp {f : hf → hf} {g : hf → hf} {s : hf} : image (f∘g) s = image f (image g s) := begin unfold image, rewrite [*to_finset_of_finset, finset.image_comp] end lemma image_subset {a b : hf} (f : hf → hf) : a ⊆ b → image f a ⊆ image f b := begin unfold [subset, image], intro h, rewrite *to_finset_of_finset, apply finset.image_subset f h end theorem image_union (f : hf → hf) (s t : hf) : image f (s ∪ t) = image f s ∪ image f t := begin unfold [image, union], rewrite [*to_finset_of_finset, finset.image_union] end /- powerset -/ definition powerset (s : hf) : hf := of_finset (finset.image of_finset (finset.powerset (to_finset s))) prefix [priority hf.prio] `𝒫`:100 := powerset theorem powerset_empty : 𝒫 ∅ = insert ∅ ∅ := rfl theorem powerset_insert {a : hf} {s : hf} : a ∉ s → 𝒫 (insert a s) = 𝒫 s ∪ image (insert a) (𝒫 s) := begin unfold [mem, powerset, insert, union, image], rewrite [*to_finset_of_finset], intro h, have (λ (x : finset hf), of_finset (finset.insert a x)) = (λ (x : finset hf), of_finset (finset.insert a (to_finset (of_finset x)))), from funext (λ x, by rewrite to_finset_of_finset), rewrite [finset.powerset_insert h, finset.image_union, -*finset.image_comp, ↑comp, this] end theorem mem_powerset_iff_subset (s : hf) : ∀ x : hf, x ∈ 𝒫 s ↔ x ⊆ s := begin intro x, unfold [mem, powerset, subset], rewrite [to_finset_of_finset, finset.mem_image_eq], apply iff.intro, suppose (∃ (w : finset hf), finset.mem w (finset.powerset (to_finset s)) ∧ of_finset w = x), obtain w h₁ h₂, from this, begin subst x, rewrite to_finset_of_finset, exact iff.mp !finset.mem_powerset_iff_subset h₁ end, suppose finset.subset (to_finset x) (to_finset s), have finset.mem (to_finset x) (finset.powerset (to_finset s)), from iff.mpr !finset.mem_powerset_iff_subset this, exists.intro (to_finset x) (and.intro this (of_finset_to_finset x)) end theorem subset_of_mem_powerset {s t : hf} (H : s ∈ 𝒫 t) : s ⊆ t := iff.mp (mem_powerset_iff_subset t s) H theorem mem_powerset_of_subset {s t : hf} (H : s ⊆ t) : s ∈ 𝒫 t := iff.mpr (mem_powerset_iff_subset t s) H theorem empty_mem_powerset (s : hf) : ∅ ∈ 𝒫 s := mem_powerset_of_subset (empty_subset s) /- hf as lists -/ open - [notation] list definition of_list (s : list hf) : hf := @equiv.to_fun _ _ list_nat_equiv_nat s definition to_list (h : hf) : list hf := @equiv.inv _ _ list_nat_equiv_nat h lemma to_list_of_list (s : list hf) : to_list (of_list s) = s := @equiv.left_inv _ _ list_nat_equiv_nat s lemma of_list_to_list (s : hf) : of_list (to_list s) = s := @equiv.right_inv _ _ list_nat_equiv_nat s lemma to_list_inj {s₁ s₂ : hf} : to_list s₁ = to_list s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse of_list_to_list h lemma of_list_inj {s₁ s₂ : list hf} : of_list s₁ = of_list s₂ → s₁ = s₂ := λ h, function.injective_of_left_inverse to_list_of_list h definition nil : hf := of_list list.nil lemma empty_eq_nil : ∅ = nil := rfl definition cons (a l : hf) : hf := of_list (list.cons a (to_list l)) infixr :: := cons lemma cons_ne_nil (a l : hf) : a::l ≠ nil := by contradiction lemma head_eq_of_cons_eq {h₁ h₂ t₁ t₂ : hf} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := begin unfold cons, intro h, apply list.head_eq_of_cons_eq (of_list_inj h) end lemma tail_eq_of_cons_eq {h₁ h₂ t₁ t₂ : hf} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := begin unfold cons, intro h, apply to_list_inj (list.tail_eq_of_cons_eq (of_list_inj h)) end lemma cons_inj {a : hf} : injective (cons a) := take l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe /- append -/ definition append (l₁ l₂ : hf) : hf := of_list (list.append (to_list l₁) (to_list l₂)) notation l₁ ++ l₂ := append l₁ l₂ attribute [simp] theorem append_nil_left (t : hf) : nil ++ t = t := begin unfold [nil, append], rewrite [to_list_of_list, list.append_nil_left, of_list_to_list] end attribute [simp] theorem append_cons (x s t : hf) : (x::s) ++ t = x::(s ++ t) := begin unfold [cons, append], rewrite [*to_list_of_list, list.append_cons] end attribute [simp] theorem append_nil_right (t : hf) : t ++ nil = t := begin unfold [nil, append], rewrite [to_list_of_list, list.append_nil_right, of_list_to_list] end attribute [simp] theorem append.assoc (s t u : hf) : s ++ t ++ u = s ++ (t ++ u) := begin unfold append, rewrite [*to_list_of_list, list.append.assoc] end /- length -/ definition length (l : hf) : nat := list.length (to_list l) attribute [simp] theorem length_nil : length nil = 0 := begin unfold [length, nil] end attribute [simp] theorem length_cons (x t : hf) : length (x::t) = length t + 1 := begin unfold [length, cons], rewrite to_list_of_list end attribute [simp] theorem length_append (s t : hf) : length (s ++ t) = length s + length t := begin unfold [length, append], rewrite [to_list_of_list, list.length_append] end theorem eq_nil_of_length_eq_zero {l : hf} : length l = 0 → l = nil := begin unfold [length, nil], intro h, rewrite [-list.eq_nil_of_length_eq_zero h, of_list_to_list] end theorem ne_nil_of_length_eq_succ {l : hf} {n : nat} : length l = succ n → l ≠ nil := begin unfold [length, nil], intro h₁ h₂, subst l, rewrite to_list_of_list at h₁, contradiction end /- head and tail -/ definition head (l : hf) : hf := list.head (to_list l) attribute [simp] theorem head_cons (a l : hf) : head (a::l) = a := begin unfold [head, cons], rewrite to_list_of_list end private lemma to_list_ne_list_nil {s : hf} : s ≠ nil → to_list s ≠ list.nil := begin unfold nil, intro h, suppose to_list s = list.nil, by rewrite [-this at h, of_list_to_list at h]; exact absurd rfl h end attribute [simp] theorem head_append (t : hf) {s : hf} : s ≠ nil → head (s ++ t) = head s := begin unfold [nil, head, append], rewrite to_list_of_list, suppose s ≠ of_list list.nil, by rewrite [list.head_append _ (to_list_ne_list_nil this)] end definition tail (l : hf) : hf := of_list (list.tail (to_list l)) attribute [simp] theorem tail_nil : tail nil = nil := begin unfold [tail, nil] end attribute [simp] theorem tail_cons (a l : hf) : tail (a::l) = l := begin unfold [tail, cons], rewrite [to_list_of_list, list.tail_cons, of_list_to_list] end theorem cons_head_tail {l : hf} : l ≠ nil → (head l)::(tail l) = l := begin unfold [nil, head, tail, cons], suppose l ≠ of_list list.nil, by rewrite [to_list_of_list, list.cons_head_tail (to_list_ne_list_nil this), of_list_to_list] end end hf
c62fc7750bdf7eff58f41d818d83cbe88adaada8
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/set_theory/cardinal.lean
edb555b7eaa71e75cd93a0e48257deef9885d1d2
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
46,604
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic: addition, multiplication, power, cardinal successor, minimum, supremum, infinitary sums and products The fact that the cardinality of `α × α` coincides with that of `α` when `α` is infinite is not proved in this file, as it relies on facts on well-orders. Instead, it is in `cardinal_ordinal.lean` (together with many other facts on cardinals, for instance the cardinality of `list α`). ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. There is a lift operation lifting cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/ordinal.lean`, because concepts from that file are used in the proof. ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩ theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α := by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp } instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) @[simp] lemma pow_cast_right (κ : cardinal.{u}) : ∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.prod_map e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } instance : canonically_ordered_add_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩), cases not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.injective h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [←le_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine lt_succ.1 (lt_of_not_ge $ λ hn, _), rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn, cases hn with f, refine not_lt_of_le (H $ finset.univ.map f) _, rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨coe, λ a b, fin.ext⟩⟩ @[simp] theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (le_add_right _ _) h, lt_of_le_of_lt (le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} : mk α = 1 ↔ (subsingleton α ∧ nonempty α) := calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : mk (subtype p) ≤ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ := begin split, { intro h, have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T := @mk_union_add_mk_inter α S T ▸ le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union H⟩ lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := mk_subtype_le s lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : mk {a : α // p (e a)} = mk {b : β // p b} := quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal
a95fd11ea8226a24d96703a74ccee240ce65f24d
ba4794a0deca1d2aaa68914cd285d77880907b5c
/world_experiments/used_to_be_level2_stupid_exact_tactic.lean
efa735f4359a0f50843e26c1b92f2ba15c8c0663
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,671
lean
import mynat.definition -- Imports the natural numbers. -- hide import mynat.mul -- hide namespace mynat -- hide /- # World 1: Tutorial world ## level 2: the `exact` tactic. Delete the `sorry` below and let's look at the box on the top right. It should look like this: ``` a b : mynat, h : 2 * a = b + 7 ⊢ 2 * a = b + 7 ``` So here `a` and `b` are natural numbers, we have a hypothesis `h` that `2 * a = b + 7` (think of `h` as a *proof* that `2 * a = b + 7`), and our goal is to prove that `2 * a = b + 7`. Unfortunately `refl` won't work here. `refl` proves things like `3 = 3` or `x + y = x + y`. `refl` works when both sides of an equality are *exactly the same strings of characters in the same order*. The reason why `2 * a = b + 7` is true is *not* because `2 * a` and `b + 7` are exactly the same strings of characters in the same order. The reason it's true is because it's a hypothesis. The numbers `2 * a` and `b + 7` are equal because of a theorem, and the proof of the theorem is `h`. That's what a hypothesis is -- it's a way of saying "imagine we have a proof of this". We're hence in a situation where we have a hypothesis `h`, which is *exactly* equal to the goal we're trying to prove. In this situation, the tactic `exact h,` will close the goal. Try typing `exact h,` where the `sorry` was, and hit enter after the comma to go onto a new line. **Don't forget the `h`** and **don't forget the comma.** You should see the "Proof complete!" message, and the error in the bottom right goal will disappear. The reason this works is that `h` is *exactly* a proof of the goal. -/ /- Lemma : no-side-bar For all natural numbers $a$ and $b$, if $2a=b + 7$, then $2a=b+7$. -/ lemma example2 (a b : mynat) (h : 2 * a = b + 7): 2 * a = b + 7 := begin [less_leaky] exact h end /- Tactic : exact If your goal is a proposition and you have access to a proof of that proposition, either because it is a hypothesis `h` or because it is a theorem which is already proved, then `exact h,` or `exact <name_of_theorem>,` will close the goal. ### Examples 1) If the top right box (the "local context") looks like this: ``` x y : mynat h : y = x + 3 ⊢ y = x + 3 ``` then `exact h,` will close the goal. 2) (from world 2 onwards) If the top right box looks like this: ``` a b : mynat ⊢ a + succ(b) = succ(a + b) ``` then `exact add_succ a b,` will close the goal. -/ /- These two tactics, `refl` and `exact`, clearly only have limited capabilities by themselves. The next tactic we will learn, the rewrite tactic `rw`, is far more powerful. Click on "next level" to move onto the next level in tutorial world. -/ end mynat -- hide
8215e61907f570dd8b4f8aaffaf07bbe5a639181
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/box_integral/partition/additive.lean
4053718388593fc3debc739c76dec4b21e6fb42d
[ "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
9,745
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.partition.split import analysis.normed_space.operator_norm import data.set.intervals.proj_Icc /-! # Box additive functions We say that a function `f : box ι → M` from boxes in `ℝⁿ` to a commutative additive monoid `M` is *box additive* on subboxes of `I₀ : with_top (box ι)` if for any box `J`, `↑J ≤ I₀`, and a partition `π` of `J`, `f J = ∑ J' in π.boxes, f J'`. We use `I₀ : with_top (box ι)` instead of `I₀ : box ι` to use the same definition for functions box additive on subboxes of a box and for functions box additive on all boxes. Examples of box-additive functions include the measure of a box and the integral of a fixed integrable function over a box. In this file we define box-additive functions and prove that a function such that `f J = f (J ∩ {x | x i < y}) + f (J ∩ {x | y ≤ x i})` is box-additive. ### Tags rectangular box, additive function -/ noncomputable theory open_locale classical big_operators open function set namespace box_integral variables {ι M : Type*} {n : ℕ} /-- A function on `box ι` is called box additive if for every box `J` and a partition `π` of `J` we have `f J = ∑ Ji in π.boxes, f Ji`. A function is called box additive on subboxes of `I : box ι` if the same property holds for `J ≤ I`. We formalize these two notions in the same definition using `I : with_bot (box ι)`: the value `I = ⊤` corresponds to functions box additive on the whole space. -/ structure box_additive_map (ι M : Type*) [add_comm_monoid M] (I : with_top (box ι)) := (to_fun : box ι → M) (sum_partition_boxes' : ∀ J : box ι, ↑J ≤ I → ∀ π : prepartition J, π.is_partition → ∑ Ji in π.boxes, to_fun Ji = to_fun J) localized "notation ι ` →ᵇᵃ `:25 M := box_integral.box_additive_map ι M ⊤" in box_integral localized "notation ι ` →ᵇᵃ[`:25 I `] ` M := box_integral.box_additive_map ι M I" in box_integral namespace box_additive_map open box prepartition finset variables {N : Type*} [add_comm_monoid M] [add_comm_monoid N] {I₀ : with_top (box ι)} {I J : box ι} {i : ι} instance : has_coe_to_fun (ι →ᵇᵃ[I₀] M) (λ _, box ι → M) := ⟨to_fun⟩ initialize_simps_projections box_integral.box_additive_map (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : ι →ᵇᵃ[I₀] M) : f.to_fun = f := rfl @[simp] lemma coe_mk (f h) : ⇑(mk f h : ι →ᵇᵃ[I₀] M) = f := rfl lemma coe_injective : injective (λ (f : ι →ᵇᵃ[I₀] M) x, f x) := by { rintro ⟨f, hf⟩ ⟨g, hg⟩ (rfl : f = g), refl } @[simp] lemma coe_inj {f g : ι →ᵇᵃ[I₀] M} : (f : box ι → M) = g ↔ f = g := coe_injective.eq_iff lemma sum_partition_boxes (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π : prepartition I} (h : π.is_partition) : ∑ J in π.boxes, f J = f I := f.sum_partition_boxes' I hI π h @[simps { fully_applied := ff }] instance : has_zero (ι →ᵇᵃ[I₀] M) := ⟨⟨0, λ I hI π hπ, sum_const_zero⟩⟩ instance : inhabited (ι →ᵇᵃ[I₀] M) := ⟨0⟩ instance : has_add (ι →ᵇᵃ[I₀] M) := ⟨λ f g, ⟨f + g, λ I hI π hπ, by simp only [pi.add_apply, sum_add_distrib, sum_partition_boxes _ hI hπ]⟩⟩ instance {R} [monoid R] [distrib_mul_action R M] : has_scalar R (ι →ᵇᵃ[I₀] M) := ⟨λ r f, ⟨r • f, λ I hI π hπ, by simp only [pi.smul_apply, ←smul_sum, sum_partition_boxes _ hI hπ]⟩⟩ instance : add_comm_monoid (ι →ᵇᵃ[I₀] M) := function.injective.add_comm_monoid _ coe_injective rfl (λ _ _, rfl) (λ _ _, rfl) @[simp] lemma map_split_add (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) (i : ι) (x : ℝ) : (I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I := by rw [← f.sum_partition_boxes hI (is_partition_split I i x), sum_split_boxes] /-- If `f` is box-additive on subboxes of `I₀`, then it is box-additive on subboxes of any `I ≤ I₀`. -/ @[simps] def restrict (f : ι →ᵇᵃ[I₀] M) (I : with_top (box ι)) (hI : I ≤ I₀) : ι →ᵇᵃ[I] M := ⟨f, λ J hJ, f.2 J (hJ.trans hI)⟩ /-- If `f : box ι → M` is box additive on partitions of the form `split I i x`, then it is box additive. -/ def of_map_split_add [fintype ι] (f : box ι → M) (I₀ : with_top (box ι)) (hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ {i x}, x ∈ Ioo (I.lower i) (I.upper i) → (I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I) : ι →ᵇᵃ[I₀] M := begin refine ⟨f, _⟩, replace hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ s, ∑ J in (split_many I s).boxes, f J = f I, { intros I hI s, induction s using finset.induction_on with a s ha ihs, { simp }, rw [split_many_insert, inf_split, ← ihs, bUnion_boxes, sum_bUnion_boxes], refine finset.sum_congr rfl (λ J' hJ', _), by_cases h : a.2 ∈ Ioo (J'.lower a.1) (J'.upper a.1), { rw sum_split_boxes, exact hf _ ((with_top.coe_le_coe.2 $ le_of_mem _ hJ').trans hI) h }, { rw [split_of_not_mem_Ioo h, top_boxes, finset.sum_singleton] } }, intros I hI π hπ, have Hle : ∀ J ∈ π, ↑J ≤ I₀, from λ J hJ, (with_top.coe_le_coe.2 $ π.le_of_mem hJ).trans hI, rcases hπ.exists_split_many_le with ⟨s, hs⟩, rw [← hf _ hI, ← inf_of_le_right hs, inf_split_many, bUnion_boxes, sum_bUnion_boxes], exact finset.sum_congr rfl (λ J hJ, (hf _ (Hle _ hJ) _).symm) end /-- If `g : M → N` is an additive map and `f` is a box additive map, then `g ∘ f` is a box additive map. -/ @[simps { fully_applied := ff }] def map (f : ι →ᵇᵃ[I₀] M) (g : M →+ N) : ι →ᵇᵃ[I₀] N := { to_fun := g ∘ f, sum_partition_boxes' := λ I hI π hπ, by rw [← g.map_sum, f.sum_partition_boxes hI hπ] } /-- If `f` is a box additive function on subboxes of `I` and `π₁`, `π₂` are two prepartitions of `I` that cover the same part of `I`, then `∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J`. -/ lemma sum_boxes_congr [fintype ι] (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π₁ π₂ : prepartition I} (h : π₁.Union = π₂.Union) : ∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J := begin rcases exists_split_many_inf_eq_filter_of_finite {π₁, π₂} ((finite_singleton _).insert _) with ⟨s, hs⟩, simp only [inf_split_many] at hs, rcases ⟨hs _ (or.inl rfl), hs _ (or.inr rfl)⟩ with ⟨h₁, h₂⟩, clear hs, rw h at h₁, calc ∑ J in π₁.boxes, f J = ∑ J in π₁.boxes, ∑ J' in (split_many J s).boxes, f J' : finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _)).symm) ... = ∑ J in (π₁.bUnion (λ J, split_many J s)).boxes, f J : (sum_bUnion_boxes _ _ _).symm ... = ∑ J in (π₂.bUnion (λ J, split_many J s)).boxes, f J : by rw [h₁, h₂] ... = ∑ J in π₂.boxes, ∑ J' in (split_many J s).boxes, f J' : sum_bUnion_boxes _ _ _ ... = ∑ J in π₂.boxes, f J : finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _))), exacts [(with_top.coe_le_coe.2 $ π₁.le_of_mem hJ).trans hI, (with_top.coe_le_coe.2 $ π₂.le_of_mem hJ).trans hI] end section to_smul variables {E : Type*} [normed_group E] [normed_space ℝ E] /-- If `f` is a box-additive map, then so is the map sending `I` to the scalar multiplication by `f I` as a continuous linear map from `E` to itself. -/ def to_smul (f : ι →ᵇᵃ[I₀] ℝ) : ι →ᵇᵃ[I₀] (E →L[ℝ] E) := f.map (continuous_linear_map.lsmul ℝ ℝ).to_linear_map.to_add_monoid_hom @[simp] lemma to_smul_apply (f : ι →ᵇᵃ[I₀] ℝ) (I : box ι) (x : E) : f.to_smul I x = f I • x := rfl end to_smul /-- Given a box `I₀` in `ℝⁿ⁺¹`, `f x : box (fin n) → G` is a family of functions indexed by a real `x` and for `x ∈ [I₀.lower i, I₀.upper i]`, `f x` is box-additive on subboxes of the `i`-th face of `I₀`, then `λ J, f (J.upper i) (J.face i) - f (J.lower i) (J.face i)` is box-additive on subboxes of `I₀`. -/ @[simps] def {u} upper_sub_lower {G : Type u} [add_comm_group G] (I₀ : box (fin (n + 1))) (i : fin (n + 1)) (f : ℝ → box (fin n) → G) (fb : Icc (I₀.lower i) (I₀.upper i) → fin n →ᵇᵃ[I₀.face i] G) (hf : ∀ x (hx : x ∈ Icc (I₀.lower i) (I₀.upper i)) J, f x J = fb ⟨x, hx⟩ J) : fin (n + 1) →ᵇᵃ[I₀] G := of_map_split_add (λ J : box (fin (n + 1)), f (J.upper i) (J.face i) - f (J.lower i) (J.face i)) I₀ begin intros J hJ j, rw with_top.coe_le_coe at hJ, refine i.succ_above_cases _ _ j, { intros x hx, simp only [box.split_lower_def hx, box.split_upper_def hx, update_same, ← with_bot.some_eq_coe, option.elim, box.face, (∘), update_noteq (fin.succ_above_ne _ _)], abel }, { clear j, intros j x hx, have : (J.face i : with_top (box (fin n))) ≤ I₀.face i, from with_top.coe_le_coe.2 (face_mono hJ i), rw [le_iff_Icc, @box.Icc_eq_pi _ I₀] at hJ, rw [hf _ (hJ J.upper_mem_Icc _ trivial), hf _ (hJ J.lower_mem_Icc _ trivial), ← (fb _).map_split_add this j x, ← (fb _).map_split_add this j x], have hx' : x ∈ Ioo ((J.face i).lower j) ((J.face i).upper j) := hx, simp only [box.split_lower_def hx, box.split_upper_def hx, box.split_lower_def hx', box.split_upper_def hx', ← with_bot.some_eq_coe, option.elim, box.face_mk, update_noteq (fin.succ_above_ne _ _).symm, sub_add_sub_comm, update_comp_eq_of_injective _ i.succ_above.injective j x, ← hf], simp only [box.face] } end end box_additive_map end box_integral
83984d9763425cf42a26fa8f918e2c6f31baab56
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/maps.lean
965e9414cd96adc286b8ce00516c399e6b954e22
[ "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
15,693
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, Patrick Massot -/ import topology.order /-! # Specific classes of maps between topological spaces This file introduces the following properties of a map `f : X → Y` between topological spaces: * `is_open_map f` means the image of an open set under `f` is open. * `is_closed_map f` means the image of a closed set under `f` is closed. (Open and closed maps need not be continuous.) * `inducing f` means the topology on `X` is the one induced via `f` from the topology on `Y`. These behave like embeddings except they need not be injective. Instead, points of `X` which are identified by `f` are also indistinguishable in the topology on `X`. * `embedding f` means `f` is inducing and also injective. Equivalently, `f` identifies `X` with a subspace of `Y`. * `open_embedding f` means `f` is an embedding with open image, so it identifies `X` with an open subspace of `Y`. Equivalently, `f` is an embedding and an open map. * `closed_embedding f` similarly means `f` is an embedding with closed image, so it identifies `X` with a closed subspace of `Y`. Equivalently, `f` is an embedding and a closed map. * `quotient_map f` is the dual condition to `embedding f`: `f` is surjective and the topology on `Y` is the one coinduced via `f` from the topology on `X`. Equivalently, `f` identifies `Y` with a quotient of `X`. Quotient maps are also sometimes known as identification maps. ## References * <https://en.wikipedia.org/wiki/Open_and_closed_maps> * <https://en.wikipedia.org/wiki/Embedding#General_topology> * <https://en.wikipedia.org/wiki/Quotient_space_(topology)#Quotient_map> ## Tags open map, closed map, embedding, quotient map, identification map -/ open set filter open_locale topological_space filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section inducing structure inducing [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := (induced : tα = tβ.induced f) variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma inducing_id : inducing (@id α) := ⟨induced_id.symm⟩ protected lemma inducing.comp {g : β → γ} {f : α → β} (hg : inducing g) (hf : inducing f) : inducing (g ∘ f) := ⟨by rw [hf.induced, hg.induced, induced_compose]⟩ lemma inducing_of_inducing_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : inducing (g ∘ f)) : inducing f := ⟨le_antisymm (by rwa ← continuous_iff_le_induced) (by { rw [hgf.induced, ← continuous_iff_le_induced], apply hg.comp continuous_induced_dom })⟩ lemma inducing_open {f : α → β} {s : set α} (hf : inducing f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.induced] at hs; exact hs in have is_open (t ∩ range f), from is_open_inter ht h, h_eq ▸ by rwa [image_preimage_eq_inter_range] lemma inducing_is_closed {f : α → β} {s : set α} (hf : inducing f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.induced, is_closed_induced_iff] at hs; exact hs in have is_closed (t ∩ range f), from is_closed_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] lemma inducing.nhds_eq_comap {f : α → β} (hf : inducing f) : ∀ (a : α), 𝓝 a = comap f (𝓝 $ f a) := (induced_iff_nhds_eq f).1 hf.induced lemma inducing.map_nhds_eq {f : α → β} (hf : inducing f) (a : α) (h : range f ∈ 𝓝 (f a)) : (𝓝 a).map f = 𝓝 (f a) := hf.induced.symm ▸ map_nhds_induced_eq h lemma inducing.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : inducing g) : tendsto f a (𝓝 b) ↔ tendsto (g ∘ f) a (𝓝 (g b)) := by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map] lemma inducing.continuous_iff {f : α → β} {g : β → γ} (hg : inducing g) : continuous f ↔ continuous (g ∘ f) := by simp [continuous_iff_continuous_at, continuous_at, inducing.tendsto_nhds_iff hg] lemma inducing.continuous {f : α → β} (hf : inducing f) : continuous f := hf.continuous_iff.mp continuous_id end inducing section embedding /-- A function between topological spaces is an embedding if it is injective, and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/ structure embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β) extends inducing f : Prop := (inj : function.injective f) variables [topological_space α] [topological_space β] [topological_space γ] lemma embedding.mk' (f : α → β) (inj : function.injective f) (induced : ∀a, comap f (𝓝 (f a)) = 𝓝 a) : embedding f := ⟨⟨(induced_iff_nhds_eq f).2 (λ a, (induced a).symm)⟩, inj⟩ lemma embedding_id : embedding (@id α) := ⟨inducing_id, assume a₁ a₂ h, h⟩ lemma embedding.comp {g : β → γ} {f : α → β} (hg : embedding g) (hf : embedding f) : embedding (g ∘ f) := { inj:= assume a₁ a₂ h, hf.inj $ hg.inj h, ..hg.to_inducing.comp hf.to_inducing } lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : embedding (g ∘ f)) : embedding f := { induced := (inducing_of_inducing_compose hf hg hgf.to_inducing).induced, inj := assume a₁ a₂ h, hgf.inj $ by simp [h, (∘)] } lemma embedding_open {f : α → β} {s : set α} (hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := inducing_open hf.1 h hs lemma embedding_is_closed {f : α → β} {s : set α} (hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := inducing_is_closed hf.1 h hs lemma embedding.map_nhds_eq {f : α → β} (hf : embedding f) (a : α) (h : range f ∈ 𝓝 (f a)) : (𝓝 a).map f = 𝓝 (f a) := inducing.map_nhds_eq hf.1 a h lemma embedding.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : embedding g) : tendsto f a (𝓝 b) ↔ tendsto (g ∘ f) a (𝓝 (g b)) := by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map] lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) : continuous f ↔ continuous (g ∘ f) := inducing.continuous_iff hg.1 lemma embedding.continuous {f : α → β} (hf : embedding f) : continuous f := inducing.continuous hf.1 lemma embedding.closure_eq_preimage_closure_image {e : α → β} (he : embedding e) (s : set α) : closure s = e ⁻¹' closure (e '' s) := by { ext x, rw [set.mem_preimage, ← closure_induced he.inj, he.induced] } end embedding /-- A function between topological spaces is a quotient map if it is surjective, and for all `s : set β`, `s` is open iff its preimage is an open set. -/ def quotient_map {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.surjective f ∧ tβ = tα.coinduced f namespace quotient_map variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] protected lemma id : quotient_map (@id α) := ⟨assume a, ⟨a, rfl⟩, coinduced_id.symm⟩ protected lemma comp {g : β → γ} {f : α → β} (hg : quotient_map g) (hf : quotient_map f) : quotient_map (g ∘ f) := ⟨hg.left.comp hf.left, by rw [hg.right, hf.right, coinduced_compose]⟩ protected lemma of_quotient_map_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : quotient_map (g ∘ f)) : quotient_map g := ⟨assume b, let ⟨a, h⟩ := hgf.left b in ⟨f a, h⟩, le_antisymm (by rw [hgf.right, ← continuous_iff_coinduced_le]; apply continuous_coinduced_rng.comp hf) (by rwa ← continuous_iff_coinduced_le)⟩ protected lemma continuous_iff {f : α → β} {g : β → γ} (hf : quotient_map f) : continuous g ↔ continuous (g ∘ f) := by rw [continuous_iff_coinduced_le, continuous_iff_coinduced_le, hf.right, coinduced_compose] protected lemma continuous {f : α → β} (hf : quotient_map f) : continuous f := hf.continuous_iff.mp continuous_id end quotient_map /-- A map `f : α → β` is said to be an *open map*, if the image of any open `U : set α` is open in `β`. -/ def is_open_map [topological_space α] [topological_space β] (f : α → β) := ∀ U : set α, is_open U → is_open (f '' U) namespace is_open_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_open_map (@id α) := assume s hs, by rwa [image_id] protected lemma comp {g : β → γ} {f : α → β} (hg : is_open_map g) (hf : is_open_map f) : is_open_map (g ∘ f) := by intros s hs; rw [image_comp]; exact hg _ (hf _ hs) lemma is_open_range {f : α → β} (hf : is_open_map f) : is_open (range f) := by { rw ← image_univ, exact hf _ is_open_univ } lemma image_mem_nhds {f : α → β} (hf : is_open_map f) {x : α} {s : set α} (hx : s ∈ 𝓝 x) : f '' s ∈ 𝓝 (f x) := let ⟨t, hts, ht, hxt⟩ := mem_nhds_sets_iff.1 hx in mem_sets_of_superset (mem_nhds_sets (hf t ht) (mem_image_of_mem _ hxt)) (image_subset _ hts) lemma nhds_le {f : α → β} (hf : is_open_map f) (a : α) : 𝓝 (f a) ≤ (𝓝 a).map f := le_map $ λ s, hf.image_mem_nhds lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_open_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ h s hs lemma to_quotient_map {f : α → β} (open_map : is_open_map f) (cont : continuous f) (surj : function.surjective f) : quotient_map f := ⟨ surj, begin ext s, show is_open s ↔ is_open (f ⁻¹' s), split, { exact cont s }, { assume h, rw ← @image_preimage_eq _ _ _ s surj, exact open_map _ h } end⟩ end is_open_map lemma is_open_map_iff_nhds_le [topological_space α] [topological_space β] {f : α → β} : is_open_map f ↔ ∀(a:α), 𝓝 (f a) ≤ (𝓝 a).map f := begin refine ⟨λ hf, hf.nhds_le, λ h s hs, is_open_iff_mem_nhds.2 _⟩, rintros b ⟨a, ha, rfl⟩, exact h _ (filter.image_mem_map $ mem_nhds_sets hs ha) end section is_closed_map variables [topological_space α] [topological_space β] def is_closed_map (f : α → β) := ∀ U : set α, is_closed U → is_closed (f '' U) end is_closed_map namespace is_closed_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_closed_map (@id α) := assume s hs, by rwa image_id protected lemma comp {g : β → γ} {f : α → β} (hg : is_closed_map g) (hf : is_closed_map f) : is_closed_map (g ∘ f) := by { intros s hs, rw image_comp, exact hg _ (hf _ hs) } lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_closed_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ continuous_iff_is_closed.mp h s hs end is_closed_map section open_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- An open embedding is an embedding with open image. -/ structure open_embedding (f : α → β) extends embedding f : Prop := (open_range : is_open $ range f) lemma open_embedding.open_iff_image_open {f : α → β} (hf : open_embedding f) {s : set α} : is_open s ↔ is_open (f '' s) := ⟨embedding_open hf.to_embedding hf.open_range, λ h, begin convert ←hf.to_embedding.continuous _ h, apply preimage_image_eq _ hf.inj end⟩ lemma open_embedding.is_open_map {f : α → β} (hf : open_embedding f) : is_open_map f := λ s, hf.open_iff_image_open.mp lemma open_embedding.continuous {f : α → β} (hf : open_embedding f) : continuous f := hf.to_embedding.continuous lemma open_embedding.open_iff_preimage_open {f : α → β} (hf : open_embedding f) {s : set β} (hs : s ⊆ range f) : is_open s ↔ is_open (f ⁻¹' s) := begin convert ←hf.open_iff_image_open.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma open_embedding_of_embedding_open {f : α → β} (h₁ : embedding f) (h₂ : is_open_map f) : open_embedding f := ⟨h₁, by convert h₂ univ is_open_univ; simp⟩ lemma open_embedding_of_continuous_injective_open {f : α → β} (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_open_map f) : open_embedding f := begin refine open_embedding_of_embedding_open ⟨⟨_⟩, h₂⟩ h₃, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s, change is_open _ ≤ is_open _, rw is_open_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma open_embedding_id : open_embedding (@id α) := ⟨embedding_id, by convert is_open_univ; apply range_id⟩ lemma open_embedding.comp {g : β → γ} {f : α → β} (hg : open_embedding g) (hf : open_embedding f) : open_embedding (g ∘ f) := ⟨hg.1.comp hf.1, show is_open (range (g ∘ f)), by rw [range_comp, ←hg.open_iff_image_open]; exact hf.2⟩ end open_embedding section closed_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- A closed embedding is an embedding with closed image. -/ structure closed_embedding (f : α → β) extends embedding f : Prop := (closed_range : is_closed $ range f) variables {f : α → β} lemma closed_embedding.continuous (hf : closed_embedding f) : continuous f := hf.to_embedding.continuous lemma closed_embedding.closed_iff_image_closed (hf : closed_embedding f) {s : set α} : is_closed s ↔ is_closed (f '' s) := ⟨embedding_is_closed hf.to_embedding hf.closed_range, λ h, begin convert ←continuous_iff_is_closed.mp hf.continuous _ h, apply preimage_image_eq _ hf.inj end⟩ lemma closed_embedding.is_closed_map (hf : closed_embedding f) : is_closed_map f := λ s, hf.closed_iff_image_closed.mp lemma closed_embedding.closed_iff_preimage_closed (hf : closed_embedding f) {s : set β} (hs : s ⊆ range f) : is_closed s ↔ is_closed (f ⁻¹' s) := begin convert ←hf.closed_iff_image_closed.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma closed_embedding_of_embedding_closed (h₁ : embedding f) (h₂ : is_closed_map f) : closed_embedding f := ⟨h₁, by convert h₂ univ is_closed_univ; simp⟩ lemma closed_embedding_of_continuous_injective_closed (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_closed_map f) : closed_embedding f := begin refine closed_embedding_of_embedding_closed ⟨⟨_⟩, h₂⟩ h₃, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s', change is_open _ ≤ is_open _, rw [←is_closed_compl_iff, ←is_closed_compl_iff], generalize : s'ᶜ = s, rw is_closed_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma closed_embedding_id : closed_embedding (@id α) := ⟨embedding_id, by convert is_closed_univ; apply range_id⟩ lemma closed_embedding.comp {g : β → γ} {f : α → β} (hg : closed_embedding g) (hf : closed_embedding f) : closed_embedding (g ∘ f) := ⟨hg.to_embedding.comp hf.to_embedding, show is_closed (range (g ∘ f)), by rw [range_comp, ←hg.closed_iff_image_closed]; exact hf.closed_range⟩ end closed_embedding
4b45ef0ee15c3ed809977231a09fe3dacb29756d
a339bc2ac96174381fb610f4b2e1ba42df2be819
/hott/homotopy/chain_complex.hlean
56a653e5cf7ceb2d5785065f8d22db02420e7fe4
[ "Apache-2.0" ]
permissive
kalfsvag/lean2
25b2dccc07a98e5aa20f9a11229831f9d3edf2e7
4d4a0c7c53a9922c5f630f6f8ebdccf7ddef2cc7
refs/heads/master
1,610,513,122,164
1,483,135,198,000
1,483,135,198,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,293
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Chain complexes. We define chain complexes in a general way as a sequence X of types indexes over an arbitrary type N with a successor S. There are maps X (S n) → X n for n : N. We can vary N to have chain complexes indexed by ℕ, ℤ, a finite type or something else, and for both ℕ and ℤ we can choose the maps to go up or down. We also use the indexing ℕ × 3 for the LES of homotopy groups, because then it computes better (see [LES_of_homotopy_groups]). We have two separate notions of chain complexes: - type_chain_complex: sequence of types, where exactness is formulated using pure existence. - chain_complex: sequence of sets, where exactness is formulated using mere existence. -/ import types.int algebra.group_theory types.fin types.unit open eq pointed int unit is_equiv equiv is_trunc trunc function algebra group sigma.ops sum prod nat bool fin structure succ_str : Type := (carrier : Type) (succ : carrier → carrier) attribute succ_str.carrier [coercion] definition succ_str.S {X : succ_str} : X → X := succ_str.succ X open succ_str definition snat [reducible] [constructor] : succ_str := succ_str.mk ℕ nat.succ definition snat' [reducible] [constructor] : succ_str := succ_str.mk ℕ nat.pred definition sint [reducible] [constructor] : succ_str := succ_str.mk ℤ int.succ definition sint' [reducible] [constructor] : succ_str := succ_str.mk ℤ int.pred notation `+ℕ` := snat notation `-ℕ` := snat' notation `+ℤ` := sint notation `-ℤ` := sint' definition stratified_type [reducible] (N : succ_str) (n : ℕ) : Type₀ := N × fin (succ n) definition stratified_succ {N : succ_str} {n : ℕ} (x : stratified_type N n) : stratified_type N n := (if val (pr2 x) = n then S (pr1 x) else pr1 x, cyclic_succ (pr2 x)) definition stratified [reducible] [constructor] (N : succ_str) (n : ℕ) : succ_str := succ_str.mk (stratified_type N n) stratified_succ notation `+3ℕ` := stratified +ℕ 2 notation `-3ℕ` := stratified -ℕ 2 notation `+3ℤ` := stratified +ℤ 2 notation `-3ℤ` := stratified -ℤ 2 notation `+6ℕ` := stratified +ℕ 5 notation `-6ℕ` := stratified -ℕ 5 notation `+6ℤ` := stratified +ℤ 5 notation `-6ℤ` := stratified -ℤ 5 namespace succ_str protected definition add [reducible] {N : succ_str} (n : N) (k : ℕ) : N := iterate S k n infix ` +' `:65 := succ_str.add definition add_succ {N : succ_str} (n : N) (k : ℕ) : n +' (k + 1) = (S n) +' k := by induction k with k p; reflexivity; exact ap S p end succ_str namespace chain_complex export [notation] succ_str /- We define "type chain complexes" which are chain complexes without the "set"-requirement. Exactness is formulated without propositional truncation. -/ structure type_chain_complex (N : succ_str) : Type := (car : N → Type*) (fn : Π(n : N), car (S n) →* car n) (is_chain_complex : Π(n : N) (x : car (S (S n))), fn n (fn (S n) x) = pt) section variables {N : succ_str} (X : type_chain_complex N) (n : N) definition tcc_to_car [unfold 2] [coercion] := @type_chain_complex.car definition tcc_to_fn [unfold 2] : X (S n) →* X n := type_chain_complex.fn X n definition tcc_is_chain_complex [unfold 2] : Π(x : X (S (S n))), tcc_to_fn X n (tcc_to_fn X (S n) x) = pt := type_chain_complex.is_chain_complex X n -- important: these notions are shifted by one! (this is to avoid transports) definition is_exact_at_t [reducible] /- X n -/ : Type := Π(x : X (S n)), tcc_to_fn X n x = pt → fiber (tcc_to_fn X (S n)) x definition is_exact_t [reducible] /- X -/ : Type := Π(n : N), is_exact_at_t X n -- A chain complex on +ℕ can be trivially extended to a chain complex on +ℤ definition type_chain_complex_from_left (X : type_chain_complex +ℕ) : type_chain_complex +ℤ := type_chain_complex.mk (int.rec X (λn, punit)) begin intro n, fconstructor, { induction n with n n, { exact tcc_to_fn X n}, { esimp, intro x, exact star}}, { induction n with n n, { apply respect_pt}, { reflexivity}} end begin intro n, induction n with n n, { exact tcc_is_chain_complex X n}, { esimp, intro x, reflexivity} end definition is_exact_t_from_left {X : type_chain_complex +ℕ} {n : ℕ} (H : is_exact_at_t X n) : is_exact_at_t (type_chain_complex_from_left X) (of_nat n) := H /- Given a natural isomorphism between a chain complex and any other sequence, we can give the other sequence the structure of a chain complex, which is exact at the positions where the original sequence is. -/ definition transfer_type_chain_complex [constructor] /- X -/ {Y : N → Type*} (g : Π{n : N}, Y (S n) →* Y n) (e : Π{n}, X n ≃* Y n) (p : Π{n} (x : X (S n)), e (tcc_to_fn X n x) = g (e x)) : type_chain_complex N := type_chain_complex.mk Y @g abstract begin intro n, apply equiv_rect (equiv_of_pequiv e), intro x, refine ap g (p x)⁻¹ ⬝ _, refine (p _)⁻¹ ⬝ _, refine ap e (tcc_is_chain_complex X n _) ⬝ _, apply respect_pt end end theorem is_exact_at_t_transfer {X : type_chain_complex N} {Y : N → Type*} {g : Π{n : N}, Y (S n) →* Y n} (e : Π{n}, X n ≃* Y n) (p : Π{n} (x : X (S n)), e (tcc_to_fn X n x) = g (e x)) {n : N} (H : is_exact_at_t X n) : is_exact_at_t (transfer_type_chain_complex X @g @e @p) n := begin intro y q, esimp at *, have H2 : tcc_to_fn X n (e⁻¹ᵉ* y) = pt, begin refine (inv_commute (λn, equiv_of_pequiv e) _ _ @p _)⁻¹ᵖ ⬝ _, refine ap _ q ⬝ _, exact respect_pt e⁻¹ᵉ* end, cases (H _ H2) with x r, refine fiber.mk (e x) _, refine (p x)⁻¹ ⬝ _, refine ap e r ⬝ _, apply right_inv end /- We want a theorem which states that if we have a chain complex, but with some where the maps are composed by an equivalences, we want to remove this equivalence. The following two theorems give sufficient conditions for when this is allowed. We use this to transform the LES of homotopy groups where on the odd levels we have maps -πₙ(...) into the LES of homotopy groups where we remove the minus signs (which represents composition with path inversion). -/ definition type_chain_complex_cancel_aut [constructor] /- X -/ (g : Π{n : N}, X (S n) →* X n) (e : Π{n}, X n ≃* X n) (r : Π{n}, X n →* X n) (p : Π{n : N} (x : X (S n)), g (e x) = tcc_to_fn X n x) (pr : Π{n : N} (x : X (S n)), g x = r (g (e x))) : type_chain_complex N := type_chain_complex.mk X @g abstract begin have p' : Π{n : N} (x : X (S n)), g x = tcc_to_fn X n (e⁻¹ x), from λn, homotopy_inv_of_homotopy_pre e _ _ p, intro n x, refine ap g !p' ⬝ !pr ⬝ _, refine ap r !p ⬝ _, refine ap r (tcc_is_chain_complex X n _) ⬝ _, apply respect_pt end end theorem is_exact_at_t_cancel_aut {X : type_chain_complex N} {g : Π{n : N}, X (S n) →* X n} {e : Π{n}, X n ≃* X n} {r : Π{n}, X n →* X n} (l : Π{n}, X n →* X n) (p : Π{n : N} (x : X (S n)), g (e x) = tcc_to_fn X n x) (pr : Π{n : N} (x : X (S n)), g x = r (g (e x))) (pl : Π{n : N} (x : X (S n)), g (l x) = e (g x)) (H : is_exact_at_t X n) : is_exact_at_t (type_chain_complex_cancel_aut X @g @e @r @p @pr) n := begin intro y q, esimp at *, have H2 : tcc_to_fn X n (e⁻¹ y) = pt, from (homotopy_inv_of_homotopy_pre e _ _ p _)⁻¹ ⬝ q, cases (H _ H2) with x s, refine fiber.mk (l (e x)) _, refine !pl ⬝ _, refine ap e (!p ⬝ s) ⬝ _, apply right_inv end /- A more general transfer theorem. Here the base type can also change by an equivalence. -/ definition transfer_type_chain_complex2 [constructor] {M : succ_str} {Y : M → Type*} (f : M ≃ N) (c : Π(m : M), S (f m) = f (S m)) (g : Π{m : M}, Y (S m) →* Y m) (e : Π{m}, X (f m) ≃* Y m) (p : Π{m} (x : X (S (f m))), e (tcc_to_fn X (f m) x) = g (e (cast (ap (λx, X x) (c m)) x))) : type_chain_complex M := type_chain_complex.mk Y @g begin intro m, apply equiv_rect (equiv_of_pequiv e), apply equiv_rect (equiv_of_eq (ap (λx, X x) (c (S m)))), esimp, apply equiv_rect (equiv_of_eq (ap (λx, X (S x)) (c m))), esimp, intro x, refine ap g (p _)⁻¹ ⬝ _, refine ap g (ap e (fn_cast_eq_cast_fn (c m) (tcc_to_fn X) x)) ⬝ _, refine (p _)⁻¹ ⬝ _, refine ap e (tcc_is_chain_complex X (f m) _) ⬝ _, apply respect_pt end definition is_exact_at_t_transfer2 {X : type_chain_complex N} {M : succ_str} {Y : M → Type*} (f : M ≃ N) (c : Π(m : M), S (f m) = f (S m)) (g : Π{m : M}, Y (S m) →* Y m) (e : Π{m}, X (f m) ≃* Y m) (p : Π{m} (x : X (S (f m))), e (tcc_to_fn X (f m) x) = g (e (cast (ap (λx, X x) (c m)) x))) {m : M} (H : is_exact_at_t X (f m)) : is_exact_at_t (transfer_type_chain_complex2 X f c @g @e @p) m := begin intro y q, esimp at *, have H2 : tcc_to_fn X (f m) ((equiv_of_eq (ap (λx, X x) (c m)))⁻¹ᵉ (e⁻¹ y)) = pt, begin refine _ ⬝ ap e⁻¹ᵉ* q ⬝ (respect_pt (e⁻¹ᵉ*)), apply eq_inv_of_eq, clear q, revert y, apply inv_homotopy_of_homotopy_pre e, apply inv_homotopy_of_homotopy_pre, apply p end, induction (H _ H2) with x r, refine fiber.mk (e (cast (ap (λx, X x) (c (S m))) (cast (ap (λx, X (S x)) (c m)) x))) _, refine (p _)⁻¹ ⬝ _, refine ap e (fn_cast_eq_cast_fn (c m) (tcc_to_fn X) x) ⬝ _, refine ap (λx, e (cast _ x)) r ⬝ _, esimp [equiv.symm], rewrite [-ap_inv], refine ap e !cast_cast_inv ⬝ _, apply right_inv end end /- actual (set) chain complexes -/ structure chain_complex (N : succ_str) : Type := (car : N → Set*) (fn : Π(n : N), car (S n) →* car n) (is_chain_complex : Π(n : N) (x : car (S (S n))), fn n (fn (S n) x) = pt) section variables {N : succ_str} (X : chain_complex N) (n : N) definition cc_to_car [unfold 2] [coercion] := @chain_complex.car definition cc_to_fn [unfold 2] : X (S n) →* X n := @chain_complex.fn N X n definition cc_is_chain_complex [unfold 2] : Π(x : X (S (S n))), cc_to_fn X n (cc_to_fn X (S n) x) = pt := @chain_complex.is_chain_complex N X n -- important: these notions are shifted by one! (this is to avoid transports) definition is_exact_at [reducible] /- X n -/ : Type := Π(x : X (S n)), cc_to_fn X n x = pt → image (cc_to_fn X (S n)) x definition is_exact [reducible] /- X -/ : Type := Π(n : N), is_exact_at X n definition chain_complex_from_left (X : chain_complex +ℕ) : chain_complex +ℤ := chain_complex.mk (int.rec X (λn, punit)) begin intro n, fconstructor, { induction n with n n, { exact cc_to_fn X n}, { esimp, intro x, exact star}}, { induction n with n n, { apply respect_pt}, { reflexivity}} end begin intro n, induction n with n n, { exact cc_is_chain_complex X n}, { esimp, intro x, reflexivity} end definition is_exact_from_left {X : chain_complex +ℕ} {n : ℕ} (H : is_exact_at X n) : is_exact_at (chain_complex_from_left X) (of_nat n) := H definition transfer_chain_complex [constructor] {Y : N → Set*} (g : Π{n : N}, Y (S n) →* Y n) (e : Π{n}, X n ≃* Y n) (p : Π{n} (x : X (S n)), e (cc_to_fn X n x) = g (e x)) : chain_complex N := chain_complex.mk Y @g abstract begin intro n, apply equiv_rect (equiv_of_pequiv e), intro x, refine ap g (p x)⁻¹ ⬝ _, refine (p _)⁻¹ ⬝ _, refine ap e (cc_is_chain_complex X n _) ⬝ _, apply respect_pt end end theorem is_exact_at_transfer {X : chain_complex N} {Y : N → Set*} (g : Π{n : N}, Y (S n) →* Y n) (e : Π{n}, X n ≃* Y n) (p : Π{n} (x : X (S n)), e (cc_to_fn X n x) = g (e x)) {n : N} (H : is_exact_at X n) : is_exact_at (transfer_chain_complex X @g @e @p) n := begin intro y q, esimp at *, have H2 : cc_to_fn X n (e⁻¹ᵉ* y) = pt, begin refine (inv_commute (λn, equiv_of_pequiv e) _ _ @p _)⁻¹ᵖ ⬝ _, refine ap _ q ⬝ _, exact respect_pt e⁻¹ᵉ* end, induction (H _ H2) with x r, refine image.mk (e x) _, refine (p x)⁻¹ ⬝ _, refine ap e r ⬝ _, apply right_inv end /- A type chain complex can be set-truncated to a chain complex -/ definition trunc_chain_complex [constructor] (X : type_chain_complex N) : chain_complex N := chain_complex.mk (λn, ptrunc 0 (X n)) (λn, ptrunc_functor 0 (tcc_to_fn X n)) begin intro n x, esimp at *, refine @trunc.rec _ _ _ (λH, !is_trunc_eq) _ x, clear x, intro x, esimp, exact ap tr (tcc_is_chain_complex X n x) end definition is_exact_at_trunc (X : type_chain_complex N) {n : N} (H : is_exact_at_t X n) : is_exact_at (trunc_chain_complex X) n := begin intro x p, esimp at *, induction x with x, esimp at *, note q := !tr_eq_tr_equiv p, induction q with q, induction H x q with y r, refine image.mk (tr y) _, esimp, exact ap tr r end definition transfer_chain_complex2 [constructor] {M : succ_str} {Y : M → Set*} (f : N ≃ M) (c : Π(n : N), f (S n) = S (f n)) (g : Π{m : M}, Y (S m) →* Y m) (e : Π{n}, X n ≃* Y (f n)) (p : Π{n} (x : X (S n)), e (cc_to_fn X n x) = g (c n ▸ e x)) : chain_complex M := chain_complex.mk Y @g begin refine equiv_rect f _ _, intro n, have H : Π (x : Y (f (S (S n)))), g (c n ▸ g (c (S n) ▸ x)) = pt, begin apply equiv_rect (equiv_of_pequiv e), intro x, refine ap (λx, g (c n ▸ x)) (@p (S n) x)⁻¹ᵖ ⬝ _, refine (p _)⁻¹ ⬝ _, refine ap e (cc_is_chain_complex X n _) ⬝ _, apply respect_pt end, refine pi.pi_functor _ _ H, { intro x, exact (c (S n))⁻¹ ▸ (c n)⁻¹ ▸ x}, -- with implicit arguments, this is: -- transport (λx, Y x) (c (S n))⁻¹ (transport (λx, Y (S x)) (c n)⁻¹ x) { intro x, intro p, refine _ ⬝ p, rewrite [tr_inv_tr, fn_tr_eq_tr_fn (c n)⁻¹ @g, tr_inv_tr]} end definition is_exact_at_transfer2 {X : chain_complex N} {M : succ_str} {Y : M → Set*} (f : N ≃ M) (c : Π(n : N), f (S n) = S (f n)) (g : Π{m : M}, Y (S m) →* Y m) (e : Π{n}, X n ≃* Y (f n)) (p : Π{n} (x : X (S n)), e (cc_to_fn X n x) = g (c n ▸ e x)) {n : N} (H : is_exact_at X n) : is_exact_at (transfer_chain_complex2 X f c @g @e @p) (f n) := begin intro y q, esimp at *, have H2 : cc_to_fn X n (e⁻¹ᵉ* ((c n)⁻¹ ▸ y)) = pt, begin refine (inv_commute (λn, equiv_of_pequiv e) _ _ @p _)⁻¹ᵖ ⬝ _, rewrite [tr_inv_tr, q], exact respect_pt e⁻¹ᵉ* end, induction (H _ H2) with x r, refine image.mk (c n ▸ c (S n) ▸ e x) _, rewrite [fn_tr_eq_tr_fn (c n) @g], refine ap (λx, c n ▸ x) (p x)⁻¹ ⬝ _, refine ap (λx, c n ▸ e x) r ⬝ _, refine ap (λx, c n ▸ x) !right_inv ⬝ _, apply tr_inv_tr, end /- This is a start of a development of chain complexes consisting only on groups. This might be useful to have in stable algebraic topology, but in the unstable case it's less useful, since the smallest terms usually don't have a group structure. We don't use it yet, so it's commented out for now -/ -- structure group_chain_complex : Type := -- (car : N → Group) -- (fn : Π(n : N), car (S n) →g car n) -- (is_chain_complex : Π{n : N} (x : car ((S n) + 1)), fn n (fn (S n) x) = 1) -- structure group_chain_complex : Type := -- chain complex on the naturals with maps going down -- (car : N → Group) -- (fn : Π(n : N), car (S n) →g car n) -- (is_chain_complex : Π{n : N} (x : car ((S n) + 1)), fn n (fn (S n) x) = 1) -- structure right_group_chain_complex : Type := -- chain complex on the naturals with maps going up -- (car : N → Group) -- (fn : Π(n : N), car n →g car (S n)) -- (is_chain_complex : Π{n : N} (x : car n), fn (S n) (fn n x) = 1) -- definition gcc_to_car [unfold 1] [coercion] := @group_chain_complex.car -- definition gcc_to_fn [unfold 1] := @group_chain_complex.fn -- definition gcc_is_chain_complex [unfold 1] := @group_chain_complex.is_chain_complex -- definition lgcc_to_car [unfold 1] [coercion] := @left_group_chain_complex.car -- definition lgcc_to_fn [unfold 1] := @left_group_chain_complex.fn -- definition lgcc_is_chain_complex [unfold 1] := @left_group_chain_complex.is_chain_complex -- definition rgcc_to_car [unfold 1] [coercion] := @right_group_chain_complex.car -- definition rgcc_to_fn [unfold 1] := @right_group_chain_complex.fn -- definition rgcc_is_chain_complex [unfold 1] := @right_group_chain_complex.is_chain_complex -- -- important: these notions are shifted by one! (this is to avoid transports) -- definition is_exact_at_g [reducible] (X : group_chain_complex) (n : N) : Type := -- Π(x : X (S n)), gcc_to_fn X n x = 1 → image (gcc_to_fn X (S n)) x -- definition is_exact_at_lg [reducible] (X : left_group_chain_complex) (n : N) : Type := -- Π(x : X (S n)), lgcc_to_fn X n x = 1 → image (lgcc_to_fn X (S n)) x -- definition is_exact_at_rg [reducible] (X : right_group_chain_complex) (n : N) : Type := -- Π(x : X (S n)), rgcc_to_fn X (S n) x = 1 → image (rgcc_to_fn X n) x -- definition is_exact_g [reducible] (X : group_chain_complex) : Type := -- Π(n : N), is_exact_at_g X n -- definition is_exact_lg [reducible] (X : left_group_chain_complex) : Type := -- Π(n : N), is_exact_at_lg X n -- definition is_exact_rg [reducible] (X : right_group_chain_complex) : Type := -- Π(n : N), is_exact_at_rg X n -- definition group_chain_complex_from_left (X : left_group_chain_complex) : group_chain_complex := -- group_chain_complex.mk (int.rec X (λn, G0)) -- begin -- intro n, fconstructor, -- { induction n with n n, -- { exact @lgcc_to_fn X n}, -- { esimp, intro x, exact star}}, -- { induction n with n n, -- { apply respect_mul}, -- { intro g h, reflexivity}} -- end -- begin -- intro n, induction n with n n, -- { exact lgcc_is_chain_complex X}, -- { esimp, intro x, reflexivity} -- end -- definition is_exact_g_from_left {X : left_group_chain_complex} {n : N} (H : is_exact_at_lg X n) -- : is_exact_at_g (group_chain_complex_from_left X) n := -- H -- definition transfer_left_group_chain_complex [constructor] (X : left_group_chain_complex) -- {Y : N → Group} (g : Π{n : N}, Y (S n) →g Y n) (e : Π{n}, X n ≃* Y n) -- (p : Π{n} (x : X (S n)), e (lgcc_to_fn X n x) = g (e x)) : left_group_chain_complex := -- left_group_chain_complex.mk Y @g -- begin -- intro n, apply equiv_rect (pequiv_of_equiv e), intro x, -- refine ap g (p x)⁻¹ ⬝ _, -- refine (p _)⁻¹ ⬝ _, -- refine ap e (lgcc_is_chain_complex X _) ⬝ _, -- exact respect_pt -- end -- definition is_exact_at_t_transfer {X : left_group_chain_complex} {Y : N → Type*} -- {g : Π{n : N}, Y (S n) →* Y n} (e : Π{n}, X n ≃* Y n) -- (p : Π{n} (x : X (S n)), e (lgcc_to_fn X n x) = g (e x)) {n : N} -- (H : is_exact_at_lg X n) : is_exact_at_lg (transfer_left_group_chain_complex X @g @e @p) n := -- begin -- intro y q, esimp at *, -- have H2 : lgcc_to_fn X n (e⁻¹ᵉ* y) = pt, -- begin -- refine (inv_commute (λn, equiv_of_pequiv e) _ _ @p _)⁻¹ᵖ ⬝ _, -- refine ap _ q ⬝ _, -- exact respect_pt e⁻¹ᵉ* -- end, -- cases (H _ H2) with x r, -- refine image.mk (e x) _, -- refine (p x)⁻¹ ⬝ _, -- refine ap e r ⬝ _, -- apply right_inv -- end /- The following theorems state that in a chain complex, if certain types are contractible, and the chain complex is exact at the right spots, a map in the chain complex is an embedding/surjection/equivalence. For the first and third we also need to assume that the map is a group homomorphism (and hence that the two types around it are groups). -/ definition is_embedding_of_trivial (X : chain_complex N) {n : N} (H : is_exact_at X n) [HX : is_contr (X (S (S n)))] [pgroup (X n)] [pgroup (X (S n))] [is_homomorphism (cc_to_fn X n)] : is_embedding (cc_to_fn X n) := begin apply is_embedding_homomorphism, intro g p, induction H g p with x q, have r : pt = x, from !is_prop.elim, induction r, refine q⁻¹ ⬝ _, apply respect_pt end definition is_surjective_of_trivial (X : chain_complex N) {n : N} (H : is_exact_at X n) [HX : is_contr (X n)] : is_surjective (cc_to_fn X (S n)) := begin intro g, refine trunc.elim _ (H g !is_prop.elim), apply tr end definition is_equiv_of_trivial (X : chain_complex N) {n : N} (H1 : is_exact_at X n) (H2 : is_exact_at X (S n)) [HX1 : is_contr (X n)] [HX2 : is_contr (X (S (S (S n))))] [pgroup (X (S n))] [pgroup (X (S (S n)))] [is_homomorphism (cc_to_fn X (S n))] : is_equiv (cc_to_fn X (S n)) := begin apply is_equiv_of_is_surjective_of_is_embedding, { apply is_embedding_of_trivial X, apply H2}, { apply is_surjective_of_trivial X, apply H1}, end definition is_contr_of_is_embedding_of_is_surjective {N : succ_str} (X : chain_complex N) {n : N} (H : is_exact_at X (S n)) [is_embedding (cc_to_fn X n)] [H2 : is_surjective (cc_to_fn X (S (S (S n))))] : is_contr (X (S (S n))) := begin apply is_contr.mk pt, intro x, have p : cc_to_fn X n (cc_to_fn X (S n) x) = cc_to_fn X n pt, from !cc_is_chain_complex ⬝ !respect_pt⁻¹, have q : cc_to_fn X (S n) x = pt, from is_injective_of_is_embedding p, induction H x q with y r, induction H2 y with z s, exact (cc_is_chain_complex X _ z)⁻¹ ⬝ ap (cc_to_fn X _) s ⬝ r end end end chain_complex
71fd97b9a43296e2c1ca28a24c4c12fd8f853f38
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/group/commutator.lean
2627a9b8b79fa0ad7ee830aa5632b900daa51cfd
[ "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
748
lean
/- Copyright (c) 2022 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.group.defs import data.bracket /-! # The bracket on a group given by commutator. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/582 > Any changes to this file require a corresponding PR to mathlib4. -/ /-- The commutator of two elements `g₁` and `g₂`. -/ instance commutator_element {G : Type*} [group G] : has_bracket G G := ⟨λ g₁ g₂, g₁ * g₂ * g₁⁻¹ * g₂⁻¹⟩ lemma commutator_element_def {G : Type*} [group G] (g₁ g₂ : G) : ⁅g₁, g₂⁆ = g₁ * g₂ * g₁⁻¹ * g₂⁻¹ := rfl
a71cbe637203941c5413c5e51e11f7f8e38c773a
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/universal/identity.lean
64b85ce98adc457cc9862213b789df130e5f469e
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
2,348
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .substitution import .homomorphism namespace universal variables {τ : Type} {σ : Type*} (sig : signature τ σ) structure identity := (cod : τ) (dom : list τ) (eqn : equation sig dom cod) variable {sig} definition equation.to_identity {dom} {{cod}} : equation sig dom cod → identity sig := λ e, ⟨_, _, e⟩ definition term.to_identity {dom} {{cod}} : term sig dom cod → term sig dom cod → identity sig := λ x₁ x₂, ⟨_, _, ⟨x₁, x₂⟩⟩ namespace identity variables {sig} (ax : identity sig) abbreviation lhs : term sig ax.dom ax.cod := ax.eqn.lhs abbreviation rhs : term sig ax.dom ax.cod := ax.eqn.rhs abbreviation subst {dom : list τ} (sub : substitution sig ax.dom dom) : identity sig := { cod := ax.cod , dom := dom , eqn := ax.eqn.subst sub } theorem subst_lhs {dom : list τ} (sub : substitution sig ax.dom dom) : (ax.subst sub).lhs = ax.lhs.subst sub := rfl theorem subst_rhs {dom : list τ} (sub : substitution sig ax.dom dom) : (ax.subst sub).rhs = ax.rhs.subst sub := rfl end identity namespace algebra variables (alg : algebra sig) {alg₁ : algebra sig} {alg₂ : algebra sig} (h : homomorphism alg₁ alg₂) definition satisfies (ax : identity sig) : Prop := ∀ (val : Π (i : index ax.dom), alg.sort i.val), alg.eval ax.lhs val = alg.eval ax.rhs val theorem satisfies_of_injective_hom [homomorphism.injective h] (ax : identity sig) : alg₂.satisfies ax → alg₁.satisfies ax := begin intros H₂ val₁, apply homomorphism.injective.elim h, rw h.eval, rw h.eval, apply H₂, end theorem satisfies_of_surjective_hom [homomorphism.surjective h] (ax : identity sig) : alg₁.satisfies ax → alg₂.satisfies ax := begin intros H₁ val₂, have : nonempty (Π (i : index ax.dom), { x : alg₁.sort i.val // h.map i.val x = val₂ i}), begin apply index.choice, intro i, cases homomorphism.surjective.elim h i.val (val₂ i) with x hx, exact nonempty.intro ⟨x, hx⟩, end, cases this with pval₁, let val₁ := λ i, (pval₁ i).val, have : val₂ = (λ i, h.map _ (val₁ i)), from funext (λ i, eq.symm (pval₁ i).property), rw this, rw ← h.eval, rw ← h.eval, apply congr_arg, apply H₁, end end algebra end universal
9710fde558643e31a362781356519a1bee125844
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/multiset/antidiagonal.lean
1efc8e414afbd7bd757748507bec70bf9ecd9e86
[ "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,616
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.multiset.powerset /-! # The antidiagonal on a multiset. The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ namespace multiset open list variables {α β : Type*} /-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem antidiagonal_coe (l : list α) : @antidiagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem antidiagonal_coe' (l : list α) : @antidiagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' /-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s` if and only if `t₁ + t₂ = s`. -/ @[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} : x ∈ antidiagonal s ↔ x.1 + x.2 = s := quotient.induction_on s $ λ l, begin simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], cases x with x₁ x₂, dsimp only, exact ⟨x₁, le_add_right _ _, by rw add_tsub_cancel_left x₁ x₂⟩ end @[simp] theorem antidiagonal_map_fst (s : multiset α) : (antidiagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_map_snd (s : multiset α) : (antidiagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_zero : @antidiagonal α 0 = {(0, 0)} := rfl @[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a ::ₘ s) = map (prod.map id (cons a)) (antidiagonal s) + map (prod.map (cons a) id) (antidiagonal s) := quotient.induction_on s $ λ l, begin simp only [revzip, reverse_append, quot_mk_to_coe, coe_eq_coe, powerset_aux'_cons, cons_coe, coe_map, antidiagonal_coe', coe_add], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end theorem antidiagonal_eq_map_powerset [decidable_eq α] (s : multiset α) : s.antidiagonal = s.powerset.map (λ t, (s - t, t)) := begin induction s using multiset.induction_on with a s hs, { simp only [antidiagonal_zero, powerset_zero, zero_tsub, map_singleton] }, { simp_rw [antidiagonal_cons, powerset_cons, map_add, hs, map_map, function.comp, prod.map_mk, id.def, sub_cons, erase_cons_head], rw add_comm, congr' 1, refine multiset.map_congr rfl (λ x hx, _), rw cons_sub_of_le _ (mem_powerset.mp hx) } end @[simp] theorem card_antidiagonal (s : multiset α) : card (antidiagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← antidiagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, have := @sum_map_mul_left α β _, simp [ih, add_mul, mul_comm, mul_left_comm (f a), mul_left_comm (g a), mul_assoc, sum_map_mul_left.symm], cc }, end end multiset
0c01539bfc22dc64349d24f2fbb2550bdf499001
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/monoidal/rigid/basic.lean
a8c467d0f03620b6a8047e66720ca7ac012f7147
[ "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
28,129
lean
/- Copyright (c) 2021 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer -/ import category_theory.monoidal.coherence_lemmas import category_theory.closed.monoidal import tactic.apply_fun /-! # Rigid (autonomous) monoidal categories This file defines rigid (autonomous) monoidal categories and the necessary theory about exact pairings and duals. ## Main definitions * `exact_pairing` of two objects of a monoidal category * Type classes `has_left_dual` and `has_right_dual` that capture that a pairing exists * The `right_adjoint_mate f` as a morphism `fᘁ : Yᘁ ⟶ Xᘁ` for a morphism `f : X ⟶ Y` * The classes of `right_rigid_category`, `left_rigid_category` and `rigid_category` ## Main statements * `comp_right_adjoint_mate`: The adjoint mates of the composition is the composition of adjoint mates. ## Notations * `η_` and `ε_` denote the coevaluation and evaluation morphism of an exact pairing. * `Xᘁ` and `ᘁX` denote the right and left dual of an object, as well as the adjoint mate of a morphism. ## Future work * Show that `X ⊗ Y` and `Yᘁ ⊗ Xᘁ` form an exact pairing. * Show that the left adjoint mate of the right adjoint mate of a morphism is the morphism itself. * Simplify constructions in the case where a symmetry or braiding is present. * Show that `ᘁ` gives an equivalence of categories `C ≅ (Cᵒᵖ)ᴹᵒᵖ`. * Define pivotal categories (rigid categories equipped with a natural isomorphism `ᘁᘁ ≅ 𝟙 C`). ## Notes Although we construct the adjunction `tensor_left Y ⊣ tensor_left X` from `exact_pairing X Y`, this is not a bijective correspondence. I think the correct statement is that `tensor_left Y` and `tensor_left X` are module endofunctors of `C` as a right `C` module category, and `exact_pairing X Y` is in bijection with adjunctions compatible with this right `C` action. ## References * <https://ncatlab.org/nlab/show/rigid+monoidal+category> ## Tags rigid category, monoidal category -/ open category_theory universes v v₁ v₂ v₃ u u₁ u₂ u₃ noncomputable theory namespace category_theory variables {C : Type u₁} [category.{v₁} C] [monoidal_category C] /-- An exact pairing is a pair of objects `X Y : C` which admit a coevaluation and evaluation morphism which fulfill two triangle equalities. -/ class exact_pairing (X Y : C) := (coevaluation [] : 𝟙_ C ⟶ X ⊗ Y) (evaluation [] : Y ⊗ X ⟶ 𝟙_ C) (coevaluation_evaluation' [] : (𝟙 Y ⊗ coevaluation) ≫ (α_ _ _ _).inv ≫ (evaluation ⊗ 𝟙 Y) = (ρ_ Y).hom ≫ (λ_ Y).inv . obviously) (evaluation_coevaluation' [] : (coevaluation ⊗ 𝟙 X) ≫ (α_ _ _ _).hom ≫ (𝟙 X ⊗ evaluation) = (λ_ X).hom ≫ (ρ_ X).inv . obviously) open exact_pairing notation `η_` := exact_pairing.coevaluation notation `ε_` := exact_pairing.evaluation restate_axiom coevaluation_evaluation' attribute [simp, reassoc] exact_pairing.coevaluation_evaluation restate_axiom evaluation_coevaluation' attribute [simp, reassoc] exact_pairing.evaluation_coevaluation instance exact_pairing_unit : exact_pairing (𝟙_ C) (𝟙_ C) := { coevaluation := (ρ_ _).inv, evaluation := (ρ_ _).hom, coevaluation_evaluation' := by coherence, evaluation_coevaluation' := by coherence, } /-- A class of objects which have a right dual. -/ class has_right_dual (X : C) := (right_dual : C) [exact : exact_pairing X right_dual] /-- A class of objects with have a left dual. -/ class has_left_dual (Y : C) := (left_dual : C) [exact : exact_pairing left_dual Y] attribute [instance] has_right_dual.exact attribute [instance] has_left_dual.exact open exact_pairing has_right_dual has_left_dual monoidal_category prefix (name := left_dual) `ᘁ`:1025 := left_dual postfix (name := right_dual) `ᘁ`:1025 := right_dual instance has_right_dual_unit : has_right_dual (𝟙_ C) := { right_dual := 𝟙_ C } instance has_left_dual_unit : has_left_dual (𝟙_ C) := { left_dual := 𝟙_ C } instance has_right_dual_left_dual {X : C} [has_left_dual X] : has_right_dual (ᘁX) := { right_dual := X } instance has_left_dual_right_dual {X : C} [has_right_dual X] : has_left_dual Xᘁ := { left_dual := X } @[simp] lemma left_dual_right_dual {X : C} [has_right_dual X] : ᘁ(Xᘁ) = X := rfl @[simp] lemma right_dual_left_dual {X : C} [has_left_dual X] : (ᘁX)ᘁ = X := rfl /-- The right adjoint mate `fᘁ : Xᘁ ⟶ Yᘁ` of a morphism `f : X ⟶ Y`. -/ def right_adjoint_mate {X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) : Yᘁ ⟶ Xᘁ := (ρ_ _).inv ≫ (𝟙 _ ⊗ η_ _ _) ≫ (𝟙 _ ⊗ (f ⊗ 𝟙 _)) ≫ (α_ _ _ _).inv ≫ ((ε_ _ _) ⊗ 𝟙 _) ≫ (λ_ _).hom /-- The left adjoint mate `ᘁf : ᘁY ⟶ ᘁX` of a morphism `f : X ⟶ Y`. -/ def left_adjoint_mate {X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) : ᘁY ⟶ ᘁX := (λ_ _).inv ≫ (η_ (ᘁX) X ⊗ 𝟙 _) ≫ ((𝟙 _ ⊗ f) ⊗ 𝟙 _) ≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ ε_ _ _) ≫ (ρ_ _).hom notation (name := right_adjoint_mate) f `ᘁ` := right_adjoint_mate f notation (name := left_adjoint_mate) `ᘁ` f := left_adjoint_mate f @[simp] lemma right_adjoint_mate_id {X : C} [has_right_dual X] : (𝟙 X)ᘁ = 𝟙 (Xᘁ) := by simp only [right_adjoint_mate, monoidal_category.tensor_id, category.id_comp, coevaluation_evaluation_assoc, category.comp_id, iso.inv_hom_id] @[simp] lemma left_adjoint_mate_id {X : C} [has_left_dual X] : ᘁ(𝟙 X) = 𝟙 (ᘁX) := by simp only [left_adjoint_mate, monoidal_category.tensor_id, category.id_comp, evaluation_coevaluation_assoc, category.comp_id, iso.inv_hom_id] lemma right_adjoint_mate_comp {X Y Z : C} [has_right_dual X] [has_right_dual Y] {f : X ⟶ Y} {g : Xᘁ ⟶ Z} : fᘁ ≫ g = (ρ_ Yᘁ).inv ≫ (𝟙 _ ⊗ η_ X Xᘁ) ≫ (𝟙 _ ⊗ f ⊗ g) ≫ (α_ Yᘁ Y Z).inv ≫ (ε_ Y Yᘁ ⊗ 𝟙 _) ≫ (λ_ Z).hom := begin dunfold right_adjoint_mate, rw [category.assoc, category.assoc, associator_inv_naturality_assoc, associator_inv_naturality_assoc, ←tensor_id_comp_id_tensor g, category.assoc, category.assoc, category.assoc, category.assoc, id_tensor_comp_tensor_id_assoc, ←left_unitor_naturality, tensor_id_comp_id_tensor_assoc], end lemma left_adjoint_mate_comp {X Y Z : C} [has_left_dual X] [has_left_dual Y] {f : X ⟶ Y} {g : ᘁX ⟶ Z} : ᘁf ≫ g = (λ_ _).inv ≫ (η_ (ᘁX) X ⊗ 𝟙 _) ≫ ((g ⊗ f) ⊗ 𝟙 _) ≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ ε_ _ _) ≫ (ρ_ _).hom := begin dunfold left_adjoint_mate, rw [category.assoc, category.assoc, associator_naturality_assoc, associator_naturality_assoc, ←id_tensor_comp_tensor_id _ g, category.assoc, category.assoc, category.assoc, category.assoc, tensor_id_comp_id_tensor_assoc, ←right_unitor_naturality, id_tensor_comp_tensor_id_assoc], end /-- The composition of right adjoint mates is the adjoint mate of the composition. -/ @[reassoc] lemma comp_right_adjoint_mate {X Y Z : C} [has_right_dual X] [has_right_dual Y] [has_right_dual Z] {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g)ᘁ = gᘁ ≫ fᘁ := begin rw right_adjoint_mate_comp, simp only [right_adjoint_mate, comp_tensor_id, iso.cancel_iso_inv_left, id_tensor_comp, category.assoc], symmetry, iterate 5 { transitivity, rw [←category.id_comp g, tensor_comp] }, rw ←category.assoc, symmetry, iterate 2 { transitivity, rw ←category.assoc }, apply eq_whisker, repeat { rw ←id_tensor_comp }, congr' 1, rw [←id_tensor_comp_tensor_id (λ_ Xᘁ).hom g, id_tensor_right_unitor_inv, category.assoc, category.assoc, right_unitor_inv_naturality_assoc, ←associator_naturality_assoc, tensor_id, tensor_id_comp_id_tensor_assoc, ←associator_naturality_assoc], slice_rhs 2 3 { rw [←tensor_comp, tensor_id, category.comp_id, ←category.id_comp (η_ Y Yᘁ), tensor_comp] }, rw [←id_tensor_comp_tensor_id _ (η_ Y Yᘁ), ←tensor_id], repeat { rw category.assoc }, rw [pentagon_hom_inv_assoc, ←associator_naturality_assoc, associator_inv_naturality_assoc], slice_rhs 5 7 { rw [←comp_tensor_id, ←comp_tensor_id, evaluation_coevaluation, comp_tensor_id] }, rw associator_inv_naturality_assoc, slice_rhs 4 5 { rw [←tensor_comp, left_unitor_naturality, tensor_comp] }, repeat { rw category.assoc }, rw [triangle_assoc_comp_right_inv_assoc, ←left_unitor_tensor_assoc, left_unitor_naturality_assoc, unitors_equal, ←category.assoc, ←category.assoc], simp end /-- The composition of left adjoint mates is the adjoint mate of the composition. -/ @[reassoc] lemma comp_left_adjoint_mate {X Y Z : C} [has_left_dual X] [has_left_dual Y] [has_left_dual Z] {f : X ⟶ Y} {g : Y ⟶ Z} : ᘁ(f ≫ g) = ᘁg ≫ ᘁf := begin rw left_adjoint_mate_comp, simp only [left_adjoint_mate, id_tensor_comp, iso.cancel_iso_inv_left, comp_tensor_id, category.assoc], symmetry, iterate 5 { transitivity, rw [←category.id_comp g, tensor_comp] }, rw ← category.assoc, symmetry, iterate 2 { transitivity, rw ←category.assoc }, apply eq_whisker, repeat { rw ←comp_tensor_id }, congr' 1, rw [←tensor_id_comp_id_tensor g (ρ_ (ᘁX)).hom, left_unitor_inv_tensor_id, category.assoc, category.assoc, left_unitor_inv_naturality_assoc, ←associator_inv_naturality_assoc, tensor_id, id_tensor_comp_tensor_id_assoc, ←associator_inv_naturality_assoc], slice_rhs 2 3 { rw [←tensor_comp, tensor_id, category.comp_id, ←category.id_comp (η_ (ᘁY) Y), tensor_comp] }, rw [←tensor_id_comp_id_tensor (η_ (ᘁY) Y), ←tensor_id], repeat { rw category.assoc }, rw [pentagon_inv_hom_assoc, ←associator_inv_naturality_assoc, associator_naturality_assoc], slice_rhs 5 7 { rw [←id_tensor_comp, ←id_tensor_comp, coevaluation_evaluation, id_tensor_comp ]}, rw associator_naturality_assoc, slice_rhs 4 5 { rw [←tensor_comp, right_unitor_naturality, tensor_comp] }, repeat { rw category.assoc }, rw [triangle_assoc_comp_left_inv_assoc, ←right_unitor_tensor_assoc, right_unitor_naturality_assoc, ←unitors_equal, ←category.assoc, ←category.assoc], simp end /-- Given an exact pairing on `Y Y'`, we get a bijection on hom-sets `(Y' ⊗ X ⟶ Z) ≃ (X ⟶ Y ⊗ Z)` by "pulling the string on the left" up or down. This gives the adjunction `tensor_left_adjunction Y Y' : tensor_left Y' ⊣ tensor_left Y`. This adjunction is often referred to as "Frobenius reciprocity" in the fusion categories / planar algebras / subfactors literature. -/ def tensor_left_hom_equiv (X Y Y' Z : C) [exact_pairing Y Y'] : (Y' ⊗ X ⟶ Z) ≃ (X ⟶ Y ⊗ Z) := { to_fun := λ f, (λ_ _).inv ≫ (η_ _ _ ⊗ 𝟙 _) ≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ f), inv_fun := λ f, (𝟙 Y' ⊗ f) ≫ (α_ _ _ _).inv ≫ (ε_ _ _ ⊗ 𝟙 _) ≫ (λ_ _).hom, left_inv := λ f, begin dsimp, simp only [id_tensor_comp], slice_lhs 4 5 { rw associator_inv_naturality, }, slice_lhs 5 6 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_lhs 2 5 { simp only [←tensor_id, associator_inv_conjugation], }, have c : (α_ Y' (Y ⊗ Y') X).hom ≫ (𝟙 Y' ⊗ (α_ Y Y' X).hom) ≫ (α_ Y' Y (Y' ⊗ X)).inv ≫ (α_ (Y' ⊗ Y) Y' X).inv = (α_ _ _ _).inv ⊗ 𝟙 _, pure_coherence, slice_lhs 4 7 { rw c, }, slice_lhs 3 5 { rw [←comp_tensor_id, ←comp_tensor_id, coevaluation_evaluation], }, simp only [left_unitor_conjugation], coherence, end, right_inv := λ f, begin dsimp, simp only [id_tensor_comp], slice_lhs 3 4 { rw ←associator_naturality, }, slice_lhs 2 3 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], }, slice_lhs 3 6 { simp only [←tensor_id, associator_inv_conjugation], }, have c : (α_ (Y ⊗ Y') Y Z).hom ≫ (α_ Y Y' (Y ⊗ Z)).hom ≫ (𝟙 Y ⊗ (α_ Y' Y Z).inv) ≫ (α_ Y (Y' ⊗ Y) Z).inv = (α_ _ _ _).hom ⊗ 𝟙 Z, pure_coherence, slice_lhs 5 8 { rw c, }, slice_lhs 4 6 { rw [←comp_tensor_id, ←comp_tensor_id, evaluation_coevaluation], }, simp only [left_unitor_conjugation], coherence, end, } /-- Given an exact pairing on `Y Y'`, we get a bijection on hom-sets `(X ⊗ Y ⟶ Z) ≃ (X ⟶ Z ⊗ Y')` by "pulling the string on the right" up or down. -/ def tensor_right_hom_equiv (X Y Y' Z : C) [exact_pairing Y Y'] : (X ⊗ Y ⟶ Z) ≃ (X ⟶ Z ⊗ Y') := { to_fun := λ f, (ρ_ _).inv ≫ (𝟙 _ ⊗ η_ _ _) ≫ (α_ _ _ _).inv ≫ (f ⊗ 𝟙 _), inv_fun := λ f, (f ⊗ 𝟙 _) ≫ (α_ _ _ _).hom ≫ (𝟙 _ ⊗ ε_ _ _) ≫ (ρ_ _).hom, left_inv := λ f, begin dsimp, simp only [comp_tensor_id], slice_lhs 4 5 { rw associator_naturality, }, slice_lhs 5 6 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], }, slice_lhs 2 5 { simp only [←tensor_id, associator_conjugation], }, have c : (α_ X (Y ⊗ Y') Y).inv ≫ ((α_ X Y Y').inv ⊗ 𝟙 Y) ≫ (α_ (X ⊗ Y) Y' Y).hom ≫ (α_ X Y (Y' ⊗ Y)).hom = 𝟙 _ ⊗ (α_ _ _ _).hom, pure_coherence, slice_lhs 4 7 { rw c, }, slice_lhs 3 5 { rw [←id_tensor_comp, ←id_tensor_comp, evaluation_coevaluation], }, simp only [right_unitor_conjugation], coherence, end, right_inv := λ f, begin dsimp, simp only [comp_tensor_id], slice_lhs 3 4 { rw ←associator_inv_naturality, }, slice_lhs 2 3 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_lhs 3 6 { simp only [←tensor_id, associator_conjugation], }, have c : (α_ Z Y' (Y ⊗ Y')).inv ≫ (α_ (Z ⊗ Y') Y Y').inv ≫ ((α_ Z Y' Y).hom ⊗ 𝟙 Y') ≫ (α_ Z (Y' ⊗ Y) Y').hom = 𝟙 _ ⊗ (α_ _ _ _).inv, pure_coherence, slice_lhs 5 8 { rw c, }, slice_lhs 4 6 { rw [←id_tensor_comp, ←id_tensor_comp, coevaluation_evaluation], }, simp only [right_unitor_conjugation], coherence, end, } lemma tensor_left_hom_equiv_naturality {X Y Y' Z Z' : C} [exact_pairing Y Y'] (f : Y' ⊗ X ⟶ Z) (g : Z ⟶ Z') : (tensor_left_hom_equiv X Y Y' Z') (f ≫ g) = (tensor_left_hom_equiv X Y Y' Z) f ≫ (𝟙 Y ⊗ g) := begin dsimp [tensor_left_hom_equiv], simp only [id_tensor_comp, category.assoc], end lemma tensor_left_hom_equiv_symm_naturality {X X' Y Y' Z : C} [exact_pairing Y Y'] (f : X ⟶ X') (g : X' ⟶ Y ⊗ Z) : (tensor_left_hom_equiv X Y Y' Z).symm (f ≫ g) = (𝟙 _ ⊗ f) ≫ (tensor_left_hom_equiv X' Y Y' Z).symm g := begin dsimp [tensor_left_hom_equiv], simp only [id_tensor_comp, category.assoc], end lemma tensor_right_hom_equiv_naturality {X Y Y' Z Z' : C} [exact_pairing Y Y'] (f : X ⊗ Y ⟶ Z) (g : Z ⟶ Z') : (tensor_right_hom_equiv X Y Y' Z') (f ≫ g) = (tensor_right_hom_equiv X Y Y' Z) f ≫ (g ⊗ 𝟙 Y') := begin dsimp [tensor_right_hom_equiv], simp only [comp_tensor_id, category.assoc], end lemma tensor_right_hom_equiv_symm_naturality {X X' Y Y' Z : C} [exact_pairing Y Y'] (f : X ⟶ X') (g : X' ⟶ Z ⊗ Y') : ((tensor_right_hom_equiv X Y Y' Z).symm) (f ≫ g) = (f ⊗ 𝟙 Y) ≫ ((tensor_right_hom_equiv X' Y Y' Z).symm) g := begin dsimp [tensor_right_hom_equiv], simp only [comp_tensor_id, category.assoc], end /-- If `Y Y'` have an exact pairing, then the functor `tensor_left Y'` is left adjoint to `tensor_left Y`. -/ def tensor_left_adjunction (Y Y' : C) [exact_pairing Y Y'] : tensor_left Y' ⊣ tensor_left Y := adjunction.mk_of_hom_equiv { hom_equiv := λ X Z, tensor_left_hom_equiv X Y Y' Z, hom_equiv_naturality_left_symm' := λ X X' Z f g, tensor_left_hom_equiv_symm_naturality f g, hom_equiv_naturality_right' := λ X Z Z' f g, tensor_left_hom_equiv_naturality f g, } /-- If `Y Y'` have an exact pairing, then the functor `tensor_right Y` is left adjoint to `tensor_right Y'`. -/ def tensor_right_adjunction (Y Y' : C) [exact_pairing Y Y'] : tensor_right Y ⊣ tensor_right Y' := adjunction.mk_of_hom_equiv { hom_equiv := λ X Z, tensor_right_hom_equiv X Y Y' Z, hom_equiv_naturality_left_symm' := λ X X' Z f g, tensor_right_hom_equiv_symm_naturality f g, hom_equiv_naturality_right' := λ X Z Z' f g, tensor_right_hom_equiv_naturality f g, } /-- If `Y` has a left dual `ᘁY`, then it is a closed object, with the internal hom functor `Y ⟶[C] -` given by left tensoring by `ᘁY`. This has to be a definition rather than an instance to avoid diamonds, for example between `category_theory.monoidal_closed.functor_closed` and `category_theory.monoidal.functor_has_left_dual`. Moreover, in concrete applications there is often a more useful definition of the internal hom object than `ᘁY ⊗ X`, in which case the closed structure shouldn't come from `has_left_dual` (e.g. in the category `FinVect k`, it is more convenient to define the internal hom as `Y →ₗ[k] X` rather than `ᘁY ⊗ X` even though these are naturally isomorphic). -/ @[priority 100] def closed_of_has_left_dual (Y : C) [has_left_dual Y] : closed Y := { is_adj := ⟨_, tensor_left_adjunction (ᘁY) Y⟩, } /-- `tensor_left_hom_equiv` commutes with tensoring on the right -/ lemma tensor_left_hom_equiv_tensor {X X' Y Y' Z Z' : C} [exact_pairing Y Y'] (f : X ⟶ Y ⊗ Z) (g : X' ⟶ Z') : (tensor_left_hom_equiv (X ⊗ X') Y Y' (Z ⊗ Z')).symm ((f ⊗ g) ≫ (α_ _ _ _).hom) = (α_ _ _ _).inv ≫ ((tensor_left_hom_equiv X Y Y' Z).symm f ⊗ g) := begin dsimp [tensor_left_hom_equiv], simp only [id_tensor_comp], simp only [associator_inv_conjugation], slice_lhs 2 2 { rw ←id_tensor_comp_tensor_id, }, conv_rhs { rw [←id_tensor_comp_tensor_id, comp_tensor_id, comp_tensor_id], }, simp, coherence, end /-- `tensor_right_hom_equiv` commutes with tensoring on the left -/ lemma tensor_right_hom_equiv_tensor {X X' Y Y' Z Z' : C} [exact_pairing Y Y'] (f : X ⟶ Z ⊗ Y') (g : X' ⟶ Z') : (tensor_right_hom_equiv (X' ⊗ X) Y Y' (Z' ⊗ Z)).symm ((g ⊗ f) ≫ (α_ _ _ _).inv) = (α_ _ _ _).hom ≫ (g ⊗ (tensor_right_hom_equiv X Y Y' Z).symm f) := begin dsimp [tensor_right_hom_equiv], simp only [comp_tensor_id], simp only [associator_conjugation], slice_lhs 2 2 { rw ←tensor_id_comp_id_tensor, }, conv_rhs { rw [←tensor_id_comp_id_tensor, id_tensor_comp, id_tensor_comp], }, simp only [←tensor_id, associator_conjugation], simp, coherence, end @[simp] lemma tensor_left_hom_equiv_symm_coevaluation_comp_id_tensor {Y Y' Z : C} [exact_pairing Y Y'] (f : Y' ⟶ Z) : (tensor_left_hom_equiv _ _ _ _).symm (η_ _ _ ≫ (𝟙 Y ⊗ f)) = (ρ_ _).hom ≫ f := begin dsimp [tensor_left_hom_equiv], rw id_tensor_comp, slice_lhs 2 3 { rw associator_inv_naturality, }, slice_lhs 3 4 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_lhs 1 3 { rw coevaluation_evaluation, }, simp, end @[simp] lemma tensor_left_hom_equiv_symm_coevaluation_comp_tensor_id {X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) : (tensor_left_hom_equiv _ _ _ _).symm (η_ _ _ ≫ (f ⊗ 𝟙 Xᘁ)) = (ρ_ _).hom ≫ fᘁ := begin dsimp [tensor_left_hom_equiv, right_adjoint_mate], simp, end @[simp] lemma tensor_right_hom_equiv_symm_coevaluation_comp_id_tensor {X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) : (tensor_right_hom_equiv _ (ᘁY) _ _).symm (η_ (ᘁX) X ≫ (𝟙 (ᘁX) ⊗ f)) = (λ_ _).hom ≫ (ᘁf) := begin dsimp [tensor_right_hom_equiv, left_adjoint_mate], simp, end @[simp] lemma tensor_right_hom_equiv_symm_coevaluation_comp_tensor_id {Y Y' Z : C} [exact_pairing Y Y'] (f : Y ⟶ Z) : (tensor_right_hom_equiv _ Y _ _).symm (η_ Y Y' ≫ (f ⊗ 𝟙 Y')) = (λ_ _).hom ≫ f := begin dsimp [tensor_right_hom_equiv], rw comp_tensor_id, slice_lhs 2 3 { rw associator_naturality, }, slice_lhs 3 4 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], }, slice_lhs 1 3 { rw evaluation_coevaluation, }, simp, end @[simp] lemma tensor_left_hom_equiv_id_tensor_comp_evaluation {Y Z : C} [has_left_dual Z] (f : Y ⟶ (ᘁZ)) : (tensor_left_hom_equiv _ _ _ _) ((𝟙 Z ⊗ f) ≫ ε_ _ _) = f ≫ (ρ_ _).inv := begin dsimp [tensor_left_hom_equiv], rw id_tensor_comp, slice_lhs 3 4 { rw ←associator_naturality, }, slice_lhs 2 3 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], }, slice_lhs 3 5 { rw evaluation_coevaluation, }, simp, end @[simp] lemma tensor_left_hom_equiv_tensor_id_comp_evaluation {X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) : (tensor_left_hom_equiv _ _ _ _) ((f ⊗ 𝟙 _) ≫ ε_ _ _) = (ᘁf) ≫ (ρ_ _).inv := begin dsimp [tensor_left_hom_equiv, left_adjoint_mate], simp, end @[simp] lemma tensor_right_hom_equiv_id_tensor_comp_evaluation {X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) : (tensor_right_hom_equiv _ _ _ _) ((𝟙 Yᘁ ⊗ f) ≫ ε_ _ _) = fᘁ ≫ (λ_ _).inv := begin dsimp [tensor_right_hom_equiv, right_adjoint_mate], simp, end @[simp] lemma tensor_right_hom_equiv_tensor_id_comp_evaluation {X Y : C} [has_right_dual X] (f : Y ⟶ Xᘁ) : (tensor_right_hom_equiv _ _ _ _) ((f ⊗ 𝟙 X) ≫ ε_ X Xᘁ) = f ≫ (λ_ _).inv := begin dsimp [tensor_right_hom_equiv], rw comp_tensor_id, slice_lhs 3 4 { rw ←associator_inv_naturality, }, slice_lhs 2 3 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_lhs 3 5 { rw coevaluation_evaluation, }, simp, end -- Next four lemmas passing `fᘁ` or `ᘁf` through (co)evaluations. lemma coevaluation_comp_right_adjoint_mate {X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) : η_ Y Yᘁ ≫ (𝟙 _ ⊗ fᘁ) = η_ _ _ ≫ (f ⊗ 𝟙 _) := begin apply_fun (tensor_left_hom_equiv _ Y Yᘁ _).symm, simp, end lemma left_adjoint_mate_comp_evaluation {X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) : (𝟙 X ⊗ (ᘁf)) ≫ ε_ _ _ = (f ⊗ 𝟙 _) ≫ ε_ _ _ := begin apply_fun (tensor_left_hom_equiv _ (ᘁX) X _), simp, end lemma coevaluation_comp_left_adjoint_mate {X Y : C} [has_left_dual X] [has_left_dual Y] (f : X ⟶ Y) : η_ (ᘁY) Y ≫ ((ᘁf) ⊗ 𝟙 Y) = η_ (ᘁX) X ≫ (𝟙 (ᘁX) ⊗ f) := begin apply_fun (tensor_right_hom_equiv _ (ᘁY) Y _).symm, simp, end lemma right_adjoint_mate_comp_evaluation {X Y : C} [has_right_dual X] [has_right_dual Y] (f : X ⟶ Y) : (fᘁ ⊗ 𝟙 X) ≫ ε_ X Xᘁ = (𝟙 Yᘁ ⊗ f) ≫ ε_ Y Yᘁ := begin apply_fun (tensor_right_hom_equiv _ X (Xᘁ) _), simp, end /-- Transport an exact pairing across an isomorphism in the first argument. -/ def exact_pairing_congr_left {X X' Y : C} [exact_pairing X' Y] (i : X ≅ X') : exact_pairing X Y := { evaluation := (𝟙 Y ⊗ i.hom) ≫ ε_ _ _, coevaluation := η_ _ _ ≫ (i.inv ⊗ 𝟙 Y), evaluation_coevaluation' := begin rw [id_tensor_comp, comp_tensor_id], slice_lhs 2 3 { rw [associator_naturality], }, slice_lhs 3 4 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], }, slice_lhs 4 5 { rw [tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], }, slice_lhs 2 3 { rw [←associator_naturality], }, slice_lhs 1 2 { rw [tensor_id, tensor_id_comp_id_tensor, ←id_tensor_comp_tensor_id], }, slice_lhs 2 4 { rw [evaluation_coevaluation], }, slice_lhs 1 2 { rw [left_unitor_naturality], }, slice_lhs 3 4 { rw [←right_unitor_inv_naturality], }, simp, end, coevaluation_evaluation' := begin rw [id_tensor_comp, comp_tensor_id], simp only [iso.inv_hom_id_assoc, associator_conjugation, category.assoc], slice_lhs 2 3 { rw [←tensor_comp], simp, }, simp, end, } /-- Transport an exact pairing across an isomorphism in the second argument. -/ def exact_pairing_congr_right {X Y Y' : C} [exact_pairing X Y'] (i : Y ≅ Y') : exact_pairing X Y := { evaluation := (i.hom ⊗ 𝟙 X) ≫ ε_ _ _, coevaluation := η_ _ _ ≫ (𝟙 X ⊗ i.inv), evaluation_coevaluation' := begin rw [id_tensor_comp, comp_tensor_id], simp only [iso.inv_hom_id_assoc, associator_conjugation, category.assoc], slice_lhs 3 4 { rw [←tensor_comp], simp, }, simp, end, coevaluation_evaluation' := begin rw [id_tensor_comp, comp_tensor_id], slice_lhs 3 4 { rw [←associator_inv_naturality], }, slice_lhs 2 3 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_lhs 1 2 { rw [id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_lhs 3 4 { rw [associator_inv_naturality], }, slice_lhs 4 5 { rw [tensor_id, id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_lhs 2 4 { rw [coevaluation_evaluation], }, slice_lhs 1 2 { rw [right_unitor_naturality], }, slice_lhs 3 4 { rw [←left_unitor_inv_naturality], }, simp, end, } /-- Transport an exact pairing across isomorphisms. -/ def exact_pairing_congr {X X' Y Y' : C} [exact_pairing X' Y'] (i : X ≅ X') (j : Y ≅ Y') : exact_pairing X Y := begin haveI : exact_pairing X' Y := exact_pairing_congr_right j, exact exact_pairing_congr_left i, end /-- Right duals are isomorphic. -/ def right_dual_iso {X Y₁ Y₂ : C} (_ : exact_pairing X Y₁) (_ : exact_pairing X Y₂) : Y₁ ≅ Y₂ := { hom := @right_adjoint_mate C _ _ X X ⟨Y₂⟩ ⟨Y₁⟩ (𝟙 X), inv := @right_adjoint_mate C _ _ X X ⟨Y₁⟩ ⟨Y₂⟩ (𝟙 X), hom_inv_id' := by rw [←comp_right_adjoint_mate, category.comp_id, right_adjoint_mate_id], inv_hom_id' := by rw [←comp_right_adjoint_mate, category.comp_id, right_adjoint_mate_id] } /-- Left duals are isomorphic. -/ def left_dual_iso {X₁ X₂ Y : C} (p₁ : exact_pairing X₁ Y) (p₂ : exact_pairing X₂ Y) : X₁ ≅ X₂ := { hom := @left_adjoint_mate C _ _ Y Y ⟨X₂⟩ ⟨X₁⟩ (𝟙 Y), inv := @left_adjoint_mate C _ _ Y Y ⟨X₁⟩ ⟨X₂⟩ (𝟙 Y), hom_inv_id' := by rw [←comp_left_adjoint_mate, category.comp_id, left_adjoint_mate_id], inv_hom_id' := by rw [←comp_left_adjoint_mate, category.comp_id, left_adjoint_mate_id] } @[simp] lemma right_dual_iso_id {X Y : C} (p : exact_pairing X Y) : right_dual_iso p p = iso.refl Y := by { ext, simp only [right_dual_iso, iso.refl_hom, right_adjoint_mate_id] } @[simp] lemma left_dual_iso_id {X Y : C} (p : exact_pairing X Y) : left_dual_iso p p = iso.refl X := by { ext, simp only [left_dual_iso, iso.refl_hom, left_adjoint_mate_id] } /-- A right rigid monoidal category is one in which every object has a right dual. -/ class right_rigid_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] := [right_dual : Π (X : C), has_right_dual X] /-- A left rigid monoidal category is one in which every object has a right dual. -/ class left_rigid_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] := [left_dual : Π (X : C), has_left_dual X] attribute [instance, priority 100] right_rigid_category.right_dual attribute [instance, priority 100] left_rigid_category.left_dual /-- Any left rigid category is monoidal closed, with the internal hom `X ⟶[C] Y = ᘁX ⊗ Y`. This has to be a definition rather than an instance to avoid diamonds, for example between `category_theory.monoidal_closed.functor_category` and `category_theory.monoidal.left_rigid_functor_category`. Moreover, in concrete applications there is often a more useful definition of the internal hom object than `ᘁY ⊗ X`, in which case the monoidal closed structure shouldn't come the rigid structure (e.g. in the category `FinVect k`, it is more convenient to define the internal hom as `Y →ₗ[k] X` rather than `ᘁY ⊗ X` even though these are naturally isomorphic). -/ @[priority 100] def monoidal_closed_of_left_rigid_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] [left_rigid_category C] : monoidal_closed C := { closed' := λ X, closed_of_has_left_dual X, } /-- A rigid monoidal category is a monoidal category which is left rigid and right rigid. -/ class rigid_category (C : Type u) [category.{v} C] [monoidal_category.{v} C] extends right_rigid_category C, left_rigid_category C end category_theory
a201fa7f8084783dafe5639cb5375ca1f41201ee
9338c56dfd6ceacc3e5e63e32a7918cfec5d5c69
/src/Kenny/subsheaf.lean
8605b236e0053e237a2b157b23a0168362fda4db
[]
no_license
Project-Reykjavik/lean-scheme
7322eefce504898ba33737970be89dc751108e2b
6d3ec18fecfd174b79d0ce5c85a783f326dd50f6
refs/heads/master
1,669,426,172,632
1,578,284,588,000
1,578,284,588,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,457
lean
import Kenny.sheaf_on_opens universes v u open topological_space variables {X : Type u} [topological_space X] structure subpresheaf (F : presheaf.{u v} X) : Type (max u v) := (to_set : Π U : opens X, set (F U)) (res_mem_to_set : ∀ {U V : opens X} (HVU : V ⊆ U) {x : F U}, x ∈ to_set U → F.res U V HVU x ∈ to_set V) namespace subpresheaf instance (F : presheaf.{u v} X) : has_coe_to_fun (subpresheaf F) := ⟨_, to_set⟩ instance (F : presheaf.{u v} X) : partial_order (subpresheaf F) := partial_order.lift to_set (λ ⟨x, hx⟩ ⟨y, hy⟩, mk.inj_eq.mpr) infer_instance def to_subsheaf {F : presheaf.{u v} X} (S : subpresheaf F) : subpresheaf F := { to_set := λ U, { x | ∃ OC : covering.{u} U, ∀ i : OC.γ, F.res U (OC.Uis i) (subset_covering i) x ∈ S (OC.Uis i) }, res_mem_to_set := λ U V HVU x ⟨OC, hx⟩, ⟨opens.covering_res U V HVU OC, λ i, have _ ∈ S ((opens.covering_res U V HVU OC).Uis i) := S.res_mem_to_set (set.inter_subset_right _ _) (hx i), by rwa ← presheaf.Hcomp' at this ⊢⟩ } theorem le_to_subsheaf {F : presheaf.{u v} X} (S : subpresheaf F) : S ≤ S.to_subsheaf := λ U x hx, ⟨{ γ := punit, Uis := λ _, U, Hcov := le_antisymm (lattice.supr_le $ λ _, le_refl U) (lattice.le_supr (λ _, U) punit.star) }, λ i, by erw F.Hid'; exact hx⟩ def to_presheaf {F : presheaf.{u v} X} (S : subpresheaf F) : presheaf X := { F := λ U, S U, res := λ U V HVU x, ⟨F.res U V HVU x.1, S.2 HVU x.2⟩, Hid := λ U, funext $ λ x, subtype.eq $ F.Hid' U x.1, Hcomp := λ U V W HWV HVU, funext $ λ x, subtype.eq $ F.Hcomp' U V W HWV HVU x.1 } theorem locality {O : sheaf.{u v} X} (S : subpresheaf O.to_presheaf) : locality S.to_presheaf := λ U OC s t H, subtype.eq $ O.locality OC s.1 t.1 $ λ i, have _ := congr_arg subtype.val (H i), this end subpresheaf class is_subsheaf {F : presheaf.{u v} X} (S : subpresheaf F) : Prop := (mem_of_res_mem : ∀ {U : opens X}, ∀ {x : F U}, ∀ OC : covering.{u} U, (∀ i : OC.γ, F.res U (OC.Uis i) (subset_covering i) x ∈ S (OC.Uis i)) → x ∈ S U) theorem covering.exists {U : opens X} (OC : covering U) {x : X} (hx : x ∈ U) : ∃ i : OC.γ, x ∈ OC.Uis i := let ⟨_, ⟨_, ⟨i, rfl⟩, rfl⟩, hi⟩ := set.mem_sUnion.1 (((set.ext_iff _ _).1 (congr_arg subtype.val OC.Hcov) x).2 hx) in ⟨i, hi⟩ def covering.glue {U : opens X} (OC : covering U) (F : Π i : OC.γ, covering (OC.Uis i)) : covering U := { γ := Σ i : OC.γ, (F i).γ, Uis := λ P, (F P.1).Uis P.2, Hcov := opens.ext $ (set.sUnion_image _ _).trans $ set.subset.antisymm (set.bUnion_subset $ set.range_subset_iff.2 $ λ P, set.subset.trans (subset_covering P.2) (subset_covering P.1)) (λ x hx, let ⟨i, hi⟩ := OC.exists hx, ⟨j, hj⟩ := (F i).exists hi in set.mem_bUnion ⟨⟨i, j⟩, rfl⟩ hj) } theorem is_subsheaf_to_subsheaf {F : presheaf.{u v} X} (S : subpresheaf F) : is_subsheaf S.to_subsheaf := ⟨λ U x OC H, ⟨OC.glue $ λ i, classical.some (H i), λ P, have _ := classical.some_spec (H P.1) P.2, by rw ← F.Hcomp' at this; convert this⟩⟩ theorem is_subsheaf.is_sheaf_to_presheaf {O : sheaf.{u v} X} (S : subpresheaf O.to_presheaf) [is_subsheaf S] : is_sheaf S.to_presheaf := { left := λ U, S.locality, right := λ U OC s H, let ⟨f, hf⟩ := O.gluing OC (λ i, (s i).1) (λ j k, congr_arg subtype.val (H j k)) in ⟨⟨f, is_subsheaf.mem_of_res_mem OC $ λ i, (hf i).symm ▸ (s i).2⟩, λ i, subtype.eq $ hf i⟩ }
8fd6d61212bad7befb563cf37159ff46d60ba476
b9def12ac9858ba514e44c0758ebb4e9b73ae5ed
/src/monoidal_categories_reboot/rigid_monoidal_category.lean
d141cc4880dc49e06a6ae4314390bd632c4e6598
[ "Apache-2.0" ]
permissive
cipher1024/monoidal-categories-reboot
5f826017db2f71920336331739a0f84be2f97bf7
998f2a0553c22369d922195dc20a20fa7dccc6e5
refs/heads/master
1,586,710,273,395
1,543,592,573,000
1,543,592,573,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,502
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. import .monoidal_category import .braided_monoidal_category universes u v namespace category_theory.monoidal open monoidal_category class right_duality {C : Type u} (A A' : C) [monoidal_category.{u v} C] := (right_unit : tensor_unit C ⟶ A ⊗ A') (right_counit : A' ⊗ A ⟶ tensor_unit C) (triangle_right_1' : ((𝟙 A') ⊗ right_unit) ≫ (associator A' A A').inv ≫ (right_counit ⊗ (𝟙 A')) = (right_unitor A').hom ≫ (left_unitor A').inv . obviously) (triangle_right_2' : (right_unit ⊗ (𝟙 A)) ≫ (associator A A' A).hom ≫ ((𝟙 A) ⊗ right_counit) = (left_unitor A).hom ≫ (right_unitor A).inv . obviously) class left_duality {C : Type u} (A A' : C) [monoidal_category.{u v} C] := (left_unit : tensor_unit C ⟶ A' ⊗ A) (left_counit : A ⊗ A' ⟶ tensor_unit C) (triangle_left_1' : ((𝟙 A) ⊗ left_unit) ≫ (associator A A' A).inv ≫ (left_counit ⊗ (𝟙 A)) = (right_unitor A).hom ≫ (left_unitor A).inv . obviously) (triangle_left_2' : (left_unit ⊗ (𝟙 A')) ≫ (associator A' A A').hom ≫ ((𝟙 A') ⊗ left_counit) = (left_unitor A').hom ≫ (right_unitor A').inv . obviously) class duality {C : Type u} (A A' : C) [braided_monoidal_category.{u v} C] extends right_duality.{u v} A A', left_duality.{u v} A A' def self_duality {C : Type u} (A : C) [braided_monoidal_category.{u v} C] := duality A A class right_rigid (C : Type u) [monoidal_category.{u v} C] := (right_rigidity' : Π X : C, Σ X' : C, right_duality X X') class left_rigid (C : Type u) [monoidal_category.{u v} C] := (left_rigidity' : Π X : C, Σ X' : C, left_duality X X') class rigid (C : Type u) [monoidal_category.{u v} C] extends right_rigid.{u v} C, left_rigid.{u v} C class self_dual (C : Type u) [braided_monoidal_category.{u v} C] := (self_duality' : Π X : C, self_duality X) def compact_closed (C : Type u) [symmetric_monoidal_category.{u v} C] := rigid.{u v} C section open self_dual open left_duality instance rigid_of_self_dual (C : Type u) [braided_monoidal_category.{u v} C] [𝒟 : self_dual.{u v} C] : rigid.{u v} C := { left_rigidity' := λ X : C, sigma.mk X (self_duality' X).to_left_duality, right_rigidity' := λ X : C, sigma.mk X (self_duality' X).to_right_duality } end end category_theory.monoidal
e7efb458da3acb31f3271626a92b36ccc2c15533
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/punit.lean
dbb72b1529994c23e5339c5c8806e1a6175953fd
[ "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
1,763
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.const import category_theory.discrete_category universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory namespace functor variables (C : Type u) [category.{v} C] /-- The constant functor sending everything to `punit.star`. -/ def star : C ⥤ discrete punit := (functor.const _).obj punit.star variable {C} /-- Any two functors to `discrete punit` are isomorphic. -/ def punit_ext (F G : C ⥤ discrete punit) : F ≅ G := nat_iso.of_components (λ _, eq_to_iso dec_trivial) (λ _ _ _, dec_trivial) /-- Any two functors to `discrete punit` are *equal*. You probably want to use `punit_ext` instead of this. -/ lemma punit_ext' (F G : C ⥤ discrete punit) : F = G := functor.ext (λ _, dec_trivial) (λ _ _ _, dec_trivial) /-- The functor from `discrete punit` sending everything to the given object. -/ abbreviation from_punit (X : C) : discrete punit.{v+1} ⥤ C := (functor.const _).obj X /-- Functors from `discrete punit` are equivalent to the category itself. -/ @[simps] def equiv : (discrete punit ⥤ C) ≌ C := { functor := { obj := λ F, F.obj punit.star, map := λ F G θ, θ.app punit.star }, inverse := functor.const _, unit_iso := begin apply nat_iso.of_components _ _, intro X, apply discrete.nat_iso, rintro ⟨⟩, apply iso.refl _, intros, ext ⟨⟩, simp, end, counit_iso := begin refine nat_iso.of_components iso.refl _, intros X Y f, dsimp, simp, -- See note [dsimp, simp]. end } end functor end category_theory
b66ad71d725ceed1801dd82b293a63ad06a02641
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/diamond10.lean
414e51885634ecfb80b110eafa39ea27aae18b49
[ "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
426
lean
class Zero (A : Type u) where zero : A instance {A} [Zero A] : OfNat A (nat_lit 0) := ⟨Zero.zero⟩ class AddMonoid (A : Type u) extends Add A, Zero A class Semiring (R : Type u) extends AddMonoid R class SubNegMonoid (A : Type u) extends AddMonoid A, Neg A class AddGroup (A : Type u) extends SubNegMonoid A where add_left_neg (a : A) : -a + a = 0 class Ring (R : Type u) extends Semiring R, AddGroup R #print Ring.mk
6cada724b6d1ad68759ebbb33f590fa17f5ded47
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_8/ideas/subGmodexperiments.lean
5d04e2b609f409924e586c400a177378aea0f6f2
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
1,130
lean
import group_theory.group_action.sub_mul_action set_option old_structure_cmd true structure sub_distrib_mul_action (G M : Type) [monoid G] [add_comm_group M] [distrib_mul_action G M] extends sub_mul_action G M, add_subgroup M variables {G M : Type} [monoid G] --`*` [add_comm_group M] --`+` [distrib_mul_action G M] --`•` namespace sub_distrib_mul_action -- now copy theorems from sub_mul_action if you want def bot : sub_distrib_mul_action G M := { carrier := {x | x = 0}, smul_mem' := begin sorry, end, zero_mem' := sorry, add_mem' := sorry, neg_mem' := sorry } variables {N : Type} [add_comm_group N] [distrib_mul_action G N] def ker (φ : M →+[G] N) : sub_distrib_mul_action G M := { carrier := {m | φ m = 0}, smul_mem' := sorry, zero_mem' := sorry, add_mem' := sorry, neg_mem' := sorry } def range (φ : M →+[G] N) : sub_distrib_mul_action G N := { carrier := set.range φ, smul_mem' := sorry, zero_mem' := sorry, add_mem' := sorry, neg_mem' := sorry } -- and range (φ : M →+[G] N) : sub_distrib_mul_action G N -- that's what we're after end sub_distrib_mul_action